SPB Git

Repository Public

ReferenceFormatting.swift 8.5 KB 164 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Research/ReferenceFormatting.swift3// Description: Pure formatting of bibliographic references for the research screens, the citation picker and the4//              bibliography block: the short label of an inline citation (« Doe & Roe, 2021 ») and an APA-like entry built5//              from the fields the reference really has. Only APA is implemented on the device; another style is reported6//              as such, never imitated.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesAPI1213public enum ReferenceFormatter {14    /// The styles formatted on the device.15    public static let supportedStyles: Set<String> = ["apa"]1617    public static func isSupported(style: String) -> Bool { supportedStyles.contains(style.lowercased()) }1819    /// A BibTeX field of the reference (`volume`, `number`, `pages`, `publisher`…), whatever its JSON type.20    public static func field(_ reference: ResearchReference, _ name: String) -> String? {21        guard let fields = try? reference.fields?.decode([String: Loose].self), let value = fields[name]?.text, !value.isEmpty else { return nil }22        return value23    }2425    struct Loose: Decodable {26        var text: String?27        init(from decoder: Decoder) throws {28            let container = try decoder.singleValueContainer()29            if let string = try? container.decode(String.self) { text = string }30            else if let int = try? container.decode(Int.self) { text = String(int) }31            else if let double = try? container.decode(Double.self) { text = String(double) }32            else { text = nil }33        }34    }3536    /// "First Middle Last" → (family, given names). A single word is a family name (or an institution).37    public static func split(author: String) -> (family: String, given: [String]) {38        let trimmed = author.trimmingCharacters(in: .whitespaces)39        if trimmed.contains(",") {                                   // already "Last, First"40            let parts = trimmed.split(separator: ",", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }41            return (parts[0], parts.count > 1 ? parts[1].split(separator: " ").map(String.init) : [])42        }43        var words = trimmed.split(separator: " ").map(String.init)44        guard words.count > 1 else { return (trimmed, []) }45        var family = [words.removeLast()]46        let particles: Set<String> = ["de", "del", "della", "der", "van", "von", "le", "la", "du", "da", "dos", "den", "ten", "ter", "di"]47        while let last = words.last, particles.contains(last.lowercased()), words.count > 1 { family.insert(words.removeLast(), at: 0) }48        return (family.joined(separator: " "), words)49    }5051    /// « Doe, J. R. »52    public static func apaAuthor(_ author: String) -> String {53        let (family, given) = split(author: author)54        let initials = given.map { name in55            name.split(separator: "-").compactMap { $0.first.map { String($0).uppercased() + "." } }.joined(separator: "-")56        }57        return initials.isEmpty ? family : family + ", " + initials.joined(separator: " ")58    }5960    /// « Doe, J., Roe, J., & Poe, E. A. » (more than twenty: the first nineteen, an ellipsis, the last).61    public static func apaAuthors(_ authors: [String]) -> String {62        let names = authors.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }.map(apaAuthor)63        switch names.count {64        case 0: return ""65        case 1: return names[0]66        case 2: return names[0] + ", & " + names[1]67        case 3...20: return names.dropLast().joined(separator: ", ") + ", & " + names[names.count - 1]68        default: return names.prefix(19).joined(separator: ", ") + ", … " + names[names.count - 1]69        }70    }7172    static func terminated(_ text: String) -> String {73        guard let last = text.last else { return text }74        return ".?!".contains(last) ? text : text + "."75    }7677    /// The APA-like entry as inline Markdown (the container title and the volume are in italics). Built only from what78    /// the reference has: nothing is guessed.79    public static func apaMarkdown(_ reference: ResearchReference) -> String {80        var parts: [String] = []81        let authors = apaAuthors(reference.authors ?? [])82        let year = "(" + (reference.year.map(String.init) ?? L("s. d.")) + ")."83        let title = terminated(reference.title.trimmingCharacters(in: .whitespaces))84        if authors.isEmpty {85            parts.append(title); parts.append(year)                  // no author: the title takes the author position86        } else {87            parts.append(terminated(authors)); parts.append(year); parts.append(title)88        }89        let container = reference.journal ?? field(reference, "booktitle") ?? field(reference, "publisher")90        if let container, !container.isEmpty {91            var source = "*" + escape(container) + "*"92            if reference.journal != nil {93                if let volume = field(reference, "volume") {94                    source += ", *" + escape(volume) + "*"95                    if let number = field(reference, "number") { source += "(" + escape(number) + ")" }96                }97                if let pages = field(reference, "pages") { source += ", " + escape(pages.replacingOccurrences(of: "--", with: "–")) }98            }99            parts.append(source + ".")100        }101        if let doi = reference.doi, !doi.isEmpty {102            parts.append(doi.lowercased().hasPrefix("http") ? doi : "https://doi.org/" + doi)103        } else if let url = reference.url, !url.isEmpty {104            parts.append(url)105        }106        return ([escape(parts[0])] + parts.dropFirst().enumerated().map { index, part in107            // the source part already carries its Markdown; the others are plain text108            part.hasPrefix("*") || part.hasPrefix("http") ? part : escape(part)109        }).joined(separator: " ")110    }111112    static func escape(_ text: String) -> String {113        var out = ""114        for character in text {115            if "*_`[]\\".contains(character) { out.append("\\") }116            out.append(character)117        }118        return out119    }120121    /// The same entry without Markdown (VoiceOver, copy, sorting).122    public static func apaPlain(_ reference: ResearchReference) -> String {123        String(attributed(apaMarkdown(reference)).characters)124    }125126    public static func attributed(_ markdown: String) -> AttributedString {127        let options = AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace, failurePolicy: .returnPartiallyParsedIfPossible)128        return (try? AttributedString(markdown: markdown, options: options)) ?? AttributedString(markdown)129    }130131    /// The short label cached in a `citation` node: the server's when it gave one, else « Doe, 2021 », « Doe & Roe, 2021 »,132    /// « Doe et al., 2021 »; the cite key when there is no author.133    public static func label(_ reference: ResearchReference) -> String {134        if let label = reference.label, !label.isEmpty { return label }135        let families = (reference.authors ?? []).map { split(author: $0).family }.filter { !$0.isEmpty }136        let who: String137        switch families.count {138        case 0: who = reference.citeKey139        case 1: who = families[0]140        case 2: who = families[0] + " & " + families[1]141        default: who = families[0] + " et al."142        }143        return reference.year.map { who + ", " + String($0) } ?? who144    }145146    /// One line of authors for a list row: « J. Doe, J. Roe » or « J. Doe et 3 autres ».147    public static func authorsLine(_ reference: ResearchReference) -> String {148        let authors = (reference.authors ?? []).filter { !$0.isEmpty }149        switch authors.count {150        case 0: return L("Auteur inconnu")151        case 1, 2: return authors.joined(separator: ", ")152        default: return LF("%@ et %lld autres", authors[0], authors.count - 1)153        }154    }155156    /// Whether a reference matches a search text (title, authors, year, journal, key, DOI), accent- and case-insensitive.157    public static func matches(_ reference: ResearchReference, _ text: String) -> Bool {158        let needle = text.trimmingCharacters(in: .whitespaces)159        guard !needle.isEmpty else { return true }160        let haystack = ([reference.title, reference.citeKey, reference.journal, reference.doi, reference.year.map(String.init)].compactMap { $0 } + (reference.authors ?? [])).joined(separator: " ")161        return needle.split(separator: " ").allSatisfy { haystack.range(of: $0, options: [.caseInsensitive, .diacriticInsensitive]) != nil }162    }163}164
Files main
Menu

Theme