Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocModel/Styles.swift3// Description: Named styles with inheritance, the style sheet, document themes and list definitions.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public struct Style: Codable, Hashable, Sendable, Identifiable {10 public enum Kind: String, Codable, Sendable { case paragraph, character }11 public var id: String12 public var name: String13 public var kind: Kind14 /// Parent style id. Properties not set here come from the parent, then from the document defaults.15 public var basedOn: String?16 /// Style applied to the paragraph created by pressing Return at the end of a paragraph of this style.17 public var next: String?18 public var char: CharProps19 public var para: ParaProps20 /// Headings only: prefix the paragraph with its hierarchical number ("2.1").21 public var numbered: Bool2223 public init(id: String, name: String, kind: Kind = .paragraph, basedOn: String? = nil, next: String? = nil,24 char: CharProps = .none, para: ParaProps = .none, numbered: Bool = false) {25 self.id = id; self.name = name; self.kind = kind; self.basedOn = basedOn; self.next = next26 self.char = char; self.para = para; self.numbered = numbered27 }28}2930/// Well-known style identifiers. They match the Word built-in style ids so DOCX round trips keep the semantics.31public enum StyleID {32 public static let normal = "Normal"33 public static let title = "Title"34 public static let subtitle = "Subtitle"35 public static func heading(_ level: Int) -> String { "Heading\(max(1, min(9, level)))" }36 public static let quote = "Quote"37 public static let caption = "Caption"38 public static let code = "Code"39 public static let abstract = "Abstract"40 public static let footnoteText = "FootnoteText"41 public static let header = "Header"42 public static let footer = "Footer"43 public static let bibliography = "Bibliography"44 public static let tocHeading = "TOCHeading"45 public static func toc(_ level: Int) -> String { "TOC\(max(1, min(9, level)))" }46 public static let listParagraph = "ListParagraph"47 public static let tableText = "TableText"48 // Character styles49 public static let emphasis = "Emphasis"50 public static let strong = "Strong"51 public static let hyperlink = "Hyperlink"52 public static let inlineCode = "InlineCode"53}5455public struct StyleSheet: Codable, Hashable, Sendable {56 /// Document-wide defaults at the root of every inheritance chain.57 public var defaultChar: CharProps58 public var defaultPara: ParaProps59 /// Styles in display order.60 public var styles: [Style]61 public var themeName: String6263 public init(defaultChar: CharProps, defaultPara: ParaProps, styles: [Style], themeName: String) {64 self.defaultChar = defaultChar; self.defaultPara = defaultPara; self.styles = styles; self.themeName = themeName65 }6667 public func style(_ id: String) -> Style? { styles.first { $0.id == id } }6869 public mutating func upsert(_ style: Style) {70 if let i = styles.firstIndex(where: { $0.id == style.id }) { styles[i] = style } else { styles.append(style) }71 }7273 public var paragraphStyles: [Style] { styles.filter { $0.kind == .paragraph } }74 public var characterStyles: [Style] { styles.filter { $0.kind == .character } }7576 /// The inheritance chain from the root to `id` (cycle-safe).77 public func chain(_ id: String) -> [Style] {78 var out: [Style] = []79 var seen = Set<String>()80 var cur: String? = id81 while let c = cur, !seen.contains(c), let s = style(c) {82 out.append(s); seen.insert(c); cur = s.basedOn83 }84 return out.reversed()85 }8687 /// Unresolved (still optional) properties contributed by a paragraph style and its ancestors.88 public func styleProps(_ id: String) -> (para: ParaProps, char: CharProps) {89 var p = defaultPara, c = defaultChar90 for s in chain(id) { p.apply(s.para); c.apply(s.char) }91 return (p, c)92 }9394 public func paraProps(style id: String, direct: ParaProps) -> ResolvedPara {95 var p = styleProps(id).para96 p.apply(direct)97 return ResolvedPara(p)98 }99100 /// Character properties of a run: defaults → paragraph style chain → character style chain → direct formatting.101 public func charProps(paraStyle: String, charStyle: String?, direct: CharProps) -> ResolvedChar {102 var c = styleProps(paraStyle).char103 if let cs = charStyle { for s in chain(cs) { c.apply(s.char) } }104 c.apply(direct)105 return ResolvedChar(c)106 }107108 public func isNumberedHeading(_ id: String) -> Bool { chain(id).last?.numbered ?? false }109}110111// MARK: - Lists112113public enum NumberFormat: String, Codable, Sendable, CaseIterable {114 case decimal, lowerAlpha, upperAlpha, lowerRoman, upperRoman, bullet, none115116 public func string(_ n: Int) -> String {117 switch self {118 case .decimal: return String(n)119 case .lowerAlpha: return NumberFormat.alpha(n).lowercased()120 case .upperAlpha: return NumberFormat.alpha(n)121 case .lowerRoman: return NumberFormat.roman(n).lowercased()122 case .upperRoman: return NumberFormat.roman(n)123 case .bullet, .none: return ""124 }125 }126 static func alpha(_ n: Int) -> String {127 guard n > 0 else { return String(n) }128 var n = n, s = ""129 while n > 0 { n -= 1; s = String(UnicodeScalar(UInt8(65 + n % 26))) + s; n /= 26 }130 return s131 }132 static func roman(_ n: Int) -> String {133 guard n > 0, n < 4000 else { return String(n) }134 let table: [(Int, String)] = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]135 var n = n, s = ""136 for (v, r) in table { while n >= v { s += r; n -= v } }137 return s138 }139}140141public struct ListLevel: Codable, Hashable, Sendable {142 public var format: NumberFormat143 /// Label pattern. "%1" … "%9" are replaced by the counters of levels 1…9; for bullets this is the bullet glyph itself.144 public var pattern: String145 /// Left indent of the text.146 public var indent: Points147 /// Distance between the label and the text (hanging indent).148 public var hanging: Points149 public var start: Int150 public init(format: NumberFormat, pattern: String, indent: Points, hanging: Points = 18, start: Int = 1) {151 self.format = format; self.pattern = pattern; self.indent = indent; self.hanging = hanging; self.start = start152 }153}154155public struct ListDefinition: Codable, Hashable, Sendable {156 public var id: String157 public var levels: [ListLevel]158 public init(id: String, levels: [ListLevel]) { self.id = id; self.levels = levels }159160 public static func bullets(id: String = DocID.make()) -> ListDefinition {161 let glyphs = ["•", "◦", "▪", "•", "◦", "▪", "•", "◦", "▪"]162 return ListDefinition(id: id, levels: (0..<9).map { ListLevel(format: .bullet, pattern: glyphs[$0], indent: 36 + Double($0) * 18) })163 }164 public static func numbered(id: String = DocID.make()) -> ListDefinition {165 let formats: [NumberFormat] = [.decimal, .lowerAlpha, .lowerRoman, .decimal, .lowerAlpha, .lowerRoman, .decimal, .lowerAlpha, .lowerRoman]166 return ListDefinition(id: id, levels: (0..<9).map { ListLevel(format: formats[$0], pattern: "%\($0 + 1).", indent: 36 + Double($0) * 18) })167 }168 /// Legal-style multilevel numbering: 1., 1.1., 1.1.1.169 public static func multilevel(id: String = DocID.make()) -> ListDefinition {170 ListDefinition(id: id, levels: (0..<9).map { lvl in171 ListLevel(format: .decimal, pattern: (1...(lvl + 1)).map { "%\($0)" }.joined(separator: ".") + ".", indent: 36 + Double(lvl) * 22, hanging: 22 + Double(lvl) * 8)172 })173 }174 public var isBulleted: Bool { levels.first?.format == .bullet }175}176177public struct ListItem: Codable, Hashable, Sendable {178 public var listID: String179 /// Zero-based nesting level.180 public var level: Int181 public init(listID: String, level: Int = 0) { self.listID = listID; self.level = level }182}183184// MARK: - Themes185186/// A document theme: a font pairing and an accent colour from which the built-in styles are derived.187public struct Theme: Hashable, Sendable, Identifiable {188 public var name: String189 public var bodyFont: String190 public var headingFont: String191 public var monoFont: String192 public var bodySize: Points193 public var accent: RGBA194 public var text: RGBA195 public var id: String { name }196197 public init(name: String, bodyFont: String, headingFont: String, monoFont: String = "SF Mono", bodySize: Points = 11.5, accent: RGBA, text: RGBA = RGBA(hex: 0x16181D)) {198 self.name = name; self.bodyFont = bodyFont; self.headingFont = headingFont; self.monoFont = monoFont199 self.bodySize = bodySize; self.accent = accent; self.text = text200 }201202 public static let orix = Theme(name: "ORIX", bodyFont: "New York", headingFont: "SF Pro Display", accent: RGBA(hex: 0x4F46E5))203 public static let classic = Theme(name: "Classic", bodyFont: "Times New Roman", headingFont: "Times New Roman", bodySize: 12, accent: RGBA(hex: 0x1F2937))204 public static let modern = Theme(name: "Modern", bodyFont: "Helvetica Neue", headingFont: "Helvetica Neue", bodySize: 11, accent: RGBA(hex: 0x0E7490))205 public static let academic = Theme(name: "Academic", bodyFont: "Charter", headingFont: "Charter", bodySize: 11.5, accent: RGBA(hex: 0x7C2D12))206 public static let editorial = Theme(name: "Editorial", bodyFont: "Georgia", headingFont: "Avenir Next", bodySize: 11.5, accent: RGBA(hex: 0xB45309))207 public static let technical = Theme(name: "Technical", bodyFont: "Avenir Next", headingFont: "Avenir Next", bodySize: 11, accent: RGBA(hex: 0x2563EB))208 public static let all: [Theme] = [.orix, .classic, .modern, .academic, .editorial, .technical]209 public static func named(_ name: String) -> Theme? { all.first { $0.name == name } }210}211212public extension StyleSheet {213 /// The complete built-in style set derived from a theme.214 static func standard(theme: Theme = .orix) -> StyleSheet {215 let b = theme.bodySize216 var s: [Style] = []217 s.append(Style(id: StyleID.normal, name: "Body", para: ParaProps(spaceAfter: 8, lineSpacing: .multiple(1.25))))218 s.append(Style(id: StyleID.title, name: "Title", basedOn: StyleID.normal, next: StyleID.normal,219 char: CharProps(fontFamily: theme.headingFont, fontSize: b * 2.4, bold: true, tracking: -0.3),220 para: ParaProps(spaceBefore: 0, spaceAfter: 6, lineSpacing: .multiple(1.05), keepWithNext: true)))221 s.append(Style(id: StyleID.subtitle, name: "Subtitle", basedOn: StyleID.normal, next: StyleID.normal,222 char: CharProps(fontFamily: theme.headingFont, fontSize: b * 1.3, color: RGBA(hex: 0x5B6170)),223 para: ParaProps(spaceAfter: 18, lineSpacing: .multiple(1.1), keepWithNext: true)))224 let sizes: [Double] = [1.75, 1.4, 1.2, 1.08, 1.0, 1.0, 1.0, 1.0, 1.0]225 for lvl in 1...9 {226 s.append(Style(id: StyleID.heading(lvl), name: "Heading \(lvl)", basedOn: StyleID.normal, next: StyleID.normal,227 char: CharProps(fontFamily: theme.headingFont, fontSize: (b * sizes[lvl - 1]).rounded(), bold: lvl <= 4 ? true : nil,228 italic: lvl > 4 ? true : nil, color: lvl == 1 ? theme.accent : nil),229 para: ParaProps(alignment: .left, firstLineIndent: 0, spaceBefore: lvl == 1 ? 22 : 16, spaceAfter: 6, lineSpacing: .multiple(1.1),230 keepWithNext: true, keepLinesTogether: true, hyphenate: false, outlineLevel: lvl)))231 }232 s.append(Style(id: StyleID.quote, name: "Block Quote", basedOn: StyleID.normal, char: CharProps(italic: true, color: RGBA(hex: 0x3F4553)),233 para: ParaProps(indentLeft: 28, indentRight: 28, spaceBefore: 6, spaceAfter: 10, borderLeft: BorderLine(width: 2, color: theme.accent))))234 s.append(Style(id: StyleID.caption, name: "Caption", basedOn: StyleID.normal, next: StyleID.normal,235 char: CharProps(fontSize: b - 1.5, color: RGBA(hex: 0x4B5160)), para: ParaProps(alignment: .center, spaceBefore: 4, spaceAfter: 12, lineSpacing: .multiple(1.15))))236 s.append(Style(id: StyleID.code, name: "Code Block", basedOn: StyleID.normal, char: CharProps(fontFamily: theme.monoFont, fontSize: b - 1.5, ligatures: false),237 para: ParaProps(alignment: .left, spaceAfter: 0, lineSpacing: .multiple(1.2), hyphenate: false, shading: RGBA(hex: 0xF3F4F8))))238 s.append(Style(id: StyleID.abstract, name: "Abstract", basedOn: StyleID.normal, char: CharProps(fontSize: b - 1),239 para: ParaProps(alignment: .justified, indentLeft: 30, indentRight: 30, spaceAfter: 10)))240 s.append(Style(id: StyleID.footnoteText, name: "Footnote Text", basedOn: StyleID.normal, char: CharProps(fontSize: b - 2.5),241 para: ParaProps(spaceAfter: 2, lineSpacing: .multiple(1.1))))242 s.append(Style(id: StyleID.header, name: "Header", basedOn: StyleID.normal, char: CharProps(fontFamily: theme.headingFont, fontSize: b - 2.5, color: RGBA(hex: 0x6B7180)),243 para: ParaProps(spaceAfter: 0, lineSpacing: .multiple(1.1), tabs: [TabStop(position: 234, kind: .center), TabStop(position: 468, kind: .right)])))244 s.append(Style(id: StyleID.footer, name: "Footer", basedOn: StyleID.header))245 s.append(Style(id: StyleID.bibliography, name: "Bibliography", basedOn: StyleID.normal, para: ParaProps(alignment: .left, indentLeft: 24, firstLineIndent: -24, spaceAfter: 6)))246 s.append(Style(id: StyleID.tocHeading, name: "Contents Heading", basedOn: StyleID.normal, next: StyleID.normal,247 char: CharProps(fontFamily: theme.headingFont, fontSize: (b * 1.4).rounded(), bold: true), para: ParaProps(spaceBefore: 12, spaceAfter: 10, keepWithNext: true)))248 for lvl in 1...9 {249 s.append(Style(id: StyleID.toc(lvl), name: "Contents \(lvl)", basedOn: StyleID.normal, char: CharProps(bold: lvl == 1 ? true : nil),250 para: ParaProps(alignment: .left, indentLeft: Double(lvl - 1) * 16, spaceBefore: lvl == 1 ? 4 : 0, spaceAfter: 2, lineSpacing: .multiple(1.15), hyphenate: false)))251 }252 s.append(Style(id: StyleID.listParagraph, name: "List Paragraph", basedOn: StyleID.normal, para: ParaProps(spaceAfter: 3)))253 s.append(Style(id: StyleID.tableText, name: "Table Text", basedOn: StyleID.normal, char: CharProps(fontSize: b - 1), para: ParaProps(alignment: .left, spaceAfter: 0, lineSpacing: .multiple(1.15))))254 s.append(Style(id: StyleID.emphasis, name: "Emphasis", kind: .character, char: CharProps(italic: true)))255 s.append(Style(id: StyleID.strong, name: "Strong", kind: .character, char: CharProps(bold: true)))256 s.append(Style(id: StyleID.hyperlink, name: "Hyperlink", kind: .character, char: CharProps(underline: true, color: theme.accent)))257 s.append(Style(id: StyleID.inlineCode, name: "Inline Code", kind: .character, char: CharProps(fontFamily: theme.monoFont, fontSize: b - 1, ligatures: false)))258 return StyleSheet(defaultChar: CharProps(fontFamily: theme.bodyFont, fontSize: b, color: theme.text, language: "en"),259 defaultPara: ParaProps(alignment: .left, widowControl: true), styles: s, themeName: theme.name)260 }261262 /// Re-derives the built-in styles from another theme. Custom styles and user edits to non-font properties of built-in styles are kept.263 mutating func applyTheme(_ theme: Theme) {264 let fresh = StyleSheet.standard(theme: theme)265 defaultChar.fontFamily = fresh.defaultChar.fontFamily266 defaultChar.fontSize = fresh.defaultChar.fontSize267 defaultChar.color = fresh.defaultChar.color268 for f in fresh.styles {269 if let i = styles.firstIndex(where: { $0.id == f.id }) {270 styles[i].char.fontFamily = f.char.fontFamily271 styles[i].char.fontSize = f.char.fontSize272 styles[i].char.color = f.char.color273 if f.para.borderLeft != nil { styles[i].para.borderLeft = f.para.borderLeft }274 } else {275 styles.append(f)276 }277 }278 themeName = theme.name279 }280}281