SPB Git

Repository Public

ReferenceView.swift 8.1 KB 158 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocReferences/ReferenceView.swift3// Description: A read-only view of a BibEntry for the formatters (kind of work, cleaned fields, dates, pages, DOI) and the name4//              formatting shared by the citation styles (initials, inversion, list joining, "et al." thresholds).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel1011struct Ref {12    enum Kind { case article, periodical, book, chapter, thesis, report, webpage, conference, other }13    let e: BibEntry14    let t: Terms15    let kind: Kind16    let authors: [PersonName]17    let editors: [PersonName]18    /// "and others" was present: the list is known to be incomplete.19    let authorsTruncated: Bool2021    init(_ e: BibEntry, terms: Terms) {22        self.e = e; self.t = terms23        authors = e.authors.filter { !$0.isOthers }24        editors = e.editors.filter { !$0.isOthers }25        authorsTruncated = e.authors.contains { $0.isOthers }26        let hasContainer = !(e.fields["container-title"] ?? "").isEmpty27        switch e.type {28        case "article-journal", "article", "review", "review-book": kind = .article29        case "article-magazine", "article-newspaper": kind = .periodical30        case "book", "periodical", "classic": kind = .book31        case "chapter", "entry", "entry-encyclopedia", "entry-dictionary": kind = hasContainer ? .chapter : .other32        case "paper-conference": kind = hasContainer ? .chapter : .conference33        case "thesis": kind = .thesis34        case "report": kind = .report35        case "webpage", "post", "post-weblog": kind = .webpage36        default: kind = .other37        }38    }3940    func f(_ k: String) -> String? {41        guard let v = e.fields[k]?.trimmingCharacters(in: .whitespacesAndNewlines), !v.isEmpty else { return nil }42        return v43    }44    var title: String? { f("title") }45    var container: String? { f("container-title") }46    var doi: String? { f("DOI").map(TextFold.bareDOI) }47    var doiURL: String? { doi.map { "https://doi.org/" + $0 } }48    var url: String? { f("URL") }49    var isConferencePaper: Bool { e.type == "paper-conference" }50    /// The title is a part of a larger work (set in roman or in quotation marks rather than in italics).51    var isPart: Bool { kind == .article || kind == .periodical || kind == .chapter }5253    /// A literal date that says something ("in press", "forthcoming"). "n.d.", "s. d." and "no date" mean there is no date:54    /// each style then prints its own wording.55    static func literalDate(_ e: BibEntry) -> String? {56        guard let l = e.fields[ReferenceField.issuedLiteral]?.trimmingCharacters(in: .whitespaces), !l.isEmpty else { return nil }57        let folded = l.lowercased().filter { $0.isLetter }58        return ["nd", "sd", "nodate", "sansdate", "undated"].contains(folded) ? nil : l59    }60    var literalDate: String? { Ref.literalDate(e) }6162    /// Year, or the literal date ("in press"), or nil when the work has no date.63    func yearText(suffix: String?) -> String? {64        if let y = e.year { return String(y) + (suffix ?? "") }65        if let l = literalDate { return l + (suffix.map { "-" + $0 } ?? "") }66        return nil67    }6869    /// Pages with a proper en dash in simple ranges ("12-34" → "12–34"). Anything more complicated is left as stored.70    func pages(enDash: Bool = true) -> String? {71        guard let p = f("page") else { return nil }72        guard enDash else { return p }73        return Ref.enDashRanges(p)74    }75    static func enDashRanges(_ p: String) -> String {76        p.replacingOccurrences(of: "--", with: "–").split(separator: ",", omittingEmptySubsequences: false).map { part -> String in77            let hyphens = part.filter { $0 == "-" }.count78            return hyphens == 1 && !part.contains("–") ? part.replacingOccurrences(of: "-", with: "–") : String(part)79        }.joined(separator: ",")80    }81    var pagesAreRange: Bool { guard let p = f("page") else { return false }; return p.contains("-") || p.contains("–") || p.contains(",") }8283    var accessed: RefDate.Parts? { f("accessed").flatMap { RefDate.parseEDTF($0)?.parts ?? RefDate.parseLoose($0) } }8485    /// Thesis genre classes recognised from the BibTeX defaults and common wordings.86    enum Degree { case doctoral, masters, other }87    var degree: Degree {88        let g = TextFold.fold(f("genre") ?? "")89        if g.contains("phd") || g.contains("ph.d") || g.contains("doctor") || g.contains("dissertation") { return .doctoral }90        if g.contains("master") || g.contains("maitrise") || g == "ms thesis" || g == "m.s. thesis" || g == "ma thesis" { return .masters }91        return .other92    }93    /// True when the stored genre is exactly one of the defaults produced by the BibTeX importer, so a style may substitute its own wording.94    var genreIsDefault: Bool { ["PhD thesis", "Master's thesis"].contains(f("genre") ?? "") }9596    func names(_ field: String) -> [PersonName] { f(field).map { NameParser.parseList($0).filter { !$0.isOthers } } ?? [] }97}9899enum Names {100    /// "Jean-Luc" → "J.-L.", "Mary Ann" → "M. A.", "J.S." → "J. S."; lower-case particles ("van") are kept as words.101    static func initials(_ given: String, compact: Bool = false) -> String {102        var out: [String] = []103        for token in given.replacingOccurrences(of: ".", with: ". ").split(separator: " ") {104            let tok = token.trimmingCharacters(in: CharacterSet(charactersIn: "."))105            guard let first = tok.first else { continue }106            if first.isLowercase, tok.count > 1 { if !compact { out.append(tok) }; continue }107            let parts = tok.split(separator: "-").compactMap { $0.first.map { String($0).uppercased() } }108            out.append(compact ? parts.joined() : parts.map { $0 + "." }.joined(separator: "-"))109        }110        return out.joined(separator: compact ? "" : " ")111    }112113    static func display(_ n: PersonName) -> String { n.isLiteral ? n.literal! : n.family.isEmpty ? n.given : n.family }114115    /// "Family, I. I., Jr."116    static func invertedInitials(_ n: PersonName) -> String {117        if n.isLiteral { return n.literal! }118        let (given, suffix) = n.givenAndSuffix119        let ini = initials(given)120        return [n.family, ini, suffix ?? ""].filter { !$0.isEmpty }.joined(separator: ", ")121    }122    /// "I. I. Family Jr."123    static func initialsFirst(_ n: PersonName) -> String {124        if n.isLiteral { return n.literal! }125        let (given, suffix) = n.givenAndSuffix126        return [initials(given), n.family, suffix ?? ""].filter { !$0.isEmpty }.joined(separator: " ")127    }128    /// "Family, Given, Jr."129    static func invertedFull(_ n: PersonName) -> String {130        if n.isLiteral { return n.literal! }131        let (given, suffix) = n.givenAndSuffix132        return [n.family, given, suffix ?? ""].filter { !$0.isEmpty }.joined(separator: ", ")133    }134    /// "Given Family Jr."135    static func full(_ n: PersonName) -> String {136        if n.isLiteral { return n.literal! }137        let (given, suffix) = n.givenAndSuffix138        return [given, n.family, suffix ?? ""].filter { !$0.isEmpty }.joined(separator: " ")139    }140    /// "Family II" (Vancouver): initials without full stops, suffix without punctuation.141    static func vancouver(_ n: PersonName) -> String {142        if n.isLiteral { return n.literal! }143        let (given, suffix) = n.givenAndSuffix144        return [n.family, initials(given, compact: true), (suffix ?? "").replacingOccurrences(of: ".", with: "")].filter { !$0.isEmpty }.joined(separator: " ")145    }146147    /// Joins "A", "A and B", "A, B, and C". `serial` is the comma before the conjunction in lists of three or more148    /// (never used in French); `commaForTwo` adds it for two items as well ("Grazer, Brian, and Charles Fishman"; "Judge, T. A., & Kammeyer-Mueller, J. D.").149    static func join(_ items: [String], and: String, t: Terms, commaForTwo: Bool = false) -> String {150        switch items.count {151        case 0: return ""152        case 1: return items[0]153        case 2: return items[0] + (commaForTwo && !t.french ? ", " : " ") + and + " " + items[1]154        default: return items.dropLast().joined(separator: ", ") + (t.french ? " " : ", ") + and + " " + items.last!155        }156    }157}158
Files main
Menu

Theme