SPB Git

Repository Public

Document.swift 30.3 KB 623 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocModel/Document.swift3// Description: The document model: blocks, paragraphs, runs, inline objects, tables, page setup, notes, comments, bibliography data.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89/// The character that stands for an inline object inside a run's text (one UTF-16 unit).10public let objectReplacementCharacter = "\u{FFFC}"11/// A forced line break inside a paragraph (Shift-Return).12public let lineSeparatorCharacter = "\u{2028}"1314// MARK: - Revisions and comments1516public struct Revision: Codable, Hashable, Sendable {17    public enum Kind: String, Codable, Sendable { case insertion, deletion }18    public var id: String19    public var kind: Kind20    public var author: String21    public var date: Date22    public init(id: String = DocID.make(), kind: Kind, author: String, date: Date = Date()) {23        self.id = id; self.kind = kind; self.author = author; self.date = date24    }25}2627/// A tracked formatting change: the properties the run had before the change.28public struct FormatRevision: Codable, Hashable, Sendable {29    public var id: String30    public var author: String31    public var date: Date32    public var previous: CharProps33    public var previousCharStyle: String?34    public init(id: String = DocID.make(), author: String, date: Date = Date(), previous: CharProps, previousCharStyle: String? = nil) {35        self.id = id; self.author = author; self.date = date; self.previous = previous; self.previousCharStyle = previousCharStyle36    }37}3839public struct CommentReply: Codable, Hashable, Sendable, Identifiable {40    public var id: String41    public var author: String42    public var date: Date43    public var text: String44    public init(id: String = DocID.make(), author: String, date: Date = Date(), text: String) { self.id = id; self.author = author; self.date = date; self.text = text }45}4647/// A comment. Its anchor is the set of runs whose `comments` array contains its id.48public struct Comment: Codable, Hashable, Sendable, Identifiable {49    public var id: String50    public var author: String51    public var date: Date52    public var text: String53    public var resolved: Bool54    public var replies: [CommentReply]55    public init(id: String = DocID.make(), author: String, date: Date = Date(), text: String, resolved: Bool = false, replies: [CommentReply] = []) {56        self.id = id; self.author = author; self.date = date; self.text = text; self.resolved = resolved; self.replies = replies57    }58}5960// MARK: - Inline objects6162public enum WrapMode: String, Codable, Sendable { case square, topAndBottom, behindText, inFrontOfText }63public enum HorizontalAnchor: String, Codable, Sendable { case left, center, right }6465/// How an object sits in the text: as a glyph on the line, or floating next to its anchor paragraph.66public enum Placement: Codable, Hashable, Sendable {67    case inline68    /// Floating: anchored to the paragraph that contains it, positioned relative to the column, `yOffset` below the paragraph top.69    case floating(wrap: WrapMode, align: HorizontalAnchor, xOffset: Points, yOffset: Points)70    public var isFloating: Bool { if case .floating = self { return true } else { return false } }71}7273public struct ImageObject: Codable, Hashable, Sendable {74    /// Key into `DocumentModel.assets`.75    public var asset: String76    public var width: Points77    public var height: Points78    public var altText: String79    /// Cropped fraction of the source image on each edge (0...1).80    public var crop: Insets81    /// Clockwise rotation in degrees.82    public var rotation: Double83    public var placement: Placement84    public init(asset: String, width: Points, height: Points, altText: String = "", crop: Insets = .zero, rotation: Double = 0, placement: Placement = .inline) {85        self.asset = asset; self.width = width; self.height = height; self.altText = altText; self.crop = crop; self.rotation = rotation; self.placement = placement86    }87}8889public struct ShapeObject: Codable, Hashable, Sendable {90    public enum Kind: String, Codable, Sendable, CaseIterable { case rectangle, roundedRectangle, ellipse, line, arrow, callout }91    public var kind: Kind92    public var width: Points93    public var height: Points94    public var stroke: RGBA95    public var strokeWidth: Points96    public var fill: RGBA?97    /// Text shown inside the shape (callouts, labelled boxes).98    public var text: String99    public var altText: String100    public var placement: Placement101    public init(kind: Kind, width: Points, height: Points, stroke: RGBA = RGBA(hex: 0x4F46E5), strokeWidth: Points = 1, fill: RGBA? = nil, text: String = "", altText: String = "", placement: Placement = .inline) {102        self.kind = kind; self.width = width; self.height = height; self.stroke = stroke; self.strokeWidth = strokeWidth; self.fill = fill; self.text = text; self.altText = altText; self.placement = placement103    }104}105106public struct Equation: Codable, Hashable, Sendable {107    /// LaTeX math source (without the surrounding $ delimiters).108    public var latex: String109    /// Display style (own line, larger operators) versus inline style.110    public var display: Bool111    public init(latex: String, display: Bool = false) { self.latex = latex; self.display = display }112}113114public struct NoteRef: Codable, Hashable, Sendable {115    public enum Kind: String, Codable, Sendable { case footnote, endnote }116    public var kind: Kind117    /// Key into `DocumentModel.notes`.118    public var id: String119    public init(kind: Kind, id: String) { self.kind = kind; self.id = id }120}121122public struct Note: Codable, Hashable, Sendable {123    public var id: String124    public var kind: NoteRef.Kind125    public var paragraphs: [Paragraph]126    public init(id: String = DocID.make(), kind: NoteRef.Kind, paragraphs: [Paragraph]) { self.id = id; self.kind = kind; self.paragraphs = paragraphs }127}128129public struct CitationItem: Codable, Hashable, Sendable {130    /// Key of a `BibEntry` in `DocumentModel.bibliography`.131    public var key: String132    /// Page or section locator, e.g. "pp. 12–14".133    public var locator: String?134    public var prefix: String?135    public var suffix: String?136    public var suppressAuthor: Bool137    public init(key: String, locator: String? = nil, prefix: String? = nil, suffix: String? = nil, suppressAuthor: Bool = false) {138        self.key = key; self.locator = locator; self.prefix = prefix; self.suffix = suffix; self.suppressAuthor = suppressAuthor139    }140}141142public struct Citation: Codable, Hashable, Sendable {143    public var items: [CitationItem]144    public init(items: [CitationItem]) { self.items = items }145    public init(_ keys: String...) { self.items = keys.map { CitationItem(key: $0) } }146}147148public struct CrossRef: Codable, Hashable, Sendable {149    public enum Display: String, Codable, Sendable {150        /// "2.1", "3" …151        case number152        /// "Figure 3", "Section 2.1", "Table 1", "Equation (4)".153        case labelAndNumber154        /// The page number the target lands on.155        case page156        /// The text of the target paragraph.157        case text158    }159    /// Target: a paragraph id (heading, caption, display equation) or a bookmark name.160    public var target: String161    public var display: Display162    public init(target: String, display: Display = .labelAndNumber) { self.target = target; self.display = display }163}164165public enum Field: Codable, Hashable, Sendable {166    case pageNumber167    case pageCount168    /// Current date with a Unicode date format pattern ("d MMMM yyyy").169    case date(format: String)170    case title171    case author172    /// Auto-incremented sequence used by captions: "Figure", "Table", "Equation" or any custom label.173    case sequence(String)174    /// Text of the most recent heading of the given level on or before the page (running headers).175    case headingText(level: Int)176}177178public enum Inline: Codable, Hashable, Sendable {179    case image(ImageObject)180    case shape(ShapeObject)181    case equation(Equation)182    case note(NoteRef)183    case citation(Citation)184    case crossRef(CrossRef)185    case field(Field)186    /// A named, zero-width anchor.187    case bookmark(String)188189    public var placement: Placement {190        switch self {191        case .image(let i): return i.placement192        case .shape(let s): return s.placement193        default: return .inline194        }195    }196}197198// MARK: - Runs and paragraphs199200/// A run of text sharing the same formatting. A run that carries an inline object has `text == "\u{FFFC}"`.201public struct Run: Codable, Hashable, Sendable {202    public var text: String203    public var props: CharProps204    public var charStyle: String?205    public var inline: Inline?206    /// Tracked insertion or deletion.207    public var revision: Revision?208    /// Tracked formatting change.209    public var formatRevision: FormatRevision?210    /// Ids of the comments anchored on this run.211    public var comments: [String]212213    public init(_ text: String, props: CharProps = .none, charStyle: String? = nil, revision: Revision? = nil, comments: [String] = []) {214        self.text = text; self.props = props; self.charStyle = charStyle; self.inline = nil215        self.revision = revision; self.formatRevision = nil; self.comments = comments216    }217    public init(inline: Inline, props: CharProps = .none, charStyle: String? = nil, revision: Revision? = nil) {218        self.text = objectReplacementCharacter; self.props = props; self.charStyle = charStyle; self.inline = inline219        self.revision = revision; self.formatRevision = nil; self.comments = []220    }221222    /// Length in UTF-16 code units (the unit of every text offset in the model).223    public var length: Int { text.utf16.count }224    public var isDeleted: Bool { revision?.kind == .deletion }225    public var isInserted: Bool { revision?.kind == .insertion }226227    /// True when the two runs can be merged (same formatting and annotations, no inline object).228    public func canMerge(with o: Run) -> Bool {229        inline == nil && o.inline == nil && props == o.props && charStyle == o.charStyle && revision == o.revision230            && formatRevision == o.formatRevision && comments == o.comments231    }232}233234public struct Paragraph: Codable, Hashable, Sendable, Identifiable {235    public var id: String236    public var style: String237    public var props: ParaProps238    public var runs: [Run]239    public var list: ListItem?240    /// Tracked change on the paragraph mark: an inserted mark means the paragraph break was added,241    /// a deleted mark means this paragraph is to be joined with the next one.242    public var markRevision: Revision?243244    public init(id: String = DocID.make(), style: String = StyleID.normal, props: ParaProps = .none, runs: [Run] = [], list: ListItem? = nil) {245        self.id = id; self.style = style; self.props = props; self.runs = runs; self.list = list; self.markRevision = nil246    }247    public init(_ text: String, style: String = StyleID.normal, props: ParaProps = .none, char: CharProps = .none) {248        self.init(style: style, props: props, runs: text.isEmpty ? [] : [Run(text, props: char)])249    }250}251252// MARK: - Tables253254public enum VerticalMerge: String, Codable, Sendable { case none, restart, `continue` }255public enum CellVerticalAlignment: String, Codable, Sendable { case top, center, bottom }256257public struct TableCell: Codable, Hashable, Sendable {258    public var id: String259    /// Never empty: a cell always holds at least one paragraph.260    public var paragraphs: [Paragraph]261    /// Number of grid columns covered (horizontal merge).262    public var colSpan: Int263    public var vMerge: VerticalMerge264    public var shading: RGBA?265    public var vAlign: CellVerticalAlignment266    public var borderTop: BorderLine?267    public var borderBottom: BorderLine?268    public var borderLeft: BorderLine?269    public var borderRight: BorderLine?270    /// A formula such as "=SUM(ABOVE)", "=AVERAGE(LEFT)" or "=B2*C2". The cell text holds the last computed value.271    public var formula: String?272273    public init(id: String = DocID.make(), paragraphs: [Paragraph] = [Paragraph(style: StyleID.tableText)], colSpan: Int = 1, vMerge: VerticalMerge = .none,274                shading: RGBA? = nil, vAlign: CellVerticalAlignment = .top) {275        self.id = id; self.paragraphs = paragraphs.isEmpty ? [Paragraph(style: StyleID.tableText)] : paragraphs276        self.colSpan = max(1, colSpan); self.vMerge = vMerge; self.shading = shading; self.vAlign = vAlign277    }278    public init(_ text: String, bold: Bool = false) {279        self.init(paragraphs: [Paragraph(text, style: StyleID.tableText, char: bold ? CharProps(bold: true) : .none)])280    }281    public var plainText: String { paragraphs.map(\.plainText).joined(separator: "\n") }282}283284public struct TableRow: Codable, Hashable, Sendable {285    public var id: String286    public var cells: [TableCell]287    /// Header rows are repeated at the top of every page the table spans.288    public var isHeader: Bool289    public var minHeight: Points?290    public init(id: String = DocID.make(), cells: [TableCell], isHeader: Bool = false, minHeight: Points? = nil) {291        self.id = id; self.cells = cells; self.isHeader = isHeader; self.minHeight = minHeight292    }293}294295public struct TableStyle: Codable, Hashable, Sendable {296    public var name: String297    public var outerBorder: BorderLine?298    public var innerHorizontal: BorderLine?299    public var innerVertical: BorderLine?300    public var headerShading: RGBA?301    public var headerTextColor: RGBA?302    public var bandedRowShading: RGBA?303    public var cellPadding: Insets304305    public init(name: String, outerBorder: BorderLine?, innerHorizontal: BorderLine?, innerVertical: BorderLine?, headerShading: RGBA? = nil,306                headerTextColor: RGBA? = nil, bandedRowShading: RGBA? = nil, cellPadding: Insets = Insets(top: 4, left: 6, bottom: 4, right: 6)) {307        self.name = name; self.outerBorder = outerBorder; self.innerHorizontal = innerHorizontal; self.innerVertical = innerVertical308        self.headerShading = headerShading; self.headerTextColor = headerTextColor; self.bandedRowShading = bandedRowShading; self.cellPadding = cellPadding309    }310311    static let hair = BorderLine(width: 0.5, color: RGBA(hex: 0x9AA0AE))312    public static let grid = TableStyle(name: "Grid", outerBorder: hair, innerHorizontal: hair, innerVertical: hair, headerShading: RGBA(hex: 0xEEF0F6))313    public static let plain = TableStyle(name: "Plain", outerBorder: nil, innerHorizontal: nil, innerVertical: nil)314    /// Three-rule "booktabs" table used in academic publishing.315    public static let academic = TableStyle(name: "Academic", outerBorder: nil, innerHorizontal: nil, innerVertical: nil)316    public static let banded = TableStyle(name: "Banded", outerBorder: nil, innerHorizontal: nil, innerVertical: nil, headerShading: RGBA(hex: 0x4F46E5),317                                          headerTextColor: .white, bandedRowShading: RGBA(hex: 0xF3F4FB))318    public static let lined = TableStyle(name: "Lined", outerBorder: nil, innerHorizontal: hair, innerVertical: nil, headerShading: nil)319    public static let all: [TableStyle] = [.grid, .banded, .lined, .academic, .plain]320}321322public struct Table: Codable, Hashable, Sendable, Identifiable {323    public var id: String324    /// Width of every grid column.325    public var columnWidths: [Points]326    public var rows: [TableRow]327    public var style: TableStyle328    public var alignment: HorizontalAnchor329330    public init(id: String = DocID.make(), columnWidths: [Points], rows: [TableRow], style: TableStyle = .grid, alignment: HorizontalAnchor = .left) {331        self.id = id; self.columnWidths = columnWidths; self.rows = rows; self.style = style; self.alignment = alignment332    }333334    /// An empty table of the given size filling `width`.335    public init(rows: Int, columns: Int, width: Points, headerRow: Bool = true, style: TableStyle = .grid) {336        let w = width / Double(max(1, columns))337        self.init(columnWidths: Array(repeating: w, count: max(1, columns)),338                  rows: (0..<max(1, rows)).map { r in TableRow(cells: (0..<max(1, columns)).map { _ in TableCell() }, isHeader: headerRow && r == 0) },339                  style: style)340    }341342    /// A table built from plain strings; the first row becomes the header.343    public init(strings: [[String]], width: Points, style: TableStyle = .grid) {344        let cols = strings.map(\.count).max() ?? 1345        self.init(columnWidths: Array(repeating: width / Double(max(1, cols)), count: max(1, cols)),346                  rows: strings.enumerated().map { r, row in347                      TableRow(cells: (0..<cols).map { c in TableCell(c < row.count ? row[c] : "", bold: r == 0) }, isHeader: r == 0)348                  }, style: style)349    }350351    public var columnCount: Int { columnWidths.count }352    public var totalWidth: Points { columnWidths.reduce(0, +) }353}354355// MARK: - Page setup and sections356357public struct PaperSize: Codable, Hashable, Sendable {358    public var name: String359    public var width: Points360    public var height: Points361    public init(name: String, width: Points, height: Points) { self.name = name; self.width = width; self.height = height }362    public static let letter = PaperSize(name: "US Letter", width: 612, height: 792)363    public static let legal = PaperSize(name: "US Legal", width: 612, height: 1008)364    public static let a4 = PaperSize(name: "A4", width: 595.28, height: 841.89)365    public static let a5 = PaperSize(name: "A5", width: 419.53, height: 595.28)366    public static let b5 = PaperSize(name: "B5", width: 498.9, height: 708.66)367    public static let tabloid = PaperSize(name: "Tabloid", width: 792, height: 1224)368    public static let trade6x9 = PaperSize(name: "Trade 6 × 9 in", width: 432, height: 648)369    public static let all: [PaperSize] = [.letter, .legal, .a4, .a5, .b5, .tabloid, .trade6x9]370    /// Letter in the US, Canada and a few other countries; A4 elsewhere.371    public static func `default`(for locale: Locale = .current) -> PaperSize {372        let letterRegions: Set<String> = ["US", "CA", "MX", "PH", "CL", "CO", "VE", "GT", "PA", "DO", "PR"]373        return letterRegions.contains(locale.region?.identifier ?? "") ? .letter : .a4374    }375}376377public struct HeaderFooter: Codable, Hashable, Sendable {378    public var `default`: [Paragraph]379    /// Used on the first page of the section when `PageSetup.differentFirstPage` is on.380    public var first: [Paragraph]381    /// Used on even pages when `PageSetup.differentOddEven` is on.382    public var even: [Paragraph]383    public init(default d: [Paragraph] = [], first: [Paragraph] = [], even: [Paragraph] = []) { self.default = d; self.first = first; self.even = even }384    public var isEmpty: Bool { self.default.isEmpty && first.isEmpty && even.isEmpty }385}386387public struct PageBorder: Codable, Hashable, Sendable {388    public var line: BorderLine389    /// Distance from the page edge.390    public var inset: Points391    public init(line: BorderLine = BorderLine(width: 1), inset: Points = 24) { self.line = line; self.inset = inset }392}393394public struct PageSetup: Codable, Hashable, Sendable {395    public var paper: PaperSize396    public var landscape: Bool397    public var margins: Insets398    public var columns: Int399    public var columnGap: Points400    public var columnRule: Bool401    /// Distance from the top edge of the page to the top of the header.402    public var headerDistance: Points403    /// Distance from the bottom edge of the page to the bottom of the footer.404    public var footerDistance: Points405    public var header: HeaderFooter406    public var footer: HeaderFooter407    public var differentFirstPage: Bool408    public var differentOddEven: Bool409    /// Restart page numbering at this value at the start of the section (nil = continue).410    public var pageNumberStart: Int?411    public var pageNumberFormat: NumberFormat412    public var border: PageBorder?413    public var background: RGBA?414    /// Large diagonal text behind the content ("DRAFT", "CONFIDENTIAL").415    public var watermark: String?416417    public init(paper: PaperSize = .default(), landscape: Bool = false, margins: Insets = Insets(all: 72), columns: Int = 1, columnGap: Points = 24,418                columnRule: Bool = false, headerDistance: Points = 36, footerDistance: Points = 36, header: HeaderFooter = HeaderFooter(), footer: HeaderFooter = HeaderFooter(),419                differentFirstPage: Bool = false, differentOddEven: Bool = false, pageNumberStart: Int? = nil, pageNumberFormat: NumberFormat = .decimal,420                border: PageBorder? = nil, background: RGBA? = nil, watermark: String? = nil) {421        self.paper = paper; self.landscape = landscape; self.margins = margins; self.columns = max(1, columns); self.columnGap = columnGap422        self.columnRule = columnRule; self.headerDistance = headerDistance; self.footerDistance = footerDistance; self.header = header; self.footer = footer423        self.differentFirstPage = differentFirstPage; self.differentOddEven = differentOddEven; self.pageNumberStart = pageNumberStart424        self.pageNumberFormat = pageNumberFormat; self.border = border; self.background = background; self.watermark = watermark425    }426427    public var pageWidth: Points { landscape ? max(paper.width, paper.height) : paper.width }428    public var pageHeight: Points { landscape ? min(paper.width, paper.height) : paper.height }429    public var contentWidth: Points { max(36, pageWidth - margins.left - margins.right) }430    public var columnWidth: Points { max(36, (contentWidth - Double(columns - 1) * columnGap) / Double(columns)) }431}432433public struct SectionBreak: Codable, Hashable, Sendable, Identifiable {434    public enum Kind: String, Codable, Sendable { case nextPage, continuous, oddPage, evenPage }435    public var id: String436    public var kind: Kind437    /// Page setup of the section that STARTS at this break.438    public var setup: PageSetup439    public init(id: String = DocID.make(), kind: Kind = .nextPage, setup: PageSetup) { self.id = id; self.kind = kind; self.setup = setup }440}441442public struct BreakBlock: Codable, Hashable, Sendable, Identifiable {443    public enum Kind: String, Codable, Sendable { case page, column }444    public var id: String445    public var kind: Kind446    public init(id: String = DocID.make(), kind: Kind = .page) { self.id = id; self.kind = kind }447}448449/// A generated list: table of contents, list of figures or list of tables. Its content is computed at layout time.450public struct TOCBlock: Codable, Hashable, Sendable, Identifiable {451    public enum Kind: String, Codable, Sendable { case contents, figures, tables }452    public var id: String453    public var kind: Kind454    public var title: String?455    /// Deepest heading level included (contents only).456    public var maxLevel: Int457    public init(id: String = DocID.make(), kind: Kind = .contents, title: String? = "Contents", maxLevel: Int = 3) { self.id = id; self.kind = kind; self.title = title; self.maxLevel = maxLevel }458}459460/// The generated bibliography (works cited in the document, formatted in the document's citation style).461public struct BibliographyBlock: Codable, Hashable, Sendable, Identifiable {462    public var id: String463    public var title: String?464    public init(id: String = DocID.make(), title: String? = "References") { self.id = id; self.title = title }465}466467public enum Block: Codable, Hashable, Sendable, Identifiable {468    case paragraph(Paragraph)469    case table(Table)470    case pageBreak(BreakBlock)471    case sectionBreak(SectionBreak)472    case toc(TOCBlock)473    case bibliography(BibliographyBlock)474475    public var id: String {476        switch self {477        case .paragraph(let p): return p.id478        case .table(let t): return t.id479        case .pageBreak(let b): return b.id480        case .sectionBreak(let s): return s.id481        case .toc(let t): return t.id482        case .bibliography(let b): return b.id483        }484    }485    public var paragraph: Paragraph? { if case .paragraph(let p) = self { return p } else { return nil } }486    public var table: Table? { if case .table(let t) = self { return t } else { return nil } }487    /// Blocks other than paragraphs and tables are atomic: the caret sits before or after them.488    public var isAtomic: Bool { switch self { case .paragraph, .table: return false; default: return true } }489}490491// MARK: - Bibliography data492493public struct PersonName: Codable, Hashable, Sendable {494    public var family: String495    public var given: String496    /// Institutional author kept verbatim ("World Health Organization").497    public var literal: String?498    public init(family: String, given: String = "", literal: String? = nil) { self.family = family; self.given = given; self.literal = literal }499}500501/// One bibliographic record, modelled on CSL-JSON: a type, name lists, an issue date and free-form fields.502public struct BibEntry: Codable, Hashable, Sendable, Identifiable {503    /// Citation key, unique in the document.504    public var key: String505    /// CSL type: "article-journal", "book", "chapter", "paper-conference", "thesis", "report", "webpage" …506    public var type: String507    public var authors: [PersonName]508    public var editors: [PersonName]509    public var year: Int?510    public var month: Int?511    public var day: Int?512    /// CSL variable names: title, container-title, publisher, publisher-place, volume, issue, page, DOI, URL, edition, ISBN, genre, note …513    public var fields: [String: String]514    public var id: String { key }515516    public init(key: String, type: String = "article-journal", authors: [PersonName] = [], editors: [PersonName] = [], year: Int? = nil, month: Int? = nil, day: Int? = nil, fields: [String: String] = [:]) {517        self.key = key; self.type = type; self.authors = authors; self.editors = editors; self.year = year; self.month = month; self.day = day; self.fields = fields518    }519    public var title: String { fields["title"] ?? "" }520}521522// MARK: - Document523524public struct DocumentMetadata: Codable, Hashable, Sendable {525    public var title: String526    public var author: String527    public var subject: String528    public var keywords: [String]529    public var language: String530    public var created: Date531    public var modified: Date532    public init(title: String = "", author: String = "", subject: String = "", keywords: [String] = [], language: String = "en", created: Date = Date(), modified: Date = Date()) {533        self.title = title; self.author = author; self.subject = subject; self.keywords = keywords; self.language = language; self.created = created; self.modified = modified534    }535}536537public struct DocumentSettings: Codable, Hashable, Sendable {538    public var trackChanges: Bool539    /// Citation style identifier understood by the citation engine ("apa", "chicago-author-date", "ieee", "numeric", "mla").540    public var citationStyle: String541    public var smartQuotes: Bool542    public var smartDashes: Bool543    public init(trackChanges: Bool = false, citationStyle: String = "apa", smartQuotes: Bool = true, smartDashes: Bool = true) {544        self.trackChanges = trackChanges; self.citationStyle = citationStyle; self.smartQuotes = smartQuotes; self.smartDashes = smartDashes545    }546}547548public struct Asset: Hashable, Sendable {549    public var id: String550    /// "image/png", "image/jpeg", "image/tiff", "image/gif", "application/pdf".551    public var mimeType: String552    public var data: Data553    public init(id: String = DocID.make(), mimeType: String, data: Data) { self.id = id; self.mimeType = mimeType; self.data = data }554    public var fileExtension: String {555        switch mimeType {556        case "image/jpeg": return "jpg"557        case "image/png": return "png"558        case "image/gif": return "gif"559        case "image/tiff": return "tiff"560        case "application/pdf": return "pdf"561        case "image/heic": return "heic"562        default: return "bin"563        }564    }565}566567public struct DocumentModel: Codable, Hashable, Sendable {568    public static let currentSchemaVersion = 1569570    public var schemaVersion: Int571    public var meta: DocumentMetadata572    public var settings: DocumentSettings573    public var styles: StyleSheet574    public var lists: [ListDefinition]575    /// Page setup of the first section. Later sections carry theirs in their `sectionBreak` block.576    public var pageSetup: PageSetup577    public var body: [Block]578    public var notes: [String: Note]579    public var comments: [Comment]580    public var bibliography: [BibEntry]581    /// Binary assets (images). Not part of the JSON encoding: containers store them as separate entries.582    public var assets: [String: Asset]583    /// Package parts of an imported DOCX that ORIX Docs does not interpret; written back unchanged on DOCX export.584    public var preservedParts: [String: Data]585586    enum CodingKeys: String, CodingKey { case schemaVersion, meta, settings, styles, lists, pageSetup, body, notes, comments, bibliography }587588    public init(meta: DocumentMetadata = DocumentMetadata(), styles: StyleSheet = .standard(), pageSetup: PageSetup = PageSetup(), body: [Block] = [.paragraph(Paragraph())]) {589        self.schemaVersion = DocumentModel.currentSchemaVersion590        self.meta = meta; self.settings = DocumentSettings(); self.styles = styles; self.lists = []; self.pageSetup = pageSetup591        self.body = body.isEmpty ? [.paragraph(Paragraph())] : body592        self.notes = [:]; self.comments = []; self.bibliography = []; self.assets = [:]; self.preservedParts = [:]593    }594595    public init(from decoder: Decoder) throws {596        let c = try decoder.container(keyedBy: CodingKeys.self)597        schemaVersion = try c.decode(Int.self, forKey: .schemaVersion)598        meta = try c.decode(DocumentMetadata.self, forKey: .meta)599        settings = try c.decodeIfPresent(DocumentSettings.self, forKey: .settings) ?? DocumentSettings()600        styles = try c.decode(StyleSheet.self, forKey: .styles)601        lists = try c.decodeIfPresent([ListDefinition].self, forKey: .lists) ?? []602        pageSetup = try c.decode(PageSetup.self, forKey: .pageSetup)603        body = try c.decode([Block].self, forKey: .body)604        notes = try c.decodeIfPresent([String: Note].self, forKey: .notes) ?? [:]605        comments = try c.decodeIfPresent([Comment].self, forKey: .comments) ?? []606        bibliography = try c.decodeIfPresent([BibEntry].self, forKey: .bibliography) ?? []607        assets = [:]; preservedParts = [:]608        if body.isEmpty { body = [.paragraph(Paragraph())] }609    }610611    public func list(_ id: String) -> ListDefinition? { lists.first { $0.id == id } }612    public func bibEntry(_ key: String) -> BibEntry? { bibliography.first { $0.key == key } }613    public func comment(_ id: String) -> Comment? { comments.first { $0.id == id } }614615    /// Makes sure a list definition of the wanted flavour exists and returns its id.616    public mutating func ensureList(bulleted: Bool) -> String {617        if let l = lists.first(where: { $0.isBulleted == bulleted }) { return l.id }618        let l = bulleted ? ListDefinition.bullets() : ListDefinition.numbered()619        lists.append(l)620        return l.id621    }622}623
Files main
Menu

Theme