diff --git a/QuickMD/QuickMD/MarkdownExport.swift b/QuickMD/QuickMD/MarkdownExport.swift index 68f484b..187c862 100644 --- a/QuickMD/QuickMD/MarkdownExport.swift +++ b/QuickMD/QuickMD/MarkdownExport.swift @@ -80,6 +80,8 @@ struct FocusedExportDocumentLocationKey: FocusedValueKey { struct SourceEditMenuState: Equatable { let isEditing: Bool let isDirty: Bool + /// The editor and the rendered document side by side (File ▸ Split View). + var isSplit = false var canSave: Bool { isEditing && isDirty } } @@ -93,6 +95,12 @@ struct FocusedToggleSourceEditKey: FocusedValueKey { typealias Value = () -> Void } +/// ⌥⇧⌘E — Source Edit side by side with the rendered document, or back to +/// the editor only, in the FOCUSED document only. +struct FocusedToggleSplitEditKey: FocusedValueKey { + typealias Value = () -> Void +} + /// ⌘S while editing. struct FocusedSaveSourceKey: FocusedValueKey { typealias Value = () -> Void @@ -112,6 +120,10 @@ extension FocusedValues { get { self[FocusedToggleSourceEditKey.self] } set { self[FocusedToggleSourceEditKey.self] = newValue } } + var toggleSplitEditAction: (() -> Void)? { + get { self[FocusedToggleSplitEditKey.self] } + set { self[FocusedToggleSplitEditKey.self] = newValue } + } var saveSourceAction: (() -> Void)? { get { self[FocusedSaveSourceKey.self] } set { self[FocusedSaveSourceKey.self] = newValue } diff --git a/QuickMD/QuickMD/MarkdownView.swift b/QuickMD/QuickMD/MarkdownView.swift index fd9f36e..276633a 100644 --- a/QuickMD/QuickMD/MarkdownView.swift +++ b/QuickMD/QuickMD/MarkdownView.swift @@ -152,6 +152,19 @@ struct MarkdownView: View { /// The editor's find bar height (0 = hidden): the bar sits where the pills /// and banners float, so they move below it (`topChromeInset`). @State private var editorFindBarHeight: CGFloat = 0 + /// Source Edit as a split: editor on the left, the rendered document on + /// the right. Per tab; plain Edit always starts without it. + @State private var isSplitEdit = false + private var isSplitShowing: Bool { editSession.isActive && isSplitEdit } + /// Split view's live preview: the editor's unsaved text, shown by the + /// rendered side only (nil = the saved text). `currentText` stays what is + /// on disk, so copy, export, reload and the session never see it. + @State private var previewText: String? + /// Typing pauses before the preview re-renders. A reference, so a + /// keystroke never re-evaluates this body. + @State private var previewDebounce = PreviewDebounce() + /// What the rendered list shows. + private var renderedSource: String { previewText ?? currentText } /// The text `cachedBlocks` were parsed from. Block ids are positional, so a /// scroll by id is only meaningful against the blocks of the text it was /// computed for — the landing after Source Edit checks this (S-D10). @@ -280,6 +293,12 @@ struct MarkdownView: View { ) } + HStack(spacing: 0) { + // Split edit: the left half is the editor's (overlay below). + if isSplitShowing { + Color.clear.frame(maxWidth: .infinity) + Divider() + } // Our own virtualized list (v1.9): exact row heights from // `measured.table`, one layout path for every document size, // nothing estimated — see VirtualBlockList.swift. @@ -309,13 +328,15 @@ struct MarkdownView: View { // survive; a remount would park at the top) but never takes // the focus back while covered, and leaves the // accessibility tree meanwhile (set on the AppKit view). - isCovered: graphicPreview != nil || editSession.isActive, + isCovered: graphicPreview != nil || (editSession.isActive && !isSplitEdit), readingPosition: readingPosition, column: documentColumn ) + .frame(maxWidth: .infinity) .onChange(of: scrollTrigger) { _ in scrollFocusedMatchIntoView() } + } } .overlay { // Source Edit (S-D4). The FIRST overlay, so the pills, banners @@ -325,10 +346,19 @@ struct MarkdownView: View { // one). Theme, zoom and Reading Mode reach it through `style`. Group { if editSession.isActive { - SourceEditorView(controller: editSession.editor, - style: .overDocument(theme: theme, fontScale: fontScale, - shownFontScale: renderedFontScale, - isReadingMode: isReadingMode)) + HStack(spacing: 0) { + SourceEditorView(controller: editSession.editor, + style: .overDocument(theme: theme, fontScale: fontScale, + shownFontScale: renderedFontScale, + isReadingMode: isReadingMode)) + .frame(maxWidth: .infinity) + .overlay(alignment: .topTrailing) { sourceEditPills } + // Split: the right half shows the list beneath. + if isSplitEdit { + Divider() + Color.clear.frame(maxWidth: .infinity).allowsHitTesting(false) + } + } } } // An animated transaction from elsewhere (a toast, a sidebar) @@ -466,23 +496,10 @@ struct MarkdownView: View { /// ⌥⌘E, ⌘⇧C) all still work, so nothing is lost except the thing /// hovering over the text. /// - /// Editing: ONLY Save and Done, also in Reading Mode — a mode you can only - /// leave by shortcut is not acceptable (S-D12). + /// Editing: `sourceEditPills`, drawn on the editor itself. @ViewBuilder private var chromeCluster: some View { - if editSession.isActive { - HStack(spacing: 8) { - SourceSaveButton(theme: theme, isEnabled: editSession.isDirty) { - editSession.save() - } - SourceDoneButton(theme: theme) { - editSession.requestLeave() - } - } - .chromeHoverCluster() - .padding(.top, topChromeInset) - .padding(.trailing, 24) - } else if !isReadingMode { + if !editSession.isActive && !isReadingMode { HStack(spacing: 8) { // `appliedDefaultZoom`, not `defaultZoom`: no pill flash in a // window that follows a Settings change (see its doc comment). @@ -496,9 +513,9 @@ struct MarkdownView: View { ReloadDocumentButton(theme: theme) { reloadManually() } - EditSourceButton(theme: theme) { - toggleSourceEdit() - } + EditSourceButton(theme: theme, + action: { toggleSourceEdit() }, + splitAction: { toggleSplitEdit() }) } CopySourceButton(theme: theme) { copyToClipboard(currentText) @@ -512,6 +529,26 @@ struct MarkdownView: View { } } + /// Editing: ONLY Split, Save and Done, also in Reading Mode — a mode you + /// can only leave by shortcut is not acceptable (S-D12). Top-right of the + /// editor, so in a split they stay on the editing side. + private var sourceEditPills: some View { + HStack(spacing: 8) { + SourceSplitButton(theme: theme, isSplit: isSplitEdit) { + toggleSplitEdit() + } + SourceSaveButton(theme: theme, isEnabled: editSession.isDirty) { + editSession.save() + } + SourceDoneButton(theme: theme) { + editSession.requestLeave() + } + } + .chromeHoverCluster() + .padding(.top, topChromeInset) + .padding(.trailing, 24) + } + /// S-D9: the file changed on disk while the buffer holds unsaved text. The /// rendered view (hidden) already shows the disk; the user decides about /// the buffer. Same look and place as the missing-file banner. @@ -618,8 +655,10 @@ struct MarkdownView: View { private var sourceEditStack: some View { configuredDocumentStack .focusedSceneValue(\.sourceEditState, - SourceEditMenuState(isEditing: editSession.isActive, isDirty: editSession.isDirty)) + SourceEditMenuState(isEditing: editSession.isActive, isDirty: editSession.isDirty, + isSplit: isSplitEdit)) .focusedSceneValue(\.toggleSourceEditAction, { toggleSourceEdit() }) + .focusedSceneValue(\.toggleSplitEditAction, { toggleSplitEdit() }) .focusedSceneValue(\.saveSourceAction, { editSession.save() }) .focusedSceneValue(\.discardSourceChangesAction, { editSession.discardChanges() }) // A document can be moved or renamed while open: the session's URL @@ -644,13 +683,13 @@ struct MarkdownView: View { return .handled }) .frame(minWidth: 400, minHeight: 300) - .task(id: DocumentIdentity(text: currentText, + .task(id: DocumentIdentity(text: renderedSource, colorScheme: MarkdownTheme.windowColorScheme(forThemeNamed: selectedThemeName) == nil ? colorScheme : nil, themeName: selectedThemeName, fonts: DocumentFonts(body: bodyFontFamily, code: codeFontFamily), fontScale: fontScale)) { - let text = currentText + let text = renderedSource let currentTheme = theme isParsing = true let scale = CGFloat(fontScale) @@ -1035,7 +1074,8 @@ struct MarkdownView: View { commitText: { text in if !SourceEditSession.isSameText(text, currentText) { currentText = text } }, - toast: { showToast($0) } + toast: { showToast($0) }, + bufferChanged: { previewDebounce.schedule { updatePreview() } } ) editSession.editor.onFindBarHeightChange = { height in // Reported from the scroll view's `tile()`, i.e. inside an AppKit @@ -1052,12 +1092,13 @@ struct MarkdownView: View { /// ⌥⌘E, File ▸ Edit Source / Done Editing, the Edit pill. Entering starts /// at the source line being read — the selection's first row, else the /// top visible row (`editorLine()` is 1-based, the session 0-based). - private func toggleSourceEdit() { + private func toggleSourceEdit(split: Bool = false) { if editSession.isActive { editSession.requestLeave() return } guard graphicPreview == nil else { return } + isSplitEdit = split // A rendered selection whose text is literally in its source lines is // selected in the editor (S-D14b); otherwise the caret goes to the line. if let refusal = editSession.enter(atLine: readingPosition.editorLine().map { $0 - 1 }, @@ -1072,12 +1113,36 @@ struct MarkdownView: View { editSession.focusEditor() } + /// ⌥⇧⌘E, File ▸ Split View / Editor Only, the Split pill. Editing: flips + /// the split. Reading: enters Source Edit as a split. + private func toggleSplitEdit() { + if editSession.isActive { + isSplitEdit.toggle() + updatePreview() + editSession.focusEditor() + } else { + toggleSourceEdit(split: true) + } + } + + /// The live preview follows the buffer while the split shows; otherwise + /// the rendered side is the saved text again. + private func updatePreview() { + previewDebounce.cancel() + let text = isSplitShowing ? editSession.editor.text : nil + let preview = text.flatMap { SourceEditSession.isSameText($0, currentText) ? nil : $0 } + if preview != previewText { previewText = preview } + } + /// The session left (Done, Esc, the command; after Save or Don't Save). /// The list gets the keyboard back; if the session saved or the caret /// moved off the entry line, the list lands on the block holding the /// caret's line — against the blocks of the CURRENT text (S-D10). private func didLeaveSourceEdit(_ leave: SourceEditSession.LeaveInfo) { documentFocusRequest += 1 + // Unsaved text is gone with the editor: back to the saved text first, + // so the landing below waits for (or finds) the saved parse. + updatePreview() // `==`, as `DocumentIdentity` compares: text it calls equal is never // re-parsed, so waiting for a parse of it would wait forever. let current = installedText.map { $0 == currentText } ?? false @@ -1711,3 +1776,20 @@ struct SystemColorSchemeReader: NSViewRepresentable { [Visit Apple](https://apple.com) """), documentURL: nil) } + +/// Split view's live preview runs once typing pauses (`MarkdownView.previewDebounce`). +final class PreviewDebounce { + private var work: DispatchWorkItem? + + func schedule(after delay: TimeInterval = 0.3, _ action: @escaping () -> Void) { + work?.cancel() + let item = DispatchWorkItem(block: action) + work = item + DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item) + } + + func cancel() { + work?.cancel() + work = nil + } +} diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 34d50fb..9a76972 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -167,13 +167,15 @@ struct ToggleDocumentListCommand: View { } } -/// File ▸ Edit Source / Done Editing (⌥⌘E), Save (⌘S), Discard Changes — +/// File ▸ Edit Source / Done Editing (⌥⌘E), Split View / Editor Only +/// (⌥⇧⌘E), Save (⌘S), Discard Changes — /// Source Edit for the frontmost document only, via @FocusedValue like every /// other per-document command (an NSEvent monitor would act on every tab). /// ⌘S belongs to Save only while there is something to save: the viewer has /// no other Save, so a disabled item costs nothing. struct SourceEditCommands: View { @FocusedValue(\.toggleSourceEditAction) var toggleSourceEditAction + @FocusedValue(\.toggleSplitEditAction) var toggleSplitEditAction @FocusedValue(\.saveSourceAction) var saveSourceAction @FocusedValue(\.discardSourceChangesAction) var discardSourceChangesAction @FocusedValue(\.sourceEditState) var sourceEditState @@ -185,6 +187,13 @@ struct SourceEditCommands: View { .keyboardShortcut("e", modifiers: [.command, .option]) .disabled(toggleSourceEditAction == nil) + Button(sourceEditState?.isEditing == true && sourceEditState?.isSplit == true + ? "Editor Only" : "Split View") { + toggleSplitEditAction?() + } + .keyboardShortcut("e", modifiers: [.command, .option, .shift]) + .disabled(toggleSplitEditAction == nil) + Button("Save") { saveSourceAction?() } diff --git a/QuickMD/QuickMD/SourceEditSession.swift b/QuickMD/QuickMD/SourceEditSession.swift index 4c6cb80..6baf039 100644 --- a/QuickMD/QuickMD/SourceEditSession.swift +++ b/QuickMD/QuickMD/SourceEditSession.swift @@ -63,6 +63,9 @@ final class SourceEditSession: ObservableObject { /// text that is on disk. var commitText: (String) -> Void = { _ in } var toast: (String) -> Void = { _ in } + /// Every buffer change, the session's own included (split view's live + /// preview). Never writes or commits anything. + var bufferChanged: () -> Void = {} } var environment = Environment() @@ -198,7 +201,10 @@ final class SourceEditSession: ObservableObject { static var beep: () -> Void = { NSSound.beep() } init() { - editor.onChange = { [weak self] in self?.bufferDidChange() } + editor.onChange = { [weak self] in + self?.bufferDidChange() + self?.environment.bufferChanged() + } editor.onEscape = { [weak self] in self?.escape() } } diff --git a/QuickMD/QuickMD/Views/ChromeButtons.swift b/QuickMD/QuickMD/Views/ChromeButtons.swift index e7eb729..1f9c0b9 100644 --- a/QuickMD/QuickMD/Views/ChromeButtons.swift +++ b/QuickMD/QuickMD/Views/ChromeButtons.swift @@ -384,21 +384,42 @@ struct ReloadDocumentButton: View { /// buttons side by side were one too many) — it stays on ⌘E and in the File /// menu. One of the three ways into Source Edit, with File ▸ Edit Source and /// the shortcut. +/// +/// Holding Option turns it into "Split edit" (⌥⇧⌘E), like an alternate menu +/// item: the pill shows the split icon and an Option-click enters the split. struct EditSourceButton: View { let theme: MarkdownTheme let action: () -> Void + let splitAction: () -> Void + + @State private var isOptionDown = NSEvent.modifierFlags.contains(.option) + @State private var flagsMonitor: Any? var body: some View { ChromePill( theme: theme, - title: "Edit", - help: "Edit source (⌥⌘E)", - action: action + title: isOptionDown ? "Split edit" : "Edit", + help: "Edit source (⌥⌘E) · Option-click to edit side by side (⌥⇧⌘E)", + action: { + // The flags at the click, not the last flagsChanged seen. + NSEvent.modifierFlags.contains(.option) ? splitAction() : action() + } ) { - Image(systemName: "pencil") + Image(systemName: isOptionDown ? "rectangle.split.2x1" : "pencil") .font(.system(size: 11)) } .accessibilityIdentifier("source-edit") + .onAppear { + isOptionDown = NSEvent.modifierFlags.contains(.option) + flagsMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { event in + isOptionDown = event.modifierFlags.contains(.option) + return event + } + } + .onDisappear { + if let flagsMonitor { NSEvent.removeMonitor(flagsMonitor) } + flagsMonitor = nil + } } } @@ -424,6 +445,23 @@ struct SourceSaveButton: View { } } +/// Toggles the split: editor left, rendered document right (per tab). +struct SourceSplitButton: View { + let theme: MarkdownTheme + let isSplit: Bool + let action: () -> Void + + var body: some View { + ChromePill(theme: theme, title: isSplit ? "Editor only" : "Split", + help: isSplit ? "Show the editor only (⌥⇧⌘E)" : "Show the rendered document beside the editor (⌥⇧⌘E)", + action: action) { + Image(systemName: isSplit ? "rectangle" : "rectangle.split.2x1") + .font(.system(size: 11)) + } + .accessibilityIdentifier("source-split") + } +} + struct SourceDoneButton: View { let theme: MarkdownTheme let action: () -> Void