SPB Git

Repository Public

TemplateBuilder.swift 22.3 KB 443 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocTemplates/TemplateBuilder.swift3// Description: The internal builder DSL the templates are written with: localisation and typography, run helpers, paragraphs, lists,4//              captions, figures, equations, footnotes, tables, sections, headers and footers.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel1011let nbsp = "\u{00A0}"1213// MARK: - Typography and localisation1415enum Typography {16    /// Typographic apostrophes.17    static func english(_ s: String) -> String { s.replacingOccurrences(of: "'", with: "’") }1819    /// Typographic apostrophes, and a no-break space before : ; ? ! % $ and inside « guillemets ».20    static func french(_ s: String) -> String {21        var o = s.replacingOccurrences(of: "'", with: "’")22        for mark in [":", ";", "?", "!", "»", "%", "$"] { o = o.replacingOccurrences(of: " " + mark, with: nbsp + mark) }23        return o.replacingOccurrences(of: "« ", with: "«" + nbsp)24    }25}2627/// Picks the string of the context's language and applies that language's typographic conventions.28struct Loc: Sendable {29    let french: Bool3031    func callAsFunction(_ en: String, _ fr: String) -> String { french ? Typography.french(fr) : Typography.english(en) }3233    var languageTag: String { french ? "fr-CA" : "en" }34    var dateFormat: String { french ? "d MMMM yyyy" : "MMMM d, yyyy" }3536    private func formatter(_ format: String) -> DateFormatter {37        let f = DateFormatter()38        f.calendar = Calendar(identifier: .gregorian)39        f.locale = Locale(identifier: french ? "fr_CA" : "en_US")40        f.dateFormat = format41        return f42    }4344    /// "March 14, 2025" / "14 mars 2025" ("1er mars 2025" on the first of the month).45    func date(_ d: Date) -> String {46        let s = formatter(dateFormat).string(from: d)47        return french && s.hasPrefix("1 ") ? "1er" + s.dropFirst(1) : s48    }4950    func year(_ d: Date) -> String { formatter("yyyy").string(from: d) }51    func monthYear(_ d: Date) -> String { formatter("MMMM yyyy").string(from: d) }5253    /// "1,234.50" / "1 234,50".54    func number(_ v: Double, decimals: Int = 0) -> String {55        let scale = pow(10.0, Double(decimals))56        let scaled = Int((abs(v) * scale).rounded())57        let whole = String(scaled / Int(scale))58        var grouped = ""59        for (i, ch) in whole.reversed().enumerated() {60            if i > 0, i % 3 == 0 { grouped = (french ? nbsp : ",") + grouped }61            grouped = String(ch) + grouped62        }63        var out = (v < 0 && scaled != 0 ? "-" : "") + grouped64        if decimals > 0 {65            let frac = String(scaled % Int(scale))66            out += (french ? "," : ".") + String(repeating: "0", count: decimals - frac.count) + frac67        }68        return out69    }7071    /// "$1,234.50" / "1 234,50 $".72    func money(_ v: Double, decimals: Int = 2) -> String {73        french ? number(v, decimals: decimals) + nbsp + "$" : (v < 0 ? "-$" : "$") + number(abs(v), decimals: decimals)74    }7576    /// "10.3%" / "10,3 %".77    func percent(_ v: Double, decimals: Int = 1) -> String {78        number(v, decimals: decimals) + (french ? nbsp + "%" : "%")79    }80}8182// MARK: - Runs8384func r(_ text: String) -> Run { Run(text) }85func strong(_ text: String) -> Run { Run(text, charStyle: StyleID.strong) }86func em(_ text: String) -> Run { Run(text, charStyle: StyleID.emphasis) }87func code(_ text: String) -> Run { Run(text, charStyle: StyleID.inlineCode) }88func field(_ f: Field) -> Run { Run(inline: .field(f)) }89func xref(_ target: String, _ display: CrossRef.Display = .labelAndNumber) -> Run { Run(inline: .crossRef(CrossRef(target: target, display: display))) }90func cite(_ key: String, locator: String? = nil) -> Run { Run(inline: .citation(Citation(items: [CitationItem(key: key, locator: locator)]))) }91func math(_ latex: String) -> Run { Run(inline: .equation(Equation(latex: latex, display: false))) }92let tab = Run("\t")9394// MARK: - Table cells9596/// Custom style identifiers shared by every template.97enum TStyle {98    static let tableNumber = "TableNumber"99    static let tableHeading = "TableHeading"100    static let tableHeadingNumber = "TableHeadingNumber"101    static let tableTotal = "TableTotal"102    static let tableTotalNumber = "TableTotalNumber"103    static let figure = "Figure"104    static let equation = "Equation"105    static let unnumberedHeading = "HeadingUnnumbered"106}107108struct CellSpec {109    var runs: [Run]110    var style: String111    var formula: String?112    var span: Int = 1113}114115func cell(_ text: String, style: String = StyleID.tableText) -> CellSpec { CellSpec(runs: text.isEmpty ? [] : [Run(text)], style: style) }116func cell(_ runs: [Run], style: String = StyleID.tableText) -> CellSpec { CellSpec(runs: runs, style: style) }117/// A right-aligned numeric cell. `formula` makes it a computed cell whose text is the current value.118func num(_ text: String, formula: String? = nil) -> CellSpec { CellSpec(runs: [Run(text)], style: TStyle.tableNumber, formula: formula) }119func th(_ text: String) -> CellSpec { cell(text, style: TStyle.tableHeading) }120func thNum(_ text: String) -> CellSpec { cell(text, style: TStyle.tableHeadingNumber) }121func total(_ text: String) -> CellSpec { cell(text, style: TStyle.tableTotal) }122func totalNum(_ text: String, formula: String? = nil, style: String = TStyle.tableTotalNumber) -> CellSpec {123    CellSpec(runs: [Run(text)], style: style, formula: formula)124}125126enum CaptionKind {127    case figure, table128    /// Name of the sequence field. Language-independent, so lists of figures and tables work in every language.129    var sequence: String { self == .figure ? "Figure" : "Table" }130}131132enum RefKind { case figure, table, equation, section, chapter }133134// MARK: - Builder135136struct TemplateBuilder {137    let context: TemplateContext138    let t: Loc139    let theme: Theme140    var styles: StyleSheet141    /// Page setup of the first section.142    var setup: PageSetup143    private var lastSection: PageSetup?144    private(set) var blocks: [Block] = []145    private(set) var lists: [ListDefinition] = []146    private(set) var notes: [String: Note] = [:]147    var bibliography: [BibEntry] = []148    var subject = ""149    var keywords: [String] = []150    var citationStyle = "apa"151    private var bulletListID: String?152153    init(_ context: TemplateContext, theme: Theme, margins: Insets = Insets(all: 72)) {154        self.context = context155        self.t = Loc(french: context.isFrench)156        self.theme = theme157        styles = .standard(theme: theme)158        styles.defaultChar.language = t.languageTag159        setup = PageSetup(paper: context.paper, margins: margins)160        // Header and footer tab stops follow the text width of this document, not the 6.5 in of the standard sheet.161        let w = setup.contentWidth162        adjust(StyleID.header) { $0.para.tabs = [TabStop(position: (w / 2).rounded(), kind: .center), TabStop(position: w, kind: .right)] }163    }164165    // MARK: Context166167    /// Page setup of the section being written.168    var current: PageSetup { lastSection ?? setup }169    /// Width of the text column being written.170    var width: Points { current.columnWidth }171    var author: String { context.author.isEmpty ? t("[Your name]", "[Votre nom]") : context.author }172    var organization: String { context.organization.isEmpty ? t("[Organization name]", "[Nom de l'organisation]") : context.organization }173    var dateText: String { t.date(context.date) }174    /// The author as a real field when the context provides one (the field reads the document properties).175    var authorRun: Run { context.author.isEmpty ? Run(author) : field(.author) }176    var hair: BorderLine { BorderLine(width: 0.5, color: RGBA(hex: 0x9AA0AE)) }177    var accentRule: BorderLine { BorderLine(width: 1, color: theme.accent) }178    var muted: RGBA { RGBA(hex: 0x5B6170) }179    var tint: RGBA { RGBA(r: theme.accent.r, g: theme.accent.g, b: theme.accent.b, a: 0.08) }180181    // MARK: Styles182183    mutating func define(_ id: String, _ name: String, basedOn: String = StyleID.normal, next: String? = nil,184                         char: CharProps = .none, para: ParaProps = .none, numbered: Bool = false) {185        styles.upsert(Style(id: id, name: name, kind: .paragraph, basedOn: basedOn, next: next, char: char, para: para, numbered: numbered))186    }187188    mutating func adjust(_ id: String, _ change: (inout Style) -> Void) {189        guard var s = styles.style(id) else { return }190        change(&s)191        styles.upsert(s)192    }193194    /// Turns on hierarchical numbering for the heading styles of the given levels and adds an unnumbered level-1 heading style195    /// for the headings that stay out of the numbering (summary, references, appendices).196    mutating func numberHeadings(_ levels: ClosedRange<Int> = 1...3) {197        for l in levels { adjust(StyleID.heading(l)) { $0.numbered = true } }198        ensureUnnumberedHeading()199    }200201    mutating func ensureUnnumberedHeading() {202        guard styles.style(TStyle.unnumberedHeading) == nil else { return }203        define(TStyle.unnumberedHeading, t("Heading 1 (unnumbered)", "Titre 1 (non numéroté)"), basedOn: StyleID.heading(1), next: StyleID.normal)204    }205206    private mutating func ensureTableStyles() {207        guard styles.style(TStyle.tableNumber) == nil else { return }208        define(TStyle.tableNumber, t("Table Number", "Nombre de tableau"), basedOn: StyleID.tableText, para: ParaProps(alignment: .right))209        define(TStyle.tableHeading, t("Table Heading", "Titre de colonne"), basedOn: StyleID.tableText, char: CharProps(bold: true),210               para: ParaProps(keepWithNext: true))211        define(TStyle.tableHeadingNumber, t("Table Heading (number)", "Titre de colonne (nombre)"), basedOn: TStyle.tableHeading, para: ParaProps(alignment: .right))212        define(TStyle.tableTotal, t("Table Total", "Total de tableau"), basedOn: StyleID.tableText, char: CharProps(bold: true))213        define(TStyle.tableTotalNumber, t("Table Total (number)", "Total de tableau (nombre)"), basedOn: TStyle.tableTotal, para: ParaProps(alignment: .right))214    }215216    // MARK: Paragraphs217218    mutating func add(_ block: Block) { blocks.append(block) }219220    @discardableResult221    mutating func p(_ style: String, _ runs: [Run], id: String = DocID.make(), props: ParaProps = .none) -> String {222        blocks.append(.paragraph(Paragraph(id: id, style: style, props: props, runs: runs.filter { !$0.text.isEmpty })))223        return id224    }225226    @discardableResult227    mutating func p(_ style: String, _ text: String, id: String = DocID.make()) -> String { p(style, [Run(text)], id: id) }228229    mutating func body(_ text: String) { p(StyleID.normal, [Run(text)]) }230    mutating func body(_ runs: [Run]) { p(StyleID.normal, runs) }231232    /// A heading of the given outline level. `style` substitutes a style based on that heading level (chapter title, unnumbered heading …).233    @discardableResult234    mutating func heading(_ level: Int, _ text: String, id: String = DocID.make(), style: String? = nil) -> String {235        p(style ?? StyleID.heading(level), [Run(text)], id: id)236    }237238    mutating func pageBreak() { blocks.append(.pageBreak(BreakBlock(kind: .page))) }239    mutating func columnBreak() { blocks.append(.pageBreak(BreakBlock(kind: .column))) }240241    mutating func toc(_ kind: TOCBlock.Kind = .contents, maxLevel: Int = 3) {242        let title: String243        switch kind {244        case .contents: title = t("Table of Contents", "Table des matières")245        case .figures: title = t("List of Figures", "Liste des figures")246        case .tables: title = t("List of Tables", "Liste des tableaux")247        }248        blocks.append(.toc(TOCBlock(kind: kind, title: title, maxLevel: maxLevel)))249    }250251    // MARK: Lists252253    @discardableResult254    mutating func newList(_ definition: ListDefinition) -> String {255        lists.append(definition)256        return definition.id257    }258259    mutating func item(_ runs: [Run], list: String, level: Int = 0, style: String = StyleID.listParagraph) {260        blocks.append(.paragraph(Paragraph(style: style, runs: runs, list: ListItem(listID: list, level: level))))261    }262263    /// Bulleted items. Every bulleted list of a document shares one definition.264    mutating func bullets(_ items: [[Run]], level: Int = 0) {265        let id = bulletListID ?? newList(.bullets())266        bulletListID = id267        for i in items { item(i, list: id, level: level) }268    }269270    mutating func bullets(_ items: [String], level: Int = 0) { bullets(items.map { [Run($0)] }, level: level) }271272    /// Numbered items. Each call starts a new list (numbering restarts at 1). Returns the list id so nested items can be added.273    @discardableResult274    mutating func numbered(_ items: [[Run]], definition: ListDefinition = .numbered()) -> String {275        let id = newList(definition)276        for i in items { item(i, list: id) }277        return id278    }279280    @discardableResult281    mutating func numbered(_ items: [String], definition: ListDefinition = .numbered()) -> String {282        numbered(items.map { [Run($0)] }, definition: definition)283    }284285    // MARK: Captions, figures, equations, notes, references286287    /// "Figure 1. …" / "Tableau 1 – …": a `Caption` paragraph whose number is a real sequence field.288    @discardableResult289    mutating func caption(_ kind: CaptionKind, _ text: String, id: String = DocID.make()) -> String {290        let label = kind == .figure ? "Figure" : t("Table", "Tableau")291        let runs = [strong(label + nbsp), Run(inline: .field(.sequence(kind.sequence)), charStyle: StyleID.strong),292                    Run((t.french ? nbsp + "– " : ". ") + text)]293        // A table caption sits above its table and must stay with it.294        return p(StyleID.caption, runs, id: id, props: kind == .table ? ParaProps(spaceBefore: 12, spaceAfter: 4, keepWithNext: true) : .none)295    }296297    /// A rectangle standing in for a figure (no binary image), with alternative text. Follow it with `caption(.figure, …)`.298    mutating func figure(label: String, alt: String, height: Points = 170, fraction: Double = 0.85) {299        if styles.style(TStyle.figure) == nil {300            define(TStyle.figure, "Figure", next: StyleID.caption, para: ParaProps(alignment: .center, firstLineIndent: 0, spaceBefore: 10, spaceAfter: 2, keepWithNext: true))301        }302        let shape = ShapeObject(kind: .rectangle, width: (width * fraction).rounded(), height: height, stroke: RGBA(hex: 0x9AA0AE), strokeWidth: 0.75,303                                fill: RGBA(hex: 0xF3F4F8), text: label, altText: alt)304        p(TStyle.figure, [Run(inline: .shape(shape))])305    }306307    /// A numbered display equation: tab, equation, tab, "(n)" where n is a sequence field, on centre and right tab stops.308    @discardableResult309    mutating func displayEquation(_ latex: String, id: String = DocID.make()) -> String {310        if styles.style(TStyle.equation) == nil {311            define(TStyle.equation, t("Equation", "Équation"), next: StyleID.normal,312                   para: ParaProps(alignment: .left, firstLineIndent: 0, spaceBefore: 8, spaceAfter: 10, keepLinesTogether: true,313                                   tabs: [TabStop(position: (width / 2).rounded(), kind: .center), TabStop(position: width, kind: .right)]))314        }315        return p(TStyle.equation, [tab, Run(inline: .equation(Equation(latex: latex, display: true))), Run("\t("), field(.sequence("Equation")), Run(")")], id: id)316    }317318    /// Registers a footnote and returns its reference mark, to be placed in a paragraph.319    mutating func footnote(_ text: String) -> Run {320        let note = Note(kind: .footnote, paragraphs: [Paragraph(text, style: StyleID.footnoteText)])321        notes[note.id] = note322        return Run(inline: .note(NoteRef(kind: .footnote, id: note.id)))323    }324325    /// A cross-reference worded for the document language. The model words `.labelAndNumber` in English only,326    /// so the French variants write the label as text and reference the number.327    func ref(_ target: String, _ kind: RefKind) -> [Run] {328        switch kind {329        case .figure: return t.french ? [Run("figure" + nbsp), xref(target, .number)] : [xref(target, .labelAndNumber)]330        case .table: return t.french ? [Run("tableau" + nbsp), xref(target, .number)] : [xref(target, .labelAndNumber)]331        case .equation: return [Run(t("equation", "équation") + nbsp), xref(target, .labelAndNumber)]332        case .section: return t.french ? [Run("section" + nbsp), xref(target, .number)] : [xref(target, .labelAndNumber)]333        case .chapter: return [Run(t("Chapter", "chapitre") + nbsp), xref(target, .number)]334        }335    }336337    /// Placeholder bibliography entries that cannot be mistaken for real sources. Returns their keys.338    mutating func placeholderBibliography() -> (article: String, book: String) {339        bibliography = [340            BibEntry(key: "placeholder2026", type: "article-journal", authors: [PersonName(family: t("Author", "Auteur"), given: "A.")], year: 2026,341                     fields: ["title": t("[Title of the work]", "[Titre de l'ouvrage]"), "container-title": t("[Journal name]", "[Nom de la revue]"),342                              "volume": "[vol.]", "page": "[pp.]"]),343            BibEntry(key: "placeholder2026b", type: "book", authors: [PersonName(family: t("Author", "Auteur"), given: "B.")], year: 2026,344                     fields: ["title": t("[Title of the book]", "[Titre du livre]"), "publisher": t("[Publisher]", "[Maison d'édition]"),345                              "publisher-place": t("[City]", "[Ville]")]),346        ]347        return ("placeholder2026", "placeholder2026b")348    }349350    mutating func bibliographyBlock() {351        blocks.append(.bibliography(BibliographyBlock(title: t("References", "Références"))))352    }353354    // MARK: Tables355356    /// The lined table of the document theme: accent header rule, hairlines between rows.357    var linedTable: TableStyle { TableStyle(name: "Lined", outerBorder: nil, innerHorizontal: hair, innerVertical: nil, headerShading: tint) }358    /// Accent header band with banded rows.359    var bandedTable: TableStyle {360        TableStyle(name: "Banded", outerBorder: nil, innerHorizontal: nil, innerVertical: nil, headerShading: theme.accent, headerTextColor: .white,361                   bandedRowShading: RGBA(hex: 0xF5F6FA))362    }363364    /// A table whose columns share the text width in the given proportions. `rules` adds the three rules of an academic table365    /// (above and below the header row, below the last row) as explicit cell borders.366    mutating func table(_ fractions: [Double], header: [CellSpec]? = nil, rows: [[CellSpec]], style: TableStyle? = nil, rules: Bool = false,367                        width: Points? = nil, alignment: HorizontalAnchor = .left) {368        ensureTableStyles()369        let w = width ?? self.width370        let sum = fractions.reduce(0, +)371        let widths = fractions.map { ($0 / sum * w * 100).rounded() / 100 }372        func cells(_ specs: [CellSpec]) -> [TableCell] {373            specs.map { s in374                var c = TableCell(paragraphs: [Paragraph(style: s.style, runs: s.runs)], colSpan: s.span, vAlign: .center)375                c.formula = s.formula376                return c377            }378        }379        var out: [TableRow] = []380        if let header { out.append(TableRow(cells: cells(header), isHeader: true)) }381        out += rows.map { TableRow(cells: cells($0)) }382        if rules, !out.isEmpty {383            let heavy = BorderLine(width: 1, color: theme.text), light = BorderLine(width: 0.5, color: theme.text)384            for i in out[0].cells.indices { out[0].cells[i].borderTop = heavy; if header != nil { out[0].cells[i].borderBottom = light } }385            for i in out[out.count - 1].cells.indices { out[out.count - 1].cells[i].borderBottom = heavy }386        }387        blocks.append(.table(Table(columnWidths: widths, rows: out, style: style ?? (rules ? .academic : linedTable), alignment: alignment)))388    }389390    // MARK: Sections, headers and footers391392    /// Starts a new section. It inherits the page setup of the current one (headers and footers are copied with fresh ids,393    /// page numbering continues) and `configure` changes what differs.394    mutating func section(_ kind: SectionBreak.Kind = .nextPage, _ configure: (inout PageSetup) -> Void) {395        var s = current396        s.pageNumberStart = nil397        s.header = TemplateBuilder.fresh(s.header)398        s.footer = TemplateBuilder.fresh(s.footer)399        configure(&s)400        blocks.append(.sectionBreak(SectionBreak(kind: kind, setup: s)))401        lastSection = s402    }403404    static func fresh(_ hf: HeaderFooter) -> HeaderFooter {405        func copy(_ ps: [Paragraph]) -> [Paragraph] { ps.map { var p = $0; p.id = DocID.make(); return p } }406        return HeaderFooter(default: copy(hf.default), first: copy(hf.first), even: copy(hf.even))407    }408409    func header(_ runs: [Run]) -> Paragraph { Paragraph(style: StyleID.header, runs: runs) }410    func footer(_ runs: [Run]) -> Paragraph { Paragraph(style: StyleID.footer, runs: runs) }411412    /// "Page 3 of 12" / "Page 3 de 12" with real page-number and page-count fields.413    var pageOfTotal: [Run] { [Run("Page" + nbsp), field(.pageNumber), Run(t(" of ", " de ")), field(.pageCount)] }414415    /// A footer holding the page number field, on the left, centre or right tab stop.416    func pageNumberFooter(_ align: HorizontalAnchor = .center, ofTotal: Bool = false) -> Paragraph {417        let lead: [Run] = align == .left ? [] : (align == .center ? [tab] : [tab, tab])418        return footer(lead + (ofTotal ? pageOfTotal : [field(.pageNumber)]))419    }420421    /// Re-targets the centre and right tab stops of header and footer paragraphs for a section whose text width differs422    /// from the first section's (the Header style carries the first section's stops).423    static func retab(_ hf: HeaderFooter, width: Points) -> HeaderFooter {424        func fix(_ ps: [Paragraph]) -> [Paragraph] {425            ps.map { var p = $0; p.props.tabs = [TabStop(position: (width / 2).rounded(), kind: .center), TabStop(position: width, kind: .right)]; return p }426        }427        return HeaderFooter(default: fix(hf.default), first: fix(hf.first), even: fix(hf.even))428    }429430    // MARK: Result431432    func build(title: String) -> DocumentModel {433        let meta = DocumentMetadata(title: title, author: context.author, subject: subject, keywords: keywords, language: t.languageTag,434                                    created: context.date, modified: context.date)435        var doc = DocumentModel(meta: meta, styles: styles, pageSetup: setup, body: blocks)436        doc.lists = lists437        doc.notes = notes438        doc.bibliography = bibliography439        doc.settings.citationStyle = citationStyle440        return doc441    }442}443
Files main
Menu

Theme