SPB Git

Repository Public

TemplateLibrary.swift 15.6 KB 222 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocTemplates/TemplateLibrary.swift3// Description: Public API of the template library: the context a template is instantiated with, the template descriptor and the catalogue.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import DocModel910/// What a template needs to know about the writer to produce a ready-to-edit document.11public struct TemplateContext: Sendable, Hashable {12    /// Writer's name. Empty = a bracketed prompt is shown instead.13    public var author: String14    /// Company, university or firm. Empty = a bracketed prompt is shown instead.15    public var organization: String16    /// Date printed on dated documents (letters, memoranda, invoices …) and stored as the creation date.17    public var date: Date18    /// "en" or "fr" (fr = Canadian French). Any tag starting with "fr" selects French.19    public var language: String20    public var paper: PaperSize2122    public init(author: String = "", organization: String = "", date: Date = Date(), language: String = "en", paper: PaperSize = .default()) {23        self.author = author; self.organization = organization; self.date = date; self.language = language; self.paper = paper24    }2526    public var isFrench: Bool { language.lowercased().hasPrefix("fr") }27}2829public enum TemplateCategory: String, Sendable, CaseIterable {30    case basic, business, academic, legal, personal, publishing3132    public func name(_ language: String) -> String {33        let french = language.lowercased().hasPrefix("fr")34        switch self {35        case .basic: return french ? "De base" : "Basic"36        case .business: return french ? "Affaires" : "Business"37        case .academic: return french ? "Universitaire" : "Academic"38        case .legal: return french ? "Juridique" : "Legal"39        case .personal: return french ? "Personnel" : "Personal"40        case .publishing: return french ? "Édition" : "Publishing"41        }42    }43}4445/// The structural machinery a template promises to contain. The chooser can show these as badges; the tests hold every template to its promise.46public struct TemplateFeatures: OptionSet, Sendable, Hashable {47    public let rawValue: Int48    public init(rawValue: Int) { self.rawValue = rawValue }4950    /// A generated table of contents (`TOCBlock` of kind `.contents`).51    public static let tableOfContents = TemplateFeatures(rawValue: 1 << 0)52    /// A `.pageNumber` field in a header or footer.53    public static let pageNumbers = TemplateFeatures(rawValue: 1 << 1)54    /// Heading styles with `Style.numbered`.55    public static let numberedHeadings = TemplateFeatures(rawValue: 1 << 2)56    /// A `BibliographyBlock`, placeholder entries and a citation.57    public static let bibliography = TemplateFeatures(rawValue: 1 << 3)58    /// More than one section (`sectionBreak` blocks).59    public static let multipleSections = TemplateFeatures(rawValue: 1 << 4)60    /// Table cells with formulas.61    public static let formulas = TemplateFeatures(rawValue: 1 << 5)62    /// Captions with sequence fields.63    public static let captions = TemplateFeatures(rawValue: 1 << 6)64    /// Cross-references to headings, captions or equations.65    public static let crossReferences = TemplateFeatures(rawValue: 1 << 7)66    /// Footnotes.67    public static let footnotes = TemplateFeatures(rawValue: 1 << 8)68    /// A numbered display equation.69    public static let equations = TemplateFeatures(rawValue: 1 << 9)70    /// Different odd and even headers with running heading text.71    public static let mirroredPages = TemplateFeatures(rawValue: 1 << 10)72    /// Lists of figures and of tables.73    public static let listsOfFiguresAndTables = TemplateFeatures(rawValue: 1 << 11)74    /// A section with two or more columns.75    public static let columns = TemplateFeatures(rawValue: 1 << 12)76    /// A landscape section.77    public static let landscapeSection = TemplateFeatures(rawValue: 1 << 13)78    /// Front matter numbered in roman numerals, body restarting at 1 in arabic numerals.79    public static let romanFrontMatter = TemplateFeatures(rawValue: 1 << 14)80}8182public struct DocumentTemplate: Sendable, Identifiable {83    /// Stable identifier ("business-letter", "thesis" …).84    public var id: String85    public var category: TemplateCategory86    /// Name of the built-in `Theme` the template's style sheet derives from.87    public var themeName: String88    /// SF Symbol for the chooser.89    public var symbolName: String90    public var features: TemplateFeatures9192    var names: (en: String, fr: String)93    var summaries: (en: String, fr: String)94    var builder: @Sendable (TemplateContext) -> DocumentModel9596    init(id: String, category: TemplateCategory, theme: Theme, symbol: String, features: TemplateFeatures = [],97         name: (en: String, fr: String), summary: (en: String, fr: String), builder: @escaping @Sendable (TemplateContext) -> DocumentModel) {98        self.id = id; self.category = category; self.themeName = theme.name; self.symbolName = symbol; self.features = features99        self.names = name; self.summaries = summary; self.builder = builder100    }101102    public func name(_ language: String) -> String {103        language.lowercased().hasPrefix("fr") ? Typography.french(names.fr) : Typography.english(names.en)104    }105106    public func summary(_ language: String) -> String {107        language.lowercased().hasPrefix("fr") ? Typography.french(summaries.fr) : Typography.english(summaries.en)108    }109110    /// A new document. Every call returns fresh object identifiers.111    public func make(_ context: TemplateContext) -> DocumentModel { builder(context) }112}113114public enum TemplateLibrary {115    public static let blank = DocumentTemplate(116        id: "blank", category: .basic, theme: .orix, symbol: "doc",117        name: ("Blank", "Vierge"),118        summary: ("An empty document with the standard styles.", "Un document vide muni des styles standards."),119        builder: { blankDocument($0) })120121    /// Blank first, then the fifteen designed templates.122    public static let all: [DocumentTemplate] = [123        blank,124        DocumentTemplate(id: "business-letter", category: .business, theme: .classic, symbol: "envelope", features: [.pageNumbers],125                         name: ("Business letter", "Lettre d'affaires"),126                         summary: ("Letterhead, recipient block, subject line and signature; continuation header from page 2.",127                                   "En-tête, vedette, objet et signature ; en-tête de suite à partir de la page 2."),128                         builder: { businessLetter($0) }),129        DocumentTemplate(id: "academic-paper", category: .academic, theme: .academic, symbol: "graduationcap",130                         features: [.pageNumbers, .numberedHeadings, .bibliography, .captions, .crossReferences, .footnotes, .equations],131                         name: ("Academic paper", "Article scientifique"),132                         summary: ("Abstract, keywords, numbered sections, equation, figure, three-rule table, footnote, references and appendix.",133                                   "Résumé, mots-clés, sections numérotées, équation, figure, tableau à trois filets, note, références et annexe."),134                         builder: { academicPaper($0) }),135        DocumentTemplate(id: "research-report", category: .academic, theme: .orix, symbol: "doc.text.magnifyingglass",136                         features: [.tableOfContents, .pageNumbers, .numberedHeadings, .bibliography, .captions, .crossReferences, .footnotes],137                         name: ("Research report", "Rapport de recherche"),138                         summary: ("Cover page, contents, executive summary, numbered sections, findings table and figure, references.",139                                   "Page couverture, table des matières, sommaire, sections numérotées, tableau et figure de résultats, références."),140                         builder: { researchReport($0) }),141        DocumentTemplate(id: "thesis", category: .academic, theme: .academic, symbol: "books.vertical",142                         features: [.tableOfContents, .pageNumbers, .numberedHeadings, .bibliography, .multipleSections, .captions, .crossReferences,143                                    .footnotes, .equations, .mirroredPages, .listsOfFiguresAndTables, .romanFrontMatter],144                         name: ("Thesis", "Thèse ou mémoire"),145                         summary: ("Title page, roman-numbered front matter with contents and lists, numbered chapters, mirrored running headers, bibliography, appendices.",146                                   "Page de titre, pages liminaires en chiffres romains avec table et listes, chapitres numérotés, en-têtes en miroir, bibliographie, annexes."),147                         builder: { thesis($0) }),148        DocumentTemplate(id: "proposal", category: .business, theme: .orix, symbol: "lightbulb",149                         features: [.pageNumbers, .formulas, .captions, .crossReferences],150                         name: ("Proposal", "Proposition"),151                         summary: ("Cover page, summary, approach, schedule and budget tables with a computed total, acceptance block.",152                                   "Page couverture, sommaire, démarche, tableaux d'échéancier et de budget avec total calculé, bloc d'acceptation."),153                         builder: { proposal($0) }),154        DocumentTemplate(id: "financial-report", category: .business, theme: .modern, symbol: "chart.bar.doc.horizontal",155                         features: [.tableOfContents, .pageNumbers, .multipleSections, .formulas, .captions, .crossReferences, .footnotes, .landscapeSection],156                         name: ("Financial report", "Rapport financier"),157                         summary: ("Cover, contents, highlights, statement tables with computed totals and a landscape section for the quarterly table.",158                                   "Couverture, table des matières, faits saillants, tableaux à totaux calculés et section en paysage pour le tableau trimestriel."),159                         builder: { financialReport($0) }),160        DocumentTemplate(id: "legal-memorandum", category: .legal, theme: .classic, symbol: "building.columns",161                         features: [.pageNumbers, .numberedHeadings, .crossReferences, .footnotes],162                         name: ("Legal memorandum", "Note de service juridique"),163                         summary: ("TO / FROM / DATE / RE block, numbered headings and paragraphs, footnotes, confidentiality footer.",164                                   "Bloc destinataire, expéditeur, date et objet, titres et paragraphes numérotés, notes, pied de page de confidentialité."),165                         builder: { legalMemorandum($0) }),166        DocumentTemplate(id: "meeting-minutes", category: .business, theme: .technical, symbol: "person.3", features: [.pageNumbers],167                         name: ("Meeting minutes", "Procès-verbal de réunion"),168                         summary: ("Meeting details, attendance, numbered agenda, decisions and an action-item table.",169                                   "Renseignements sur la réunion, présences, ordre du jour numéroté, décisions et tableau de suivi."),170                         builder: { meetingMinutes($0) }),171        DocumentTemplate(id: "resume", category: .personal, theme: .modern, symbol: "person.text.rectangle", features: [.pageNumbers],172                         name: ("Résumé", "Curriculum vitæ"),173                         summary: ("Name block, profile, experience with dated entries and achievement bullets, education, skills.",174                                   "Bloc d'identité, profil, expérience avec entrées datées et réalisations, formation, compétences."),175                         builder: { resume($0) }),176        DocumentTemplate(id: "cover-letter", category: .personal, theme: .modern, symbol: "envelope.open", features: [],177                         name: ("Cover letter", "Lettre de présentation"),178                         summary: ("One-page application letter matching the résumé, with guided paragraphs.",179                                   "Lettre de candidature d'une page assortie au curriculum vitæ, avec paragraphes guidés."),180                         builder: { coverLetter($0) }),181        DocumentTemplate(id: "technical-manual", category: .publishing, theme: .technical, symbol: "wrench.and.screwdriver",182                         features: [.tableOfContents, .pageNumbers, .numberedHeadings, .captions, .crossReferences, .listsOfFiguresAndTables],183                         name: ("Technical manual", "Manuel technique"),184                         summary: ("Cover, revision history, contents, numbered chapters, procedures, notes and warnings, reference tables, glossary.",185                                   "Couverture, historique des révisions, table des matières, chapitres numérotés, procédures, remarques et mises en garde, tableaux de référence, glossaire."),186                         builder: { technicalManual($0) }),187        DocumentTemplate(id: "book-manuscript", category: .publishing, theme: .classic, symbol: "book",188                         features: [.tableOfContents, .pageNumbers, .multipleSections, .mirroredPages, .romanFrontMatter],189                         name: ("Book manuscript", "Manuscrit de livre"),190                         summary: ("Title and copyright pages, contents, auto-numbered chapters with drop caps, mirrored running headers.",191                                   "Pages de titre et de droits, table des matières, chapitres numérotés automatiquement avec lettrines, en-têtes en miroir."),192                         builder: { bookManuscript($0) }),193        DocumentTemplate(id: "project-report", category: .business, theme: .technical, symbol: "chart.gantt" ,194                         features: [.pageNumbers, .formulas, .captions, .crossReferences],195                         name: ("Project report", "Rapport de projet"),196                         summary: ("Status block, summary, milestone, budget and risk tables with computed variances, next steps.",197                                   "Bloc d'état, sommaire, tableaux des jalons, du budget et des risques avec écarts calculés, prochaines étapes."),198                         builder: { projectReport($0) }),199        DocumentTemplate(id: "invoice", category: .business, theme: .modern, symbol: "dollarsign.square", features: [.pageNumbers, .formulas],200                         name: ("Invoice", "Facture"),201                         summary: ("Letterhead, billing details, line-item table with computed amounts, taxes and total, payment terms.",202                                   "En-tête, renseignements de facturation, tableau des articles avec montants, taxes et total calculés, modalités de paiement."),203                         builder: { invoice($0) }),204        DocumentTemplate(id: "newsletter", category: .publishing, theme: .editorial, symbol: "newspaper",205                         features: [.pageNumbers, .multipleSections, .captions, .columns],206                         name: ("Newsletter", "Infolettre"),207                         summary: ("Masthead and lead story, then a two-column section with articles, sidebar, pull quote and figure.",208                                   "Cartouche et article de tête, puis une section à deux colonnes avec articles, encadré, exergue et figure."),209                         builder: { newsletter($0) }),210    ]211212    public static func template(id: String) -> DocumentTemplate? { all.first { $0.id == id } }213214    public static func templates(in category: TemplateCategory) -> [DocumentTemplate] { all.filter { $0.category == category } }215216    static func blankDocument(_ c: TemplateContext) -> DocumentModel {217        var b = TemplateBuilder(c, theme: .orix)218        b.p(StyleID.normal, [])219        return b.build(title: "")220    }221}222
Files main
Menu

Theme