Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocReferences/RichText.swift3// Description: The small formatted-text builder the citation styles write into (italic, bold, superscript, links), its conversion to4// model runs, and the localised terms (English, basic French) used by the styles.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel1011struct Rich {12 struct Seg { var text: String; var props: CharProps }13 private(set) var segs: [Seg] = []1415 init() {}16 init(_ text: String) { add(text) }1718 var isEmpty: Bool { segs.allSatisfy { $0.text.isEmpty } }19 var plain: String { segs.map(\.text).joined() }20 var last: Character? { segs.last(where: { !$0.text.isEmpty })?.text.last }2122 mutating func add(_ text: String, _ props: CharProps = .none) {23 guard !text.isEmpty else { return }24 if let l = segs.indices.last, segs[l].props == props { segs[l].text += text } else { segs.append(Seg(text: text, props: props)) }25 }26 mutating func add(_ other: Rich) { for s in other.segs { add(s.text, s.props) } }27 mutating func italic(_ text: String) { add(text, CharProps(italic: true)) }28 mutating func link(_ text: String, to url: String) { add(text, CharProps(link: url)) }2930 /// Adds a title that may carry `<i>`, `<b>`, `<sup>`, `<sub>` and small-caps markup. Inside an italic title, `<i>` reverses to roman.31 mutating func title(_ text: String, italic: Bool = false) {32 guard text.contains("<") else { add(text, italic ? CharProps(italic: true) : .none); return }33 var i = 0, b = 0, sup = 0, sub = 0, sc = 034 var rest = Substring(text)35 func props() -> CharProps {36 var p = CharProps()37 if italic != (i > 0) { p.italic = true }38 if b > 0 { p.bold = true }39 if sup > 0 { p.vertical = .superscript } else if sub > 0 { p.vertical = .subscript }40 if sc > 0 { p.smallCaps = true }41 return p42 }43 let tags: [(String, (inout Int, inout Int, inout Int, inout Int, inout Int) -> Void)] = [44 ("<i>", { i, _, _, _, _ in i += 1 }), ("</i>", { i, _, _, _, _ in i = max(0, i - 1) }),45 ("<b>", { _, b, _, _, _ in b += 1 }), ("</b>", { _, b, _, _, _ in b = max(0, b - 1) }),46 ("<sup>", { _, _, s, _, _ in s += 1 }), ("</sup>", { _, _, s, _, _ in s = max(0, s - 1) }),47 ("<sub>", { _, _, _, s, _ in s += 1 }), ("</sub>", { _, _, _, s, _ in s = max(0, s - 1) }),48 (LaTeXText.smallCapsOpen, { _, _, _, _, s in s += 1 }), (LaTeXText.smallCapsClose, { _, _, _, _, s in s = max(0, s - 1) }),49 ]50 while let lt = rest.firstIndex(of: "<") {51 add(String(rest[..<lt]), props())52 rest = rest[lt...]53 if let (tag, apply) = tags.first(where: { rest.hasPrefix($0.0) }) {54 apply(&i, &b, &sup, &sub, &sc)55 rest = rest.dropFirst(tag.count)56 } else {57 add("<", props())58 rest = rest.dropFirst()59 }60 }61 add(String(rest), props())62 }6364 /// Ends the current element with a full stop unless it already ends with terminal punctuation.65 mutating func period() {66 guard let l = last else { return }67 if l == "." || l == "?" || l == "!" || l == "…" { return }68 if l == "”" || l == "’" || l == "»", let before = plain.dropLast().last, before == "." || before == "?" || before == "!" { return }69 add(".")70 }7172 /// A full stop that goes inside a closing double quotation mark (American usage): `the help of “Dr. House.”`73 mutating func periodInsideQuote() {74 guard last == "”", let l = segs.indices.last(where: { !segs[$0].text.isEmpty }) else { period(); return }75 let before = plain.dropLast().last76 if before == "." || before == "?" || before == "!" { return }77 segs[l].text.removeLast()78 segs[l].text += ".”"79 }8081 var runs: [Run] { segs.filter { !$0.text.isEmpty }.map { Run($0.text, props: $0.props) } }82}8384/// Connecting words and abbreviations of a language. Only what the styles need; this is not a CSL locale.85struct Terms {86 var french: Bool87 var and: String, ampersand: String, etAl: String, noDate: String, inWord: String88 var ed: String, eds: String, editionAbbrev: String, editor: String, editors: String, editedBy: String, translatedBy: String89 var retrieved: String, from: String, accessed: String, volumeAbbrev: String, volumeCap: String, numberAbbrev: String, numberCap: String90 var page: String, pages: String, article: String91 var months: [String], shortMonths: [String]9293 static let english = Terms(94 french: false, and: "and", ampersand: "&", etAl: "et al.", noDate: "n.d.", inWord: "In",95 ed: "Ed.", eds: "Eds.", editionAbbrev: "ed.", editor: "editor", editors: "editors", editedBy: "edited by", translatedBy: "translated by",96 retrieved: "Retrieved", from: "from", accessed: "Accessed", volumeAbbrev: "vol.", volumeCap: "Vol.", numberAbbrev: "no.", numberCap: "No.",97 page: "p.", pages: "pp.", article: "Article",98 months: RefDate.monthsEN, shortMonths: ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June", "July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."])99100 static let frenchCA = Terms(101 french: true, and: "et", ampersand: "et", etAl: "et al.", noDate: "s. d.", inWord: "Dans",102 ed: "dir.", eds: "dir.", editionAbbrev: "éd.", editor: "directeur", editors: "directeurs", editedBy: "sous la direction de", translatedBy: "traduit par",103 retrieved: "Consulté le", from: "à l’adresse", accessed: "Consulté le", volumeAbbrev: "vol.", volumeCap: "Vol.", numberAbbrev: "nº", numberCap: "Nº",104 page: "p.", pages: "p.", article: "Article",105 months: RefDate.monthsFR, shortMonths: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juill.", "août", "sept.", "oct.", "nov.", "déc."])106107 static func forLanguage(_ tag: String) -> Terms { tag.lowercased().hasPrefix("fr") ? .frenchCA : .english }108109 func ordinal(_ n: Int) -> String {110 if french { return n == 1 ? "1re" : "\(n)e" }111 let t = n % 100112 if (11...13).contains(t) { return "\(n)th" }113 switch n % 10 { case 1: return "\(n)st"; case 2: return "\(n)nd"; case 3: return "\(n)rd"; default: return "\(n)th" }114 }115116 /// "2" → "2nd ed."; "2nd" → "2nd ed."; "Revised" → "Revised ed."; a value that already says "ed." or "edition" is kept.117 func edition(_ raw: String) -> String {118 let s = raw.trimmingCharacters(in: .whitespaces)119 if let n = Int(s) { return ordinal(n) + " " + editionAbbrev }120 let lower = s.lowercased()121 if lower.contains("ed.") || lower.contains("éd.") || lower.contains("edition") || lower.contains("édition") { return s }122 return s + " " + editionAbbrev123 }124125 /// "May 24, 2018" (English) or "24 mai 2018" (French).126 func longDate(_ y: Int, _ m: Int?, _ d: Int?) -> String {127 guard let m, (1...12).contains(m) else { return String(y) }128 if french { return (d.map { "\($0 == 1 ? "1er" : String($0)) " } ?? "") + months[m - 1] + " \(y)" }129 return months[m - 1] + (d.map { " \($0)," } ?? "") + " \(y)"130 }131}132