Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions QuickMD/QuickMD/MarkdownExport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
Expand All @@ -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
Expand All @@ -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 }
Expand Down
138 changes: 110 additions & 28 deletions QuickMD/QuickMD/MarkdownView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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).
Expand All @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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 },
Expand All @@ -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
Expand Down Expand Up @@ -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
}
}
11 changes: 10 additions & 1 deletion QuickMD/QuickMD/QuickMDApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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?()
}
Expand Down
8 changes: 7 additions & 1 deletion QuickMD/QuickMD/SourceEditSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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() }
}

Expand Down
Loading
Loading