From 2864801c0dc21dff2f0209ea636e68fef6142977 Mon Sep 17 00:00:00 2001 From: Assaf Inbal Date: Thu, 26 Nov 2026 09:07:21 +0200 Subject: [PATCH 1/2] feat: HTML comments are hidden instead of shown as text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A line starting with `` draws nothing, as on GitHub; an unclosed comment runs to the end of the document. Definitions inside a comment are not taken. Inline `` in a paragraph, heading or cell is dropped too (one space kept between the words around it); an unclosed one stays text. HTMLBlockSyntax.swift is the new home of block-level HTML recognizers. --- QuickMD/QuickMD.xcodeproj/project.pbxproj | 10 +++ QuickMD/QuickMD/HTMLBlockSyntax.swift | 71 ++++++++++++++++++ QuickMD/QuickMD/MarkdownBlockParser.swift | 26 ++++++- QuickMD/QuickMD/MarkdownRenderer.swift | 18 +++++ QuickMD/QuickMDTests/HTMLBlockTests.swift | 87 +++++++++++++++++++++++ QuickMD/QuickMDTests/HTMLImageTests.swift | 2 +- 6 files changed, 212 insertions(+), 2 deletions(-) create mode 100644 QuickMD/QuickMD/HTMLBlockSyntax.swift create mode 100644 QuickMD/QuickMDTests/HTMLBlockTests.swift diff --git a/QuickMD/QuickMD.xcodeproj/project.pbxproj b/QuickMD/QuickMD.xcodeproj/project.pbxproj index 418175f..712a1f2 100644 --- a/QuickMD/QuickMD.xcodeproj/project.pbxproj +++ b/QuickMD/QuickMD.xcodeproj/project.pbxproj @@ -133,7 +133,10 @@ A1B2C3D401000482 /* InlineEmphasis.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000480 /* InlineEmphasis.swift */; }; A1B2C3D4010000E0 /* HTMLImageSyntax.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000E0 /* HTMLImageSyntax.swift */; }; A1B2C3D4010000E1 /* HTMLImageSyntax.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000E0 /* HTMLImageSyntax.swift */; }; + A1B2C3D4010009E0 /* HTMLBlockSyntax.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000009E0 /* HTMLBlockSyntax.swift */; }; + A1B2C3D4010009E1 /* HTMLBlockSyntax.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000009E0 /* HTMLBlockSyntax.swift */; }; A1B2C3D4010000E2 /* HTMLImageTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000E1 /* HTMLImageTests.swift */; }; + A1B2C3D4010009E2 /* HTMLBlockTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000009E2 /* HTMLBlockTests.swift */; }; A1B2C3D40100004D /* FileWatchManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000049 /* FileWatchManager.swift */; }; A1B2C3D40100004E /* ExternalEditorManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000004A /* ExternalEditorManager.swift */; }; A1B2C3D40100004F /* ExternalEditorPickerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000004B /* ExternalEditorPickerView.swift */; }; @@ -394,7 +397,9 @@ A1B2C3D4000000A0 /* InlineSyntaxScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InlineSyntaxScanner.swift; sourceTree = ""; }; A1B2C3D400000480 /* InlineEmphasis.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InlineEmphasis.swift; sourceTree = ""; }; A1B2C3D4000000E0 /* HTMLImageSyntax.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLImageSyntax.swift; sourceTree = ""; }; + A1B2C3D4000009E0 /* HTMLBlockSyntax.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLBlockSyntax.swift; sourceTree = ""; }; A1B2C3D4000000E1 /* HTMLImageTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLImageTests.swift; sourceTree = ""; }; + A1B2C3D4000009E2 /* HTMLBlockTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLBlockTests.swift; sourceTree = ""; }; A1B2C3D400000049 /* FileWatchManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileWatchManager.swift; sourceTree = ""; }; A1B2C3D40000004A /* ExternalEditorManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExternalEditorManager.swift; sourceTree = ""; }; A1B2C3D40000004B /* ExternalEditorPickerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExternalEditorPickerView.swift; sourceTree = ""; }; @@ -460,6 +465,7 @@ A1B2C3D4000004A0 /* FootnoteTests.swift */, A1B2C3D400000082 /* ImageLoadingTests.swift */, A1B2C3D4000000E1 /* HTMLImageTests.swift */, + A1B2C3D4000009E2 /* HTMLBlockTests.swift */, A1B2C3D4000000F0 /* HeadingLayoutTests.swift */, A1B2C3D4000001B2 /* TableTextTests.swift */, A1B2C3D400000221 /* FrontMatterTests.swift */, @@ -535,6 +541,7 @@ A1B2C3D4000000A0 /* InlineSyntaxScanner.swift */, A1B2C3D400000480 /* InlineEmphasis.swift */, A1B2C3D4000000E0 /* HTMLImageSyntax.swift */, + A1B2C3D4000009E0 /* HTMLBlockSyntax.swift */, A1B2C3D400000049 /* FileWatchManager.swift */, A1B2C3D40000004A /* ExternalEditorManager.swift */, A1B2C3D403000004 /* Views */, @@ -799,6 +806,7 @@ A1B2C3D4010000A0 /* InlineSyntaxScanner.swift in Sources */, A1B2C3D401000481 /* InlineEmphasis.swift in Sources */, A1B2C3D4010000E0 /* HTMLImageSyntax.swift in Sources */, + A1B2C3D4010009E0 /* HTMLBlockSyntax.swift in Sources */, A1B2C3D40100004D /* FileWatchManager.swift in Sources */, A1B2C3D40100004E /* ExternalEditorManager.swift in Sources */, A1B2C3D40100004F /* ExternalEditorPickerView.swift in Sources */, @@ -867,6 +875,7 @@ A1B2C3D4010000A1 /* InlineSyntaxScanner.swift in Sources (Tests) */, A1B2C3D401000482 /* InlineEmphasis.swift in Sources (Tests) */, A1B2C3D4010000E1 /* HTMLImageSyntax.swift in Sources (Tests) */, + A1B2C3D4010009E1 /* HTMLBlockSyntax.swift in Sources (Tests) */, A1B2C3D401000051 /* FileWatcherTests.swift in Sources */, A1B2C3D401000052 /* FileWatchManager.swift in Sources (Tests) */, A1B2C3D401000053 /* ExternalEditorManager.swift in Sources (Tests) */, @@ -926,6 +935,7 @@ A1B2C3D401000083 /* ImageLoader.swift in Sources (Tests) */, A1B2C3D401000084 /* ImageLoadingTests.swift in Sources */, A1B2C3D4010000E2 /* HTMLImageTests.swift in Sources */, + A1B2C3D4010009E2 /* HTMLBlockTests.swift in Sources */, A1B2C3D4010000C1 /* DocumentSelection.swift in Sources (Tests) */, A1B2C3D4010001C1 /* SelectionRows.swift in Sources (Tests) */, A1B2C3D4010002A1 /* VerticalRhythm.swift in Sources (Tests) */, diff --git a/QuickMD/QuickMD/HTMLBlockSyntax.swift b/QuickMD/QuickMD/HTMLBlockSyntax.swift new file mode 100644 index 0000000..f69a0c6 --- /dev/null +++ b/QuickMD/QuickMD/HTMLBlockSyntax.swift @@ -0,0 +1,71 @@ +import Foundation + +// MARK: - HTML in Markdown (v1.17) +// +// QuickMD draws documents natively and never hands HTML to a web view, so +// raw HTML is not rendered by a browser engine. Instead, a few HTML +// constructs that READMEs actually use are recognised here and turned into +// the parser's own blocks. Anything not recognised stays text, as before. +// +// This file is where block-level HTML syntax lives: one entry point per +// construct, all built on the same small helpers. To support another tag, +// add its recognizer here and call it from `MarkdownBlockParser.parse` (see +// "HTML blocks" there). +// +// * Comments (``, CommonMark HTML block kind 2, and inline raw +// HTML): drawn as nothing, like GitHub. +// +// `HTMLImageSyntax` (the `` line idiom) predates this file and keeps +// its own byte scanner. + +enum HTMLBlockSyntax { + + // MARK: Comments + + /// The line after the HTML comment block that starts on `lines[index]`, + /// or nil when no comment block starts there. + /// + /// CommonMark HTML block kind 2: the line, indented at most three + /// spaces, starts with `` (the start line included: ``, ``). + /// A comment that never closes runs to the end of the document, as it + /// does on GitHub. + static func commentBlockEnd(in lines: [String], at index: Int) -> Int? { + let line = lines[index] + guard let start = commentStart(in: line) else { return nil } + // The closer may overlap the opener's dashes (``, ``). + let afterBang = line.utf8.index(start, offsetBy: 2) + if line[afterBang...].contains("-->") { return index + 1 } + var next = index + 1 + while next < lines.count { + if lines[next].contains("-->") { return next + 1 } + next += 1 + } + return lines.count + } + + /// Where ``, ``, or ``. An unclosed `") else { return nil } + return text[closer.upperBound...] + } +} diff --git a/QuickMD/QuickMD/MarkdownBlockParser.swift b/QuickMD/QuickMD/MarkdownBlockParser.swift index 0199d2c..54c96f3 100644 --- a/QuickMD/QuickMD/MarkdownBlockParser.swift +++ b/QuickMD/QuickMD/MarkdownBlockParser.swift @@ -454,6 +454,19 @@ struct MarkdownBlockParser: Sendable { continue } + // HTML blocks (`HTMLBlockSyntax`) — after code and math, whose + // lines are verbatim, before every other block start. + // + // A comment (``, kind 2) is drawn as nothing, as on + // GitHub. It may interrupt a paragraph and ends one; at the + // margin it ends a list, like any block. + if let end = HTMLBlockSyntax.commentBlockEnd(in: lines, at: i) { + flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) + _ = nesting.block(startingAt: line) + i = end + continue + } + // ATX headers (# H1 ... ###### H6) — detect at block level let nsRange = NSRange(line.startIndex..., in: line) if let match = Self.headerRegex.firstMatch(in: line, range: nsRange), @@ -1699,9 +1712,12 @@ struct MarkdownBlockParser: Sendable { private var fence: Fence? /// Index of the line that closes the open `$$` block. private var mathCloses: Int? + /// An HTML comment block (`HTMLBlockSyntax.commentBlockEnd`) is open: + /// a definition commented out is not one. + private var inComment = false /// Inside such a block: the next line is its text or its closing line. - var isOpen: Bool { fence != nil || mathCloses != nil } + var isOpen: Bool { fence != nil || mathCloses != nil || inComment } /// Whether the line `index` (its `markerLine`) opens, continues or /// closes such a block. `nextMath` is `nextMathLines` of the lines and @@ -1717,6 +1733,14 @@ struct MarkdownBlockParser: Sendable { if index >= closes { mathCloses = nil } return true } + if inComment { + if marker.contains("-->") { inComment = false } + return true + } + if marker.hasPrefix("") + return true + } if let opening = MarkdownBlockParser.fenceOpening(marker) { fence = opening return true diff --git a/QuickMD/QuickMD/MarkdownRenderer.swift b/QuickMD/QuickMD/MarkdownRenderer.swift index e1ac0f3..5f8f6cb 100644 --- a/QuickMD/QuickMD/MarkdownRenderer.swift +++ b/QuickMD/QuickMD/MarkdownRenderer.swift @@ -1120,6 +1120,8 @@ struct MarkdownRenderer: Sendable { // (`escapesDisabled`) is front matter, which has no math. var formulas = escapesDisabled || formulasDisabled ? InlineMathSegmenter.Cursor() : InlineMathSegmenter.Cursor(text, codeSpans: parse.codeSpans, entities: !entitiesLiteral) + // An inline comment found no `-->` (see the `<` case). + var commentCloserMissing = false while let byte = remaining.utf8.first { var plainLimit = remaining.endIndex @@ -1181,6 +1183,22 @@ struct MarkdownRenderer: Sendable { } continue case UInt8(ascii: "<"): + // An HTML comment is drawn as nothing (GitHub). Once one + // finds no `-->`, no later ` b` reads "a b", one space, as a + // browser collapses it. + if remaining.startIndex > text.startIndex, + text[text.index(before: remaining.startIndex)] == " " { + rest = rest.drop(while: { $0 == " " }) + } + remaining = rest + continue + } + commentCloserMissing = true + } if let (attr, rest) = tryParseAngleAutolink(remaining) { parse.append(.atom(attr, .body)) remaining = rest diff --git a/QuickMD/QuickMDTests/HTMLBlockTests.swift b/QuickMD/QuickMDTests/HTMLBlockTests.swift new file mode 100644 index 0000000..4de6319 --- /dev/null +++ b/QuickMD/QuickMDTests/HTMLBlockTests.swift @@ -0,0 +1,87 @@ +import XCTest +import SwiftUI +import AppKit + +/// HTML in Markdown (`HTMLBlockSyntax`): constructs QuickMD recognises and +/// draws natively instead of showing their tags as text. +final class HTMLBlockTests: XCTestCase { + + private func parse(_ markdown: String) -> [MarkdownBlock] { + MarkdownBlockParser(theme: MarkdownTheme.cached(for: .light)).parse(markdown) + } + + private func plainText(_ block: MarkdownBlock) -> String? { + if case .text(let attr) = block.content { + return String(attr.characters).trimmingCharacters(in: .whitespacesAndNewlines) + } + return nil + } + + private func texts(_ blocks: [MarkdownBlock]) -> [String] { + blocks.compactMap(plainText) + } + + // MARK: - Comments + + func testOneLineCommentDrawsNothing() { + let blocks = parse("before\n\n\n\nafter") + XCTAssertEqual(texts(blocks), ["before", "after"]) + } + + func testMultiLineCommentDrawsNothing() { + let blocks = parse("before\n\n\n\nafter") + XCTAssertEqual(texts(blocks), ["before", "after"]) + XCTAssertFalse(blocks.contains { if case .heading = $0.content { return true } else { return false } }) + } + + func testCommentInterruptsAParagraph() { + let blocks = parse("one\n\ntwo") + XCTAssertEqual(texts(blocks), ["one", "two"]) + } + + func testEmptyCommentFormsClose() { + XCTAssertEqual(texts(parse("\nafter")), ["after"]) + XCTAssertEqual(texts(parse("\nafter")), ["after"]) + } + + func testUnclosedCommentRunsToTheEnd() { + XCTAssertEqual(texts(parse("before\n\n") + XCTAssertFalse(texts(blocks).isEmpty) + } + + func testCommentInsideFenceIsCode() { + let blocks = parse("```\n\n```") + guard case .codeBlock(let code, _)? = blocks.first?.content else { return XCTFail("no code block") } + XCTAssertEqual(code, "") + } + + func testDefinitionsInsideACommentAreNotDefinitions() { + let blocks = parse("\n\ntext") + XCTAssertEqual(texts(blocks), ["text"], "no footnotes section from a commented-out definition") + } + + func testInlineCommentIsHidden() { + XCTAssertEqual(texts(parse("a b")), ["a b"]) + XCTAssertEqual(texts(parse("ab")), ["ab"]) + XCTAssertEqual(texts(parse("**bold** text")), ["bold text"]) + } + + func testInlineUnclosedCommentIsText() { + XCTAssertEqual(texts(parse("a `")), [""]) + } + + func testManyUnclosedInlineCommentsStayText() { + let line = String(repeating: "", "", "< img src=a.png>", "", + "", "< img src=a.png>", "", "\"x\"", "", "
", "

![a](x.png)

"] { let blocks = parse(line) XCTAssertTrue(images(blocks).isEmpty, line) From 418c09bd5e9d997ce8f2f4be6a326424a086fb46 Mon Sep 17 00:00:00 2001 From: Assaf Inbal Date: Thu, 26 Nov 2026 10:00:44 +0200 Subject: [PATCH 2/2] feat:
blocks collapse and expand `
` / `
` with a `` (on its own line, on the opening tag's line, or over several lines) is a collapsible section: the summary row has a disclosure triangle (GitHub's filled one), and a click on the triangle or the caption shows or hides the Markdown blocks inside. Both show the pointing hand and say "Expand" or "Collapse". Nesting works; a `
` without a summary reads "Details"; an unclosed one runs to the end of the document; a stray `
` draws nothing. Simple inline tags in a summary (``, ``, ``, ...) become Markdown, others are dropped. Print and PDF show every section open. Design, so more HTML tags can follow: - HTMLBlockSyntax has a generic tag lexer and a registry of container tags (`containerTags` + `HTMLContainerKind`); `
` is its first entry. - The parser keeps one flat block list and tags each block with the containers it is inside (`MarkdownBlock.containers`); the summary row is a text block with `opensContainer`, so it is measured, searched, selected and copied like any text. Its caption carries a toggle link. - The row is [triangle][caption]: the measurer wraps the caption at the column less the triangle's (`BlockLayout.ContainerSummary`), and the triangle is a small AppKit view beside the text view, never over it, so it owns its click, cursor and tooltip. - The view hands the list a `ContainerPresentation`: the blocks of closed containers left out, the height table cut to match and the spacing after a hidden run derived again. Search, the table of contents and anchors still see every block; jumping to a hidden one opens the containers around it first. Toggles survive a re-parse. --- QuickMD/QuickMD/BlockHeightMeasurer.swift | 39 +- QuickMD/QuickMD/DocumentSelection.swift | 2 + QuickMD/QuickMD/HTMLBlockSyntax.swift | 426 ++++++++++++++++++- QuickMD/QuickMD/MarkdownBlock.swift | 39 +- QuickMD/QuickMD/MarkdownBlockParser.swift | 116 +++++ QuickMD/QuickMD/MarkdownExport.swift | 18 +- QuickMD/QuickMD/MarkdownRenderer.swift | 15 + QuickMD/QuickMD/MarkdownView.swift | 172 +++++++- QuickMD/QuickMD/Views/TextBlockView.swift | 26 +- QuickMD/QuickMD/Views/VirtualBlockList.swift | 9 +- QuickMD/QuickMDTests/HTMLBlockTests.swift | 269 ++++++++++++ QuickMD/QuickMDTests/HTMLImageTests.swift | 2 +- 12 files changed, 1113 insertions(+), 20 deletions(-) diff --git a/QuickMD/QuickMD/BlockHeightMeasurer.swift b/QuickMD/QuickMD/BlockHeightMeasurer.swift index 66cdcc7..313c6fd 100644 --- a/QuickMD/QuickMD/BlockHeightMeasurer.swift +++ b/QuickMD/QuickMD/BlockHeightMeasurer.swift @@ -212,6 +212,32 @@ enum BlockLayout { } } + // MARK: Container summaries (`
`) + + /// A `
` summary row (`MarkdownBlock.opensContainer`): the + /// disclosure control, then the caption's text view beside it — never + /// under it, so the control is no part of the text (its cursor, clicks + /// and tooltip are its own). The measurer wraps the caption at + /// `textWidth`, the view gives the control `controlWidth`. + enum ContainerSummary { + /// The control's column at 100 % zoom. + static let controlWidth: CGFloat = 18 + + static func controlWidth(fontScale: CGFloat) -> CGFloat { controlWidth * fontScale } + + /// The width the caption wraps at: the column less the control. + static func textWidth(contentWidth: CGFloat, fontScale: CGFloat) -> CGFloat { + BlockLayout.clampedWidth(contentWidth - min(controlWidth(fontScale: fontScale), contentWidth / 2)) + } + + /// The text width of `block`'s row: the summary's, or `textWidth` + /// for any other text row. + static func textWidth(of block: MarkdownBlock, textWidth: CGFloat, contentWidth: CGFloat, + fontScale: CGFloat) -> CGFloat { + block.opensContainer == nil ? textWidth : self.textWidth(contentWidth: contentWidth, fontScale: fontScale) + } + } + // MARK: Blockquotes enum Quote { @@ -782,9 +808,7 @@ struct MathRendering { else { return blocks } return blocks.map { block in guard case .mathBlock(let latex) = block.content, !typesets(latex) else { return block } - return MarkdownBlock(id: block.id, - content: .codeBlock(code: latex, language: "latex"), - sourceLine: block.sourceLine, substitutesFormula: true) + return block.replacingContent(.codeBlock(code: latex, language: "latex"), substitutesFormula: true) } } } @@ -1994,7 +2018,8 @@ enum BlockHeightMeasurer { from: attributed, hasInlineMath: hasMath, theme: theme, fontScale: fontScale, math: engine) converted[block.id] = ns - let ink = textInk(text: ns, width: textWidth) + let ink = textInk(text: ns, width: BlockLayout.ContainerSummary.textWidth( + of: block, textWidth: textWidth, contentWidth: contentWidth, fontScale: fontScale)) heights.append(ink.height) kinds.append(.exact) textEdges = .text(ink) @@ -2301,7 +2326,8 @@ enum BlockHeightMeasurer { // this string are still the right images and only the wrap // has to be recomputed. converted[block.id] = existing - let ink = textInk(text: existing, width: textWidth) + let ink = textInk(text: existing, width: BlockLayout.ContainerSummary.textWidth( + of: block, textWidth: textWidth, contentWidth: contentWidth, fontScale: fontScale)) heights[index] = ink.height rhythm[index] = rhythmRow(block, edges: .text(ink)) continue @@ -2314,7 +2340,8 @@ enum BlockHeightMeasurer { from: attributed, hasInlineMath: hasMath, theme: theme, fontScale: fontScale, math: math) converted[block.id] = ns - let ink = textInk(text: ns, width: textWidth) + let ink = textInk(text: ns, width: BlockLayout.ContainerSummary.textWidth( + of: block, textWidth: textWidth, contentWidth: contentWidth, fontScale: fontScale)) heights[index] = ink.height rhythm[index] = rhythmRow(block, edges: .text(ink)) diff --git a/QuickMD/QuickMD/DocumentSelection.swift b/QuickMD/QuickMD/DocumentSelection.swift index a951f96..723f06c 100644 --- a/QuickMD/QuickMD/DocumentSelection.swift +++ b/QuickMD/QuickMD/DocumentSelection.swift @@ -383,6 +383,8 @@ enum DocumentCopyBuilder { result.removeAttribute(.qmdInlineMathSource, range: full) result.removeAttribute(.qmdDisplayMathSource, range: full) result.removeAttribute(.qmdInlineMathDelimiter, range: full) + // A `
` summary's toggle is the view's, not a link to paste. + HTMLBlockSyntax.removeToggleLinks(from: result) return DocumentCopyOutput(plain: result.string, rtf: result) } diff --git a/QuickMD/QuickMD/HTMLBlockSyntax.swift b/QuickMD/QuickMD/HTMLBlockSyntax.swift index f69a0c6..5c08789 100644 --- a/QuickMD/QuickMD/HTMLBlockSyntax.swift +++ b/QuickMD/QuickMD/HTMLBlockSyntax.swift @@ -1,4 +1,4 @@ -import Foundation +import AppKit // MARK: - HTML in Markdown (v1.17) // @@ -14,12 +14,350 @@ import Foundation // // * Comments (``, CommonMark HTML block kind 2, and inline raw // HTML): drawn as nothing, like GitHub. +// * Containers: an element whose content is more Markdown blocks. The +// parser keeps every block of the document in one flat list and tags +// each with the containers it is inside (`MarkdownBlock.containers`); +// the view decides what that means (`ContainerPresentation`). The one +// container today is `
`, whose `` becomes a header +// row that shows or hides the blocks inside. A new container tag is one +// entry in `containerTags` and one `HTMLContainerKind` case. +// +// The tag grammar (`tags(in:)`) follows CommonMark's raw HTML: tag names +// `[A-Za-z][A-Za-z0-9-]*`, attribute names `[A-Za-z_:][A-Za-z0-9_.:-]*`, +// quoted or unquoted values, case-insensitive names. // // `HTMLImageSyntax` (the `` line idiom) predates this file and keeps // its own byte scanner. +// MARK: - Containers + +/// What kind of HTML container a block is in — the extension point for +/// container tags (`HTMLBlockSyntax.containerTags`). +enum HTMLContainerKind: Sendable, Equatable { + /// `
` / `
`: a summary row that shows or hides the + /// blocks inside, closed unless the tag has `open`. Print and PDF always + /// show them. + case details(isOpenByDefault: Bool) + + /// Whether the container's blocks are shown before the reader toggles it. + var isOpenByDefault: Bool { + switch self { + case .details(let isOpen): return isOpen + } + } +} + +/// One HTML container of a parsed document. +struct HTMLContainer: Sendable, Equatable { + /// 0-based, in order of the opening tags in the document — an outer + /// container's id is lower than its inner ones'. Positional, like block + /// ids: stable across a re-parse of the same text. + let id: Int + let kind: HTMLContainerKind +} + enum HTMLBlockSyntax { + // MARK: Container lines + + /// What a container line says, in source order. One line can say + /// several things: `
More` opens a container + /// and gives its summary. + enum ContainerEvent: Equatable { + /// An opening container tag. + case open(HTMLContainerKind) + /// The container's caption (`…`), as Markdown + /// inline text (`summaryText`). + case summary(String) + /// Other text on the line, outside any recognised tag (a one-line + /// `
abody
`): paragraph text. + case text(String) + /// A closing container tag. + case close + } + + /// Container tags: name → the kind its opening tag makes. + private static let containerTags: [String: (HTMLTag) -> HTMLContainerKind] = [ + "details": { .details(isOpenByDefault: $0.hasAttribute("open")) }, + ] + + /// The caption tag of a container (`
`'s). + private static let summaryTag = "summary" + + /// A `` spread over several lines is joined at most this many + /// lines down (like `HTMLImageSyntax`'s multi-line `` never makes a scan run to the end of the document. + private static let summaryLineLimit = 10 + + /// The container line starting at `lines[index]` — its events and the + /// line after it — or nil when the line is not one. + /// + /// A container line starts (after any spaces or tabs) with a container + /// tag, opening or closing, or with ``. The rest of the line is + /// read too: more container tags, a summary, text. A `` that + /// does not close on its line takes the following lines up to the one + /// with `` (at most `summaryLineLimit`); without one, the + /// summary is the rest of its own line. + static func containerLine(in lines: [String], at index: Int) -> (events: [ContainerEvent], end: Int)? { + let first = lines[index].drop(while: { $0 == " " || $0 == "\t" }) + guard let tag = leadingTag(first), + containerTags[tag.name] != nil || (tag.name == summaryTag && !tag.isClosing) else { return nil } + + var text = String(first) + var end = index + 1 + if opensUnclosedSummary(text) { + var next = index + 1 + while next < lines.count, next <= index + summaryLineLimit { + if lines[next].range(of: " Bool { + guard let tag = leadingTag(line.drop(while: { $0 == " " || $0 == "\t" })) else { return false } + return tag.name == summaryTag && !tag.isClosing + } + + /// The container or summary tag `text` starts with, nil for anything + /// else. The name is checked before the tag is read: a line of other + /// HTML (a multi-megabyte ``) is rejected after a few + /// characters. + private static func leadingTag(_ text: Substring) -> HTMLTag? { + guard text.hasPrefix("<") else { return nil } + var nameStart = text.index(after: text.startIndex) + if nameStart < text.endIndex, text[nameStart] == "/" { nameStart = text.index(after: nameStart) } + let name = text[nameStart...].prefix(while: { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-") }) + .lowercased() + guard containerTags[name] != nil || name == summaryTag else { return nil } + return tag(in: text, at: text.startIndex)?.0 + } + + /// ` Bool { + guard let open = text.range(of: " [ContainerEvent] { + var events: [ContainerEvent] = [] + var summary: [Piece]? + func addText(_ text: String) { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { events.append(.text(trimmed)) } + } + var pending = "" + for piece in pieces { + if summary != nil { + if case .tag(let tag) = piece, tag.name == summaryTag, tag.isClosing { + events.append(.summary(summaryText(summary!))) + summary = nil + } else { + summary!.append(piece) + } + continue + } + switch piece { + case .text(let text): + pending += text + case .tag(let tag): + if tag.name == summaryTag { + // A stray `` says nothing. + guard !tag.isClosing else { continue } + addText(pending) + pending = "" + summary = [] + } else if let kind = containerTags[tag.name] { + addText(pending) + pending = "" + events.append(tag.isClosing ? .close : .open(kind(tag))) + } else { + // Another tag between them (`

`, `
`) is dropped; its + // text is kept, as a browser shows it. + pending += " " + } + } + } + // A summary left open at the end: the rest is its text. + if let summary { events.append(.summary(summaryText(summary))) } + addText(pending) + return events + } + + /// A summary's content as Markdown inline text: the inline tags + /// Markdown can say are said its way (``/`` `**`, ``/`` + /// `*`, `` a backtick), a `
` is a space, any other tag is + /// dropped and its text kept. Line breaks are spaces; runs of + /// whitespace are one. + static func summaryText(_ pieces: [Piece]) -> String { + var out = "" + for piece in pieces { + switch piece { + case .text(let text): + out += text + case .tag(let tag): + switch tag.name { + case "b", "strong": out += "**" + case "i", "em": out += "*" + case "code": out += "`" + default: out += " " + } + } + } + return out.split(whereSeparator: { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" }) + .joined(separator: " ") + } + + // MARK: Tags + + /// A piece of HTML text: a tag, or the text between tags. + enum Piece: Equatable { + case tag(HTMLTag) + case text(String) + } + + /// `text` cut into tags and the text between them. A `<` that does not + /// start a well-formed tag is text. Only called on container lines + /// (they start with a container tag), never on paragraph text. + static func tags(in text: Substring) -> [Piece] { + var pieces: [Piece] = [] + var plain = "" + var i = text.startIndex + while i < text.endIndex { + if text[i] == "<", let (tag, next) = tag(in: text, at: i) { + if !plain.isEmpty { pieces.append(.text(plain)); plain = "" } + pieces.append(.tag(tag)) + i = next + } else { + plain.append(text[i]) + i = text.index(after: i) + } + } + if !plain.isEmpty { pieces.append(.text(plain)) } + return pieces + } + + /// The tag starting at `start` (a `<`) and the index after its `>`. + private static func tag(in text: Substring, at start: Substring.Index) -> (HTMLTag, Substring.Index)? { + var i = text.index(after: start) + func peek() -> Character? { i < text.endIndex ? text[i] : nil } + func advance() { i = text.index(after: i) } + func skipWhitespace() -> Bool { + let before = i + while let c = peek(), c == " " || c == "\t" || c == "\n" || c == "\r" { advance() } + return i > before + } + func isNameStart(_ c: Character) -> Bool { c.isASCII && c.isLetter } + + let isClosing = peek() == "/" + if isClosing { advance() } + guard let c = peek(), isNameStart(c) else { return nil } + let nameStart = i + while let c = peek(), c.isASCII && (c.isLetter || c.isNumber || c == "-") { advance() } + let name = text[nameStart.." else { return nil } + advance() + return (HTMLTag(name: name, isClosing: true, attributes: [:]), i) + } + + var attributes: [String: String] = [:] + while true { + let spaced = skipWhitespace() + guard let c = peek() else { return nil } + if c == ">" { advance(); break } + if c == "/" { + advance() + guard peek() == ">" else { return nil } + advance() + break + } + // Attributes are separated from the name and each other by whitespace. + guard spaced, c.isASCII, c.isLetter || c == "_" || c == ":" else { return nil } + let attrStart = i + while let c = peek(), c.isASCII && (c.isLetter || c.isNumber || "_.:-".contains(c)) { advance() } + let attrName = text[attrStart..`".contains(c)) { advance() } + guard i > valueStart else { return nil } + value = String(text[valueStart.. URL { + URL(string: "\(toggleScheme):\(container)")! + } + + /// The container a `toggleURL` names; nil for any other URL. + static func toggledContainer(_ url: URL) -> Int? { + guard url.scheme?.lowercased() == toggleScheme else { return nil } + return Int(url.absoluteString.dropFirst(toggleScheme.count + 1)) + } + + private static let toggleScheme = "x-quickmd-container" + + /// An `NSAttributedString` `.link` value (a URL or a string) as a URL. + static func url(fromLink value: Any?) -> URL? { + (value as? URL) ?? (value as? String).flatMap(URL.init(string:)) + } + + /// `text` without its toggle links (print: SwiftUI `Text` would draw + /// them as links); every other link kept. + static func removingToggleLinks(_ text: AttributedString) -> AttributedString { + var text = text + for (link, range) in text.runs[\.link] { + if let link, toggledContainer(link) != nil { text[range].link = nil } + } + return text + } + + /// The same for a copy's string (`DocumentCopyBuilder`). + static func removeToggleLinks(from text: NSMutableAttributedString) { + var ranges: [NSRange] = [] + text.enumerateAttribute(.link, in: NSRange(location: 0, length: text.length)) { value, range, _ in + if let url = url(fromLink: value), toggledContainer(url) != nil { ranges.append(range) } + } + for range in ranges { text.removeAttribute(.link, range: range) } + } + // MARK: Comments /// The line after the HTML comment block that starts on `lines[index]`, @@ -69,3 +407,89 @@ enum HTMLBlockSyntax { return text[closer.upperBound...] } } + +/// One HTML tag as written: ``, ``, ``. +struct HTMLTag: Equatable { + /// Lowercased. + let name: String + let isClosing: Bool + /// Lowercased attribute names → their values as written ("" for a bare + /// attribute like `open`). Character references are not decoded. + let attributes: [String: String] + + func hasAttribute(_ name: String) -> Bool { attributes[name] != nil } +} + +// MARK: - Presentation + +/// What the document list shows of a parse: every block except those +/// inside a closed container (`MarkdownBlock.containers`), with the height +/// table cut to match. +/// +/// The parse and its measurement always hold EVERY block — search, copy, +/// the table of contents and print see a closed `

`'s content — +/// and only the list is handed this subset. Hiding rows changes no height, +/// only the space above the first row after a hidden run, which is derived +/// again from the rhythm (`BlockLayout.Spacing.above`) as if the rows had +/// been parsed next to each other. +struct ContainerPresentation { + let blocks: [MarkdownBlock] + let table: BlockHeightTable + /// The parse's row of each shown row; nil when every row is shown. + private let documentRows: [Int]? + + /// The parse's row of shown row `row`. + func documentRow(_ row: Int) -> Int { + guard let documentRows else { return row } + return row >= 0 && row < documentRows.count ? documentRows[row] : -1 + } + + /// `blocks` with the rows of every closed container left out. `table` + /// must be `blocks`' own (same count), `rhythm` its spacing input + /// (`MeasuredBlocks.rhythm`, may be empty: the measured spacing is then + /// kept), `fontScale` the scale it was measured at. + init(blocks: [MarkdownBlock], table: BlockHeightTable, rhythm: [BlockLayout.Spacing.Row], + fontScale: CGFloat, isOpen: (HTMLContainer) -> Bool) { + var closed = Set() + for block in blocks { + if let container = block.opensContainer, !isOpen(container) { closed.insert(container.id) } + } + guard !closed.isEmpty else { + self.blocks = blocks + self.table = table + self.documentRows = nil + return + } + let measured = table.count == blocks.count + let canRespace = measured && rhythm.count == blocks.count + var shown: [MarkdownBlock] = [] + var rows: [Int] = [] + var heights: [CGFloat] = [] + var kinds: [RowKind] = [] + var spacing: [CGFloat] = [] + for (row, block) in blocks.enumerated() where !block.containers.contains(where: closed.contains) { + if measured { + heights.append(table.heights[row]) + kinds.append(table.kinds[row]) + // Right after the previous shown row: its measured spacing + // holds. After a hidden run, the rhythm decides again. + let previous = rows.last + if canRespace, previous != row - 1 { + spacing.append(BlockLayout.Spacing.above(rhythm[row], after: previous.map { rhythm[$0] }, + fontScale: fontScale)) + } else { + spacing.append(previous == nil ? 0 : table.spacing(row)) + } + } + shown.append(block) + rows.append(row) + } + self.blocks = shown + self.documentRows = rows + self.table = measured + ? BlockHeightTable(heights: heights, kinds: kinds, contentWidth: table.contentWidth, spacingAbove: spacing) + // Not measured yet: an equally unmeasured table (the list waits + // for a table of the blocks' count). + : table + } +} diff --git a/QuickMD/QuickMD/MarkdownBlock.swift b/QuickMD/QuickMD/MarkdownBlock.swift index ac122b6..af940b2 100644 --- a/QuickMD/QuickMD/MarkdownBlock.swift +++ b/QuickMD/QuickMD/MarkdownBlock.swift @@ -175,9 +175,20 @@ struct MarkdownBlock: Identifiable, Sendable { /// narrows the code by `BlockLayout.Code.leadingInset` of it; print by /// `MarkdownRenderer.printedListIndent`. let listIndent: CGFloat + /// The HTML containers (`
`, `HTMLContainer`) this block is + /// inside, by `HTMLContainer.id`, outermost first. Empty outside any — + /// every block of a document without one. Whether the block is shown + /// is the view's decision (`ContainerPresentation`): the parser keeps + /// every block, open or not, so search, copy and print see them all. + let containers: [Int] + /// The container this row is the header of: a `
`'s summary + /// row (a `.text` block), which shows or hides the container's blocks. + /// The row itself is inside the ENCLOSING containers only. + let opensContainer: HTMLContainer? init(id: String, content: BlockContent, sourceLine: Int, joinsPrevious: Bool = false, - isFrontMatter: Bool = false, substitutesFormula: Bool = false, listIndent: CGFloat = 0) { + isFrontMatter: Bool = false, substitutesFormula: Bool = false, listIndent: CGFloat = 0, + containers: [Int] = [], opensContainer: HTMLContainer? = nil) { self.id = id self.content = content self.sourceLine = sourceLine @@ -185,12 +196,29 @@ struct MarkdownBlock: Identifiable, Sendable { self.isFrontMatter = isFrontMatter self.substitutesFormula = substitutesFormula self.listIndent = listIndent + self.containers = containers + self.opensContainer = opensContainer } /// This block drawn under a list item whose text starts `indent` points in. func withListIndent(_ indent: CGFloat) -> MarkdownBlock { MarkdownBlock(id: id, content: content, sourceLine: sourceLine, joinsPrevious: joinsPrevious, - isFrontMatter: isFrontMatter, substitutesFormula: substitutesFormula, listIndent: indent) + isFrontMatter: isFrontMatter, substitutesFormula: substitutesFormula, listIndent: indent, + containers: containers, opensContainer: opensContainer) + } + + /// This block inside the containers `ids` (outermost first). + func inContainers(_ ids: [Int]) -> MarkdownBlock { + MarkdownBlock(id: id, content: content, sourceLine: sourceLine, joinsPrevious: joinsPrevious, + isFrontMatter: isFrontMatter, substitutesFormula: substitutesFormula, listIndent: listIndent, + containers: ids, opensContainer: opensContainer) + } + + /// This block with another content, everything else kept. + func replacingContent(_ content: BlockContent, substitutesFormula: Bool) -> MarkdownBlock { + MarkdownBlock(id: id, content: content, sourceLine: sourceLine, joinsPrevious: joinsPrevious, + isFrontMatter: isFrontMatter, substitutesFormula: substitutesFormula, listIndent: listIndent, + containers: containers, opensContainer: opensContainer) } /// A cheap content fingerprint of the block, to find the scroll anchor @@ -323,4 +351,11 @@ struct MarkdownBlock: Identifiable, Sendable { static func svgImage(index: Int, source: String, sourceLine: Int) -> MarkdownBlock { MarkdownBlock(id: "svg-\(index)", content: .svgImage(source: source), sourceLine: sourceLine) } + /// The header row of an HTML container (`
`'s ``): + /// text, drawn with the disclosure control in its leading indent. + static func containerSummary(index: Int, _ attributed: AttributedString, container: HTMLContainer, + sourceLine: Int) -> MarkdownBlock { + let text = MarkdownBlock.text(index: index, attributed, sourceLine: sourceLine) + return MarkdownBlock(id: text.id, content: text.content, sourceLine: sourceLine, opensContainer: container) + } } diff --git a/QuickMD/QuickMD/MarkdownBlockParser.swift b/QuickMD/QuickMD/MarkdownBlockParser.swift index 54c96f3..3f9870e 100644 --- a/QuickMD/QuickMD/MarkdownBlockParser.swift +++ b/QuickMD/QuickMD/MarkdownBlockParser.swift @@ -306,6 +306,42 @@ struct MarkdownBlockParser: Sendable { var ruleOwners: [Int: Int] = [:] var everyBlockOwner: [Int: Int] = [:] + // HTML containers (`HTMLBlockSyntax.containerLine`, `
`): + // the open ones, innermost last, and the block positions each one's + // body took (`assignContainers` tags those blocks at the end). + var openContainers: [OpenContainer] = [] + var containerBodies: [(id: Int, range: Range)] = [] + var containerCount = 0 + // The innermost open container gets its summary row now: `caption`, + // or the kind's default when it has none (`
` without a + // `` reads "Details", as in a browser). Its body starts + // after the row. + func appendSummary(_ caption: String?, line: Int) { + guard var open = openContainers.popLast() else { return } + flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) + let text = caption.flatMap { MarkdownRenderer.isBlankLine($0) ? nil : $0 } + ?? Self.defaultSummary(of: open.container.kind) + blocks.append(.containerSummary(index: blockIndex, + activeRenderer.renderContainerSummary(text, container: open.container.id), + container: open.container, sourceLine: line)) + blockIndex += 1 + open.bodyStart = blocks.count + openContainers.append(open) + } + // The innermost open container has no summary yet and something + // other than one comes: it gets the default. + func summarizeIfAwaiting() { + if let open = openContainers.last, open.bodyStart == nil { + appendSummary(nil, line: open.sourceLine) + } + } + func closeContainer() { + summarizeIfAwaiting() + guard let open = openContainers.popLast(), let bodyStart = open.bodyStart else { return } + flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) + containerBodies.append((id: open.container.id, range: bodyStart..`, `…`, + // `
`, or several on one line): opens and closes + // containers and gives them their summary rows. The blocks + // between are parsed as usual, each tagged with its containers + // at the end. Text on the line outside the tags is paragraph + // text, so the next line may go on with it. A `
` + // with nothing open draws nothing; one never closed is closed + // at the end of the document, as a browser does. + if let html = HTMLBlockSyntax.containerLine(in: lines, at: i) { + flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) + _ = nesting.block(startingAt: line) + for event in html.events { + switch event { + case .open(let kind): + summarizeIfAwaiting() + flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) + openContainers.append(OpenContainer(container: HTMLContainer(id: containerCount, kind: kind), + sourceLine: sourceLine)) + containerCount += 1 + case .summary(let caption): + if let open = openContainers.last, open.bodyStart == nil { + appendSummary(caption, line: sourceLine) + } else { + // A summary outside a container, or a second one: + // its text, as a browser shows it. + textBuffer.append((line: caption, originalIndex: sourceLine)) + } + case .text(let text): + summarizeIfAwaiting() + textBuffer.append((line: text, originalIndex: sourceLine)) + case .close: + closeContainer() + } + } + i = html.end + continue + } + // ATX headers (# H1 ... ###### H6) — detect at block level let nsRange = NSRange(line.startIndex..., in: line) if let match = Self.headerRegex.firstMatch(in: line, range: nsRange), @@ -846,9 +927,12 @@ struct MarkdownBlockParser: Sendable { } flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) + while !openContainers.isEmpty { closeContainer() } renderPendingRows(pendingRows, in: &blocks, allLines: allLines, using: activeRenderer, owners: ListOwners(paragraphs: paragraphOwners, blocks: blockOwners, rules: ruleOwners, everyBlock: everyBlockOwner)) + // After the text rows are rendered (they replace their placeholders). + if !containerBodies.isEmpty { Self.assignContainers(containerBodies, to: &blocks) } // Append footnotes block at end of document if any definitions exist if !footnoteDefinitions.isEmpty { @@ -895,6 +979,38 @@ struct MarkdownBlockParser: Sendable { return blocks } + // MARK: - HTML containers + + /// A container the block loop has opened and not closed yet. + struct OpenContainer { + let container: HTMLContainer + /// The line of its opening tag. + let sourceLine: Int + /// Where its body starts in the block list: after its summary row. + /// Nil until that row is appended. + var bodyStart: Int? + } + + /// A container's summary when the source gives none. + static func defaultSummary(of kind: HTMLContainerKind) -> String { + switch kind { + case .details: return "Details" + } + } + + /// Tags every block of each body with its container + /// (`MarkdownBlock.containers`), outermost first: bodies nest, and an + /// outer container opened first has the lower id. + static func assignContainers(_ bodies: [(id: Int, range: Range)], to blocks: inout [MarkdownBlock]) { + var ids = [[Int]](repeating: [], count: blocks.count) + for body in bodies.sorted(by: { $0.id < $1.id }) { + for position in body.range where position < blocks.count { ids[position].append(body.id) } + } + for position in blocks.indices where !ids[position].isEmpty { + blocks[position] = blocks[position].inContainers(ids[position]) + } + } + // MARK: - Heading Helpers /// An ATX heading's optional closing sequence (CommonMark): a run of `#` diff --git a/QuickMD/QuickMD/MarkdownExport.swift b/QuickMD/QuickMD/MarkdownExport.swift index c435894..2a9e61b 100644 --- a/QuickMD/QuickMD/MarkdownExport.swift +++ b/QuickMD/QuickMD/MarkdownExport.swift @@ -509,8 +509,22 @@ struct MarkdownPrintableBlockView: View { Group { switch block.content { case .text(let attributedString): - PrintableMath.text(from: attributedString) - .foregroundColor(.black) + if block.opensContainer != nil { + // A `
` summary. Print shows every container + // open (the parse keeps their blocks), so its chevron + // points down, in the control's column as on screen. + HStack(alignment: .firstTextBaseline, spacing: 0) { + Image(systemName: "arrowtriangle.down.fill") + .font(.system(size: 9)) + .foregroundColor(.black) + .frame(width: BlockLayout.ContainerSummary.controlWidth, alignment: .center) + PrintableMath.text(from: HTMLBlockSyntax.removingToggleLinks(attributedString)) + .foregroundColor(.black) + } + } else { + PrintableMath.text(from: attributedString) + .foregroundColor(.black) + } case .table(let headers, let rows, let alignments, let style): PrintableTableView(headers: headers, rows: rows, alignments: alignments, style: style) diff --git a/QuickMD/QuickMD/MarkdownRenderer.swift b/QuickMD/QuickMD/MarkdownRenderer.swift index 5f8f6cb..4bd9e7c 100644 --- a/QuickMD/QuickMD/MarkdownRenderer.swift +++ b/QuickMD/QuickMD/MarkdownRenderer.swift @@ -215,6 +215,21 @@ struct MarkdownRenderer: Sendable { return result } + /// A container's summary row (`
`'s ``, see + /// `HTMLBlockSyntax`): the caption as one paragraph, drawn beside the + /// disclosure control (`BlockLayout.ContainerSummary`), with a link on + /// the text that toggles the container (`HTMLBlockSyntax.toggleURL`): a + /// click on the caption opens or closes it, as in a browser. A link of + /// the caption's own keeps its destination. + func renderContainerSummary(_ markdown: String, container: Int) -> AttributedString { + var text = render(Self.asParagraphText(markdown)) + let toggle = HTMLBlockSyntax.toggleURL(for: container) + for (link, range) in text.runs[\.link] where link == nil { + text[range].link = toggle + } + return text + } + /// What an ordered item shows: its marker as drawn (indent spaces + "N. ") /// and the widest drawn marker of its list (what its text hangs under). struct OrderedMarker: Equatable { diff --git a/QuickMD/QuickMD/MarkdownView.swift b/QuickMD/QuickMD/MarkdownView.swift index fd4230f..2409b5f 100644 --- a/QuickMD/QuickMD/MarkdownView.swift +++ b/QuickMD/QuickMD/MarkdownView.swift @@ -33,6 +33,18 @@ struct MarkdownView: View { /// What the `fileMissing` banner says (gone, or there but unreadable). @State private var fileProblem: FileWatcher.Problem = .missing @State private var cachedBlocks: [MarkdownBlock] = [] + /// Some block of `cachedBlocks` opens an HTML container (`
`): + /// only then is the list handed a `ContainerPresentation`. + @State private var documentHasContainers = false + /// The containers (`HTMLContainer.id`) the reader toggled away from + /// their default (`
` or not). Positional ids, like block + /// ids: kept across a re-parse, so a reload or a keystroke side by side + /// does not close what the reader opened. + @State private var containerToggles = Set() + /// Bumped on every toggle: the list redraws its rows even when the + /// toggle showed or hid none (an empty `
`), so the disclosure + /// control turns. + @State private var containerToggleVersion = 0 /// Incremented on every successful parse. Text blocks use it to invalidate /// their NSAttributedString caches — a font-size-only change leaves the /// characters identical, so nothing cheaper detects it reliably. @@ -316,10 +328,15 @@ struct MarkdownView: View { // Our own virtualized list (v1.9): exact row heights from // `measured.table`, one layout path for every document size, // nothing estimated — see VirtualBlockList.swift. + // Closed `
` leave their blocks out of the list + // (`ContainerPresentation`); rows it reports are mapped + // back to the parse's. + let shown = shownContainers VirtualBlockList( - blocks: cachedBlocks, - table: measured.table, + blocks: shown?.blocks ?? cachedBlocks, + table: shown?.table ?? measured.table, contentVersion: contentVersion, + rowStateVersion: containerToggleVersion, searchText: searchText, focusedBlockId: focusedBlockId, focusedOccInBlock: focusedOccInBlock, @@ -327,7 +344,7 @@ struct MarkdownView: View { layoutStyle: isReadingMode ? .reading(fontScale: CGFloat(renderedFontScale)) : .standard, contentWidth: $contentWidth, onHeightReport: { blockId, row, height in - applyHeightReport(blockId: blockId, row: row, height: height) + applyHeightReport(blockId: blockId, row: shown?.documentRow(row) ?? row, height: height) }, content: { block in AnyView(hostedBlockView(for: block)) }, selectableText: { block, version in @@ -886,6 +903,7 @@ struct MarkdownView: View { let blocks = MathRendering.swiftMath.substitutingUntypesettableMath(in: parsed.blocks) heightCache.removeAll() // new content/theme — stale heights would mis-seed diagrams cachedBlocks = blocks + documentHasContainers = blocks.contains { $0.opensContainer != nil } renderedFontScale = Double(scale) contentVersion += 1 // The column this parse was measured at, in the same transaction @@ -1472,7 +1490,7 @@ struct MarkdownView: View { // hasInlineMath is precomputed at parse time (see textBlockMeta). // TextBlockView handles search highlighting (temporaryAttributes) // and inline math (NSTextAttachment) natively. - TextBlockView( + let text = TextBlockView( blockId: block.id, attributed: attributedString, hasInlineMath: textBlockMeta[block.id]?.hasInlineMath ?? false, @@ -1484,8 +1502,29 @@ struct MarkdownView: View { // D12 — the measurer already built this string to size the // row; nil until the document has been measured. preconverted: measured.converted[block.id], - onLink: { handleLinkActivation($0) } + onLink: { handleLinkActivation($0) }, + toggleToolTip: block.opensContainer.map { container in + { url in + HTMLBlockSyntax.toggledContainer(url) == container.id + ? ContainerDisclosureControl.toolTip(isOpen: isContainerOpen(container)) : nil + } + } ) + if let container = block.opensContainer { + // A `
` summary: the control, then the caption + // beside it (`BlockLayout.ContainerSummary`, the width + // the measurer wrapped it at). A click on the caption + // toggles too, through its link. + HStack(alignment: .top, spacing: 0) { + ContainerDisclosureControl(isOpen: isContainerOpen(container), theme: theme, + fontScale: scale) { + toggleContainer(container.id) + } + text + } + } else { + text + } case .table(let headers, let rows, let alignments, let style): // One NSTextView over the measurer's own `TableText` (v1.13 @@ -1577,6 +1616,37 @@ struct MarkdownView: View { .id(block.id) } + // MARK: - HTML containers (`
`) + + /// What the list shows when the document has containers; nil when it + /// has none (every block shown, nothing to map). + private var shownContainers: ContainerPresentation? { + guard documentHasContainers else { return nil } + return ContainerPresentation(blocks: cachedBlocks, table: measured.table, rhythm: measured.rhythm, + fontScale: CGFloat(renderedFontScale), isOpen: isContainerOpen) + } + + private func isContainerOpen(_ container: HTMLContainer) -> Bool { + container.kind.isOpenByDefault != containerToggles.contains(container.id) + } + + private func toggleContainer(_ id: Int) { + if containerToggles.remove(id) == nil { containerToggles.insert(id) } + containerToggleVersion += 1 + } + + /// Opens every closed container block `blockId` is inside. + private func revealContainers(of blockId: String) { + guard documentHasContainers, + let block = cachedBlocks.first(where: { $0.id == blockId }), !block.containers.isEmpty else { return } + let around = Set(block.containers) + for summary in cachedBlocks { + guard let container = summary.opensContainer, around.contains(container.id), + !isContainerOpen(container) else { continue } + toggleContainer(container.id) + } + } + // MARK: - Search Helpers private func toggleSearch() { @@ -1751,6 +1821,10 @@ struct MarkdownView: View { /// the coordinator acts on, so asking twice for the same block scrolls twice /// and an unrelated body re-evaluation scrolls not at all. private func requestScroll(to blockId: String, anchor: VirtualBlockList.Anchor, animated: Bool) { + // A heading, match or anchor inside a closed `
`: open it + // (and every one around it) first, as a browser's find does. The + // list installs the new rows before it scrolls. + revealContainers(of: blockId) scrollRequestToken += 1 scrollRequest = VirtualBlockList.ScrollRequest(blockId: blockId, anchor: anchor, animated: animated, token: scrollRequestToken) @@ -1878,6 +1952,11 @@ struct MarkdownView: View { } private func handleLinkActivation(_ url: URL) { + // A `
` summary's caption (`HTMLBlockSyntax.toggleURL`). + if let container = HTMLBlockSyntax.toggledContainer(url) { + toggleContainer(container) + return + } // In-document link (`#install`, #43). Never a file: it used to resolve // to the document's folder and open it in Finder. if let fragment = HeadingAnchors.inDocumentFragment(of: url) { @@ -2111,3 +2190,86 @@ struct SystemColorSchemeReader: NSViewRepresentable { [Visit Apple](https://apple.com) """), documentURL: nil) } + +// MARK: - Container disclosure control + +/// The control of a `
` summary row: a filled triangle (GitHub's +/// disclosure marker) in its own column left of the caption +/// (`BlockLayout.ContainerSummary.controlWidth`), centred on the first +/// line, pointing right when closed and down when open. +/// +/// No text view lies under it, so it is no part of the text. The click, the +/// cursor and the tooltip belong to an AppKit view over the triangle +/// (`DisclosureHitArea`): as the view under the pointer it receives the +/// cursor updates, which the cell's hosting view would otherwise answer +/// with the arrow. +struct ContainerDisclosureControl: View { + let isOpen: Bool + let theme: MarkdownTheme + let fontScale: CGFloat + let toggle: () -> Void + + /// What a click does: the control's tooltip and the caption's. + static func toolTip(isOpen: Bool) -> String { isOpen ? "Collapse" : "Expand" } + + var body: some View { + let font = theme.fonts.appKit(size: BlockLayout.Spacing.bodySize * fontScale) + let lineHeight = NSLayoutManager().defaultLineHeight(for: font) + Image(systemName: "arrowtriangle.right.fill") + .font(.system(size: 9 * fontScale)) + .foregroundColor(theme.textColor) + .rotationEffect(.degrees(isOpen ? 90 : 0)) + .frame(width: BlockLayout.ContainerSummary.controlWidth(fontScale: fontScale), height: lineHeight) + .overlay(DisclosureHitArea(toolTip: Self.toolTip(isOpen: isOpen), action: toggle)) + .accessibilityElement() + .accessibilityAddTraits(.isButton) + .accessibilityLabel(Self.toolTip(isOpen: isOpen)) + .accessibilityAction { toggle() } + } +} + +/// A transparent AppKit view that is clicked (`action` on a mouse-up inside +/// it), shows the pointing hand while the pointer is over it, and has a +/// tooltip. +struct DisclosureHitArea: NSViewRepresentable { + let toolTip: String + let action: () -> Void + + final class HitView: NSView { + var action: () -> Void = {} + private var tracking: NSTrackingArea? + + override func updateTrackingAreas() { + super.updateTrackingAreas() + if let tracking { removeTrackingArea(tracking) } + let area = NSTrackingArea(rect: .zero, options: [.cursorUpdate, .activeInKeyWindow, .inVisibleRect], + owner: self) + addTrackingArea(area) + tracking = area + } + override func resetCursorRects() { addCursorRect(bounds, cursor: .pointingHand) } + override func cursorUpdate(with event: NSEvent) { NSCursor.pointingHand.set() } + // A click in a background window acts at once, like a link. + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + // Taken here, so the list starts no selection from it. + override func mouseDown(with event: NSEvent) {} + override func mouseUp(with event: NSEvent) { + guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return } + action() + // The rows may be re-laid out under the pointer: keep the hand. + NSCursor.pointingHand.set() + } + } + + func makeNSView(context: Context) -> HitView { + let view = HitView() + view.action = action + view.toolTip = toolTip + return view + } + + func updateNSView(_ view: HitView, context: Context) { + view.action = action + if view.toolTip != toolTip { view.toolTip = toolTip } + } +} diff --git a/QuickMD/QuickMD/Views/TextBlockView.swift b/QuickMD/QuickMD/Views/TextBlockView.swift index ed55760..e60c91d 100644 --- a/QuickMD/QuickMD/Views/TextBlockView.swift +++ b/QuickMD/QuickMD/Views/TextBlockView.swift @@ -56,6 +56,11 @@ struct TextBlockView: View { var typesetsTextKindMath: Bool = false var mathFontSize: CGFloat? = nil let onLink: (URL) -> Void + /// The tooltip of a `
` summary's toggle link + /// (`HTMLBlockSyntax.toggleURL`): "Expand" / "Collapse", from the view + /// that knows the state. Nil, or nil for the URL: no tooltip, never the + /// internal URL. Other links keep the text view's own. + var toggleToolTip: ((URL) -> String?)? = nil @State private var cachedNS: NSAttributedString? @State private var cachedKey: String = "" @@ -67,7 +72,8 @@ struct TextBlockView: View { cacheScope: String = "", typesetsTextKindMath: Bool = false, mathFontSize: CGFloat? = nil, - onLink: @escaping (URL) -> Void) { + onLink: @escaping (URL) -> Void, + toggleToolTip: ((URL) -> String?)? = nil) { self.blockId = blockId self.attributed = attributed self.hasInlineMath = hasInlineMath @@ -81,6 +87,7 @@ struct TextBlockView: View { self.typesetsTextKindMath = typesetsTextKindMath self.mathFontSize = mathFontSize self.onLink = onLink + self.toggleToolTip = toggleToolTip } /// Keyed on `contentVersion`, NOT on a theme/scale/length fingerprint. @@ -108,7 +115,8 @@ struct TextBlockView: View { attributed: ns, searchTerm: searchTerm, focusedOccurrence: focusedOccurrence, - onLink: onLink + onLink: onLink, + toggleToolTip: toggleToolTip ) .frame(maxWidth: .infinity, alignment: .leading) .task(id: cacheKey) { @@ -160,6 +168,7 @@ private struct BlockTextView: NSViewRepresentable { let searchTerm: String let focusedOccurrence: Int? let onLink: (URL) -> Void + var toggleToolTip: ((URL) -> String?)? = nil func makeCoordinator() -> TextViewLinkDelegate { TextViewLinkDelegate(onLink: onLink) } @@ -180,6 +189,7 @@ private struct BlockTextView: NSViewRepresentable { func updateNSView(_ textView: SelfSizingTextView, context: Context) { context.coordinator.onLink = onLink + context.coordinator.toggleToolTip = toggleToolTip let textChanged = (textView.cachedAttributed !== attributed) if textChanged { @@ -216,6 +226,8 @@ private struct BlockTextView: NSViewRepresentable { /// `MarkdownView.handleLinkActivation`. final class TextViewLinkDelegate: NSObject, NSTextViewDelegate { var onLink: (URL) -> Void + /// `TextBlockView.toggleToolTip`. + var toggleToolTip: ((URL) -> String?)? init(onLink: @escaping (URL) -> Void) { self.onLink = onLink } @@ -230,4 +242,14 @@ final class TextViewLinkDelegate: NSObject, NSTextViewDelegate { } return false } + + /// A `
` summary's toggle link says what a click does, not its + /// internal URL (`HTMLBlockSyntax.toggleURL`). + func textView(_ view: NSTextView, willDisplayToolTip tooltip: String, + forCharacterAt characterIndex: Int) -> String? { + guard let storage = view.textStorage, characterIndex < storage.length, + let url = HTMLBlockSyntax.url(fromLink: storage.attribute(.link, at: characterIndex, effectiveRange: nil)), + HTMLBlockSyntax.toggledContainer(url) != nil else { return tooltip } + return toggleToolTip?(url) + } } diff --git a/QuickMD/QuickMD/Views/VirtualBlockList.swift b/QuickMD/QuickMD/Views/VirtualBlockList.swift index c2a1788..bc02129 100644 --- a/QuickMD/QuickMD/Views/VirtualBlockList.swift +++ b/QuickMD/QuickMD/Views/VirtualBlockList.swift @@ -125,6 +125,10 @@ struct VirtualBlockList: NSViewRepresentable { let table: BlockHeightTable /// Bumped by `MarkdownView` on every parse. THE signal that `blocks` are new. let contentVersion: Int + /// Bumped when what the rows DRAW changes without the rows changing (a + /// `
` toggled: its summary's control turns): the materialized + /// cells get fresh root views, like a search change. + var rowStateVersion: Int = 0 let searchText: String let focusedBlockId: String? let focusedOccInBlock: Int? @@ -313,7 +317,8 @@ struct VirtualBlockList: NSViewRepresentable { coordinator.install(blocks: blocks, table: table, contentVersion: contentVersion) } else if coordinator.searchText != searchText || coordinator.focusedBlockId != focusedBlockId - || coordinator.focusedOccInBlock != focusedOccInBlock { + || coordinator.focusedOccInBlock != focusedOccInBlock + || coordinator.rowStateVersion != rowStateVersion { // D11 — same rows, new highlighting: hand the materialized cells // a fresh root view. SwiftUI diffs it and `.id(block.id)` keeps // each block's state (loaded images, rendered diagrams). @@ -323,6 +328,7 @@ struct VirtualBlockList: NSViewRepresentable { coordinator.searchText = searchText coordinator.focusedBlockId = focusedBlockId coordinator.focusedOccInBlock = focusedOccInBlock + coordinator.rowStateVersion = rowStateVersion if let request = scrollRequest, request.token != coordinator.lastScrollToken { coordinator.lastScrollToken = request.token @@ -417,6 +423,7 @@ struct VirtualBlockList: NSViewRepresentable { var onHeightReport: (String, Int, CGFloat) -> Void = { _, _, _ in } var setContentWidth: (CGFloat) -> Void = { _ in } var searchText: String = "" + var rowStateVersion = 0 var focusedBlockId: String? var focusedOccInBlock: Int? var lastScrollToken: Int = .min diff --git a/QuickMD/QuickMDTests/HTMLBlockTests.swift b/QuickMD/QuickMDTests/HTMLBlockTests.swift index 4de6319..84eb6e1 100644 --- a/QuickMD/QuickMDTests/HTMLBlockTests.swift +++ b/QuickMD/QuickMDTests/HTMLBlockTests.swift @@ -84,4 +84,273 @@ final class HTMLBlockTests: XCTestCase { let line = String(repeating: "