// Markdown, read into blocks and set in a voice — ONE parser for every surface// in this app that prints somebody's markdown.//// The briefing sheet had the only reader (`BriefingPaper.blocks`) and the// repository pages borrowed it; every table's page is the third caller (a// note's body among them), and a third hand-rolled reader would have been the// point where three surfaces started disagreeing about what `> ` means. So the// reader is here, the drawing is here, and the surfaces differ only in their// VOICE — which type a heading is set in, how big the body runs.//// ## What it reads, and what it deliberately does not//// ATX headings, bullet and numbered items, block quotes, fenced code,// horizontal rules, ordinary lines — and ``, the// one thing that is not plain markdown: a note's body pointing at a picture// the note carries.//// **A LINE AT A TIME**, because that is how the surfaces that feed this compose// their text: the briefing handler joins its parts with `\n` and separates them// with blank lines, so two adjacent lines are two sentences and fusing them// into one paragraph would say something nobody wrote. Blank lines are dropped// — the air between blocks is `gap(before:first:)`'s, not the source's.//// **A fenced block passes through VERBATIM**, indentation and markers intact:// its lines are already the literal text somebody meant, and reading markdown// inside one would rewrite the very thing it fences off.//// Inline marks are set by FaceMarkdown, the same setter the faces and// reader use. These legacy conversation blocks retain their table layout.//// ## The picture reference, and why the list is the authority//// `` is a reference, not a picture: the// note's `attachments` list says which references this note actually carries.// A reference whose `{kind, id}` is NOT in that list renders as its caption// text and NOTHING is fetched — a body is text a person types, and a typed// reference must never be able to make the app go looking for bytes.importCottonFacesimportCottonKitimportSwiftUI// MARK: - What a body points at/// One record a body points at — the pair a note's attachments list is keyed/// by.structMarkdownImageRef: Hashable, Sendable {let kind: Stringlet id: Stringinit(kind: String, id: String) {self.kind = kindself.id = id }}// MARK: - The blocks/// One block of markdown, as a sheet prints it.enumMarkdownBlock: Equatable {/// `# …` — the page's own name.case heading(String)/// `## …` and deeper — a section of it.case section(String)/// `- …`, `* …`, `+ …` — one entry.case item(String)/// `1. …` — an entry that carries its own number, because a numbered list/// counts something and a bullet does not.case numbered(number: Int, text: String)/// An ordinary line.case line(String)/// `> …` — somebody else's words, or an aside.case quote(String)/// A fenced block, its lines VERBATIM.case code([String])/// A fenced block opened as ```` ```diff ````: each line's first/// character says what the line is — `+` added, `-` removed, `@` a hunk's/// header, anything else context — and the rest is what is drawn, washed/// in the status colour of its kind (`DiffRun`).case diff([String])/// A table: `| a | b |` over `|---|---|`, then its rows — drawn as a/// table, never as pipes (295 E12). Each row has the header's count of/// cells, a short row padded and a long one cut.case table(header: [String], rows: [[String]])/// `---`.case rule/// ``, and the note carries it.case image(kind: String, id: String, caption: String?)}enumMarkdownBlocks {// ── The reader ────────────────────────────────────────────────────────/// Markdown as blocks to print.////// `attached` is the note's own attachments list: a `cotton:` reference in/// it becomes a picture, and one that is not becomes its caption. The/// surfaces with no attachments at all — a briefing, a pull request's body/// — pass none, so every reference on them is text.staticfunc parse( _ markdown: String, attached: Set<MarkdownImageRef> = [] ) -> [MarkdownBlock] { placed(markdown, attached: attached).map(\.block) }/// `parse`, each block with the source line it starts on (counted from/// 0) — what lets a long text's editor open at the paragraph being read.staticfunc placed( _ markdown: String, attached: Set<MarkdownImageRef> = [] ) -> [(block: MarkdownBlock, line: Int)] {var out: [(block: MarkdownBlock, line: Int)] = []var fenced: [String]?var fenceLine = 0var fenceIsDiff = falsefunc closed(_ lines: [String]) -> MarkdownBlock { fenceIsDiff ? .diff(lines) : .code(lines) }let lines = markdown.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)var tableEnds = -1for (index, verbatim) in lines.enumerated() {func append(_ block: MarkdownBlock) { out.append((block, index)) }if index <= tableEnds { continue }let line = verbatim.trimmingCharacters(in: .whitespaces)if line.hasPrefix("```") {ifletopen = fenced {if !open.isEmpty { out.append((closed(open), fenceLine)) } fenced = nil } else { fenced = [] fenceLine = index fenceIsDiff = line.dropFirst(3).trimmingCharacters(in: .whitespaces) == "diff" }continue }if fenced != nil { fenced?.append(verbatim)continue }if line.isEmpty { continue }iflet table = table(lines, at: index) { append(.table(header: table.header, rows: table.rows)) tableEnds = table.lastcontinue }if isRule(line) { append(.rule)continue }iflet heading = heading(line) { append(heading.level == 1 ? .heading(heading.text) : .section(heading.text))continue }iflet picture = picture(line) {let ref = MarkdownImageRef(kind: picture.kind, id: picture.id)if attached.contains(ref) { append(.image(kind: picture.kind, id: picture.id, caption: picture.caption)) } elseiflet caption = picture.caption {// The list is the authority: nothing is fetched for a// reference the note does not carry, and the caption is// what the person typed. append(.line(caption)) }continue }iflet quote = quote(line) { append(.quote(quote))continue }iflet item = item(line) { append(item)continue } append(.line(line)) }// A body that ends INSIDE a fence still has words in it; dropping them// would lose whatever somebody was in the middle of typing.ifletopen = fenced, !open.isEmpty { out.append((closed(open), fenceLine)) }return out }/// A code block's lines in runs of `size`, each run one string — an/// empty line kept as a space so it still takes its height.staticfunc runs(of lines: [String], size: Int = 50) -> [String] { stride(from: 0, to: lines.count, by: max(1, size)).map { start in lines[start..<min(lines.count, start + max(1, size))].map { $0.isEmpty ? " " : $0 }.joined(separator: "\n") } }/// A diff block's lines as runs of one kind — consecutive added lines one/// run, removed lines another — each at most `size` lines, so the wash is/// drawn behind a whole run at once rather than a view per line.staticfunc diffRuns(of lines: [String], size: Int = 50) -> [DiffRun] {var runs: [DiffRun] = []for line in lines {let kind = DiffRun.Kind(line.first)let drawn = kind == .header ? line : String(line.dropFirst())iflet last = runs.last, last.kind == kind, last.lines.count < max(1, size) { runs[runs.count - 1].lines.append(drawn.isEmpty ? " " : drawn) } else { runs.append(DiffRun(kind: kind, lines: [drawn.isEmpty ? " " : drawn])) } }return runs }/// The air above a block: a section breathes, an item sits close under the/// one before it, and the first block never pushes the sheet's own inset/// down.staticfunc gap(before block: MarkdownBlock, first: Bool) -> CGFloat {if first { return0 }switch block {case .heading: return20case .section: return22case .item, .numbered: return7case .line: return12case .quote: return14case .code, .diff, .table: return14case .rule: return16case .image: return16 } }// ── One line, read ────────────────────────────────────────────────────/// A table starting at `index`: a row of cells, a separator of dashes/// (`|---|:--:|`), then every row of cells after it — and the index of/// its last line. Nil when the line under the first is no separator.staticfunc table(_ lines: [String], at index: Int) -> (header: [String], rows: [[String]], last: Int)? {guard index + 1 < lines.count, let header = cells(lines[index]), separates(lines[index + 1]), cells(lines[index + 1])?.count == header.countelse { returnnil }var rows: [[String]] = []var last = index + 1while last + 1 < lines.count, let row = cells(lines[last + 1]) { rows.append(Array((row + Array(repeating: "", count: max(0, header.count - row.count))).prefix(header.count))) last += 1 }return (header, rows, last) }/// A line's cells between its pipes, or nil for a line that holds none.staticfunc cells(_ line: String) -> [String]? {var text = line.trimmingCharacters(in: .whitespaces)guard text.contains("|") else { returnnil }if text.hasPrefix("|") { text.removeFirst() }if text.hasSuffix("|") { text.removeLast() }return text.split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) } }/// The separator under a table's head: every cell dashes, a colon at/// either end for alignment.staticfunc separates(_ line: String) -> Bool {guardlet cells = cells(line), !cells.isEmpty else { returnfalse }return cells.allSatisfy { cell inlet dashes = cell.trimmingCharacters(in: CharacterSet(charactersIn: ":"))return dashes.count >= 1 && dashes.allSatisfy { $0 == "-" } } }/// `#{1,6}` followed by a space — the level and what it names.staticfunc heading(_ line: String) -> (level: Int, text: String)? {let hashes = line.prefix(while: { $0 == "#" }).countguard (1...6).contains(hashes) else { returnnil }let rest = line.dropFirst(hashes)guard rest.first == " "else { returnnil }let text = String(rest).trimmingCharacters(in: .whitespaces)return text.isEmpty ? nil : (hashes, text) }/// `- `, `* `, `+ ` or `1. ` — and what the entry says.staticfunc item(_ line: String) -> MarkdownBlock? {var rest = Substring(line)var number: Int?iflet marker = rest.first, "-*+".contains(marker) { rest = rest.dropFirst() } else {let digits = rest.prefix(while: \.isNumber)guard !digits.isEmpty, rest.dropFirst(digits.count).first == "."else { returnnil } number = Int(digits) rest = rest.dropFirst(digits.count + 1) }guard rest.first == " "else { returnnil }let text = String(rest).trimmingCharacters(in: .whitespaces)guard !text.isEmpty else { returnnil }iflet number { return .numbered(number: number, text: text) }return .item(text) }/// `> ` — and what is quoted. A bare `>` with nothing after it is not a/// quote of anything.staticfunc quote(_ line: String) -> String? {guard line.hasPrefix(">") else { returnnil }let text = String(line.dropFirst()).trimmingCharacters(in: .whitespaces)return text.isEmpty ? nil : text }/// Three or more of one rule character, and nothing else on the line.staticfunc isRule(_ line: String) -> Bool {guard line.count >= 3, let first = line.first, "-*_".contains(first) else { returnfalse }return line.allSatisfy { $0 == first } }/// `` — and ONLY when that is the whole line.////// The id is taken VERBATIM, because a record's id already carries its own/// prefix (`photo:3f9a…`); splitting on the first `/` alone is what keeps/// the rest of it intact. A reference in the middle of a sentence is left/// to the inline reader, which draws it as its own label — a picture/// cannot sit mid-sentence on a sheet.staticfunc picture(_ line: String) -> (kind: String, id: String, caption: String?)? {guard line.hasPrefix("!["), line.hasSuffix(")") else { returnnil }guardlet close = line.firstIndex(of: "]") else { returnnil }let caption = String(line[line.index(line.startIndex, offsetBy: 2)..<close])let after = line.index(after: close)guard after < line.endIndex, line[after] == "("else { returnnil }let inside = String(line[line.index(after: after)..<line.index(before: line.endIndex)])guard inside.hasPrefix("cotton:") else { returnnil }let target = String(inside.dropFirst("cotton:".count))guardlet slash = target.firstIndex(of: "/") else { returnnil }let kind = String(target[target.startIndex..<slash])let id = String(target[target.index(after: slash)...])guard !kind.isEmpty, !id.isEmpty, !id.contains(")") else { returnnil }let trimmed = caption.trimmingCharacters(in: .whitespaces)return (kind, id, trimmed.isEmpty ? nil : trimmed) }}// MARK: - One line's inline markdown, drawnenumMarkdownInline {/// Shared inline setting inside the conversation's existing blocks.staticfunc attributed(_ text: String, theme: Theme) -> AttributedString {FaceMarkdown.inline(text, theme: theme) }}// MARK: - The voice/// How a surface sets markdown. Not a layout choice — the three differ in which/// type a heading is in and how big the body runs, and nothing else.enumMarkdownVoice: Equatable {/// The briefing sheet: its own name in the serif, sections handwritten.case briefing/// A pull request, an issue, a commit: every heading handwritten, one size.case repoBody/// A long text column drawn whole, at the size the words around it are/// set in.case page/// A message's words on its note in a conversation: the note's own type,/// and a line only as wide as its words, so a short note stays short.case notevar bodySize: CGFloat {switchself {case .briefing, .repoBody: return13case .page, .note: return15 } }var lineSpacing: CGFloat {switchself {case .briefing, .repoBody, .page: return4case .note: return3 } }/// The seed the pencil rule is drawn from, so a rule is the same stroke on/// every launch of the same sheet.var ruleSeed: String {switchself {case .briefing: return"briefing-rule"case .repoBody: return"repo-rule"case .page: return"page-rule"case .note: return"note-rule" } }}// MARK: - One block, drawn/// One block in its voice — the drawing the briefing sheet and the repository/// pages carried a copy of each.////// A picture block is drawn as its CAPTION here: only a surface that holds an/// attachments list can draw the picture itself, and it intercepts the block/// before it reaches this view.structMarkdownBlockView: View {let block: MarkdownBlockvar voice: MarkdownVoice = .briefing @Environment(\.theme) privatevar themeprivatefunc wash(_ kind: DiffRun.Kind) -> Color {switch kind {case .added: return theme.colors.successLight.colorcase .removed: return theme.colors.errorLight.colorcase .context, .header: return .clear } }var body: someView {switch block {case .heading(let text): heading(text)case .section(let text): section(text)case .item(let text): entry(marker: "\u{2022}", text: text)case .numbered(let number, let text): entry(marker: "\(number).", text: text)case .line(let text): typed(text)case .quote(let text): HStack(alignment: .top, spacing: 10) {Rectangle() .fill(theme.print(.pencil)) .frame(width: 1.5) typed(text, ink: .pencil) } .fixedSize(horizontal: false, vertical: true)case .diff(let lines):// The old commit screen's wash: added and removed lines on the// status colours' light grounds, the INK left alone, a hunk's// header in the faint ink — a run of one kind per `Text`. VStack(alignment: .leading, spacing: 0) {ForEach(Array(MarkdownBlocks.diffRuns(of: lines).enumerated()), id: \.offset) { _, run inText(run.lines.joined(separator: "\n")) .font(.system(size: voice.bodySize - 1.5, design: .monospaced)) .lineSpacing(2) .foregroundStyle(run.kind == .header ? theme.colors.inkTertiary.color : theme.colors.ink.color) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 1) .background(wash(run.kind)) } } .padding(.leading, 10) .frame(maxWidth: .infinity, alignment: .leading)case .code(let lines):// A run of lines is one `Text`, not a view per line: a commit's// diff or a job's log is thousands of lines, and a view apiece is// a page that stops answering while it lays them out. VStack(alignment: .leading, spacing: 2) {ForEach(Array(MarkdownBlocks.runs(of: lines).enumerated()), id: \.offset) { _, run inText(run) .font(.system(size: voice.bodySize - 1.5, design: .monospaced)) .lineSpacing(2) .foregroundStyle(CottonColors.ink) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) } } .padding(.leading, 10) .frame(maxWidth: .infinity, alignment: .leading)case .table(let header, let rows):// A table in the page's own type: the head in the hand over a// hairline, each row's cells under their column, wrapped.Grid(alignment: .topLeading, horizontalSpacing: theme.scale[.slipGap], verticalSpacing: theme.scale[.slipGap] / 2) {GridRow {ForEach(Array(header.enumerated()), id: \.offset) { _, cell inText(MarkdownInline.attributed(cell, theme: theme)).paperHand(theme.scale[.typeCaptionSize]) .fixedSize(horizontal: false, vertical: true) } }Rectangle().fill(theme.colors.hairline.color).frame(height: theme.scale[.slipEdge]).gridCellUnsizedAxes(.horizontal)ForEach(Array(rows.enumerated()), id: \.offset) { _, row inGridRow {ForEach(Array(row.enumerated()), id: \.offset) { _, cell in typed(cell) } } } } .accessibilityElement(children: .contain)case .rule:PencilRule(seed: voice.ruleSeed, theme: theme) .stroke(theme.print(.pencil), lineWidth: 0.8) .frame(height: 3)case .image(_, _, let caption):iflet caption { typed(caption) } } } @ViewBuilder privatefunc heading(_ text: String) -> someView {switch voice {case .briefing:Text(MarkdownInline.attributed(text, theme: theme)) .paperTitle(22) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader)case .repoBody:Text(MarkdownInline.attributed(text, theme: theme)) .paperHand(18, ink: .ink) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader)case .note:Text(MarkdownInline.attributed(text, theme: theme)) .paperHand(19, ink: .ink) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader)case .page:Text(MarkdownInline.attributed(text, theme: theme)) .paperHand(21, ink: .ink) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader) } } @ViewBuilder privatefunc section(_ text: String) -> someView {switch voice {case .briefing:Text(MarkdownInline.attributed(text, theme: theme)) .paperHand(19, ink: .ink) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader)case .repoBody:Text(MarkdownInline.attributed(text, theme: theme)) .paperHand(18, ink: .ink) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader)case .page, .note:Text(MarkdownInline.attributed(text, theme: theme)) .paperHand(18, ink: .ink) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader) } }privatefunc entry(marker: String, text: String) -> someView { HStack(alignment: .firstTextBaseline, spacing: 8) {Text(marker).paperBody(voice.bodySize, ink: .pencil) typed(text) } }privatefunc typed(_ text: String, ink: PaperInk = .ink) -> someView {Text(MarkdownInline.attributed(text, theme: theme)) .paperBody(voice.bodySize, ink: ink) .lineSpacing(voice.lineSpacing) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: voice == .note ? nil : .infinity, alignment: .leading) }}/// Consecutive lines of one kind in a diff block.structDiffRun: Equatable {enumKind: Equatable {case added, removed, context, header/// What a diff line's first character says it is.init(_ marker: Character?) {switch marker {case"+": self = .addedcase"-": self = .removedcase"@": self = .headerdefault: self = .context } } }let kind: Kindvar lines: [String]}