SPB Git

Repository Public

ReferenceLibrary.swift 10.6 KB 216 lines swift

1// ORIX Docs2// File: App/Sources/Inspector/ReferenceLibrary.swift3// Description: Operations on the document's reference library shared by the References inspector and the citation picker: import4//              (.bib, .ris, CSL-JSON) with a full report, export, saving and deleting entries, and the citation check computed from the model.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import UniformTypeIdentifiers10import DocModel11import DocReferences1213/// What an import did, file by file: nothing is dropped without a line here.14nonisolated struct ReferenceImportReport: Sendable, Equatable {15    nonisolated struct File: Sendable, Equatable, Identifiable {16        var id: String { name }17        var name: String18        /// Entries the parser read.19        var parsed: Int20        /// The parser's remarks (line numbers, generated keys, encoding).21        var issues: [String]22        /// One line per skipped or renamed entry, then the totals.23        var log: [String]24    }25    var files: [File]26    var added: Int27}2829/// A place in the document where a citation sits.30nonisolated struct CitationSite: Sendable, Hashable {31    var story: StoryID32    var path: ParaPath33    var offset: Int34}3536/// The state of the citations against the library, computed from the model.37nonisolated struct CitationCheck: Sendable, Equatable {38    nonisolated struct Missing: Sendable, Equatable, Identifiable { var id: String { key }; var key: String; var sites: [CitationSite] }39    nonisolated struct Incomplete: Sendable, Equatable, Identifiable { var id: String { key }; var key: String; var missing: [String]; var firstSite: CitationSite? }40    /// Cited keys that no library entry has.41    var missingKeys: [Missing] = []42    /// Keys of library entries no citation refers to.43    var neverCited: [String] = []44    /// Entries that lack fields a complete record of their type needs.45    var incomplete: [Incomplete] = []46    /// Key → places where it is cited.47    var sites: [String: [CitationSite]] = [:]48    var citationCount = 049    var hasBibliographyBlock = false5051    static func compute(_ doc: DocumentModel) -> CitationCheck {52        var check = CitationCheck()53        var order: [String] = []54        doc.forEachParagraphEverywhere { p, story, path in55            var offset = 056            for r in p.runs {57                if !r.isDeleted, case .citation(let c)? = r.inline {58                    check.citationCount += 159                    for item in c.items {60                        if check.sites[item.key] == nil { order.append(item.key) }61                        check.sites[item.key, default: []].append(CitationSite(story: story, path: path, offset: offset))62                    }63                }64                offset += r.length65            }66        }67        let keys = Set(doc.bibliography.map(\.key))68        check.missingKeys = order.filter { !keys.contains($0) }.map { Missing(key: $0, sites: check.sites[$0] ?? []) }69        check.neverCited = doc.bibliography.map(\.key).filter { check.sites[$0] == nil }70        check.incomplete = doc.bibliography.compactMap { e in71            let missing = ReferenceChecks.missingFields(e)72            return missing.isEmpty ? nil : Incomplete(key: e.key, missing: missing, firstSite: check.sites[e.key]?.first)73        }74        check.hasBibliographyBlock = doc.body.contains { if case .bibliography = $0 { return true } else { return false } }75        return check76    }77}7879enum ReferenceLibrary {80    /// Readable name of a CSL variable reported by `ReferenceChecks.missingFields`.81    static func fieldName(_ variable: String) -> String {82        switch variable {83        case "author": return String(localized: "author")84        case "issued": return String(localized: "date")85        case "title": return String(localized: "title")86        case "container-title": return String(localized: "journal or book title")87        case "volume": return String(localized: "volume")88        case "page": return String(localized: "pages")89        case "page or DOI": return String(localized: "pages or DOI")90        case "publisher": return String(localized: "publisher")91        case "genre": return String(localized: "thesis type")92        case "URL": return String(localized: "URL")93        default: return variable94        }95    }9697    static func missingSummary(_ fields: [String]) -> String {98        String(localized: "Missing: \(fields.map(fieldName).joined(separator: ", "))")99    }100101    /// Lets the user pick bibliography files and merges them into the document's library (one undoable step).102    /// Returns nil when the panel is cancelled.103    static func importReferences(into session: DocumentSession) -> ReferenceImportReport? {104        let panel = NSOpenPanel()105        panel.title = String(localized: "Import References")106        panel.message = String(localized: "Choose BibTeX (.bib), RIS (.ris) or CSL-JSON (.json) files.")107        panel.prompt = String(localized: "Import")108        panel.allowsMultipleSelection = true109        panel.canChooseDirectories = false110        panel.allowedContentTypes = ["bib", "bibtex", "ris", "json"].compactMap { UTType(filenameExtension: $0) }111        panel.allowsOtherFileTypes = true112        guard panel.runModal() == .OK, !panel.urls.isEmpty else { return nil }113        return importReferences(from: panel.urls, into: session)114    }115116    static func importReferences(from urls: [URL], into session: DocumentSession) -> ReferenceImportReport {117        let before = session.doc.bibliography118        var library = before119        var files: [ReferenceImportReport.File] = []120        for url in urls {121            let name = url.lastPathComponent122            let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0123            guard size <= 64 * 1024 * 1024 else {124                files.append(.init(name: name, parsed: 0, issues: [String(localized: "The file is larger than 64 MB and was not read.")], log: []))125                continue126            }127            guard let data = try? Data(contentsOf: url) else {128                files.append(.init(name: name, parsed: 0, issues: [String(localized: "The file could not be read.")], log: []))129                continue130            }131            let parsed = BibliographyImporter.importEntries(data, fileExtension: url.pathExtension)132            let merged = BibliographyImporter.merge(parsed.entries, into: library)133            library = merged.entries134            files.append(.init(name: name, parsed: parsed.entries.count, issues: parsed.issues, log: merged.log))135        }136        if library != before {137            session.perform(String(localized: "Import References")) { $0.doc.bibliography = library }138        }139        return ReferenceImportReport(files: files, added: library.count - before.count)140    }141142    enum ExportFormat: String, CaseIterable, Identifiable {143        case bibtex, ris, cslJSON144        var id: String { rawValue }145        var title: String {146            switch self { case .bibtex: return "BibTeX (.bib)"; case .ris: return "RIS (.ris)"; case .cslJSON: return "CSL-JSON (.json)" }147        }148        var fileExtension: String { switch self { case .bibtex: return "bib"; case .ris: return "ris"; case .cslJSON: return "json" } }149    }150151    /// Writes the library to a file chosen by the user. Returns a sentence for the status bar, nil when cancelled.152    @discardableResult153    static func export(_ entries: [BibEntry], format: ExportFormat, suggestedName: String, window: NSWindow?) -> String? {154        let panel = NSSavePanel()155        panel.title = String(localized: "Export References")156        panel.allowedContentTypes = [UTType(filenameExtension: format.fileExtension) ?? .data]157        panel.nameFieldStringValue = suggestedName + "." + format.fileExtension158        panel.canCreateDirectories = true159        guard panel.runModal() == .OK, let url = panel.url else { return nil }160        do {161            let data: Data162            switch format {163            case .bibtex: data = Data(BibTeXWriter.write(entries).utf8)164            case .ris: data = Data(RISWriter.write(entries).utf8)165            case .cslJSON: data = try CSLJSON.write(entries)166            }167            try data.write(to: url, options: .atomic)168            return String(localized: "Exported \(entries.count) references to \(url.lastPathComponent)")169        } catch {170            let alert = NSAlert()171            alert.messageText = String(localized: "The references could not be exported.")172            alert.informativeText = "\(error.localizedDescription)"173            if let window { alert.beginSheetModal(for: window) } else { alert.runModal() }174            return nil175        }176    }177178    /// Adds an entry or replaces the one whose key was `originalKey`. When the key of a cited entry changes, its citations follow.179    static func save(_ entry: BibEntry, replacing originalKey: String?, in session: DocumentSession) {180        session.perform(originalKey == nil ? String(localized: "Add Reference") : String(localized: "Edit Reference")) { e in181            if let originalKey, let i = e.doc.bibliography.firstIndex(where: { $0.key == originalKey }) {182                e.doc.bibliography[i] = entry183                if originalKey != entry.key {184                    e.doc.mutateEveryParagraph { p in185                        for r in p.runs.indices {186                            guard case .citation(var c)? = p.runs[r].inline, c.items.contains(where: { $0.key == originalKey }) else { continue }187                            for k in c.items.indices where c.items[k].key == originalKey { c.items[k].key = entry.key }188                            p.runs[r].inline = .citation(c)189                        }190                    }191                }192            } else {193                e.doc.bibliography.append(entry)194            }195        }196    }197198    static func delete(key: String, in session: DocumentSession) {199        session.perform(String(localized: "Delete Reference")) { e in e.doc.bibliography.removeAll { $0.key == key } }200    }201202    static func reveal(_ site: CitationSite, in session: DocumentSession) {203        guard session.doc.blocks(in: site.story).paragraph(at: site.path) != nil else { return }204        session.reveal(story: site.story, path: site.path, range: site.offset..<(site.offset + 1))205    }206207    /// Appends the generated bibliography at the end of the body.208    static func appendBibliography(in session: DocumentSession) {209        let title = session.doc.meta.language.hasPrefix("fr") ? "Références" : String(localized: "References")210        session.perform(String(localized: "Insert Bibliography")) { e in211            e.doc.body.append(.bibliography(BibliographyBlock(title: title)))212            e.doc.body.append(.paragraph(Paragraph()))213        }214    }215}216
Files main
Menu

Theme