diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab0eee2..2f820f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,11 +33,20 @@ jobs: - name: Run landing-page tests run: python3 -m unittest discover -s site -p 'test_*.py' + - name: Run signup lifecycle tests + run: node --test Tests/Site/signup.test.cjs + - name: Check scripts and property lists run: | zsh -n scripts/*.sh plutil -lint scripts/Info.plist scripts/QuickLook-Info.plist scripts/QuickLook.entitlements + - name: Verify the Universal 2 application bundle + run: | + ./scripts/build-app.sh + codesign --verify --deep --strict dist/PreviewMD.app + codesign --verify --strict dist/PreviewMD.app/Contents/PlugIns/PreviewMDQuickLook.appex + dco: name: DCO sign-off if: github.event_name == 'pull_request' && github.event.pull_request.user.login != 'dependabot[bot]' diff --git a/AGENTS.md b/AGENTS.md index e6fabc0..88623e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -250,7 +250,9 @@ spctl --assess --type open --context context:primary-signature --verbose=4 \ dist/PreviewMD---macOS.dmg ``` -The most recently accepted release is PreviewMD `1.7 (11)`. +The most recently accepted release is PreviewMD `1.8 (12)`. Its application +notarization submission is `561f54d2-cace-4732-aa60-569e2f2b9cdb`; the final +DMG submission is `efdec2e8-a377-4607-8bd4-3dea9ee9df78`. ## Versioning diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 982c961..f90af6f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -64,6 +64,7 @@ Useful checks: ```bash swift test python3 -m unittest discover -s site -p 'test_*.py' +node --test Tests/Site/signup.test.cjs zsh -n scripts/*.sh ./scripts/build-app.sh ``` @@ -93,7 +94,9 @@ In particular: ## Tests and reviewability Prefer a failing test before a bug fix when the behavior can be isolated. -Tests live in `Tests/PreviewMDTests/`; site tests live in `site/test_server.py`. +Native and renderer tests live in `Tests/PreviewMDTests/`. Server tests live in +`site/test_server.py`; signup lifecycle tests execute the actual modal JavaScript +from `Tests/Site/signup.test.cjs`, outside the public document root. In a pull request, include: diff --git a/README.md b/README.md index f6af841..7825c87 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ Run the test suite: ```bash swift test python3 -m unittest discover -s site -p 'test_*.py' +node --test Tests/Site/signup.test.cjs ``` Build the Universal 2 app bundle used for local testing: diff --git a/Sources/PreviewMD/AppState.swift b/Sources/PreviewMD/AppState.swift index 2c05856..1567b89 100644 --- a/Sources/PreviewMD/AppState.swift +++ b/Sources/PreviewMD/AppState.swift @@ -9,6 +9,26 @@ enum TabCloseDecision { case discard } +private struct ExternalPollInput: Sendable { + let id: UUID + let url: URL + let snapshot: FileSnapshot + let contentRevision: Int + let originalContent: String + let previousReview: ExternalChangeReview? +} + +private struct ExternalPollResult: Sendable { + enum Change: Sendable { + case unchanged + case changed(MarkdownFileIO.ReadResult, ExternalChangeReview?) + case unavailable + } + + let input: ExternalPollInput + let change: Change +} + @MainActor final class AppState: ObservableObject { @Published var documents: [MarkdownDocument] = [] @@ -41,6 +61,7 @@ final class AppState: ObservableObject { @Published private(set) var workspaceFolderURL: URL? @Published private(set) var workspaceFolderItems: [FolderTreeItem] = [] @Published private(set) var isWorkspaceFolderLoading = false + @Published private(set) var workspaceFolderError: String? @Published private(set) var workspaceSearchQuery = "" @Published private(set) var workspaceSearchResults: [FolderSearchResult] = [] @Published private(set) var isWorkspaceSearching = false @@ -63,6 +84,10 @@ final class AppState: ObservableObject { private var workspaceSearchRequestID = UUID() private var workspaceSearchTask: Task? private let closeTabDecision: (MarkdownDocument) -> TabCloseDecision + private let saveDestination: (MarkdownDocument) -> URL? + private let errorPresenter: (String) -> Void + private let externalPollData: @Sendable (URL) throws -> Data + private var isExternalChangePollRunning = false /// Restored when focus mode ends, so entering it to read does not quietly /// throw away the split/source view or inspector you were working with. @@ -71,10 +96,16 @@ final class AppState: ObservableObject { init( defaults: UserDefaults = .standard, - closeTabDecision: ((MarkdownDocument) -> TabCloseDecision)? = nil + closeTabDecision: ((MarkdownDocument) -> TabCloseDecision)? = nil, + saveDestination: ((MarkdownDocument) -> URL?)? = nil, + errorPresenter: ((String) -> Void)? = nil, + externalPollData: @escaping @Sendable (URL) throws -> Data = { try Data(contentsOf: $0) } ) { self.defaults = defaults self.closeTabDecision = closeTabDecision ?? Self.promptForTabClose + self.saveDestination = saveDestination ?? Self.promptForSaveDestination + self.errorPresenter = errorPresenter ?? Self.showError + self.externalPollData = externalPollData loadPreferences() loadRecentDocuments() startLiveReloadPolling() @@ -91,8 +122,15 @@ final class AppState: ObservableObject { } var currentOutline: [OutlineHeading] { - guard let currentDocument else { return [] } - return MarkdownOutline.headings(in: currentDocument.content) + currentDocument?.outline ?? [] + } + + func updateOutline(_ headings: [OutlineHeading], for documentID: UUID, content: String) { + guard let index = documents.firstIndex(where: { $0.id == documentID }), + documents[index].content == content, + documents[index].outline != headings + else { return } + documents[index].outline = headings } var effectiveReadingWidth: Int { @@ -311,6 +349,7 @@ final class AppState: ObservableObject { workspaceFolderURL = nil workspaceFolderItems = [] isWorkspaceFolderLoading = false + workspaceFolderError = nil sidebarMode = .recent } @@ -341,7 +380,7 @@ final class AppState: ObservableObject { let items = workspaceFolderItems let overrides: [String: String] = documents.reduce(into: [:]) { result, document in guard let url = document.url else { return } - result[url.standardizedFileURL.path] = document.content + result[url.path] = document.content } workspaceSearchRequestID = requestID isWorkspaceSearching = true @@ -409,10 +448,17 @@ final class AppState: ObservableObject { } private func refreshWorkspaceSearchIfNeeded(for documentID: UUID) { + refreshWorkspaceSearchIfNeeded( + for: documents.first(where: { $0.id == documentID })?.url + ) + } + + private func refreshWorkspaceSearchIfNeeded(for url: URL?) { guard !workspaceSearchQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, - let document = documents.first(where: { $0.id == documentID }), - let url = document.url, - isInsideWorkspaceFolder(url) + let url, + isInsideWorkspaceFolder(url) || workspaceFolderItems.flatMap(\.flattenedFiles).contains(where: { + MarkdownFileIO.canonicalURL(for: $0.url) == url + }) else { return } setWorkspaceSearchQuery(workspaceSearchQuery) } @@ -422,14 +468,7 @@ final class AppState: ObservableObject { clearsExistingItems: Bool, showsLoading: Bool = true ) { - var isDirectory: ObjCBool = false - guard url.isFileURL, - FileManager.default.fileExists( - atPath: url.path, - isDirectory: &isDirectory - ), - isDirectory.boolValue - else { + guard url.isFileURL else { present(error: "Couldn’t open “\(url.lastPathComponent)” as a folder.") return } @@ -450,6 +489,7 @@ final class AppState: ObservableObject { } if clearsExistingItems { workspaceFolderItems = [] + if workspaceFolderError != nil { workspaceFolderError = nil } } if showsLoading { isWorkspaceFolderLoading = true @@ -473,6 +513,9 @@ final class AppState: ObservableObject { if showsLoading { self.isWorkspaceFolderLoading = false } + if self.workspaceFolderError != nil { + self.workspaceFolderError = nil + } self.workspaceFolderLoadTask = nil if !self.workspaceSearchQuery.isEmpty, showsLoading || folderContentsChanged { @@ -493,10 +536,18 @@ final class AppState: ObservableObject { self.isWorkspaceFolderLoading = false } self.workspaceFolderLoadTask = nil + let message = "Couldn’t read “\(url.lastPathComponent)”. \(error.localizedDescription)" + if self.workspaceFolderError != message { + self.workspaceFolderError = message + } + if !self.workspaceFolderItems.isEmpty { + self.workspaceFolderItems = [] + } + if self.workspaceSearchTask != nil || !self.workspaceSearchResults.isEmpty || self.isWorkspaceSearching { + self.cancelWorkspaceSearch(clearsQuery: false) + } if showsLoading { - self.present( - error: "Couldn’t read “\(url.lastPathComponent)”. \(error.localizedDescription)" - ) + self.present(error: message) } } } onCancel: { @@ -511,8 +562,8 @@ final class AppState: ObservableObject { return } - let normalizedURL = url.standardizedFileURL - if let existing = documents.first(where: { $0.url?.standardizedFileURL == normalizedURL }) { + let normalizedURL = MarkdownFileIO.canonicalURL(for: url) + if let existing = documents.first(where: { $0.url == normalizedURL }) { selectedDocumentID = existing.id sidebarSelection = normalizedURL.path touchRecent(normalizedURL) @@ -611,7 +662,9 @@ final class AppState: ObservableObject { private func removeTab(_ id: UUID) { guard let index = documents.firstIndex(where: { $0.id == id }) else { return } + let removedURL = documents[index].url documents.remove(at: index) + refreshWorkspaceSearchIfNeeded(for: removedURL) if selectedDocumentID == id { if documents.indices.contains(index) { @@ -758,20 +811,24 @@ final class AppState: ObservableObject { completion?(false) return } + guard let url = saveDestination(documents[index]) else { + completion?(false) + return + } + write(documentID: documentID, to: url, updatesLocation: true, completion: completion) + } + + private static func promptForSaveDestination(_ document: MarkdownDocument) -> URL? { let panel = NSSavePanel() panel.title = "Save Markdown" panel.prompt = "Save" - panel.nameFieldStringValue = documents[index].isSample + panel.nameFieldStringValue = document.isSample ? "PreviewMD Showcase.md" - : "\(documents[index].title).md" + : "\(document.title).md" panel.allowedContentTypes = Self.markdownContentTypes panel.canCreateDirectories = true - guard panel.runModal() == .OK, let url = panel.url else { - completion?(false) - return - } - write(documentID: documentID, to: url, updatesLocation: true, completion: completion) + return panel.runModal() == .OK ? panel.url : nil } private func confirmAndSaveDirtyDocuments( @@ -873,18 +930,7 @@ final class AppState: ObservableObject { isApplied: true ) : nil - documents[index].content = readResult.content - documents[index].lastSavedContent = readResult.content - documents[index].contentRevision &+= 1 - documents[index].undoHistory.removeAll() - documents[index].redoHistory.removeAll() - documents[index].lastEditOrigin = nil - documents[index].lastEditAt = nil - documents[index].fileFormat = readResult.format - documents[index].diskSnapshot = readResult.snapshot - documents[index].fileModifiedAt = readResult.snapshot.modificationDate - documents[index].hasExternalChanges = false - documents[index].externalChangeReview = review + applyReadResult(readResult, at: index, review: review) return true } catch { present(error: "Couldn’t reload “\(url.lastPathComponent)”. \(error.localizedDescription)") @@ -892,6 +938,26 @@ final class AppState: ObservableObject { } } + private func applyReadResult( + _ readResult: MarkdownFileIO.ReadResult, + at index: Int, + review: ExternalChangeReview? + ) { + documents[index].content = readResult.content + documents[index].lastSavedContent = readResult.content + documents[index].contentRevision &+= 1 + documents[index].undoHistory.removeAll() + documents[index].redoHistory.removeAll() + documents[index].lastEditOrigin = nil + documents[index].lastEditAt = nil + documents[index].fileFormat = readResult.format + documents[index].diskSnapshot = readResult.snapshot + documents[index].fileModifiedAt = readResult.snapshot.modificationDate + documents[index].hasExternalChanges = false + documents[index].externalChangeReview = review + refreshWorkspaceSearchIfNeeded(for: documents[index].id) + } + func moveExternalChangeSelection( for documentID: UUID, by offset: Int @@ -929,18 +995,29 @@ final class AppState: ObservableObject { return } + let destination = MarkdownFileIO.canonicalURL(for: url) + let duplicateDocuments = documents.filter { + $0.id != documentID && $0.url == destination + } + guard !duplicateDocuments.contains(where: \.isDirty) else { + present(error: "“\(url.lastPathComponent)” is already open with unsaved changes. Save or close that tab before replacing this file.") + completion?(false) + return + } + let previousURL = documents[index].url + do { let snapshot = try MarkdownFileIO.write( documents[index].content, - to: url, + to: destination, format: documents[index].fileFormat ) if updatesLocation { - documents[index].url = url - documents[index].title = url.deletingPathExtension().lastPathComponent + documents[index].url = destination + documents[index].title = destination.deletingPathExtension().lastPathComponent documents[index].isSample = false if selectedDocumentID == documentID { - sidebarSelection = url.path + sidebarSelection = destination.path } } documents[index].lastSavedContent = documents[index].content @@ -948,8 +1025,11 @@ final class AppState: ObservableObject { documents[index].fileModifiedAt = snapshot.modificationDate documents[index].hasExternalChanges = false documents[index].externalChangeReview = nil - touchRecent(url) - if updatesLocation, isInsideWorkspaceFolder(url) { + duplicateDocuments.forEach { removeTab($0.id) } + touchRecent(destination) + refreshWorkspaceSearchIfNeeded(for: previousURL) + refreshWorkspaceSearchIfNeeded(for: destination) + if updatesLocation, isInsideWorkspaceFolder(destination) { refreshWorkspaceFolder() } completion?(true) @@ -973,8 +1053,8 @@ final class AppState: ObservableObject { private func isInsideWorkspaceFolder(_ url: URL) -> Bool { guard let workspaceFolderURL else { return false } - let rootComponents = workspaceFolderURL.standardizedFileURL.pathComponents - let fileComponents = url.standardizedFileURL.pathComponents + let rootComponents = MarkdownFileIO.canonicalURL(for: workspaceFolderURL).pathComponents + let fileComponents = MarkdownFileIO.canonicalURL(for: url).pathComponents return fileComponents.count > rootComponents.count && fileComponents.starts(with: rootComponents) } @@ -1171,50 +1251,19 @@ final class AppState: ObservableObject { while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(750)) guard let self else { return } - self.pollForExternalChanges() + await self.pollForExternalChanges() } } } - func pollForExternalChanges(now: Date = Date()) { - guard liveReloadEnabled else { return } - - for index in documents.indices { - guard let url = documents[index].url, - let savedSnapshot = documents[index].diskSnapshot, - let currentSnapshot = try? FileSnapshot.capture(url: url), - currentSnapshot.fingerprint != savedSnapshot.fingerprint - else { continue } - - if documents[index].isDirty { - if let readResult = try? MarkdownFileIO.read(from: url), - documents[index].externalChangeReview?.updatedContent != readResult.content { - let previousReview = documents[index].externalChangeReview - documents[index].externalChangeReview = ExternalChangeReview( - id: previousReview?.id ?? UUID(), - originalContent: previousReview?.originalContent - ?? documents[index].lastSavedContent, - updatedContent: readResult.content, - selectedHunkIndex: previousReview?.selectedHunkIndex ?? 0, - isApplied: false - ) - } - // Keep the conflict visible without publishing the same value - // on every 750 ms polling pass. Repeated publication also - // invalidates open menu hierarchies. - if !documents[index].hasExternalChanges { - documents[index].hasExternalChanges = true - } - } else { - _ = reload( - documentID: documents[index].id, - tracksExternalChanges: true - ) - } - } + func pollForExternalChanges(now: Date = Date()) async { + guard liveReloadEnabled, !isExternalChangePollRunning else { return } + isExternalChangePollRunning = true + defer { isExternalChangePollRunning = false } if let workspaceFolderURL, !isWorkspaceFolderLoading, + workspaceFolderLoadTask == nil, now.timeIntervalSince(lastWorkspaceLiveRefresh) >= 2 { lastWorkspaceLiveRefresh = now loadFolder( @@ -1223,6 +1272,100 @@ final class AppState: ObservableObject { showsLoading: false ) } + + let inputs = documents.compactMap { document -> ExternalPollInput? in + guard let url = document.url, let snapshot = document.diskSnapshot else { return nil } + return ExternalPollInput( + id: document.id, + url: url, + snapshot: snapshot, + contentRevision: document.contentRevision, + originalContent: document.externalChangeReview?.originalContent ?? document.lastSavedContent, + previousReview: document.externalChangeReview + ) + } + guard !inputs.isEmpty else { return } + + // Both full-file fingerprinting and line diffs can be expensive. Do + // them away from the main actor and never overlap polling passes. + let readData = externalPollData + let pollTask = Task.detached(priority: .utility) { + try inputs.map { input -> ExternalPollResult in + try Task.checkCancellation() + do { + let data = try readData(input.url) + let snapshot = try FileSnapshot.capture(url: input.url, data: data) + guard snapshot.fingerprint != input.snapshot.fingerprint else { + return ExternalPollResult(input: input, change: .unchanged) + } + let read = try MarkdownFileIO.read(from: input.url, data: data, snapshot: snapshot) + let review: ExternalChangeReview? + if input.previousReview?.updatedContent == read.content { + review = input.previousReview + } else { + review = ExternalChangeReview( + id: input.previousReview?.id ?? UUID(), + originalContent: input.originalContent, + updatedContent: read.content, + selectedHunkIndex: input.previousReview?.selectedHunkIndex ?? 0, + isApplied: false + ) + } + return ExternalPollResult(input: input, change: .changed(read, review)) + } catch { + return ExternalPollResult(input: input, change: .unavailable) + } + } + } + let results: [ExternalPollResult] + do { + results = try await withTaskCancellationHandler { + try await pollTask.value + } onCancel: { + pollTask.cancel() + } + } catch { + return + } + guard liveReloadEnabled, !Task.isCancelled else { return } + + for result in results { + let input = result.input + guard let index = documents.firstIndex(where: { $0.id == input.id }), + documents[index].url == input.url, + documents[index].diskSnapshot == input.snapshot, + documents[index].contentRevision == input.contentRevision + else { continue } + + switch result.change { + case .unchanged: + if documents[index].hasExternalChanges { + documents[index].hasExternalChanges = false + if documents[index].externalChangeReview?.isApplied == false { + documents[index].externalChangeReview = nil + } + } + case .unavailable: + // Deleted or temporarily unreadable files must not trigger a + // repeating modal alert from an automatic background check. + if !documents[index].hasExternalChanges { + documents[index].hasExternalChanges = true + } + case let .changed(read, review): + if documents[index].isDirty { + if documents[index].externalChangeReview?.updatedContent != read.content { + documents[index].externalChangeReview = review + } + if !documents[index].hasExternalChanges { + documents[index].hasExternalChanges = true + } + } else { + var appliedReview = review + appliedReview?.isApplied = true + applyReadResult(read, at: index, review: appliedReview) + } + } + } } private func loadRecentDocuments() { @@ -1264,6 +1407,10 @@ final class AppState: ObservableObject { private func present(error: String) { errorMessage = error + errorPresenter(error) + } + + private static func showError(_ error: String) { let alert = NSAlert() alert.messageText = "PreviewMD" alert.informativeText = error diff --git a/Sources/PreviewMD/DOCXDocumentWriter.swift b/Sources/PreviewMD/DOCXDocumentWriter.swift index f9d8695..9f42f52 100644 --- a/Sources/PreviewMD/DOCXDocumentWriter.swift +++ b/Sources/PreviewMD/DOCXDocumentWriter.swift @@ -109,6 +109,13 @@ private struct WordprocessingMLBuilder { let data: Data } + private struct ListNumbering { + let id: Int + let ordered: Bool + let level: Int + let start: Int32 + } + private let title: String private let assets: [String: PortableRichTextClipboard.EmbeddedAsset] private var relationships: [Relationship] = [ @@ -126,6 +133,7 @@ private struct WordprocessingMLBuilder { ), ] private var mediaFiles: [MediaFile] = [] + private var listNumberings: [ListNumbering] = [] private var relationshipCounter = 3 private var drawingCounter = 1 @@ -236,6 +244,15 @@ private struct WordprocessingMLBuilder { ordered: Bool, level: Int ) -> [String] { + // Each HTML list has its own counter. Sharing a numbering instance + // makes Word continue a later list, even when HTML restarts it. + let numbering = ListNumbering( + id: listNumberings.count + 1, + ordered: ordered, + level: min(8, level), + start: Int32(list.attribute(forName: "start")?.stringValue ?? "1") ?? 1 + ) + listNumberings.append(numbering) var result: [String] = [] for child in list.children ?? [] { guard let item = child as? XMLElement, @@ -251,8 +268,8 @@ private struct WordprocessingMLBuilder { }.joined() result.append(numberedParagraphXML( inline: inline, - numberID: ordered ? 2 : 1, - level: min(8, level) + numberID: numbering.id, + level: numbering.level )) for nested in item.children ?? [] { guard let nestedList = nested as? XMLElement else { continue } @@ -632,7 +649,14 @@ private struct WordprocessingMLBuilder { let left = 720 + level * 360 return "" }.joined() - return "\(bulletLevels)\(decimalLevels)" + let instances = listNumberings.map { numbering in + let abstractID = numbering.ordered ? 1 : 0 + let override = numbering.ordered + ? "" + : "" + return "\(override)" + }.joined() + return "\(bulletLevels)\(decimalLevels)\(instances)" } private func xmlEscape(_ value: String) -> String { diff --git a/Sources/PreviewMD/DocumentIO.swift b/Sources/PreviewMD/DocumentIO.swift index 9cc8aa1..2595ab2 100644 --- a/Sources/PreviewMD/DocumentIO.swift +++ b/Sources/PreviewMD/DocumentIO.swift @@ -1,7 +1,7 @@ import Foundation -struct MarkdownFileFormat: Equatable { - enum LineEnding: Equatable { +struct MarkdownFileFormat: Equatable, Sendable { + enum LineEnding: Equatable, Sendable { case lineFeed case carriageReturnLineFeed case carriageReturn @@ -24,14 +24,16 @@ struct MarkdownFileFormat: Equatable { ) } -struct FileSnapshot: Equatable { +struct FileSnapshot: Equatable, Sendable { let modificationDate: Date? let size: Int let fingerprint: UInt64 static func capture(url: URL, data: Data? = nil) throws -> Self { let contents = try data ?? Data(contentsOf: url) - let values = try url.resourceValues( + // Resource values are cached on URL instances. Read fresh metadata after + // an atomic replacement rather than retaining the previous inode's values. + let values = try URL(fileURLWithPath: url.path).resourceValues( forKeys: [.contentModificationDateKey, .fileSizeKey] ) return Self( @@ -51,14 +53,22 @@ struct FileSnapshot: Equatable { } enum MarkdownFileIO { - struct ReadResult { + struct ReadResult: Sendable { let content: String let format: MarkdownFileFormat let snapshot: FileSnapshot } - static func read(from url: URL) throws -> ReadResult { - let data = try Data(contentsOf: url) + static func canonicalURL(for url: URL) -> URL { + url.standardizedFileURL.resolvingSymlinksInPath() + } + + static func read( + from url: URL, + data suppliedData: Data? = nil, + snapshot suppliedSnapshot: FileSnapshot? = nil + ) throws -> ReadResult { + let data = try suppliedData ?? Data(contentsOf: url) let hasBOM = data.starts(with: [0xEF, 0xBB, 0xBF]) let textData = hasBOM ? data.dropFirst(3) : data[...] @@ -77,7 +87,7 @@ enum MarkdownFileIO { lineEnding: lineEnding, hasUTF8ByteOrderMark: hasBOM ), - snapshot: try FileSnapshot.capture(url: url, data: data) + snapshot: try suppliedSnapshot ?? FileSnapshot.capture(url: url, data: data) ) } @@ -104,8 +114,11 @@ enum MarkdownFileIO { data.insert(contentsOf: [0xEF, 0xBB, 0xBF], at: 0) } - try data.write(to: url, options: .atomic) - return try FileSnapshot.capture(url: url, data: data) + // Atomic writes replace their destination directory entry. Resolve a + // symlink first so saving updates its target and preserves the link. + let destination = canonicalURL(for: url) + try data.write(to: destination, options: .atomic) + return try FileSnapshot.capture(url: destination, data: data) } private static func dominantLineEnding( diff --git a/Sources/PreviewMD/FolderSearch.swift b/Sources/PreviewMD/FolderSearch.swift index 6816b30..cfda92b 100644 --- a/Sources/PreviewMD/FolderSearch.swift +++ b/Sources/PreviewMD/FolderSearch.swift @@ -93,7 +93,7 @@ enum MarkdownFolderSearch { let ranked = try fileURLs(in: items).compactMap { url -> RankedResult? in try Task.checkCancellation() - let path = url.standardizedFileURL.path + let path = MarkdownFileIO.canonicalURL(for: url).path let content: String if let override = contentOverrides[path] { content = override diff --git a/Sources/PreviewMD/MarkdownSourceEditor.swift b/Sources/PreviewMD/MarkdownSourceEditor.swift index dc196a1..3639354 100644 --- a/Sources/PreviewMD/MarkdownSourceEditor.swift +++ b/Sources/PreviewMD/MarkdownSourceEditor.swift @@ -303,7 +303,7 @@ struct MarkdownSourceEditor: NSViewRepresentable { } } if contentChanged || appearanceChanged { - context.coordinator.highlight() + context.coordinator.highlight(forceFull: true) context.coordinator.lineNumberRuler?.reload() } if contentChanged, @@ -340,6 +340,9 @@ struct MarkdownSourceEditor: NSViewRepresentable { private var scheduledScrollPublication: DispatchWorkItem? private var isApplyingRemoteScroll = false private var isApplyingRemoteSelection = false + private var lastHighlightedSource: String? + private var activeHighlightRange: NSRange? + private var highlightExpressions: [String: NSRegularExpression] = [:] init( text: Binding, @@ -447,7 +450,13 @@ struct MarkdownSourceEditor: NSViewRepresentable { let scrollView, let layoutManager = textView.layoutManager, let textContainer = textView.textContainer else { return nil } - layoutManager.ensureLayout(for: textContainer) + layoutManager.ensureLayout( + forBoundingRect: textView.visibleRect.offsetBy( + dx: -textView.textContainerOrigin.x, + dy: -textView.textContainerOrigin.y + ), + in: textContainer + ) guard layoutManager.numberOfGlyphs > 0 else { return SplitEditorScrollPosition(sourceLine: 0) } @@ -562,16 +571,32 @@ struct MarkdownSourceEditor: NSViewRepresentable { DispatchQueue.main.asyncAfter(deadline: .now() + 0.035, execute: work) } - func highlight() { + func highlight(forceFull: Bool = false) { guard let textView, let storage = textView.textStorage else { return } + let appearanceChanged = lastAppearanceName != textView.effectiveAppearance.name lastAppearanceName = textView.effectiveAppearance.name let source = storage.string as NSString let fullRange = NSRange(location: 0, length: source.length) + let highlightRange: NSRange + if forceFull || appearanceChanged || lastHighlightedSource == nil { + highlightRange = fullRange + } else if let previous = lastHighlightedSource, + let changedRange = MarkdownSourceHighlighting.changedLineRange( + from: previous, + to: storage.string + ) { + highlightRange = changedRange + } else { + return + } + lastHighlightedSource = storage.string + activeHighlightRange = highlightRange + defer { activeHighlightRange = nil } let selection = textView.selectedRange() let palette = Palette(textView: textView) storage.beginEditing() - storage.setAttributes(baseAttributes(for: textView), range: fullRange) + storage.setAttributes(baseAttributes(for: textView), range: highlightRange) apply(#"(?m)^\s*(```|~~~).*$"#, color: palette.fence, to: storage, in: source) applyGroup( @@ -623,8 +648,8 @@ struct MarkdownSourceEditor: NSViewRepresentable { to storage: NSTextStorage, in source: NSString ) { - guard let expression = try? NSRegularExpression(pattern: pattern) else { return } - let range = NSRange(location: 0, length: source.length) + guard let expression = expression(for: pattern) else { return } + let range = activeHighlightRange ?? NSRange(location: 0, length: source.length) expression.enumerateMatches(in: source as String, range: range) { match, _, _ in guard let match else { return } storage.addAttribute(.foregroundColor, value: color, range: match.range) @@ -638,15 +663,57 @@ struct MarkdownSourceEditor: NSViewRepresentable { to storage: NSTextStorage, in source: NSString ) { - guard let expression = try? NSRegularExpression(pattern: pattern) else { return } + guard let expression = expression(for: pattern) else { return } let range = NSRange(location: 0, length: source.length) expression.enumerateMatches(in: source as String, range: range) { match, _, _ in guard let match else { return } let groupRange = match.range(at: group) guard groupRange.location != NSNotFound else { return } - storage.addAttribute(.foregroundColor, value: color, range: groupRange) + let affectedRange = NSIntersectionRange(groupRange, activeHighlightRange ?? range) + if affectedRange.length > 0 { + storage.addAttribute(.foregroundColor, value: color, range: affectedRange) + } } } + + private func expression(for pattern: String) -> NSRegularExpression? { + if let cached = highlightExpressions[pattern] { return cached } + guard let expression = try? NSRegularExpression(pattern: pattern) else { return nil } + highlightExpressions[pattern] = expression + return expression + } + } +} + +enum MarkdownSourceHighlighting { + /// AppKit shifts existing attributes as characters are edited. Recolor only + /// changed logical lines; edits to fence boundaries can affect the rest of + /// the document, so those deliberately retain the full pass. + static func changedLineRange(from previous: String, to current: String) -> NSRange? { + let old = previous as NSString + let new = current as NSString + var start = 0 + let commonLength = min(old.length, new.length) + while start < commonLength, old.character(at: start) == new.character(at: start) { + start += 1 + } + if start == old.length, start == new.length { return nil } + var oldEnd = old.length + var newEnd = new.length + while oldEnd > start, newEnd > start, + old.character(at: oldEnd - 1) == new.character(at: newEnd - 1) { + oldEnd -= 1 + newEnd -= 1 + } + let oldLines = old.lineRange(for: NSRange(location: start, length: oldEnd - start)) + let newLines = new.lineRange(for: NSRange(location: start, length: newEnd - start)) + let oldChangedLines = old.substring(with: oldLines) + let newChangedLines = new.substring(with: newLines) + if oldChangedLines.contains("```") || oldChangedLines.contains("~~~") + || newChangedLines.contains("```") || newChangedLines.contains("~~~") { + return NSRange(location: 0, length: new.length) + } + return newLines } } @@ -785,12 +852,12 @@ final class MarkdownLineNumberRulerView: NSView { return } - layoutManager.ensureLayout(for: textContainer) let textOrigin = textView.textContainerOrigin let visibleContainerRect = textView.visibleRect.offsetBy( dx: -textOrigin.x, dy: -textOrigin.y ) + layoutManager.ensureLayout(forBoundingRect: visibleContainerRect, in: textContainer) let visibleGlyphRange = layoutManager.glyphRange( forBoundingRect: visibleContainerRect, in: textContainer diff --git a/Sources/PreviewMD/MarkdownWebView.swift b/Sources/PreviewMD/MarkdownWebView.swift index 935c962..64c7eef 100644 --- a/Sources/PreviewMD/MarkdownWebView.swift +++ b/Sources/PreviewMD/MarkdownWebView.swift @@ -10,30 +10,50 @@ import WebKit final class RendererController: ObservableObject { private weak var webView: WKWebView? private var attachedDocumentID: UUID? + private var isEditorVisible = true + private var synchronizeRenderer: (@MainActor () async throws -> Void)? // PDFKit's print operation can hand work to Quartz after `run()` returns. // Retain the immutable source and operation until a later print replaces them. private var activePrintDocument: PDFDocument? private var activePrintOperation: NSPrintOperation? - func attach(_ webView: WKWebView, documentID: UUID) { + func attach( + _ webView: WKWebView, + documentID: UUID, + isVisible: Bool = true, + synchronize: (@MainActor () async throws -> Void)? = nil + ) { self.webView = webView attachedDocumentID = documentID + isEditorVisible = isVisible + synchronizeRenderer = synchronize } func flushMarkdown( for documentID: UUID, completion: @escaping (String?) -> Void ) { - guard let webView, attachedDocumentID == documentID else { + guard isEditorVisible, let webView, attachedDocumentID == documentID else { completion(nil) return } - webView.evaluateJavaScript( - "window.previewmdFlushEditor ? window.previewmdFlushEditor() : null" - ) { result, _ in - Task { @MainActor in + let synchronize = synchronizeRenderer + Task { @MainActor [weak self, weak webView] in + do { + try await synchronize?() + guard let self, let webView, self.isEditorVisible, + self.webView === webView, self.attachedDocumentID == documentID + else { completion(nil); return } + let result = try await webView.evaluateJavaScript( + "window.previewmdFlushEditor ? window.previewmdFlushEditor() : null" + ) + guard self.isEditorVisible, self.webView === webView, + self.attachedDocumentID == documentID + else { completion(nil); return } completion(result as? String) + } catch { + completion(nil) } } } @@ -51,20 +71,22 @@ final class RendererController: ObservableObject { NSSound.beep() return } - webView.callAsyncJavaScript( - "return window.previewmdAdvancedCopy && window.previewmdAdvancedCopy(destination, suggestedName);", - arguments: [ - "destination": format.rawValue, - "suggestedName": suggestedName, - ], - in: nil, - in: .page - ) { result in - guard case let .success(value) = result, - (value as? Bool) == true - else { + let synchronize = synchronizeRenderer + let documentID = attachedDocumentID + Task { @MainActor [weak self, weak webView] in + do { + try await synchronize?() + guard let self, let webView, self.webView === webView, + self.attachedDocumentID == documentID + else { return } + let value = try await webView.callAsyncJavaScript( + "return window.previewmdAdvancedCopy && window.previewmdAdvancedCopy(destination, suggestedName);", + arguments: ["destination": format.rawValue, "suggestedName": suggestedName], + contentWorld: .page + ) + if (value as? Bool) != true { NSSound.beep() } + } catch { NSSound.beep() - return } } } @@ -74,17 +96,22 @@ final class RendererController: ObservableObject { NSSound.beep() return } - webView.callAsyncJavaScript( - "return window.previewmdExportDOCX && window.previewmdExportDOCX(suggestedName);", - arguments: ["suggestedName": suggestedName], - in: nil, - in: .page - ) { result in - guard case let .success(value) = result, - (value as? Bool) == true - else { + let synchronize = synchronizeRenderer + let documentID = attachedDocumentID + Task { @MainActor [weak self, weak webView] in + do { + try await synchronize?() + guard let self, let webView, self.webView === webView, + self.attachedDocumentID == documentID + else { return } + let value = try await webView.callAsyncJavaScript( + "return window.previewmdExportDOCX && window.previewmdExportDOCX(suggestedName);", + arguments: ["suggestedName": suggestedName], + contentWorld: .page + ) + if (value as? Bool) != true { NSSound.beep() } + } catch { NSSound.beep() - return } } } @@ -194,7 +221,20 @@ final class RendererController: ObservableObject { return } - Task { @MainActor [weak webView] in + let synchronize = synchronizeRenderer + let documentID = attachedDocumentID + Task { @MainActor [weak self, weak webView] in + do { + try await synchronize?() + } catch { + completion(.failure(error)) + return + } + guard let self, self.attachedDocumentID == documentID, + self.webView === webView else { + completion(.failure(RendererError.rendererUnavailable)) + return + } guard let webView else { completion(.failure(RendererError.rendererUnavailable)) return @@ -668,6 +708,7 @@ struct MarkdownWebView: NSViewRepresentable { let controller: RendererController let splitSynchronizer: SplitEditorSynchronizer let isSplitSynchronizationEnabled: Bool + var isVisible = true let onContentChange: (UUID, String, Bool) -> Void let onDropFiles: ([URL]) -> Void let onDropTargeted: (Bool) -> Void @@ -682,7 +723,9 @@ struct MarkdownWebView: NSViewRepresentable { openMarkdown: state.open(url:), onContentChange: onContentChange, splitSynchronizer: splitSynchronizer, - isSplitSynchronizationEnabled: isSplitSynchronizationEnabled + isSplitSynchronizationEnabled: isSplitSynchronizationEnabled, + isVisible: isVisible, + onOutlineChange: state.updateOutline ) } @@ -717,6 +760,7 @@ struct MarkdownWebView: NSViewRepresentable { configuration.userContentController.add(context.coordinator, name: "editorChange") configuration.userContentController.add(context.coordinator, name: "pickImage") configuration.userContentController.add(context.coordinator, name: "splitSync") + configuration.userContentController.add(context.coordinator, name: "outlineChange") configuration.setURLSchemeHandler( context.coordinator.localImageSchemeHandler, forURLScheme: LocalImageSchemeHandler.scheme @@ -734,7 +778,10 @@ struct MarkdownWebView: NSViewRepresentable { context.coordinator, documentID: documentID ) - controller.attach(webView, documentID: documentID) + controller.attach(webView, documentID: documentID, isVisible: isVisible) { [weak coordinator = context.coordinator] in + guard let coordinator else { throw CancellationError() } + try await coordinator.prepareForOutput() + } let initialPayload = renderPayload webView.pageZoom = initialPayload.zoom context.coordinator.loadShell( @@ -746,12 +793,17 @@ struct MarkdownWebView: NSViewRepresentable { } func updateNSView(_ webView: WKWebView, context: Context) { - controller.attach(webView, documentID: documentID) + controller.attach(webView, documentID: documentID, isVisible: isVisible) { [weak coordinator = context.coordinator] in + guard let coordinator else { throw CancellationError() } + try await coordinator.prepareForOutput() + } context.coordinator.documentID = documentID context.coordinator.documentURL = documentURL context.coordinator.localImageSchemeHandler.updateBaseURL(baseURL) context.coordinator.openMarkdown = state.open(url:) context.coordinator.onContentChange = onContentChange + context.coordinator.onOutlineChange = state.updateOutline + context.coordinator.isVisible = isVisible context.coordinator.updateSynchronization( splitSynchronizer: splitSynchronizer, isEnabled: isSplitSynchronizationEnabled @@ -780,6 +832,9 @@ struct MarkdownWebView: NSViewRepresentable { webView.configuration.userContentController.removeScriptMessageHandler(forName: "editorChange") webView.configuration.userContentController.removeScriptMessageHandler(forName: "pickImage") webView.configuration.userContentController.removeScriptMessageHandler(forName: "splitSync") + webView.configuration.userContentController.removeScriptMessageHandler(forName: "outlineChange") + coordinator.outlineTask?.cancel() + coordinator.renderTask?.cancel() coordinator.splitSynchronizer?.detachPreview(coordinator) webView.navigationDelegate = nil webView.uiDelegate = nil @@ -909,6 +964,19 @@ struct MarkdownWebView: NSViewRepresentable { var documentURL: URL? var openMarkdown: (URL) -> Void var onContentChange: (UUID, String, Bool) -> Void + var onOutlineChange: ([OutlineHeading], UUID, String) -> Void + var isVisible: Bool + fileprivate var outlineTask: Task? + fileprivate var renderTask: Task? + private var renderGeneration = 0 + + private enum OutputPreparationError: LocalizedError { + case previewNotReady + + var errorDescription: String? { + "The document preview did not finish loading." + } + } weak var splitSynchronizer: SplitEditorSynchronizer? var isSplitSynchronizationEnabled: Bool var basePath = "" @@ -958,7 +1026,9 @@ struct MarkdownWebView: NSViewRepresentable { openMarkdown: @escaping (URL) -> Void, onContentChange: @escaping (UUID, String, Bool) -> Void, splitSynchronizer: SplitEditorSynchronizer, - isSplitSynchronizationEnabled: Bool + isSplitSynchronizationEnabled: Bool, + isVisible: Bool = true, + onOutlineChange: @escaping ([OutlineHeading], UUID, String) -> Void = { _, _, _ in } ) { self.documentID = documentID self.documentURL = documentURL @@ -966,6 +1036,8 @@ struct MarkdownWebView: NSViewRepresentable { self.onContentChange = onContentChange self.splitSynchronizer = splitSynchronizer self.isSplitSynchronizationEnabled = isSplitSynchronizationEnabled + self.isVisible = isVisible + self.onOutlineChange = onOutlineChange self.localImageSchemeHandler = LocalImageSchemeHandler( baseURL: documentURL?.deletingLastPathComponent() ?? Bundle.module.resourceURL @@ -984,6 +1056,11 @@ struct MarkdownWebView: NSViewRepresentable { } self.splitSynchronizer = splitSynchronizer isSplitSynchronizationEnabled = isEnabled + if wasEnabled != isEnabled, isLoaded { + webView?.evaluateJavaScript( + "window.previewmdSetSplitSynchronizationEnabled && window.previewmdSetSplitSynchronizationEnabled(\(isEnabled));" + ) + } if wasEnabled && !isEnabled, isLoaded { webView?.evaluateJavaScript( "window.previewmdClearSplitSynchronization && " @@ -998,6 +1075,9 @@ struct MarkdownWebView: NSViewRepresentable { initialPayload: RenderPayload, in webView: WKWebView ) { + renderTask?.cancel() + renderTask = nil + renderGeneration += 1 basePath = baseURL.path localImageSchemeHandler.updateBaseURL(baseURL) isLoaded = false @@ -1011,7 +1091,7 @@ struct MarkdownWebView: NSViewRepresentable { } func update(_ payload: RenderPayload, in webView: WKWebView) { - guard payload != lastPayload else { return } + guard payload != lastPayload || pendingPayload != nil else { return } pendingPayload = payload guard isLoaded else { return } applyPendingPayload(in: webView) @@ -1019,6 +1099,9 @@ struct MarkdownWebView: NSViewRepresentable { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation?) { isLoaded = true + webView.evaluateJavaScript( + "window.previewmdSetSplitSynchronizationEnabled && window.previewmdSetSplitSynchronizationEnabled(\(isSplitSynchronizationEnabled));" + ) applyPendingPayload(in: webView) } @@ -1109,6 +1192,12 @@ struct MarkdownWebView: NSViewRepresentable { presentImagePicker(in: webView) case "splitSync": receiveSplitSyncMessage(message.body) + case "outlineChange": + guard let body = message.body as? [String: Any], + let markdown = body["markdown"] as? String, + let headings = Self.outlineHeadings(body["headings"]) + else { return } + onOutlineChange(headings, documentID, markdown) default: break } @@ -1668,9 +1757,38 @@ struct MarkdownWebView: NSViewRepresentable { ?? relativePath } - private func applyPendingPayload(in webView: WKWebView) { + func prepareForOutput() async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + while !isLoaded { + guard ContinuousClock.now < deadline else { + throw OutputPreparationError.previewNotReady + } + try await Task.sleep(for: .milliseconds(20)) + } + guard let webView else { throw CancellationError() } + while true { + if let task = renderTask { + try await task.value + continue + } + guard pendingPayload != nil else { return } + applyPendingPayload(in: webView, forceRender: true) + } + } + + private func applyPendingPayload(in webView: WKWebView, forceRender: Bool = false) { guard let payload = pendingPayload else { return } + guard isVisible || forceRender else { + scheduleHiddenOutline(for: payload, in: webView) + return + } + // Keep the latest payload queued until the current render finishes, + // including its asynchronous diagrams and layout work. + guard renderTask == nil else { return } + outlineTask?.cancel() + outlineTask = nil + pendingPayload = nil webView.pageZoom = payload.zoom @@ -1736,7 +1854,66 @@ struct MarkdownWebView: NSViewRepresentable { lastPayload = payload lastEditorMarkdown = nil lastEditorDocumentID = nil - webView.evaluateJavaScript("window.previewmdRender(\(json));") + renderGeneration += 1 + let generation = renderGeneration + renderTask = Task { @MainActor [weak self, weak webView] in + guard let self, let webView else { throw CancellationError() } + do { + try Task.checkCancellation() + _ = try await webView.callAsyncJavaScript( + "await window.previewmdRender(\(json)); return true;", + arguments: [:], + contentWorld: .page + ) + try Task.checkCancellation() + } catch { + if self.renderGeneration == generation { + self.renderTask = nil + self.lastPayload = nil + if self.pendingPayload == nil { self.pendingPayload = payload } + } + throw error + } + guard self.renderGeneration == generation else { return } + self.renderTask = nil + if self.isVisible { self.applyPendingPayload(in: webView) } + } + } + + private func scheduleHiddenOutline(for payload: RenderPayload, in webView: WKWebView) { + outlineTask?.cancel() + outlineTask = Task { @MainActor [weak self, weak webView] in + do { + try await Task.sleep(for: .milliseconds(100)) + guard let self, let webView, !self.isVisible, + self.pendingPayload == payload else { return } + let result = try await webView.callAsyncJavaScript( + "return window.previewmdOutlineForMarkdown(markdown);", + arguments: ["markdown": payload.markdown], + contentWorld: .page + ) + guard !Task.isCancelled, !self.isVisible, + self.pendingPayload == payload, + let headings = Self.outlineHeadings(result) else { return } + self.onOutlineChange(headings, self.documentID, payload.markdown) + } catch { + // A hidden outline refresh is superseded by newer edits or + // the full render when the preview becomes visible. + } + } + } + + private static func outlineHeadings(_ value: Any?) -> [OutlineHeading]? { + guard let entries = value as? [[String: Any]] else { return nil } + var headings: [OutlineHeading] = [] + for entry in entries { + guard let id = entry["id"] as? String, + let level = entry["level"] as? Int, + (1...6).contains(level), let title = entry["title"] as? String + else { return nil } + headings.append(OutlineHeading(id: id, level: level, title: title)) + } + return headings } private func javaScriptJSON(_ value: T) -> String? { diff --git a/Sources/PreviewMD/Models.swift b/Sources/PreviewMD/Models.swift index ec13966..b7dc574 100644 --- a/Sources/PreviewMD/Models.swift +++ b/Sources/PreviewMD/Models.swift @@ -299,11 +299,33 @@ enum WorkspaceFileSort: String, CaseIterable, Identifiable { var title: String { self == .name ? "Name" : "Modified" } } +/// Each text change computes reading statistics once; SwiftUI can read them +/// repeatedly without rescanning the full document during an editing update. +@propertyWrapper +struct MarkdownText: Equatable { + var wrappedValue: String { + didSet { updateStatistics() } + } + private(set) var wordCount: Int + private(set) var characterCount: Int + + init(wrappedValue: String) { + self.wrappedValue = wrappedValue + wordCount = wrappedValue.split(whereSeparator: \.isWhitespace).count + characterCount = wrappedValue.count + } + + private mutating func updateStatistics() { + wordCount = wrappedValue.split(whereSeparator: \.isWhitespace).count + characterCount = wrappedValue.count + } +} + struct MarkdownDocument: Identifiable, Equatable { let id: UUID var url: URL? var title: String - var content: String + @MarkdownText var content: String var lastSavedContent: String /// Monotonically increasing in-memory revision shared by the source and /// rich editors. It prevents an edit echoed back from SwiftUI from @@ -321,17 +343,19 @@ struct MarkdownDocument: Identifiable, Equatable { var isSample: Bool var hasExternalChanges = false var externalChangeReview: ExternalChangeReview? = nil + /// Supplied by the bundled Markdown parser, using the rendered heading IDs. + var outline: [OutlineHeading] = [] var isDirty: Bool { content != lastSavedContent } var wordCount: Int { - content.split { $0.isWhitespace || $0.isNewline }.count + _content.wordCount } var characterCount: Int { - content.count + _content.characterCount } var readingMinutes: Int { @@ -359,66 +383,3 @@ struct OutlineHeading: Identifiable, Equatable { let level: Int let title: String } - -enum MarkdownOutline { - static func headings(in markdown: String) -> [OutlineHeading] { - var headings: [OutlineHeading] = [] - var insideFence = false - var fenceMarker = "" - - for line in markdown.components(separatedBy: .newlines) { - let trimmed = line.trimmingCharacters(in: .whitespaces) - - if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { - let marker = String(trimmed.prefix(3)) - if insideFence, marker == fenceMarker { - insideFence = false - fenceMarker = "" - } else if !insideFence { - insideFence = true - fenceMarker = marker - } - continue - } - - guard !insideFence else { continue } - - var hashCount = 0 - for character in line { - if character == "#", hashCount < 6 { - hashCount += 1 - } else { - break - } - } - - guard hashCount > 0, - line.dropFirst(hashCount).first?.isWhitespace == true - else { continue } - - var title = String(line.dropFirst(hashCount)) - .trimmingCharacters(in: .whitespaces) - title = title.replacingOccurrences( - of: #"\s+#+\s*$"#, - with: "", - options: .regularExpression - ) - title = title.replacingOccurrences( - of: #"[*_`~\[\]]"#, - with: "", - options: .regularExpression - ) - - guard !title.isEmpty else { continue } - headings.append( - OutlineHeading( - id: "heading-\(headings.count)", - level: hashCount, - title: title - ) - ) - } - - return headings - } -} diff --git a/Sources/PreviewMD/Resources/Renderer/editor.js b/Sources/PreviewMD/Resources/Renderer/editor.js index 34c8236..434be22 100644 --- a/Sources/PreviewMD/Resources/Renderer/editor.js +++ b/Sources/PreviewMD/Resources/Renderer/editor.js @@ -18,6 +18,68 @@ let ignoreSplitSelectionUntil = 0; let ignoreSplitScrollUntil = 0; let splitSynchronizedRange = null; + let splitSynchronizationEnabled = true; + let splitSourcePositionsDirty = false; + let splitLineOffsetsCache = null; + let blockSerializationCache = new WeakMap(); + + // Read mutation records synchronously when flushing: Save can arrive before + // MutationObserver's queued callback, and checkbox state is a DOM property. + const serializationObserver = new MutationObserver(invalidateSerializedBlocks); + serializationObserver.observe(article, { + subtree: true, + childList: true, + characterData: true, + attributes: true, + attributeFilter: [ + "href", "title", "alt", "src", "start", "align", "style", "class", + "data-source", "data-math-source", "data-frontmatter-source", + "data-editor-insert-markdown", "data-previewmd-source", + ], + }); + + function invalidateSerializedBlock(node) { + if (node && node.parentNode === article) { + blockSerializationCache.delete(node); + return; + } + let block = node && (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement); + while (block && block.parentElement !== article) block = block.parentElement; + if (block) blockSerializationCache.delete(block); + } + + function invalidateSerializedBlocks(records) { + records.forEach((record) => { + if (record.type === "childList" && record.target === article) { + record.addedNodes.forEach((node) => blockSerializationCache.delete(node)); + record.removedNodes.forEach((node) => blockSerializationCache.delete(node)); + return; + } + if (record.type === "attributes") { + if (record.attributeName === "class" && record.target.tagName !== "CODE") return; + if (record.attributeName === "style" && !record.target.matches("td, th")) return; + } + invalidateSerializedBlock(record.target); + }); + } + + function serializedDocumentBlock(node) { + const cached = blockSerializationCache.get(node); + if (cached && cached.checkboxes.every( + (checkbox, index) => checkbox.checked === cached.checked[index] + )) { + return cached.markdown; + } + const markdown = serializeBlock(node).trimEnd(); + const checkboxes = node.nodeType === Node.ELEMENT_NODE + ? Array.from(node.querySelectorAll('input[type="checkbox"]')) : []; + blockSerializationCache.set(node, { + markdown, + checkboxes, + checked: checkboxes.map((checkbox) => checkbox.checked), + }); + return markdown; + } const keyboardObjectSelector = ".frontmatter-card, .table-scroll, .code-card, .diagram-card, .katex-display, .katex, img, hr:not(.footnotes-sep)"; @@ -1155,6 +1217,10 @@ function editorDidRender(markdown, shouldEdit) { currentMarkdown = markdown || ""; + serializationObserver.takeRecords(); + blockSerializationCache = new WeakMap(); + splitSourcePositionsDirty = false; + splitLineOffsetsCache = null; domChanged = false; if (shouldEdit === true && !article.firstChild) { article.innerHTML = "


"; @@ -1197,7 +1263,8 @@ pendingHistoryBoundary = false; domChanged = false; currentMarkdown = markdown; - refreshSplitSourcePositions(); + splitSourcePositionsDirty = true; + splitLineOffsetsCache = null; if ( window.webkit && window.webkit.messageHandlers && @@ -1208,6 +1275,7 @@ historyBoundary: historyBoundary, }); } + if (window.previewmdPublishOutline) window.previewmdPublishOutline(markdown); return markdown; } @@ -1220,7 +1288,8 @@ const historyBoundary = pendingHistoryBoundary; pendingHistoryBoundary = false; currentMarkdown = markdown; - refreshSplitSourcePositions(); + splitSourcePositionsDirty = true; + splitLineOffsetsCache = null; if ( window.webkit && window.webkit.messageHandlers && @@ -1231,6 +1300,7 @@ historyBoundary: historyBoundary, }); } + if (window.previewmdPublishOutline) window.previewmdPublishOutline(markdown); } else { pendingHistoryBoundary = false; } @@ -1703,12 +1773,13 @@ } function serializeDocument() { + invalidateSerializedBlocks(serializationObserver.takeRecords()); const blocks = []; Array.from(article.childNodes).forEach((node) => { - const value = serializeBlock(node).trimEnd(); + const value = serializedDocumentBlock(node); if (value) blocks.push(value); }); - return blocks.join("\n\n").replace(/\n{4,}/g, "\n\n\n") + (blocks.length ? "\n" : ""); + return blocks.join("\n\n") + (blocks.length ? "\n" : ""); } function serializeFragment(container) { @@ -1718,11 +1789,11 @@ const value = serializeBlock(node).trimEnd(); if (value) blocks.push(value); }); - return blocks.join("\n\n").replace(/\n{4,}/g, "\n\n\n"); + return blocks.join("\n\n"); } function serializeBlock(node) { - if (node.nodeType === Node.TEXT_NODE) return escapeText(node.nodeValue.trim()); + if (node.nodeType === Node.TEXT_NODE) return escapeParagraphSyntax(escapeText(node.nodeValue.trim())); if (node.nodeType !== Node.ELEMENT_NODE) return ""; if (node.matches(".editor-object-source, .code-toolbar, .diagram-label")) return ""; if (node.dataset.editorInsertMarkdown !== undefined) { @@ -1736,7 +1807,7 @@ if (/^h[1-6]$/.test(tag)) { return "#".repeat(Number(tag[1])) + " " + serializeChildrenInline(node).trim(); } - if (tag === "p") return serializeChildrenInline(node).trim(); + if (tag === "p") return escapeParagraphSyntax(serializeChildrenInline(node).trim()); if (tag === "blockquote") return serializeBlockquote(node); if (tag === "ul" || tag === "ol") return serializeList(node); if (node.matches(".code-card")) return serializeCodeCard(node); @@ -1749,7 +1820,7 @@ if (tag === "hr") return node.classList.contains("footnotes-sep") ? "" : "---"; if (tag === "section" && node.classList.contains("footnotes")) return serializeFootnotes(node); if (tag === "div" && !hasDirectBlockChildren(node)) { - return serializeChildrenInline(node).trim(); + return escapeParagraphSyntax(serializeChildrenInline(node).trim()); } if (tag === "div" || tag === "section" || tag === "article") { return Array.from(node.childNodes) @@ -1810,13 +1881,29 @@ function escapeText(value) { return (value || "") .replace(/\\/g, "\\\\") - .replace(/([*_[\]`])/g, "\\$1"); + .replace(/([*_[\]`~])/g, "\\$1"); + } + + // Text that the DOM represents as a paragraph must stay a paragraph when + // reopened. Escaping inline punctuation alone misses block syntax. + function escapeParagraphSyntax(value) { + return value + .replace(/^( {0,3})(#{1,6})(?=\s|$)/gm, "$1\\$2") + .replace(/^( {0,3})(>)/gm, "$1\\$2") + .replace(/^( {0,3})([+-])(?=\s|$)/gm, "$1\\$2") + .replace(/^( {0,3}\d+)([.)])(?=\s|$)/gm, "$1\\$2") + .replace(/^( {0,3})([-=])(?=(?:[ \t]*\2)*[ \t]*$)/gm, "$1\\$2"); } function serializeInlineCode(value) { + // CommonMark code spans turn source line endings into spaces. Normalize + // before paragraph escaping so literal block markers inside code are never + // mistaken for the start of a new Markdown block. + value = value.replace(/\r\n?|\n/g, " "); const runs = (value.match(/`+/g) || []).map((run) => run.length); const fence = "`".repeat(Math.max(1, runs.length ? Math.max.apply(null, runs) + 1 : 1)); - const padding = value.startsWith("`") || value.endsWith("`") ? " " : ""; + const padding = value.startsWith("`") || value.endsWith("`") || + (value.startsWith(" ") && value.endsWith(" ") && /\S/.test(value)) ? " " : ""; return fence + padding + value + padding + fence; } @@ -1902,7 +1989,7 @@ let inline = ""; const flushInline = () => { const value = inline.trim(); - if (value) blocks.push(value); + if (value) blocks.push(escapeParagraphSyntax(value)); inline = ""; }; @@ -1915,7 +2002,7 @@ if (node.nodeType !== Node.ELEMENT_NODE) return; const value = node.tagName.toLowerCase() === "p" - ? serializeChildrenInline(node).trim() + ? escapeParagraphSyntax(serializeChildrenInline(node).trim()) : serializeBlock(node).trim(); if (value) blocks.push(value); }); @@ -2247,6 +2334,7 @@ } function splitSourceLineOffsets() { + if (splitLineOffsetsCache) return splitLineOffsetsCache; const offsets = [0]; for (let index = 0; index < currentMarkdown.length; index += 1) { const code = currentMarkdown.charCodeAt(index); @@ -2267,6 +2355,7 @@ offsets.push(index + 1); } } + splitLineOffsetsCache = offsets; return offsets; } @@ -2286,6 +2375,8 @@ } function refreshSplitSourcePositions() { + invalidateSerializedBlocks(serializationObserver.takeRecords()); + splitSourcePositionsDirty = false; article .querySelectorAll( "[data-previewmd-source-start][data-previewmd-source-end]" @@ -2297,7 +2388,7 @@ const lineOffsets = splitSourceLineOffsets(); let cursor = 0; Array.from(article.children).forEach((block) => { - const source = serializeBlock(block).trimEnd(); + const source = serializedDocumentBlock(block); if (!source) return; const found = currentMarkdown.indexOf(source, cursor); if (found < cursor) return; @@ -2316,6 +2407,11 @@ }); } + function ensureSplitSourcePositions() { + if (domChanged) flushEditor(); + if (splitSourcePositionsDirty) refreshSplitSourcePositions(); + } + function setSplitSourcePosition(element, sourceStart, sourceEnd, lineOffsets) { const startLine = splitSourceLineForOffset(sourceStart, lineOffsets); const endLine = @@ -2391,6 +2487,7 @@ } function splitMappedElements() { + ensureSplitSourcePositions(); return Array.from( article.querySelectorAll( "[data-previewmd-source-start][data-previewmd-source-end]" @@ -2523,6 +2620,7 @@ } function currentSplitSelection() { + ensureSplitSourcePositions(); const selection = window.getSelection(); if (!selectionInsideArticle(selection) || !selection.rangeCount) return null; const range = selection.getRangeAt(0); @@ -2610,6 +2708,7 @@ function applySplitSelection(position) { if (!position) return false; + ensureSplitSourcePositions(); const start = Math.max( 0, Math.min(Number(position.start) || 0, currentMarkdown.length) @@ -2750,9 +2849,11 @@ } function scheduleSplitSelectionPublication() { + if (!splitSynchronizationEnabled) return; if (splitSelectionFrame) return; splitSelectionFrame = window.requestAnimationFrame(() => { splitSelectionFrame = 0; + if (!splitSynchronizationEnabled) return; if (performance.now() < ignoreSplitSelectionUntil) return; const position = currentSplitSelection(); if (position) { @@ -2763,9 +2864,11 @@ } function scheduleSplitScrollPublication() { + if (!splitSynchronizationEnabled) return; if (splitScrollFrame) return; splitScrollFrame = window.requestAnimationFrame(() => { splitScrollFrame = 0; + if (!splitSynchronizationEnabled) return; if (performance.now() < ignoreSplitScrollUntil) return; const position = currentSplitScrollPosition(); if (position) { @@ -2830,7 +2933,10 @@ window.requestAnimationFrame(updateBlockInserter); }); article.addEventListener("change", (event) => { - if (event.target.matches('input[type="checkbox"]')) scheduleChange(true, true); + if (event.target.matches('input[type="checkbox"]')) { + invalidateSerializedBlock(event.target); + scheduleChange(true, true); + } }); article.addEventListener("paste", handlePlainTextPaste); article.addEventListener("click", (event) => { @@ -2927,6 +3033,10 @@ window.previewmdCurrentSplitSelection = currentSplitSelection; window.previewmdApplySplitSelection = applySplitSelection; window.previewmdClearSplitSynchronization = clearSplitCounterpartIndicator; + window.previewmdSetSplitSynchronizationEnabled = function (value) { + splitSynchronizationEnabled = value === true; + if (!splitSynchronizationEnabled) clearSplitCounterpartIndicator(); + }; window.previewmdCurrentSplitScrollPosition = currentSplitScrollPosition; window.previewmdApplySplitScrollPosition = applySplitScrollPosition; window.previewmdAvailableBlocks = function () { diff --git a/Sources/PreviewMD/Resources/Renderer/renderer.css b/Sources/PreviewMD/Resources/Renderer/renderer.css index c3496de..0136965 100644 --- a/Sources/PreviewMD/Resources/Renderer/renderer.css +++ b/Sources/PreviewMD/Resources/Renderer/renderer.css @@ -627,6 +627,7 @@ code { .table-scroll.is-wide .table-sizer { margin-left: var(--table-leading-gutter, 0px); + width: calc(100% - var(--table-leading-gutter, 0px)); } .table-scroll.is-wide > .table-expand, diff --git a/Sources/PreviewMD/Resources/Renderer/renderer.js b/Sources/PreviewMD/Resources/Renderer/renderer.js index e952294..d5ff1fa 100644 --- a/Sources/PreviewMD/Resources/Renderer/renderer.js +++ b/Sources/PreviewMD/Resources/Renderer/renderer.js @@ -10,6 +10,8 @@ let activeSearchText = ""; let lastRenderOptions = null; let printRestoreOptions = null; + let printRestoreViewport = null; + let lastPublishedOutline = ""; let externalChangeTargets = []; const escapeHtml = (value) => @@ -236,6 +238,55 @@ return defaultHeadingOpen(tokens, index, options, env, self); }; + function inlineOutlineText(tokens) { + return (tokens || []).map((token) => { + if (token.type === "text" || token.type === "code_inline") return token.content; + if (token.type === "softbreak" || token.type === "hardbreak") return " "; + return token.children ? inlineOutlineText(token.children) : ""; + }).join(""); + } + + function outlineFromTokens(tokens) { + const headings = []; + tokens.forEach((token, index) => { + if (token.type !== "heading_open") return; + const inline = tokens[index + 1]; + headings.push({ + id: "heading-" + headings.length, + level: Number(token.tag.slice(1)), + title: inlineOutlineText(inline && inline.children).trim(), + }); + }); + return headings; + } + + window.previewmdOutlineForMarkdown = function (markdown) { + return outlineFromTokens(md.parse(extractFrontmatter(markdown).body, {})); + }; + + function publishOutline(markdown, headings, force) { + const serialized = JSON.stringify(headings); + const bridge = window.webkit && window.webkit.messageHandlers.outlineChange; + if (!bridge || (!force && serialized === lastPublishedOutline)) return; + lastPublishedOutline = serialized; + bridge.postMessage({ markdown: markdown, headings: headings }); + } + + window.previewmdPublishOutline = function (markdown) { + const headings = Array.from(article.querySelectorAll("h1,h2,h3,h4,h5,h6")) + .map((element, index) => { + element.id = "heading-" + index; + const anchor = element.querySelector(".heading-anchor"); + if (anchor && anchor.getAttribute("href") !== "#" + element.id) { + anchor.href = "#" + element.id; + } + const content = element.cloneNode(true); + content.querySelectorAll(".heading-anchor, .katex-mathml").forEach((node) => node.remove()); + return { id: element.id, level: Number(element.tagName.slice(1)), title: content.textContent.trim() }; + }); + publishOutline(markdown, headings); + }; + const tableExpandIcon = '
  1. Four
  2. Five
+

A separate list follows.

+
  1. One
  2. Two
+
  1. Nine
+
  1. Zero
+ """) + let four = try XCTUnwrap(package.paragraphs["Four"]) + let five = try XCTUnwrap(package.paragraphs["Five"]) + let one = try XCTUnwrap(package.paragraphs["One"]) + let two = try XCTUnwrap(package.paragraphs["Two"]) + let nine = try XCTUnwrap(package.paragraphs["Nine"]) + let zero = try XCTUnwrap(package.paragraphs["Zero"]) + + XCTAssertEqual(four.id, five.id) + XCTAssertEqual(one.id, two.id) + XCTAssertEqual(Set([four.id, one.id, nine.id, zero.id]).count, 4) + for (paragraph, start) in [(four, "4"), (one, "1"), (nine, "9"), (zero, "0")] { + let instance = try XCTUnwrap(package.instances[paragraph.id]) + XCTAssertEqual(paragraph.level, "0") + XCTAssertEqual(instance.abstractID, "1") + XCTAssertEqual(instance.level, "0") + XCTAssertEqual(instance.start, start) + } + } + + func testNestedListsHaveIndependentCountersAndKeepTheParentSequence() throws { + let package = try numberingPackage(html: """ +
    +
  1. Parent first
    1. Nested first
    2. Nested second
  2. +
  3. Parent second
    1. Nested restart
  4. +
  5. Parent third
  6. +
+
  • Bullet
    1. Nested zero
+ """) + let parent = try XCTUnwrap(package.paragraphs["Parent first"]) + XCTAssertEqual(package.paragraphs["Parent second"]?.id, parent.id) + XCTAssertEqual(package.paragraphs["Parent third"]?.id, parent.id) + XCTAssertEqual(package.instances[parent.id]?.start, "3") + + let nested = try XCTUnwrap(package.paragraphs["Nested first"]) + let restart = try XCTUnwrap(package.paragraphs["Nested restart"]) + let zero = try XCTUnwrap(package.paragraphs["Nested zero"]) + XCTAssertEqual(package.paragraphs["Nested second"]?.id, nested.id) + XCTAssertEqual(Set([parent.id, nested.id, restart.id, zero.id]).count, 4) + for (paragraph, start) in [(nested, "7"), (restart, "1"), (zero, "0")] { + let instance = try XCTUnwrap(package.instances[paragraph.id]) + XCTAssertEqual(paragraph.level, "1") + XCTAssertEqual(instance.level, "1") + XCTAssertEqual(instance.start, start) + XCTAssertEqual(instance.abstractID, "1") + } + let bullet = try XCTUnwrap(package.paragraphs["Bullet"]) + XCTAssertEqual(package.instances[bullet.id]?.abstractID, "0") + XCTAssertNil(package.instances[bullet.id]?.start) + } + + func testInvalidListStartsFallBackToOne() throws { + let package = try numberingPackage(html: """ +
  1. Invalid
+
  1. Too large
+ """) + for text in ["Invalid", "Too large"] { + let paragraph = try XCTUnwrap(package.paragraphs[text]) + XCTAssertEqual(package.instances[paragraph.id]?.start, "1") + } + } + + private struct NumberedParagraph { + let id: String + let level: String + } + + private struct NumberingInstance { + let abstractID: String + let level: String? + let start: String? + } + + private func numberingPackage(html: String) throws -> ( + paragraphs: [String: NumberedParagraph], + instances: [String: NumberingInstance] + ) { + let data = try DOCXDocumentWriter.data( + html: "\(html)", + title: "Lists", + assets: [] + ) + let url = try temporaryDOCX(data) + defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + let document = try XMLDocument(data: packageEntryData("word/document.xml", in: url)) + let numbering = try XMLDocument(data: packageEntryData("word/numbering.xml", in: url)) + var paragraphs: [String: NumberedParagraph] = [:] + for node in try document.nodes(forXPath: "//w:p[w:pPr/w:numPr]") { + let text = try node.nodes(forXPath: ".//w:t").compactMap(\.stringValue).joined() + paragraphs[text] = NumberedParagraph( + id: try XCTUnwrap(node.nodes(forXPath: "./w:pPr/w:numPr/w:numId/@w:val").first?.stringValue), + level: try XCTUnwrap(node.nodes(forXPath: "./w:pPr/w:numPr/w:ilvl/@w:val").first?.stringValue) + ) + } + var instances: [String: NumberingInstance] = [:] + for node in try numbering.nodes(forXPath: "//w:num") { + let id = try XCTUnwrap(node.nodes(forXPath: "./@w:numId").first?.stringValue) + instances[id] = NumberingInstance( + abstractID: try XCTUnwrap(node.nodes(forXPath: "./w:abstractNumId/@w:val").first?.stringValue), + level: try node.nodes(forXPath: "./w:lvlOverride/@w:ilvl").first?.stringValue, + start: try node.nodes(forXPath: "./w:lvlOverride/w:startOverride/@w:val").first?.stringValue + ) + } + return (paragraphs, instances) + } + private func temporaryDOCX(_ data: Data) throws -> URL { let directory = FileManager.default.temporaryDirectory .appendingPathComponent("PreviewMD-docx-test-\(UUID().uuidString)") diff --git a/Tests/PreviewMDTests/DocumentStateRegressionTests.swift b/Tests/PreviewMDTests/DocumentStateRegressionTests.swift new file mode 100644 index 0000000..5efc61a --- /dev/null +++ b/Tests/PreviewMDTests/DocumentStateRegressionTests.swift @@ -0,0 +1,362 @@ +#if canImport(XCTest) +import AppKit +import Combine +import Foundation +import XCTest +@testable import PreviewMD + +@MainActor +final class DocumentStateRegressionTests: XCTestCase { + func testAtomicSavePreservesSymbolicLinkAndUpdatesItsTarget() throws { + let root = try makeFolder() + let target = try makeFile("target.md", content: "original\n", in: root) + let link = root.appendingPathComponent("link.md") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target) + let original = try MarkdownFileIO.read(from: link) + + let snapshot = try MarkdownFileIO.write("edited\n", to: link, format: original.format) + + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "edited\n") + XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: link.path), target.path) + XCTAssertEqual(snapshot.fingerprint, try FileSnapshot.capture(url: target).fingerprint) + } + + func testOpeningTargetAndLinkUsesOneEditableDocumentAndSavesWithoutConflict() async throws { + let root = try makeFolder() + let target = try makeFile("target.md", content: "original\n", in: root) + let link = root.appendingPathComponent("link.md") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target) + var errors: [String] = [] + let state = try makeState(errorPresenter: { errors.append($0) }) + state.open(url: link) + let id = try XCTUnwrap(state.currentDocument?.id) + state.open(url: target) + XCTAssertEqual(state.documents.count, 1) + XCTAssertEqual(state.currentDocument?.id, id) + + state.updateContent("edited\n", for: id, origin: .source) + let saved = await saveCurrent(state) + XCTAssertTrue(saved) + await state.pollForExternalChanges() + + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "edited\n") + XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: link.path), target.path) + XCTAssertFalse(state.currentDocument?.hasExternalChanges ?? true) + XCTAssertTrue(errors.isEmpty) + } + + func testSaveAsToAlreadyOpenCleanTargetMergesItsTabAndPreservesLink() async throws { + let root = try makeFolder() + let source = try makeFile("source.md", content: "source\n", in: root) + let target = try makeFile("target.md", content: "target\n", in: root) + let link = root.appendingPathComponent("alias.md") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target) + let state = try makeState(saveDestination: { _ in link }) + state.open(url: source) + let id = try XCTUnwrap(state.currentDocument?.id) + state.open(url: target) + state.select(documentID: id) + state.updateContent("replacement\n", for: id, origin: .source) + + let saved = await saveAs(state) + + XCTAssertTrue(saved) + XCTAssertEqual(state.documents.count, 1) + XCTAssertEqual(state.currentDocument?.id, id) + XCTAssertEqual(state.currentDocument?.url, MarkdownFileIO.canonicalURL(for: target)) + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "replacement\n") + XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: link.path), target.path) + } + + func testSaveAsDoesNotReplaceAnotherTabsUnsavedChanges() async throws { + let root = try makeFolder() + let source = try makeFile("source.md", content: "source\n", in: root) + let target = try makeFile("target.md", content: "target\n", in: root) + var errors: [String] = [] + let state = try makeState(saveDestination: { _ in target }, errorPresenter: { errors.append($0) }) + state.open(url: source) + let sourceID = try XCTUnwrap(state.currentDocument?.id) + state.open(url: target) + let targetID = try XCTUnwrap(state.currentDocument?.id) + state.updateContent("unsaved target\n", for: targetID, origin: .source) + state.select(documentID: sourceID) + state.updateContent("replacement\n", for: sourceID, origin: .source) + + let saved = await saveAs(state) + + XCTAssertFalse(saved) + XCTAssertEqual(state.documents.count, 2) + XCTAssertEqual(state.documents.first(where: { $0.id == targetID })?.content, "unsaved target\n") + XCTAssertEqual(try String(contentsOf: target, encoding: .utf8), "target\n") + XCTAssertEqual(state.currentDocument?.url, MarkdownFileIO.canonicalURL(for: source)) + XCTAssertEqual(errors.count, 1) + } + + func testDiscardingTabRemovesItsUnsavedContentFromFolderSearch() async throws { + let root = try makeFolder() + let file = try makeFile("note.md", content: "alpha\n", in: root) + let state = try makeState(closeTabDecision: { _ in .discard }) + await openFolder(root, in: state) + state.open(url: file) + let id = try XCTUnwrap(state.currentDocument?.id) + state.updateContent("beta\n", for: id, origin: .source) + await search("beta", in: state) + XCTAssertEqual(state.workspaceSearchResults.count, 1) + + state.closeTab(id) + await waitFor { !state.isWorkspaceSearching } + + XCTAssertTrue(state.workspaceSearchResults.isEmpty) + XCTAssertEqual(try String(contentsOf: file, encoding: .utf8), "alpha\n") + } + + func testSaveAsOutsideWorkspaceRemovesOldFilesContentOverride() async throws { + let root = try makeFolder() + let workspace = root.appendingPathComponent("workspace") + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + let old = try makeFile("note.md", content: "alpha\n", in: workspace) + let destination = root.appendingPathComponent("outside.md") + let state = try makeState(saveDestination: { _ in destination }) + await openFolder(workspace, in: state) + state.open(url: old) + let id = try XCTUnwrap(state.currentDocument?.id) + state.updateContent("beta\n", for: id, origin: .source) + await search("beta", in: state) + XCTAssertEqual(state.workspaceSearchResults.count, 1) + + let saved = await saveAs(state) + await waitFor { !state.isWorkspaceSearching } + + XCTAssertTrue(saved) + XCTAssertTrue(state.workspaceSearchResults.isEmpty) + XCTAssertEqual(try String(contentsOf: old, encoding: .utf8), "alpha\n") + XCTAssertEqual(try String(contentsOf: destination, encoding: .utf8), "beta\n") + } + + func testReloadRefreshesFolderSearchContentOverrideImmediately() async throws { + let root = try makeFolder() + let file = try makeFile("note.md", content: "alpha\n", in: root) + let state = try makeState() + await openFolder(root, in: state) + state.open(url: file) + await search("alpha", in: state) + XCTAssertEqual(state.workspaceSearchResults.count, 1) + try "beta\n".write(to: file, atomically: true, encoding: .utf8) + + state.reloadCurrent() + await waitFor { !state.isWorkspaceSearching } + + XCTAssertEqual(state.currentDocument?.content, "beta\n") + XCTAssertTrue(state.workspaceSearchResults.isEmpty) + } + + func testWorkspaceSearchUsesUnsavedContentsOfFileOpenedThroughSymlink() async throws { + let root = try makeFolder() + let workspace = root.appendingPathComponent("workspace") + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + let target = try makeFile("target.md", content: "alpha\n", in: root) + let link = workspace.appendingPathComponent("link.md") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target) + let state = try makeState() + await openFolder(workspace, in: state) + state.open(url: link) + state.updateContent("beta\n", for: try XCTUnwrap(state.currentDocument?.id), origin: .source) + + await search("beta", in: state) + + XCTAssertEqual(state.workspaceSearchResults.first?.url.standardizedFileURL, link.standardizedFileURL) + XCTAssertEqual(state.workspaceSearchResults.first?.snippet, "beta") + } + + func testMissingWorkspaceReportsNonmodalErrorOnceAndRecovers() async throws { + let root = try makeFolder() + _ = try makeFile("note.md", content: "note\n", in: root) + var errors: [String] = [] + let state = try makeState(errorPresenter: { errors.append($0) }) + await openFolder(root, in: state) + try FileManager.default.removeItem(at: root) + + await state.pollForExternalChanges(now: Date().addingTimeInterval(10)) + await waitFor { state.workspaceFolderError != nil } + XCTAssertTrue(errors.isEmpty) + XCTAssertTrue(state.workspaceFolderItems.isEmpty) + XCTAssertNotNil(state.workspaceFolderURL) + + var publicationCount = 0 + let observation = state.objectWillChange.sink { publicationCount += 1 } + await state.pollForExternalChanges(now: Date().addingTimeInterval(20)) + try await Task.sleep(for: .milliseconds(150)) + withExtendedLifetime(observation) { + XCTAssertEqual(publicationCount, 0) + } + XCTAssertTrue(errors.isEmpty) + + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + _ = try makeFile("restored.md", content: "restored\n", in: root) + state.refreshWorkspaceFolder() + await waitFor { !state.isWorkspaceFolderLoading } + XCTAssertNil(state.workspaceFolderError) + XCTAssertEqual(state.workspaceFolderItems.map(\.title), ["restored.md"]) + } + + func testInvalidExternalUTF8DoesNotTriggerRepeatingModalAndRecoveryClearsConflict() async throws { + let root = try makeFolder() + let file = try makeFile("note.md", content: "saved\n", in: root) + var errors: [String] = [] + let state = try makeState(errorPresenter: { errors.append($0) }) + state.open(url: file) + try Data([0xFF]).write(to: file) + + await state.pollForExternalChanges() + await state.pollForExternalChanges() + + XCTAssertEqual(state.currentDocument?.content, "saved\n") + XCTAssertTrue(state.currentDocument?.hasExternalChanges == true) + XCTAssertTrue(errors.isEmpty) + try "saved\n".write(to: file, atomically: true, encoding: .utf8) + await state.pollForExternalChanges() + XCTAssertFalse(state.currentDocument?.hasExternalChanges ?? true) + } + + func testPollingReadsOffMainThreadAndDoesNotOverwriteAnEditDuringTheRead() async throws { + let root = try makeFolder() + let file = try makeFile("note.md", content: "saved\n", in: root) + let gate = PollReadGate() + let state = try makeState(externalPollData: { try gate.read($0) }) + state.open(url: file) + let id = try XCTUnwrap(state.currentDocument?.id) + try "external\n".write(to: file, atomically: true, encoding: .utf8) + let poll = Task { await state.pollForExternalChanges() } + let started = await Task.detached { gate.waitUntilReadStarted() }.value + XCTAssertTrue(started) + + await state.pollForExternalChanges() + XCTAssertEqual(gate.readCount, 1, "A second polling pass must not start while the first read is pending") + + state.updateContent("local edit\n", for: id, origin: .source) + gate.release.signal() + await poll.value + + XCTAssertFalse(gate.wasReadOnMainThread) + XCTAssertEqual(state.currentDocument?.content, "local edit\n") + XCTAssertEqual(state.currentDocument?.lastSavedContent, "saved\n") + XCTAssertTrue(state.currentDocument?.isDirty == true) + } + + func testPendingPollCannotReloadTheOldFileAfterSaveAsChangesLocation() async throws { + let root = try makeFolder() + let original = try makeFile("original.md", content: "saved\n", in: root) + let destination = root.appendingPathComponent("copy.md") + let gate = PollReadGate() + let state = try makeState(saveDestination: { _ in destination }, externalPollData: { try gate.read($0) }) + state.open(url: original) + try "external\n".write(to: original, atomically: true, encoding: .utf8) + let poll = Task { await state.pollForExternalChanges() } + let started = await Task.detached { gate.waitUntilReadStarted() }.value + XCTAssertTrue(started) + + let saved = await saveAs(state) + gate.release.signal() + await poll.value + + XCTAssertTrue(saved) + XCTAssertEqual(state.currentDocument?.url, MarkdownFileIO.canonicalURL(for: destination)) + XCTAssertEqual(state.currentDocument?.content, "saved\n") + XCTAssertEqual(try String(contentsOf: destination, encoding: .utf8), "saved\n") + XCTAssertFalse(state.currentDocument?.isDirty ?? true) + } + + private func makeFolder() throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("PreviewMD-state-regression-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: root) } + return root + } + + private func makeFile(_ name: String, content: String, in root: URL) throws -> URL { + let file = root.appendingPathComponent(name) + try content.write(to: file, atomically: true, encoding: .utf8) + return file + } + + private func makeState( + closeTabDecision: ((MarkdownDocument) -> TabCloseDecision)? = nil, + saveDestination: ((MarkdownDocument) -> URL?)? = nil, + errorPresenter: ((String) -> Void)? = nil, + externalPollData: @escaping @Sendable (URL) throws -> Data = { try Data(contentsOf: $0) } + ) throws -> AppState { + let suite = "PreviewMDStateRegression.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + addTeardownBlock { defaults.removePersistentDomain(forName: suite) } + return AppState( + defaults: defaults, + closeTabDecision: closeTabDecision, + saveDestination: saveDestination, + errorPresenter: errorPresenter, + externalPollData: externalPollData + ) + } + + private func openFolder(_ root: URL, in state: AppState) async { + state.openFolder(url: root) + await waitFor { !state.isWorkspaceFolderLoading } + } + + private func search(_ query: String, in state: AppState) async { + state.setWorkspaceSearchQuery(query, immediately: true) + await waitFor { !state.isWorkspaceSearching } + } + + private func waitFor(_ condition: () -> Bool) async { + for _ in 0..<200 { + if condition() { return } + try? await Task.sleep(for: .milliseconds(10)) + } + XCTFail("Timed out waiting for the asynchronous document state") + } + + private func saveCurrent(_ state: AppState) async -> Bool { + await withCheckedContinuation { continuation in + state.saveCurrent { continuation.resume(returning: $0) } + } + } + + private func saveAs(_ state: AppState) async -> Bool { + await withCheckedContinuation { continuation in + state.saveCurrentAs { continuation.resume(returning: $0) } + } + } +} + +private final class PollReadGate: @unchecked Sendable { + let entered = DispatchSemaphore(value: 0) + let release = DispatchSemaphore(value: 0) + private let lock = NSLock() + private var readOnMainThread = false + private var reads = 0 + + var wasReadOnMainThread: Bool { + lock.withLock { readOnMainThread } + } + + var readCount: Int { + lock.withLock { reads } + } + + func waitUntilReadStarted() -> Bool { + entered.wait(timeout: .now() + 3) == .success + } + + func read(_ url: URL) throws -> Data { + lock.withLock { + readOnMainThread = Thread.isMainThread + reads += 1 + } + entered.signal() + guard release.wait(timeout: .now() + 3) == .success else { + throw CocoaError(.fileReadUnknown) + } + return try Data(contentsOf: url) + } +} +#endif diff --git a/Tests/PreviewMDTests/EditorSerializationRegressionTests.swift b/Tests/PreviewMDTests/EditorSerializationRegressionTests.swift new file mode 100644 index 0000000..9f87c0d --- /dev/null +++ b/Tests/PreviewMDTests/EditorSerializationRegressionTests.swift @@ -0,0 +1,181 @@ +#if canImport(XCTest) +import Foundation +import WebKit +import XCTest +@testable import PreviewMD + +@MainActor +final class EditorSerializationRegressionTests: XCTestCase, WKNavigationDelegate { + private var navigationExpectation: XCTestExpectation? + + func testUnrelatedRichEditPreservesBlankLinesInsideCodeAndFrontmatter() async throws { + let markdown = "---\nnotes: |\n first\n\n\n\n last\n---\n\nParagraph\n\n```text\nfirst\n\n\n\nlast\n```" + let webView = try await makeEditor(markdown: markdown) + let result = try await webView.callAsyncJavaScript( + """ + const article = document.getElementById("preview-document"); + article.querySelector("p").textContent += " edited"; + article.dispatchEvent(new InputEvent("input", { bubbles: true })); + const markdown = window.previewmdFlushEditor(); + const fragment = document.createElement("div"); + fragment.appendChild(article.querySelector(".code-card").cloneNode(true)); + return { markdown, fragment: window.previewmdSerializeFragment(fragment) }; + """, + contentWorld: .page + ) + let output = try XCTUnwrap(result as? [String: String]) + XCTAssertEqual(output["markdown"], markdown.replacingOccurrences(of: "Paragraph", with: "Paragraph edited") + "\n") + XCTAssertEqual(output["fragment"], "```text\nfirst\n\n\n\nlast\n```") + } + + func testUnrelatedRichEditKeepsLiteralMarkdownMarkersAsPlainText() async throws { + let markdown = "\\# Literal heading" + "\n\n" + #"\> Literal quote"# + + "\n\n" + #"1\. Literal list"# + "\n\n" + #"\- Literal bullet"# + + "\n\n" + #"\~\~Literal strike\~\~"# + "\n\n" + #"\>No space"# + + "\n\nSetext\n" + #"\="# + "\n\nTail" + let webView = try await makeEditor(markdown: markdown) + let result = try await webView.callAsyncJavaScript( + """ + const article = document.getElementById("preview-document"); + article.lastElementChild.textContent += " edited"; + article.dispatchEvent(new InputEvent("input", { bubbles: true })); + const markdown = window.previewmdFlushEditor(); + await window.previewmdRefreshEditor(markdown); + // Refresh is normally fire-and-forget; this document has no diagrams. + await new Promise((resolve) => setTimeout(resolve, 0)); + return { + text: Array.from(article.children, (node) => node.textContent.trim()), + tags: Array.from(article.children, (node) => node.tagName), + formatted: !!article.querySelector("h1, blockquote, ol, ul, s, del"), + }; + """, + contentWorld: .page + ) + let output = try XCTUnwrap(result as? [String: Any]) + XCTAssertEqual(output["tags"] as? [String], Array(repeating: "P", count: 8)) + XCTAssertEqual(output["text"] as? [String], ["# Literal heading", "> Literal quote", "1. Literal list", "- Literal bullet", "~~Literal strike~~", ">No space", "Setext\n=", "Tail edited"]) + XCTAssertEqual(output["formatted"] as? Bool, false) + } + + func testRichInlineCodePreservesSignificantSurroundingSpacesAfterReopening() async throws { + let webView = try await makeEditor(markdown: "Before `code` after") + let result = try await webView.callAsyncJavaScript( + """ + const article = document.getElementById("preview-document"); + article.querySelector("code").textContent = " code "; + article.dispatchEvent(new InputEvent("input", { bubbles: true })); + const markdown = window.previewmdFlushEditor(); + window.previewmdRefreshEditor(markdown); + await new Promise((resolve) => setTimeout(resolve, 0)); + return article.querySelector("code").textContent; + """, + contentWorld: .page + ) + XCTAssertEqual(result as? String, " code ") + } + + func testFormattingMultilineLiteralMarkersAsInlineCodeDoesNotAddBackslashes() async throws { + for (source, expected) in [ + ("first\n\\# literal", "first # literal"), + ("first\n\\> literal", "first > literal"), + ("first\n1\\. literal", "first 1. literal"), + ] { + let webView = try await makeEditor(markdown: source) + let result = try await webView.callAsyncJavaScript( + """ + const paragraph = document.querySelector("#preview-document p"); + const range = document.createRange(); + range.selectNodeContents(paragraph); + const selection = window.getSelection(); + selection.removeAllRanges(); + selection.addRange(range); + document.querySelector('[data-editor-action="inline-code"]').click(); + const markdown = window.previewmdFlushEditor(); + window.previewmdRefreshEditor(markdown); + await new Promise((resolve) => setTimeout(resolve, 0)); + return document.querySelector("#preview-document code").textContent; + """, + contentWorld: .page + ) + XCTAssertEqual(result as? String, expected, source) + } + } + + func testRichSerializationTracksSuccessiveEditsAndCheckboxPropertyChanges() async throws { + let webView = try await makeEditor(markdown: "Paragraph\n\n- [ ] Task\n\n```text\noriginal\n```") + let result = try await webView.callAsyncJavaScript( + """ + const article = document.getElementById("preview-document"); + const paragraph = article.querySelector("p"); + paragraph.textContent = "First edit"; + paragraph.dispatchEvent(new InputEvent("input", { bubbles: true })); + window.previewmdFlushEditor(); + paragraph.textContent = "Second edit"; + paragraph.dispatchEvent(new InputEvent("input", { bubbles: true })); + window.previewmdFlushEditor(); + const checkbox = article.querySelector("input[type=checkbox]"); + checkbox.checked = true; + checkbox.dispatchEvent(new Event("change", { bubbles: true })); + article.querySelector(".code-card code").textContent = "updated"; + article.dispatchEvent(new InputEvent("input", { bubbles: true })); + return window.previewmdFlushEditor(); + """, + contentWorld: .page + ) + XCTAssertEqual(result as? String, "Second edit\n\n- [x] Task\n\n```text\nupdated\n```\n") + } + + func testRichEditsPublishContentBeforeTheMatchingOutline() async throws { + let webView = try await makeEditor(markdown: "# Heading\n\nParagraph") + let result = try await webView.callAsyncJavaScript( + """ + const calls = []; + window.webkit = { messageHandlers: { + editorChange: { postMessage: (body) => calls.push("content:" + body.markdown) }, + } }; + window.previewmdPublishOutline = (markdown) => calls.push("outline:" + markdown); + const heading = document.querySelector("#preview-document h1"); + heading.firstChild.nodeValue = "Flushed heading"; + heading.dispatchEvent(new InputEvent("input", { bubbles: true })); + window.previewmdFlushEditor(); + heading.firstChild.nodeValue = "Emitted heading"; + heading.dispatchEvent(new InputEvent("input", { bubbles: true })); + await new Promise((resolve) => setTimeout(resolve, 10)); + return calls; + """, + contentWorld: .page + ) + let calls = try XCTUnwrap(result as? [String]) + XCTAssertEqual(calls.count, 4) + guard calls.count == 4 else { return } + XCTAssertTrue(calls[0].hasPrefix("content:")) + XCTAssertEqual(calls[1], calls[0].replacingOccurrences(of: "content:", with: "outline:")) + XCTAssertTrue(calls[2].hasPrefix("content:")) + XCTAssertEqual(calls[3], calls[2].replacingOccurrences(of: "content:", with: "outline:")) + } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation?) { + navigationExpectation?.fulfill() + } + + private func makeEditor(markdown: String) async throws -> WKWebView { + let payload = MarkdownWebView.RenderPayload( + documentID: UUID().uuidString, markdown: markdown, revision: 0, + editable: true, theme: "light", readingStyle: "modern", + customReadingPreset: nil, systemDark: false, readingWidth: 820, + readingWidthIsFluid: false, paperCanvas: false, zoom: 1, + searchText: "", outlineTarget: nil, topInset: 0 + ) + let webView = WKWebView(frame: NSRect(x: 0, y: 0, width: 900, height: 700)) + webView.navigationDelegate = self + let loaded = expectation(description: "Renderer shell loaded") + navigationExpectation = loaded + webView.loadHTMLString(RendererAssets.shellHTML(for: payload), baseURL: Bundle.module.resourceURL) + await fulfillment(of: [loaded], timeout: 5) + navigationExpectation = nil + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(payload)) as? [String: Any]) + _ = try await webView.callAsyncJavaScript("await window.previewmdRender(options); return true;", arguments: ["options": object], contentWorld: .page) + return webView + } +} +#endif diff --git a/Tests/PreviewMDTests/FolderWorkspaceTests.swift b/Tests/PreviewMDTests/FolderWorkspaceTests.swift index ca30d45..808fdb5 100644 --- a/Tests/PreviewMDTests/FolderWorkspaceTests.swift +++ b/Tests/PreviewMDTests/FolderWorkspaceTests.swift @@ -86,7 +86,7 @@ final class FolderWorkspaceTests: XCTestCase { let observation = state.objectWillChange.sink { publicationCount += 1 } - state.pollForExternalChanges(now: .distantFuture) + await state.pollForExternalChanges(now: .distantFuture) try await Task.sleep(for: .milliseconds(150)) withExtendedLifetime(observation) { diff --git a/Tests/PreviewMDTests/RendererAuditTests.swift b/Tests/PreviewMDTests/RendererAuditTests.swift new file mode 100644 index 0000000..ca88e6a --- /dev/null +++ b/Tests/PreviewMDTests/RendererAuditTests.swift @@ -0,0 +1,403 @@ +import Foundation +import PDFKit +import WebKit +import XCTest +@testable import PreviewMD + +@MainActor +final class RendererAuditTests: XCTestCase, WKNavigationDelegate { + private var navigationExpectation: XCTestExpectation? + + func testPDFIncludesRichEditsAndRestoresCurrentContentAndLayout() async throws { + let webView = try await makeEditor("Original text") + let result = try await webView.callAsyncJavaScript( + """ + const article = document.getElementById('preview-document'); + article.querySelector('p').textContent = 'Latest unsaved edit'; + article.dispatchEvent(new InputEvent('input', {bubbles: true})); + window.previewmdSetLayout(960, false, 48, false); + await window.previewmdPreparePDF({theme:'light', style:'modern'}, 515, 761); + return article.textContent; + """, contentWorld: .page + ) + XCTAssertTrue((result as? String)?.contains("Latest unsaved edit") == true) + let pdf = try await webView.pdf(configuration: WKPDFConfiguration()) + XCTAssertTrue(PDFDocument(data: pdf)?.string?.contains("Latest unsaved edit") == true) + let restored = try await webView.callAsyncJavaScript( + """ + await window.previewmdFinishPrint(); + return { + markdown: window.previewmdFlushEditor(), + width: document.documentElement.style.getPropertyValue('--reading-width'), + inset: document.documentElement.style.getPropertyValue('--top-inset'), + editable: document.getElementById('preview-document').isContentEditable, + }; + """, contentWorld: .page + ) + let output = try XCTUnwrap(restored as? [String: Any]) + XCTAssertEqual(output["markdown"] as? String, "Latest unsaved edit\n") + XCTAssertEqual(output["width"] as? String, "960px") + XCTAssertEqual(output["inset"] as? String, "48px") + XCTAssertEqual(output["editable"] as? Bool, true) + } + + func testOutlineUsesTheRenderedHeadingGrammarAndIdentifiers() async throws { + let markdown = """ + --- + title: metadata + --- + + Intro + ===== + + ## Indented **section** + + > ### Quoted section + + ````markdown + ``` + # Not a heading + ```` + + ## Real section + """ + let webView = try await makeEditor(markdown) + let result = try await webView.callAsyncJavaScript( + """ + const parsed = window.previewmdOutlineForMarkdown(markdown); + const rendered = Array.from(document.querySelectorAll('#preview-document h1,h2,h3,h4,h5,h6')); + return { parsed, ids: rendered.map(h => h.id), titles: rendered.map(h => { + const content = h.cloneNode(true); + content.querySelectorAll('.heading-anchor, .katex-mathml').forEach(node => node.remove()); + return content.textContent.trim(); + }) }; + """, arguments: ["markdown": markdown], contentWorld: .page + ) + let output = try XCTUnwrap(result as? [String: Any]) + let headings = try XCTUnwrap(output["parsed"] as? [[String: Any]]) + XCTAssertEqual(headings.compactMap { $0["id"] as? String }, output["ids"] as? [String]) + XCTAssertEqual(headings.compactMap { $0["title"] as? String }, ["Intro", "Indented section", "Quoted section", "Real section"]) + XCTAssertEqual(headings.compactMap { $0["level"] as? Int }, [1, 2, 3, 2]) + XCTAssertEqual(output["titles"] as? [String], ["Intro", "Indented section", "Quoted section", "Real section"]) + } + + func testRenderedOutlineReachesTheOpenedDocumentThroughTheWebKitBridge() async throws { + let markdown = "Intro\n=====\n\n ## Indented **section**\n\n> ### Quoted section\n" + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("PreviewMDOutlineBridge-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let fileURL = directory.appendingPathComponent("Outline.md") + try markdown.write(to: fileURL, atomically: true, encoding: .utf8) + let suiteName = "PreviewMDOutlineBridge.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + let state = AppState(defaults: defaults) + state.liveReloadEnabled = false + state.open(url: fileURL) + let document = try XCTUnwrap(state.currentDocument) + XCTAssertEqual(document.content, markdown) + + let outlineReady = expectation(description: "Rendered headings arrive through WebKit") + let coordinator = MarkdownWebView.Coordinator( + documentID: document.id, documentURL: document.url, + openMarkdown: state.open(url:), + onContentChange: { id, content, boundary in + state.updateContent(content, for: id, origin: .richEditor, startsNewUndoGroup: boundary) + }, + splitSynchronizer: SplitEditorSynchronizer(), + isSplitSynchronizationEnabled: false, + onOutlineChange: { headings, id, content in + XCTAssertEqual(id, document.id) + XCTAssertEqual(content, document.content) + state.updateOutline(headings, for: id, content: content) + outlineReady.fulfill() + } + ) + let configuration = WKWebViewConfiguration() + configuration.userContentController.add(coordinator, name: "outlineChange") + configuration.userContentController.add(coordinator, name: "editorChange") + let webView = WKWebView(frame: NSRect(x: 0, y: 0, width: 900, height: 700), configuration: configuration) + defer { + configuration.userContentController.removeScriptMessageHandler(forName: "outlineChange") + configuration.userContentController.removeScriptMessageHandler(forName: "editorChange") + } + webView.navigationDelegate = coordinator + coordinator.webView = webView + coordinator.loadShell(baseURL: directory, initialPayload: payload(document.content, documentID: document.id), in: webView) + try await coordinator.prepareForOutput() + await fulfillment(of: [outlineReady], timeout: 5) + XCTAssertEqual(state.currentOutline.map(\.title), ["Intro", "Indented section", "Quoted section"]) + XCTAssertEqual(state.currentOutline.map(\.level), [1, 2, 3]) + XCTAssertEqual(state.currentOutline.map(\.id), ["heading-0", "heading-1", "heading-2"]) + } + + func testHiddenPreviewDefersDOMRebuildButRefreshesOutlineAndSaveUsesSource() async throws { + let webView = try await makeEditor("# Original\n\nOriginal body") + let documentID = UUID() + let outlineReady = expectation(description: "Hidden source outline parsed") + var outline: [OutlineHeading] = [] + let coordinator = MarkdownWebView.Coordinator( + documentID: documentID, documentURL: nil, + openMarkdown: { _ in }, onContentChange: { _, _, _ in }, + splitSynchronizer: SplitEditorSynchronizer(), + isSplitSynchronizationEnabled: false, isVisible: false, + onOutlineChange: { headings, id, content in + XCTAssertEqual(id, documentID) + XCTAssertEqual(content, "New heading\n===========\n\nLatest source body") + outline = headings + outlineReady.fulfill() + } + ) + coordinator.webView = webView + coordinator.webView(webView, didFinish: nil) + let newPayload = payload("New heading\n===========\n\nLatest source body", documentID: documentID) + coordinator.update(newPayload, in: webView) + await fulfillment(of: [outlineReady], timeout: 5) + XCTAssertEqual(outline.map(\.title), ["New heading"]) + let original = try await webView.evaluateJavaScript("document.getElementById('preview-document').textContent") + XCTAssertTrue((original as? String)?.contains("Original body") == true) + + let controller = RendererController() + controller.attach(webView, documentID: documentID, isVisible: false) + let flushed = expectation(description: "Source-only save skips stale rich editor") + controller.flushMarkdown(for: documentID) { markdown in + XCTAssertNil(markdown) + flushed.fulfill() + } + await fulfillment(of: [flushed], timeout: 1) + + coordinator.isVisible = true + coordinator.update(newPayload, in: webView) + let visible = try await webView.callAsyncJavaScript( + """ + await new Promise(resolve => setTimeout(resolve, 50)); + return document.getElementById('preview-document').textContent; + """, contentWorld: .page + ) + XCTAssertTrue((visible as? String)?.contains("Latest source body") == true) + XCTAssertFalse((visible as? String)?.contains("Original body") == true) + } + + func testTablesSettleAtFinalColumnWidthWithoutGutterOverflow() async throws { + let webView = try await makeEditor("| A | B | C | D |\n| - | - | - | - |\n| one | two | three | four |") + webView.setFrameSize(NSSize(width: 1650, height: 700)) + for width in [560, 1100, 560, 1100] { + let result = try await webView.callAsyncJavaScript( + """ + window.previewmdSetLayout(width, false, 0, false); + await new Promise(resolve => setTimeout(resolve, 300)); + const wrapper = document.querySelector('.table-scroll'); + const article = document.getElementById('preview-document'); + const style = getComputedStyle(article); + const columnWidth = article.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight); + const viewport = wrapper.querySelector('.table-viewport'); + return { wide: wrapper.classList.contains('is-wide'), columnWidth, client:viewport.clientWidth, scroll:viewport.scrollWidth }; + """, arguments: ["width": width], contentWorld: .page + ) + let output = try XCTUnwrap(result as? [String: Any]) + let columnWidth = try XCTUnwrap(output["columnWidth"] as? Double) + XCTAssertEqual(output["wide"] as? Bool, 576 > columnWidth + 1) + XCTAssertEqual(output["client"] as? Int, output["scroll"] as? Int) + } + } + + func testHiddenSourceIsRenderedBeforePDFPreparationAndRestoredAfterward() async throws { + let webView = try await makeEditor("Old source") + let coordinator = outputCoordinator(in: webView, visible: false) + coordinator.update(payload("Latest source-only edit"), in: webView) + try await coordinator.prepareForOutput() + _ = try await webView.callAsyncJavaScript( + "await window.previewmdPreparePDF({theme:'light', style:'modern'}, 515, 761); return true;", + contentWorld: .page + ) + let pdf = try await webView.pdf(configuration: WKPDFConfiguration()) + XCTAssertTrue(PDFDocument(data: pdf)?.string?.contains("Latest source-only edit") == true) + let restored = try await webView.callAsyncJavaScript( + "await window.previewmdFinishPrint(); return window.previewmdFlushEditor();", + contentWorld: .page + ) + XCTAssertEqual(restored as? String, "Latest source-only edit") + } + + func testCopyAndDOCXCommandsSynchronizeTheHiddenPreviewBeforeReadingItsContent() async throws { + for copy in [false, true] { + let webView = try await makeEditor("Old source") + let coordinator = outputCoordinator(in: webView, visible: false) + let id = UUID() + coordinator.documentID = id + coordinator.update(payload("Latest source-only edit", documentID: id), in: webView) + _ = try await webView.evaluateJavaScript(""" + window.auditOutput = null; + window.previewmdAdvancedCopy = window.previewmdExportDOCX = function () { + window.auditOutput = window.previewmdFlushEditor(); + return true; + }; + true; + """) + let controller = RendererController() + controller.attach(webView, documentID: id, isVisible: false) { + try await coordinator.prepareForOutput() + } + if copy { controller.advancedCopy(.markdown, suggestedName: "Document") } + else { controller.exportDOCX(suggestedName: "Document") } + let output = try await webView.callAsyncJavaScript( + """ + const deadline = Date.now() + 3000; + while (window.auditOutput === null && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 10)); + } + return window.auditOutput; + """, contentWorld: .page + ) + XCTAssertEqual(output as? String, "Latest source-only edit") + withExtendedLifetime(controller) {} + } + } + + func testSaveWaitsForAnAsynchronousRenderAndUsesTheLatestQueuedSource() async throws { + let webView = try await makeEditor("Old source") + let id = UUID() + let coordinator = outputCoordinator(in: webView, visible: true) + coordinator.documentID = id + _ = try await webView.evaluateJavaScript(""" + const originalRender = window.previewmdRender; + window.auditRenderStarted = false; + window.previewmdRender = async function (options) { + window.auditRenderStarted = true; + await new Promise(resolve => setTimeout(resolve, 150)); + return originalRender(options); + }; + true; + """) + coordinator.update(payload("First source edit", documentID: id), in: webView) + let started = try await webView.callAsyncJavaScript( + """ + const deadline = Date.now() + 3000; + while (!window.auditRenderStarted && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 10)); + } + return window.auditRenderStarted; + """, contentWorld: .page + ) + XCTAssertEqual(started as? Bool, true) + coordinator.update(payload("Latest queued source", documentID: id), in: webView) + let controller = RendererController() + controller.attach(webView, documentID: id) { try await coordinator.prepareForOutput() } + let flushed = expectation(description: "Save awaits the newest render") + controller.flushMarkdown(for: id) { markdown in + XCTAssertEqual(markdown, "Latest queued source") + flushed.fulfill() + } + await fulfillment(of: [flushed], timeout: 5) + withExtendedLifetime(controller) {} + } + + func testUndoToRenderedContentReplacesAnOlderHiddenPendingEdit() async throws { + let webView = try await makeEditor("Original source") + let coordinator = outputCoordinator(in: webView, visible: true) + let original = payload("Original source") + coordinator.update(original, in: webView) + try await coordinator.prepareForOutput() + coordinator.isVisible = false + coordinator.update(payload("Discarded hidden edit"), in: webView) + coordinator.update(original, in: webView) + try await coordinator.prepareForOutput() + let markdown = try await webView.evaluateJavaScript("window.previewmdFlushEditor()") + XCTAssertEqual(markdown as? String, "Original source") + } + + func testRichInputDuringDeferredDiagramRenderingSurvivesRenderCompletionAndSave() async throws { + let webView = try await makeEditor("Old source") + let id = UUID() + let coordinator = outputCoordinator(in: webView, visible: true) + coordinator.documentID = id + _ = try await webView.evaluateJavaScript(""" + window.auditDiagramPending = false; + window.mermaid.render = async function () { + window.auditDiagramPending = true; + await new Promise(resolve => setTimeout(resolve, 150)); + window.auditDiagramPending = false; + return { svg: '' }; + }; + true; + """) + coordinator.update(payload("Paragraph\n\n```mermaid\ngraph TD; A-->B\n```", documentID: id), in: webView) + let editedDuringRender = try await webView.callAsyncJavaScript( + """ + const deadline = Date.now() + 3000; + while (!window.auditDiagramPending && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 10)); + } + const wasPending = window.auditDiagramPending; + const article = document.getElementById('preview-document'); + article.querySelector('p').textContent = 'Typed before the diagram finished'; + article.dispatchEvent(new InputEvent('input', { bubbles: true })); + await new Promise(resolve => setTimeout(resolve, 10)); + return wasPending; + """, contentWorld: .page + ) + XCTAssertEqual(editedDuringRender as? Bool, true) + let controller = RendererController() + controller.attach(webView, documentID: id) { try await coordinator.prepareForOutput() } + let flushed = expectation(description: "Save keeps typing performed during diagram rendering") + controller.flushMarkdown(for: id) { markdown in + XCTAssertTrue(markdown?.contains("Typed before the diagram finished") == true) + XCTAssertFalse(markdown?.contains("Paragraph") == true) + flushed.fulfill() + } + await fulfillment(of: [flushed], timeout: 5) + withExtendedLifetime(controller) {} + } + + private func outputCoordinator(in webView: WKWebView, visible: Bool) -> MarkdownWebView.Coordinator { + let coordinator = MarkdownWebView.Coordinator( + documentID: UUID(), documentURL: nil, + openMarkdown: { _ in }, onContentChange: { _, _, _ in }, + splitSynchronizer: SplitEditorSynchronizer(), + isSplitSynchronizationEnabled: false, isVisible: visible + ) + coordinator.webView = webView + coordinator.webView(webView, didFinish: nil) + return coordinator + } + + func testReadingStatisticsTrackUnicodeTextChanges() { + var text = MarkdownText(wrappedValue: "one\n👩🏽‍💻 two") + XCTAssertEqual(text.wordCount, 3) + XCTAssertEqual(text.characterCount, "one\n👩🏽‍💻 two".count) + text.wrappedValue = "" + XCTAssertEqual(text.wordCount, 0) + XCTAssertEqual(text.characterCount, 0) + text.wrappedValue = "zażółć\t世界" + XCTAssertEqual(text.wordCount, 2) + XCTAssertEqual(text.characterCount, "zażółć\t世界".count) + } + + private func payload(_ markdown: String, documentID: UUID = UUID()) -> MarkdownWebView.RenderPayload { + MarkdownWebView.RenderPayload( + documentID: documentID.uuidString, markdown: markdown, revision: 1, + editable: true, theme: "light", readingStyle: "modern", customReadingPreset: nil, + systemDark: false, readingWidth: 820, readingWidthIsFluid: false, + paperCanvas: false, zoom: 1, searchText: "", outlineTarget: nil, topInset: 0 + ) + } + + private func makeEditor(_ markdown: String) async throws -> WKWebView { + let options = payload(markdown) + let webView = WKWebView(frame: NSRect(x: 0, y: 0, width: 900, height: 700)) + webView.navigationDelegate = self + let loaded = expectation(description: "Renderer loaded") + navigationExpectation = loaded + webView.loadHTMLString(RendererAssets.shellHTML(for: options), baseURL: Bundle.module.resourceURL) + await fulfillment(of: [loaded], timeout: 5) + navigationExpectation = nil + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(options)) as? [String: Any]) + _ = try await webView.callAsyncJavaScript("await window.previewmdRender(options); return true;", arguments: ["options": object], contentWorld: .page) + return webView + } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation?) { + navigationExpectation?.fulfill() + } +} diff --git a/Tests/PreviewMDTests/SourceHighlightingRegressionTests.swift b/Tests/PreviewMDTests/SourceHighlightingRegressionTests.swift new file mode 100644 index 0000000..09c9874 --- /dev/null +++ b/Tests/PreviewMDTests/SourceHighlightingRegressionTests.swift @@ -0,0 +1,73 @@ +#if canImport(XCTest) +import AppKit +import SwiftUI +import XCTest +@testable import PreviewMD + +@MainActor +final class SourceHighlightingRegressionTests: XCTestCase { + func testSingleLineEditDoesNotRestyleTheWholeDocument() throws { + _ = NSApplication.shared + let source = "# Heading\n\n" + (0..<2_000).map { "Plain line \($0)" }.joined(separator: "\n") + let textView = NSTextView() + textView.string = source + let coordinator = MarkdownSourceEditor.Coordinator( + text: .constant(source), documentID: nil, + splitSynchronizer: nil, isSplitSynchronizationEnabled: false + ) + coordinator.textView = textView + coordinator.highlight() + let storage = try XCTUnwrap(textView.textStorage) + let observer = AttributeEditObserver() + storage.delegate = observer + + let range = (textView.string as NSString).range(of: "Plain line 1\n") + storage.replaceCharacters(in: NSRange(location: range.location, length: 5), with: "Other") + observer.attributeRanges.removeAll() + coordinator.highlight() + + XCTAssertFalse(observer.attributeRanges.isEmpty) + XCTAssertTrue(observer.attributeRanges.allSatisfy { $0.length < 100 }) + let headingColor = storage.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor + XCTAssertFalse(headingColor?.isEqual(NSColor.labelColor) == true) + } + + func testIncrementalHighlightingRetainsCodeColorAndHandlesFenceRemoval() throws { + _ = NSApplication.shared + let textView = NSTextView() + textView.string = "# Heading\n\n```text\nfirst\nsecond\n```\n\nTail" + let coordinator = MarkdownSourceEditor.Coordinator( + text: .constant(textView.string), documentID: nil, + splitSynchronizer: nil, isSplitSynchronizationEnabled: false + ) + coordinator.textView = textView + coordinator.highlight() + let storage = try XCTUnwrap(textView.textStorage) + let originalCodeColor = storage.attribute(.foregroundColor, at: (textView.string as NSString).range(of: "second").location, effectiveRange: nil) as? NSColor + storage.replaceCharacters(in: (textView.string as NSString).range(of: "second"), with: "changed") + coordinator.highlight() + let newCodeColor = storage.attribute(.foregroundColor, at: (textView.string as NSString).range(of: "changed").location, effectiveRange: nil) as? NSColor + XCTAssertEqual(originalCodeColor, newCodeColor) + + storage.replaceCharacters(in: (textView.string as NSString).range(of: "```text\n"), with: "") + coordinator.highlight() + let afterFenceRemoval = storage.attribute(.foregroundColor, at: (textView.string as NSString).range(of: "changed").location, effectiveRange: nil) as? NSColor + XCTAssertEqual(afterFenceRemoval, NSColor.labelColor) + } +} + +private final class AttributeEditObserver: NSObject, NSTextStorageDelegate { + var attributeRanges: [NSRange] = [] + + func textStorage( + _ textStorage: NSTextStorage, + didProcessEditing editedMask: NSTextStorageEditActions, + range editedRange: NSRange, + changeInLength delta: Int + ) { + if editedMask.contains(.editedAttributes) { + attributeRanges.append(editedRange) + } + } +} +#endif diff --git a/Tests/Site/signup.test.cjs b/Tests/Site/signup.test.cjs new file mode 100644 index 0000000..1e4de06 --- /dev/null +++ b/Tests/Site/signup.test.cjs @@ -0,0 +1,209 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const test = require("node:test"); +const vm = require("node:vm"); + +function modalHarness() { + const timers = new Map(); + const closeEvents = []; + const requests = []; + const warnings = []; + let nextTimerID = 1; + let focusedElement = null; + + class Element { + constructor() { + this.listeners = new Map(); + this.hidden = false; + this.disabled = false; + this.textContent = ""; + this.value = ""; + this.open = false; + } + addEventListener(name, listener) { + const listeners = this.listeners.get(name) || []; + listeners.push(listener); + this.listeners.set(name, listeners); + } + dispatch(name, event = {}) { + for (const listener of this.listeners.get(name) || []) { + listener({ preventDefault() {}, ...event }); + } + } + querySelector() { return elements.signupButton; } + reset() { elements.emailInput.value = ""; } + checkValidity() { return true; } + showModal() { this.open = true; } + close() { + this.open = false; + // Native dialog close events are queued rather than fired by close(). + closeEvents.push(() => this.dispatch("close")); + } + focus() { focusedElement = this; } + } + + const elements = Object.fromEntries([ + "emailCard", "cardMain", "cardSuccess", "cardError", "notifyForm", + "emailInput", "signupButton", "liveStatus", "cardClose", "cardDismiss", + "emailTitle", "download", + ].map((name) => [name, new Element()])); + elements.cardSuccess.hidden = true; + elements.cardError.hidden = true; + + const context = vm.createContext({ + $: (selector) => elements[selector.slice(1)], + $$: () => [elements.download], + AbortController, + NEWSLETTER_ENDPOINT: "api/subscribe", + DOWNLOAD_ENDPOINT: "api/download", + DOWNLOAD_FILE: "PreviewMD-1.8-12-macOS.dmg", + console: { warn: (...args) => warnings.push(args) }, + fetch: (url, options) => new Promise((resolve, reject) => { + // Deliberately allow completion after abort: responses can already be + // queued when a browser closes the dialog. + requests.push({ url, options, resolve, reject }); + }), + setTimeout: (callback, delay) => { + const id = nextTimerID++; + timers.set(id, { callback, delay }); + return id; + }, + clearTimeout: (id) => timers.delete(id), + }); + const source = fs.readFileSync( + path.join(__dirname, "../../site/main.js"), "utf8" + ); + const modalStart = source.indexOf('const card = $("#emailCard");'); + assert.notEqual(modalStart, -1, "The actual signup implementation must be tested"); + vm.runInContext(source.slice(modalStart), context); + + return { + elements, requests, warnings, timers, + focused: () => focusedElement, + open: () => vm.runInContext("showCard()", context), + close: () => vm.runInContext("dismissCard()", context), + flushCloseEvents: () => { + while (closeEvents.length) closeEvents.shift()(); + }, + submit: (email = "reader@example.com") => { + elements.emailInput.value = email; + elements.notifyForm.dispatch("submit"); + return requests.at(-1); + }, + runTimers: (delay) => { + for (const [id, timer] of [...timers]) { + if (timer.delay !== delay) continue; + timers.delete(id); + timer.callback(); + } + }, + }; +} + +const settle = () => new Promise((resolve) => setImmediate(resolve)); + +test("download opens each time, without waiting for tracking, and focuses the heading", () => { + const h = modalHarness(); + assert.equal(h.elements.emailCard.open, false); + h.elements.download.dispatch("click"); + assert.equal(h.requests[0].url, "api/download"); + h.runTimers(0); + assert.equal(h.elements.emailCard.open, true); + assert.equal(h.focused(), h.elements.emailTitle); + h.close(); + h.flushCloseEvents(); + h.elements.download.dispatch("click"); + h.runTimers(0); + assert.equal(h.elements.emailCard.open, true); +}); + +for (const outcome of ["success", "http error", "network error"]) { + test(`a stale ${outcome} cannot change a reopened form or a newer request`, async () => { + const h = modalHarness(); + h.open(); + const previous = h.submit(); + h.close(); + assert.equal(previous.options.signal.aborted, true); + h.open(); + const current = h.submit("second@example.com"); + // Even a close event queued by the old opening must leave this one alone. + h.flushCloseEvents(); + assert.equal(current.options.signal.aborted, false); + + if (outcome === "network error") previous.reject(new Error("offline")); + else previous.resolve({ ok: outcome === "success", status: 500 }); + await settle(); + + assert.equal(h.elements.emailCard.open, true); + assert.equal(h.elements.cardMain.hidden, false); + assert.equal(h.elements.cardSuccess.hidden, true); + assert.equal(h.elements.cardError.hidden, true); + assert.equal(h.elements.signupButton.disabled, true); + assert.equal(h.elements.signupButton.textContent, "Saving…"); + assert.equal(h.warnings.length, 0); + h.runTimers(1800); + assert.equal(h.elements.emailCard.open, true); + + current.resolve({ ok: true }); + await settle(); + assert.equal(h.elements.cardSuccess.hidden, false); + }); +} + +test("closing a successful signup clears its timer before the next opening", async () => { + const h = modalHarness(); + h.open(); + h.submit().resolve({ ok: true }); + await settle(); + assert.equal(h.elements.cardMain.hidden, true); + assert.equal(h.timers.size, 1); + h.close(); + h.open(); + h.flushCloseEvents(); + assert.equal(h.timers.size, 0); + h.runTimers(1800); + assert.equal(h.elements.emailCard.open, true); + assert.equal(h.elements.cardMain.hidden, false); +}); + +test("native closure also resets and aborts an outstanding signup", async () => { + const h = modalHarness(); + h.open(); + const request = h.submit(); + h.elements.emailCard.close(); + h.flushCloseEvents(); + assert.equal(request.options.signal.aborted, true); + assert.equal(h.elements.emailInput.value, ""); + assert.equal(h.elements.signupButton.disabled, false); + request.resolve({ ok: true }); + await settle(); + assert.equal(h.elements.cardSuccess.hidden, true); +}); + +test("a current failure remains retryable and a current success closes normally", async () => { + const h = modalHarness(); + h.open(); + h.submit().resolve({ ok: false, status: 500 }); + await settle(); + assert.equal(h.elements.cardError.hidden, false); + assert.equal(h.elements.signupButton.disabled, false); + assert.equal(h.warnings.length, 1); + h.submit().resolve({ ok: true }); + await settle(); + assert.equal(h.elements.cardError.hidden, true); + assert.equal(h.elements.cardSuccess.hidden, false); + h.runTimers(1800); + assert.equal(h.elements.emailCard.open, false); + assert.equal(h.elements.cardSuccess.hidden, true); +}); + +test("repeated submits cannot create competing requests within one opening", () => { + const h = modalHarness(); + h.open(); + h.submit(); + h.submit(); + assert.equal(h.requests.length, 1); +}); diff --git a/assets/screenshots/previewmd-folder-unavailable.png b/assets/screenshots/previewmd-folder-unavailable.png new file mode 100644 index 0000000..2ed4ac7 Binary files /dev/null and b/assets/screenshots/previewmd-folder-unavailable.png differ diff --git a/assets/screenshots/previewmd-native-layout.png b/assets/screenshots/previewmd-native-layout.png new file mode 100644 index 0000000..911ef91 Binary files /dev/null and b/assets/screenshots/previewmd-native-layout.png differ diff --git a/assets/screenshots/previewmd-signup-focus.png b/assets/screenshots/previewmd-signup-focus.png new file mode 100644 index 0000000..277172d Binary files /dev/null and b/assets/screenshots/previewmd-signup-focus.png differ diff --git a/docs/REGRESSION_AUDIT.md b/docs/REGRESSION_AUDIT.md new file mode 100644 index 0000000..05f80ef --- /dev/null +++ b/docs/REGRESSION_AUDIT.md @@ -0,0 +1,143 @@ +# Document and workspace regression audit + +The October 2026 audit prioritizes document integrity, then editing latency, +workspace consistency, export structure, and signup lifecycle. Each fix is +covered by a focused regression rather than a snapshot of the implementation. + +| Problem | Repair and regression coverage | +| --- | --- | +| PDF/printing used an earlier rich-edit snapshot and restored old text | Flush current edits before export; preserve current content, layout, and reading position on restoration. `RendererAuditTests` checks actual PDF text and restored editor content. | +| An unrelated rich edit collapsed blank lines inside code and metadata | Normalize separators between blocks only. `EditorSerializationRegressionTests` covers code, frontmatter, and copied fragments. | +| Literal paragraph markers became headings, quotes, lists, or strikeout | Escape paragraph syntax in context while preserving deliberate formatting. Serialization tests round-trip literal markers and inline-code spaces. | +| Atomic saves replaced symbolic links instead of updating their targets | Resolve the destination before replacement and use one document tab per canonical path. `DocumentStateRegressionTests` checks target/link integrity and Save As conflicts. | +| Inspector headings disagreed with the rendered document | Use the bundled parser's heading grammar and rendered IDs; publish rich changes after their content update. Renderer and bridge-order tests cover Setext headings, indentation, nested quotes, and long fences. | +| Folder search retained discarded or moved in-memory content | Refresh after close, reload, and Save As. Document-state tests verify results against the remaining tabs and disk. | +| Missing folders repeatedly opened background error dialogs | Keep a recoverable inline folder status; automatic checks avoid modal alerts. Tests cover disappearance and recovery. | +| DOCX ordered lists ignored starts and independent restarts | Give each list its own numbering instance and level-specific start override. `DOCXDocumentWriterTests` inspects document and numbering XML, including nested lists and zero starts. | +| A previous signup request or timer changed a reopened form | Abort requests, guard generations, cancel timers, and reset on dismissal. `Tests/Site/signup.test.cjs` exercises delayed success/failure and queued native close events against the actual signup code. | +| Packaging could copy an old product after a successful build with a newer SwiftPM | Ask SwiftPM for the output directory with the same build options and verify both architectures before packaging. Also keep the linked SDK separate from the deployment target and validate both in each executable slice. CI builds and verifies the complete bundle. | + +## GitHub reports + +- [#24: large-document input lag](https://github.com/ashtree74/PreviewMD/issues/24): + source highlighting recolors the affected logical lines and keeps full + passes for changes to code-fence boundaries. Rich serialization caches unchanged + blocks; split position work runs only when needed. Source-only edits defer + hidden DOM rebuilding, and disk fingerprints/diffs run away from the main + actor. Export and visible-editor flushes synchronize pending rendering before + using the WebView. +- [PR #25](https://github.com/ashtree74/PreviewMD/pull/25) identifies the reading + width transition race. Observe actual width changes and coalesce relayout on + animation frames, including the final transition width. +- [PR #26](https://github.com/ashtree74/PreviewMD/pull/26) identifies the leading + gutter overflow. Account for that gutter in the wide table sizer's width. + The report and CSS correction are credited to **jedrzejsieracki**. +- [#27](https://github.com/ashtree74/PreviewMD/issues/27) proposes a different + expanded-table width policy. It remains a product decision; these fixes + preserve the existing expansion policy. +- [#22](https://github.com/ashtree74/PreviewMD/issues/22) and + [PR #28](https://github.com/ashtree74/PreviewMD/pull/28) concern the Windows + port and are independent of the macOS regressions. + +## Performance evidence and limits + +On the public #24 attachment (126,669 UTF-16 units, 276 rendered top-level +blocks), focused before/after harnesses measured: + +| Operation | Before | After | +| --- | --- | --- | +| Native source highlighting, median of ten single-character insertions | 9.32 ms | 2.17 ms | +| Rich serialization flush after the first cache fill | 6–8 ms | 0–1 ms | +| First rich flush with a cold cache | 11 ms | 5 ms | + +These are component timings on macOS 27, not end-to-end keystroke latency. +The source harness excludes window layout; the rich harness excludes the +native bridge and uses a 1 ms timer. The report stays open for confirmation of +the complete user workflow on the reporter's Mac. + +## Verification + +```bash +swift test +python3 -m unittest discover -s site -p 'test_*.py' +node --test Tests/Site/signup.test.cjs +./scripts/build-app.sh +``` + +Use the complete bundle for UI smoke checks and verify both executables with +`lipo -info`. Check initial empty state, source/document/split transitions, +inspector navigation, focus-mode restoration, and offline showcase rendering. +On the site, opening signup must focus the static heading without a focus ring; +deliberate keyboard navigation must visibly focus interactive controls. + +Verified locally on October 6, 2026: + +- 174 Swift tests passed (169 XCTest and 5 Swift Testing); the eight workspace + layout tests also passed after the final folder-status presentation changes. +- 9 server tests and 8 signup lifecycle tests passed. +- The current application and embedded Quick Look executable both contain + `arm64` and `x86_64`, target macOS 14, and pass strict signature verification. + Bundled renderer sources match the current checkout. +- Live application checks covered the initial empty state, opening a folder + without opening its documents, current source saves, matching preview and + outline headings, split/focus restoration, final-tab closure, and nonmodal + folder disappearance/recovery in the tree and search views. +- Live site checks covered download-triggered signup, static initial focus, + visible keyboard focus, and clean dismissal/reopening. + +Visual evidence uses disposable test content. The folder-status capture below +predates the SDK correction described next; the corrected native-layout capture +shows the final appearance. + +![Recoverable folder status](../assets/screenshots/previewmd-folder-unavailable.png) + +![Signup initial focus](../assets/screenshots/previewmd-signup-focus.png) + +## Native appearance regression caught after the audit + +The first current-product bundle had `minOS 14.0 / SDK 14.0` in both application +slices, while the previous installed application had `minOS 14.0 / SDK 26.5`. +Its source was compiled with SDK 27.0, but Swift Build's isolated linker +environment emitted the deployment version as the linked SDK. This changed +native sidebar/toolbar styling and stretched the reading-width panel across +the preview. Sidebar controls and the panel's view code had not changed. + +The build now passes the selected SDK explicitly and supplies the complete +linker platform tuple: macOS, minimum 14.0, and the selected SDK version. It +selects Swift Build when available, using its Swift driver forwarding; older +toolchains use the Xcode backend with clang's forwarding syntax. This prevents +differences between the Xcode 26 and 27 defaults from changing linker arguments. +It validates `LC_BUILD_VERSION` plus both architectures before replacing the +application and after building Quick Look. The selected SDK version comes from +its own metadata, including when `PREVIEWMD_SDKROOT` is supplied. + +The rebuilt application and extension both report `minOS 14.0 / SDK 27.0` and +pass strict signature verification. Live comparison confirms the system +sidebar/toolbar appearance and compact centered reading-width panel are +restored, including Focus entry and Escape restoration. Apple describes this +SDK-dependent adoption of native appearance in +[Adopting Liquid Glass](https://developer.apple.com/documentation/technologyoverviews/adopting-liquid-glass). + +![Restored native layout](../assets/screenshots/previewmd-native-layout.png) + +## Follow-up order + +1. Confirm the full large-document editing workflow with the reporter of #24; + the measured component improvements alone do not close that report. +2. Decide the expanded-table width policy proposed in #27 and give any changed + policy its own regression coverage. +3. Review the independent Windows work in #22 / PR #28 separately from the + supported macOS application. + +The audit's initial local build was ad-hoc signed. The final maintainer release +is PreviewMD 1.8 (12), signed with Developer ID and Hardened Runtime. Apple +accepted both the application and final DMG; each has a stapled ticket and +passes Gatekeeper as `Notarized Developer ID`. The application inside the final +read-only DMG was checked independently for signatures, versions, architectures, +SDK metadata, bundled offline resources, licenses, and installation layout. + +The distributable DMG is tracked in `site/`, with matching download/version +metadata and a bumped JavaScript cache key. Submission IDs, artifact sizes and +SHA-256 digests are recorded in +[the release receipt](releases/PreviewMD-1.8-12.json). Production website +deployment remains separate. diff --git a/docs/releases/PreviewMD-1.8-12.json b/docs/releases/PreviewMD-1.8-12.json new file mode 100644 index 0000000..e3c57a5 --- /dev/null +++ b/docs/releases/PreviewMD-1.8-12.json @@ -0,0 +1,45 @@ +{ + "product": "PreviewMD", + "version": "1.8", + "build": "12", + "release_date": "2026-10-06", + "bundle_identifier": "pl.jesion.previewmd", + "team_identifier": "4NZF9USX28", + "signing_identity": "Developer ID Application: Astrography Sp. z o.o. (4NZF9USX28)", + "architectures": [ + "arm64", + "x86_64" + ], + "minimum_macos": "14.0", + "sdk": "27.0", + "hardened_runtime": true, + "notarization": { + "application": { + "submission_id": "561f54d2-cace-4732-aa60-569e2f2b9cdb", + "status": "Accepted", + "ticket_stapled": true + }, + "dmg": { + "submission_id": "efdec2e8-a377-4607-8bd4-3dea9ee9df78", + "status": "Accepted", + "ticket_stapled": true + } + }, + "gatekeeper": { + "application": "Notarized Developer ID", + "dmg": "Notarized Developer ID" + }, + "artifacts": [ + { + "filename": "PreviewMD-1.8-12-macOS.dmg", + "size_bytes": 7269630, + "sha256": "616617e978e5552e54aa2c444e17a5b05b13a0072a933e2e3b113d195ba2d29f" + }, + { + "filename": "PreviewMD-1.8-12-macOS.zip", + "size_bytes": 7022235, + "sha256": "4c7f2f6a6eb3d9640be182f42466ca1383492fa42e535ef70323cc45ebc9737c" + } + ], + "repository_installer": "site/PreviewMD-1.8-12-macOS.dmg" +} diff --git a/scripts/Info.plist b/scripts/Info.plist index ae32e0c..3d6de1d 100644 --- a/scripts/Info.plist +++ b/scripts/Info.plist @@ -19,9 +19,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.7 + 1.8 CFBundleVersion - 11 + 12 NSHumanReadableCopyright © 2026 Adam Jesionkiewicz (adam@jesion.pl) LSMinimumSystemVersion diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 9567182..370d38d 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -5,7 +5,6 @@ project_dir="$(cd "$(dirname "$0")/.." && pwd)" app_dir="$project_dir/dist/PreviewMD.app" contents_dir="$app_dir/Contents" legal_dir="$contents_dir/Resources/Legal" -build_dir="$project_dir/.build/apple/Products/Release" quicklook_dir="$contents_dir/PlugIns/PreviewMDQuickLook.appex" quicklook_contents_dir="$quicklook_dir/Contents" quicklook_build_dir="$project_dir/.build/quicklook" @@ -20,11 +19,51 @@ export SDKROOT="${PREVIEWMD_SDKROOT:-$(xcrun --sdk macosx --show-sdk-path)}" export SWIFTPM_MODULECACHE_OVERRIDE="$project_dir/.build/ModuleCache" export CLANG_MODULE_CACHE_PATH="$project_dir/.build/ModuleCache" -swift build \ - -c release \ - --arch arm64 \ - --arch x86_64 \ - --disable-sandbox +sdk_version="$(plutil -extract Version raw -o - "$SDKROOT/SDKSettings.json")" +# The deployment target and the linked SDK are different values. SwiftPM's +# Swift Build backend can emit the deployment version as the SDK version, +# making native controls adopt the legacy appearance on newer macOS releases. +build_options=( + -c release --arch arm64 --arch x86_64 --disable-sandbox --sdk "$SDKROOT" +) +# Swift Build links through swiftc, which forwards -Xlinker itself. The older +# Xcode backend puts these arguments directly into clang's OTHER_LDFLAGS. +# Select the available backend explicitly and use its driver's flag syntax. +swift_build_help="$(swift build --help)" +if grep -Eq '^[[:space:]]+swiftbuild[[:space:]]' <<< "$swift_build_help"; then + build_options+=( + --build-system swiftbuild + -Xlinker -platform_version -Xlinker macos + -Xlinker 14.0 -Xlinker "$sdk_version" + ) +else + build_options+=( + --build-system xcode + -Xlinker "-Wl,-platform_version,macos,14.0,$sdk_version" + ) +fi + +verify_build_version() { + local executable_path="$1" + local architecture build_metadata actual_minos actual_sdk + for architecture in arm64 x86_64; do + lipo "$executable_path" -verify_arch "$architecture" + build_metadata="$(xcrun vtool -arch "$architecture" -show-build "$executable_path")" + actual_minos="$(awk '$1 == "minos" { print $2 }' <<< "$build_metadata")" + actual_sdk="$(awk '$1 == "sdk" { print $2 }' <<< "$build_metadata")" + if [[ "$actual_minos" != "14.0" || "$actual_sdk" != "$sdk_version" ]]; then + print -u2 "Invalid build version in $executable_path ($architecture): macOS $actual_minos, SDK $actual_sdk; expected macOS 14.0, SDK $sdk_version" + return 1 + fi + done +} + +swift build "${build_options[@]}" +# SwiftPM's output directory differs between toolchain/build-system versions. +# Ask the same build configuration instead of accidentally packaging an older +# product left in .build/apple/Products/Release. +build_dir="$(swift build "${build_options[@]}" --show-bin-path)" +verify_build_version "$build_dir/PreviewMD" rm -rf "$app_dir" "$quicklook_build_dir" mkdir -p \ @@ -66,6 +105,7 @@ lipo -create \ "$quicklook_build_dir/PreviewMDQuickLook-arm64" \ "$quicklook_build_dir/PreviewMDQuickLook-x86_64" \ -output "$quicklook_contents_dir/MacOS/PreviewMDQuickLook" +verify_build_version "$quicklook_contents_dir/MacOS/PreviewMDQuickLook" chmod +x "$quicklook_contents_dir/MacOS/PreviewMDQuickLook" cp "scripts/QuickLook-Info.plist" "$quicklook_contents_dir/Info.plist" diff --git a/site/PreviewMD-1.7-11-macOS.dmg b/site/PreviewMD-1.7-11-macOS.dmg deleted file mode 100644 index 8fe8353..0000000 Binary files a/site/PreviewMD-1.7-11-macOS.dmg and /dev/null differ diff --git a/site/PreviewMD-1.8-12-macOS.dmg b/site/PreviewMD-1.8-12-macOS.dmg new file mode 100644 index 0000000..cd36c23 Binary files /dev/null and b/site/PreviewMD-1.8-12-macOS.dmg differ diff --git a/site/index.html b/site/index.html index 7023fe2..d744e34 100644 --- a/site/index.html +++ b/site/index.html @@ -4,7 +4,7 @@ PreviewMD — Plain text, properly typeset. - + @@ -18,10 +18,10 @@ - + - + @@ -42,8 +42,8 @@

A native Markdown reader and editor for the Mac.

- Download for macOS — free -

v1.7 · ~6.8 MB · Universal 2 · notarized

+ Download for macOS — free +

v1.8 · ~7.3 MB · Universal 2 · notarized

@@ -95,7 +95,7 @@

Plain text, properly typeset.

macOS14 or later BinaryUniversal 2 - Size~6.8 MB + Size~7.3 MB @@ -110,7 +110,7 @@

Plain text, properly typeset.

E = mc2

@@ -130,12 +130,12 @@

Plain text, properly typeset.

|--------|-------------| | macOS | 14 or later | | Binary | Universal 2 | -| Size | ~6.8 MB | +| Size | ~7.3 MB |
- [x] Edit in the typeset page
 - [x] Source & split editing
 - [x] Tables, diagrams, math & code
$E = mc^2$
-
[Download for macOS — free](PreviewMD-1.7-11-macOS.dmg)
+
[Download for macOS — free](PreviewMD-1.8-12-macOS.dmg)
@@ -345,7 +345,7 @@

How PreviewMD is made

Native, all the way down

-

The shell is 100% SwiftUI — a real macOS toolbar, a real sidebar, real keyboard shortcuts. On this Mac, this very page is set in the same system face as the app’s chrome, because the app is the system’s chrome. It launches fast, weighs ~6.8 MB, and behaves the way Mac software should.

+

The shell is 100% SwiftUI — a real macOS toolbar, a real sidebar, real keyboard shortcuts. On this Mac, this very page is set in the same system face as the app’s chrome, because the app is the system’s chrome. It launches fast, weighs ~7.3 MB, and behaves the way Mac software should.

Sealed like a document

@@ -364,8 +364,8 @@

Sealed like a document

@@ -389,7 +389,7 @@

Sealed like a document

- +