Cotton code
562 lines · 24.0 KB · SwiftRaw
// 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 `![caption](cotton:<kind>/<id>)`, 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//// `![caption](cotton:photo/photo:3f9a…)` 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.import CottonFacesimport CottonKitimport SwiftUI// MARK: - What a body points at/// One record a body points at — the pair a note's attachments list is keyed/// by.struct MarkdownImageRef: Hashable, Sendable {    let kind: String    let id: String    init(kind: String, id: String) {        self.kind = kind        self.id = id    }}// MARK: - The blocks/// One block of markdown, as a sheet prints it.enum MarkdownBlock: 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    /// `![caption](cotton:<kind>/<id>)`, and the note carries it.    case image(kind: String, id: String, caption: String?)}enum MarkdownBlocks {    // ── 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.    static func 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.    static func placed(        _ markdown: String,        attached: Set<MarkdownImageRef> = []    ) -> [(block: MarkdownBlock, line: Int)] {        var out: [(block: MarkdownBlock, line: Int)] = []        var fenced: [String]?        var fenceLine = 0        var fenceIsDiff = false        func closed(_ lines: [String]) -> MarkdownBlock { fenceIsDiff ? .diff(lines) : .code(lines) }        let lines = markdown.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)        var tableEnds = -1        for (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("```") {                if let open = 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 }            if let table = table(lines, at: index) {                append(.table(header: table.header, rows: table.rows))                tableEnds = table.last                continue            }            if isRule(line) {                append(.rule)                continue            }            if let heading = heading(line) {                append(heading.level == 1 ? .heading(heading.text) : .section(heading.text))                continue            }            if let 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))                } else if let 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            }            if let quote = quote(line) {                append(.quote(quote))                continue            }            if let 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.        if let open = 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.    static func 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.    static func 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())            if let 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.    static func gap(before block: MarkdownBlock, first: Bool) -> CGFloat {        if first { return 0 }        switch block {        case .heading: return 20        case .section: return 22        case .item, .numbered: return 7        case .line: return 12        case .quote: return 14        case .code, .diff, .table: return 14        case .rule: return 16        case .image: return 16        }    }    // ── 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.    static func 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.count        else { return nil }        var rows: [[String]] = []        var last = index + 1        while 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.    static func cells(_ line: String) -> [String]? {        var text = line.trimmingCharacters(in: .whitespaces)        guard text.contains("|") else { return nil }        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.    static func separates(_ line: String) -> Bool {        guard let cells = cells(line), !cells.isEmpty else { return false }        return cells.allSatisfy { cell in            let 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.    static func heading(_ line: String) -> (level: Int, text: String)? {        let hashes = line.prefix(while: { $0 == "#" }).count        guard (1...6).contains(hashes) else { return nil }        let rest = line.dropFirst(hashes)        guard rest.first == " " else { return nil }        let text = String(rest).trimmingCharacters(in: .whitespaces)        return text.isEmpty ? nil : (hashes, text)    }    /// `- `, `* `, `+ ` or `1. ` — and what the entry says.    static func item(_ line: String) -> MarkdownBlock? {        var rest = Substring(line)        var number: Int?        if let marker = rest.first, "-*+".contains(marker) {            rest = rest.dropFirst()        } else {            let digits = rest.prefix(while: \.isNumber)            guard !digits.isEmpty, rest.dropFirst(digits.count).first == "." else { return nil }            number = Int(digits)            rest = rest.dropFirst(digits.count + 1)        }        guard rest.first == " " else { return nil }        let text = String(rest).trimmingCharacters(in: .whitespaces)        guard !text.isEmpty else { return nil }        if let 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.    static func quote(_ line: String) -> String? {        guard line.hasPrefix(">") else { return nil }        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.    static func isRule(_ line: String) -> Bool {        guard line.count >= 3, let first = line.first, "-*_".contains(first) else { return false }        return line.allSatisfy { $0 == first }    }    /// `![caption](cotton:<kind>/<id>)` — 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.    static func picture(_ line: String) -> (kind: String, id: String, caption: String?)? {        guard line.hasPrefix("!["), line.hasSuffix(")") else { return nil }        guard let close = line.firstIndex(of: "]") else { return nil }        let caption = String(line[line.index(line.startIndex, offsetBy: 2)..<close])        let after = line.index(after: close)        guard after < line.endIndex, line[after] == "(" else { return nil }        let inside = String(line[line.index(after: after)..<line.index(before: line.endIndex)])        guard inside.hasPrefix("cotton:") else { return nil }        let target = String(inside.dropFirst("cotton:".count))        guard let slash = target.firstIndex(of: "/") else { return nil }        let kind = String(target[target.startIndex..<slash])        let id = String(target[target.index(after: slash)...])        guard !kind.isEmpty, !id.isEmpty, !id.contains(")") else { return nil }        let trimmed = caption.trimmingCharacters(in: .whitespaces)        return (kind, id, trimmed.isEmpty ? nil : trimmed)    }}// MARK: - One line's inline markdown, drawnenum MarkdownInline {    /// Shared inline setting inside the conversation's existing blocks.    static func 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.enum MarkdownVoice: 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 note    var bodySize: CGFloat {        switch self {        case .briefing, .repoBody: return 13        case .page, .note: return 15        }    }    var lineSpacing: CGFloat {        switch self {        case .briefing, .repoBody, .page: return 4        case .note: return 3        }    }    /// 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 {        switch self {        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.struct MarkdownBlockView: View {    let block: MarkdownBlock    var voice: MarkdownVoice = .briefing    @Environment(\.theme) private var theme    private func wash(_ kind: DiffRun.Kind) -> Color {        switch kind {        case .added: return theme.colors.successLight.color        case .removed: return theme.colors.errorLight.color        case .context, .header: return .clear        }    }    var body: some View {        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 in                    Text(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 in                    Text(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 in                        Text(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 in                    GridRow {                        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):            if let caption { typed(caption) }        }    }    @ViewBuilder private func heading(_ text: String) -> some View {        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 private func section(_ text: String) -> some View {        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)        }    }    private func entry(marker: String, text: String) -> some View {        HStack(alignment: .firstTextBaseline, spacing: 8) {            Text(marker).paperBody(voice.bodySize, ink: .pencil)            typed(text)        }    }    private func typed(_ text: String, ink: PaperInk = .ink) -> some View {        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.struct DiffRun: Equatable {    enum Kind: Equatable {        case added, removed, context, header        /// What a diff line's first character says it is.        init(_ marker: Character?) {            switch marker {            case "+": self = .added            case "-": self = .removed            case "@": self = .header            default: self = .context            }        }    }    let kind: Kind    var lines: [String]}