SPB Git

Repository Public

AcademicInspector.swift 19.6 KB 340 lines swift

1// ORIX Docs2// File: App/Sources/Inspector/AcademicInspector.swift3// Description: The inspector's References tab: citation style, the document's reference library (search, add, edit, delete, import,4//              export), the citation and cross-reference tools, and a citation check computed from the document.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import DocModel11import DocReferences1213struct AcademicInspector: View {14    /// What the reference form is editing.15    private enum FormTarget: Identifiable {16        case new, edit(BibEntry)17        var id: String { switch self { case .new: return "new"; case .edit(let e): return "edit-" + e.key } }18    }1920    let session: DocumentSession21    @State private var library: [BibEntry] = []22    @State private var styleID = "apa"23    @State private var language = "en"24    @State private var check = CitationCheck()25    @State private var query = ""26    @State private var limit = 6027    @State private var form: FormTarget?28    @State private var report: ReferenceImportReport?29    @State private var cycle: [String: Int] = [:]30    @State private var showMissing = true31    @State private var showNeverCited = false32    @State private var showIncomplete = false3334    init(session: DocumentSession) { self.session = session }3536    var body: some View {37        ScrollView {38            VStack(spacing: 0) {39                styleSection40                librarySection41                toolsSection42                checkSection43            }44        }45        .background(ORIX.Palette.chrome)46        .task(id: session.revision) { await refresh() }47        .sheet(item: $form) { target in48            let original: BibEntry? = { if case .edit(let e) = target { return e } else { return nil } }()49            ReferenceFormSheet(session: session, original: original) { saved in50                form = nil51                if let saved, original == nil { query = saved }52            }53        }54        .accessibilityIdentifier("inspector-academic")55    }5657    /// Copies what the panel shows out of the model; the citation check walks the document away from the main actor.58    private func refresh() async {59        let doc = session.doc60        library = doc.bibliography61        styleID = CitationEngine(document: doc).styleID62        language = doc.meta.language63        let result = await Task.detached(priority: .utility) { CitationCheck.compute(doc) }.value64        if !Task.isCancelled { check = result }65    }6667    // MARK: Style6869    private var styleSection: some View {70        let info = CitationEngine.styles.first { $0.id == styleID } ?? CitationEngine.styles[0]71        return InspectorSection(title: "Citation Style") {72            Picker("Citation style", selection: Binding(get: { styleID }, set: { id in73                guard id != styleID else { return }74                styleID = id75                session.perform(String(localized: "Citation Style")) { $0.doc.settings.citationStyle = id }76            })) {77                ForEach(CitationEngine.styles) { Text(verbatim: $0.name).tag($0.id) }78            }79            .labelsHidden().frame(maxWidth: .infinity, alignment: .leading)80            .accessibilityLabel(Text("Citation style")).accessibilityIdentifier("citation-style")81            HStack(alignment: .firstTextBaseline, spacing: 6) {82                Pill(text: AcademicInspector.kindName(info.kind))83                Text(verbatim: info.summary).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)84            }85            Text("Built-in styles. Titles are printed as stored; CSL style files cannot be loaded.")86                .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)87        }88    }8990    static func kindName(_ kind: CitationStyleInfo.Kind) -> String {91        switch kind {92        case .authorDate: return String(localized: "Author–date")93        case .numeric: return String(localized: "Numeric")94        case .authorPage: return String(localized: "Author–page")95        }96    }9798    // MARK: Library99100    private func matches(_ e: BibEntry, _ needle: String) -> Bool {101        if needle.isEmpty { return true }102        var hay = e.key + " " + e.title + " " + (e.year.map(String.init) ?? "") + " " + (e.fields["container-title"] ?? "")103        for n in e.authors + e.editors { hay += " " + n.family + " " + n.given + " " + (n.literal ?? "") }104        let folded = hay.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)105        return needle.split(separator: " ").allSatisfy { folded.contains($0) }106    }107108    private var librarySection: some View {109        let needle = query.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil).trimmingCharacters(in: .whitespaces)110        let shown = library.filter { matches($0, needle) }111        let engine = CitationEngine(styleID: styleID, language: language)112        let incomplete = Dictionary(uniqueKeysWithValues: check.incomplete.map { ($0.key, $0.missing) })113        return InspectorSection(title: "Reference Library") {114            HStack(spacing: 6) {115                Text(library.count == 1 ? "1 reference" : "\(library.count) references").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text)116                    .accessibilityIdentifier("library-count")117                Spacer()118                Button { form = .new } label: { Image(systemName: "plus") }119                    .buttonStyle(.borderless).help("Add a reference").accessibilityLabel(Text("Add a reference")).accessibilityIdentifier("library-add")120                Button { if let r = ReferenceLibrary.importReferences(into: session) { report = r } } label: { Image(systemName: "square.and.arrow.down") }121                    .buttonStyle(.borderless).help("Import from BibTeX, RIS or CSL-JSON").accessibilityLabel(Text("Import references")).accessibilityIdentifier("library-import")122                Menu {123                    ForEach(ReferenceLibrary.ExportFormat.allCases) { format in124                        Button(format.title) {125                            let name = session.doc.meta.title.isEmpty ? String(localized: "References") : session.doc.meta.title126                            if let message = ReferenceLibrary.export(session.doc.bibliography, format: format, suggestedName: name, window: session.canvas?.window) { session.statusMessage = message }127                        }128                    }129                } label: { Image(systemName: "square.and.arrow.up") }130                    .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().disabled(library.isEmpty)131                    .help("Export the library").accessibilityLabel(Text("Export the library")).accessibilityIdentifier("library-export")132            }133            if let report { ImportReportView(report: report) { self.report = nil } }134            if library.isEmpty {135                VStack(alignment: .leading, spacing: ORIX.Space.s) {136                    Text("The library is empty. Citations can only point to entries stored here: import a file or add a reference by hand.")137                        .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)138                    PanelButton(title: "Import References…", symbol: "square.and.arrow.down") { if let r = ReferenceLibrary.importReferences(into: session) { report = r } }139                    PanelButton(title: "Add Reference…", symbol: "plus") { form = .new }140                }141            } else {142                HStack(spacing: 6) {143                    Image(systemName: "magnifyingglass").font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)144                    TextField("", text: $query, prompt: Text("Search the library")).textFieldStyle(.plain).font(ORIX.Font.label)145                        .accessibilityLabel(Text("Search the library")).accessibilityIdentifier("library-search")146                    if !query.isEmpty {147                        Button { query = "" } label: { Image(systemName: "xmark.circle.fill") }.buttonStyle(.plain).foregroundStyle(ORIX.Palette.textTertiary)148                            .accessibilityLabel(Text("Clear the search"))149                    }150                }151                .padding(.horizontal, 7).padding(.vertical, 5)152                .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))153                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline))154                LazyVStack(alignment: .leading, spacing: 6) {155                    ForEach(shown.prefix(limit)) { e in156                        ReferenceRow(entry: e, text: engine.formattedEntry(e, number: nil).attributedText, citations: check.sites[e.key]?.count ?? 0,157                                     missing: incomplete[e.key] ?? [],158                                     onCite: { cite(e.key) }, onEdit: { form = .edit(e) }, onDelete: { delete(e) })159                    }160                }161                if shown.isEmpty {162                    Text("No reference matches “\(query)”.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)163                } else if shown.count > limit {164                    PanelButton(title: "Show more (\(shown.count - limit) hidden)", symbol: "ellipsis") { limit += 120 }165                }166            }167        }168    }169170    private func cite(_ key: String) {171        session.perform(String(localized: "Insert Citation")) { $0.insertInline(.citation(Citation(key))) }172        session.canvas?.window?.makeFirstResponder(session.canvas)173    }174175    private func delete(_ e: BibEntry) {176        let count = check.sites[e.key]?.count ?? 0177        guard count > 0 else { ReferenceLibrary.delete(key: e.key, in: session); return }178        let alert = NSAlert()179        alert.alertStyle = .warning180        alert.messageText = String(localized: "“\(e.key)” is cited in the document.")181        alert.informativeText = count == 1182            ? String(localized: "It is cited once. If you delete the entry, that citation stays in the text and is shown as missing (?\(e.key)) until you restore the entry or remove the citation.")183            : String(localized: "It is cited \(count) times. If you delete the entry, those citations stay in the text and are shown as missing (?\(e.key)) until you restore the entry or remove them.")184        alert.addButton(withTitle: String(localized: "Cancel"))185        let destructive = alert.addButton(withTitle: String(localized: "Delete Entry"))186        destructive.hasDestructiveAction = true187        let key = e.key188        let finish: (NSApplication.ModalResponse) -> Void = { [session] response in189            if response == .alertSecondButtonReturn { ReferenceLibrary.delete(key: key, in: session) }190        }191        if let window = session.canvas?.window { alert.beginSheetModal(for: window, completionHandler: finish) } else { finish(alert.runModal()) }192    }193194    // MARK: Tools195196    private var toolsSection: some View {197        let _ = session.selectionRevision198        return InspectorSection(title: "Citations and References") {199            LazyVGrid(columns: [GridItem(.flexible(), spacing: 6), GridItem(.flexible(), spacing: 6)], spacing: 6) {200                tool(.insertCitation, "Citation…", "quote.opening")201                tool(.insertBibliography, "Bibliography", "books.vertical")202                tool(.insertFigureCaption, "Figure Caption", "photo")203                tool(.insertTableCaption, "Table Caption", "tablecells")204                tool(.insertListOfFigures, "List of Figures", "list.bullet.rectangle")205                tool(.insertListOfTables, "List of Tables", "list.bullet.rectangle.portrait")206            }207            tool(.insertCrossReference, "Cross-Reference…", "arrow.triangle.branch")208            tool(.insertEquationNumber, "Numbered Display Equation…", "function")209            PanelButton(title: "Caption with Custom Label…", symbol: "text.below.photo") { session.activeSheet = .caption }210                .accessibilityIdentifier("tool-caption")211        }212    }213214    private func tool(_ command: EditorCommand, _ title: LocalizedStringKey, _ symbol: String) -> some View {215        PanelButton(title: title, symbol: symbol, isEnabled: session.isEnabled(command)) { session.run(command) }216            .help(Text(verbatim: command.title))217            .accessibilityIdentifier("tool-\(command.rawValue)")218    }219220    // MARK: Citation check221222    private var checkSection: some View {223        InspectorSection(title: "Citation Check") {224            let works = check.sites.count225            Text(check.citationCount == 0 ? String(localized: "The document has no citation yet.")226                 : String(localized: "\(check.citationCount) citations to \(works) works; \(library.count) entries in the library."))227                .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)228                .accessibilityIdentifier("check-summary")229230            if check.citationCount > 0 && !check.hasBibliographyBlock {231                Notice(kind: .warning, text: String(localized: "The document cites works but has no bibliography."))232                PanelButton(title: "Add Bibliography at the End", symbol: "books.vertical") { ReferenceLibrary.appendBibliography(in: session) }233            }234            if check.citationCount > 0 && check.missingKeys.isEmpty && check.incomplete.allSatisfy({ $0.firstSite == nil }) {235                Notice(kind: .success, text: String(localized: "Every citation has a complete entry in the library."))236            }237238            CollapsibleGroup(title: String(localized: "Cited but not in the library"), symbol: "xmark.octagon.fill", tint: ORIX.Palette.critical,239                             count: check.missingKeys.count, expanded: $showMissing) {240                if check.missingKeys.isEmpty { emptyLine("None.") }241                ForEach(check.missingKeys) { m in242                    checkRow(key: m.key, detail: m.sites.count == 1 ? String(localized: "Cited once. Show in the document.") : String(localized: "Cited \(m.sites.count) times. Show the next one.")) {243                        let i = cycle[m.key, default: 0] % max(1, m.sites.count)244                        cycle[m.key] = i + 1245                        if m.sites.indices.contains(i) { ReferenceLibrary.reveal(m.sites[i], in: session) }246                    }247                }248            }249            CollapsibleGroup(title: String(localized: "Incomplete entries"), symbol: "exclamationmark.triangle.fill", tint: ORIX.Palette.warning,250                             count: check.incomplete.count, expanded: $showIncomplete) {251                if check.incomplete.isEmpty { emptyLine("None.") }252                ForEach(check.incomplete) { inc in253                    HStack(alignment: .top, spacing: 4) {254                        checkRow(key: inc.key, detail: ReferenceLibrary.missingSummary(inc.missing) + (inc.firstSite == nil ? "" : " · " + String(localized: "Show the first citation."))) {255                            if let site = inc.firstSite { ReferenceLibrary.reveal(site, in: session) } else if let e = library.first(where: { $0.key == inc.key }) { form = .edit(e) }256                        }257                        Button { if let e = library.first(where: { $0.key == inc.key }) { form = .edit(e) } } label: { Image(systemName: "pencil") }258                            .buttonStyle(.borderless).help("Complete this entry").accessibilityLabel(Text("Edit \(inc.key)"))259                    }260                }261            }262            CollapsibleGroup(title: String(localized: "Never cited"), symbol: "circle.dashed", tint: ORIX.Palette.textSecondary,263                             count: check.neverCited.count, expanded: $showNeverCited) {264                if check.neverCited.isEmpty { emptyLine("None.") }265                ForEach(check.neverCited.prefix(200), id: \.self) { key in266                    checkRow(key: key, detail: String(localized: "Show in the library.")) { query = key; limit = 60 }267                }268                if check.neverCited.count > 200 { emptyLine("Only the first 200 are listed.") }269            }270        }271    }272273    private func emptyLine(_ text: LocalizedStringKey) -> some View {274        Text(text).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).padding(.vertical, 2)275    }276277    private func checkRow(key: String, detail: String, action: @escaping () -> Void) -> some View {278        Button(action: action) {279            VStack(alignment: .leading, spacing: 1) {280                Text(verbatim: key).font(.system(size: 11, design: .monospaced)).foregroundStyle(ORIX.Palette.text).lineLimit(1)281                Text(verbatim: detail).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)282                    .multilineTextAlignment(.leading)283            }284            .frame(maxWidth: .infinity, alignment: .leading)285            .padding(.vertical, 3)286            .contentShape(Rectangle())287        }288        .buttonStyle(.plain)289    }290}291292/// One entry of the library: formatted in the current style, with its key, use and completeness.293private struct ReferenceRow: View {294    let entry: BibEntry295    let text: AttributedString296    let citations: Int297    let missing: [String]298    let onCite: () -> Void299    let onEdit: () -> Void300    let onDelete: () -> Void301    @State private var hover = false302303    var body: some View {304        VStack(alignment: .leading, spacing: 4) {305            Text(text).font(.system(size: 11)).foregroundStyle(ORIX.Palette.text).lineLimit(4).fixedSize(horizontal: false, vertical: true)306                .textSelection(.enabled)307            FlowLayout(spacing: 4, lineSpacing: 3) {308                Text(verbatim: entry.key).font(.system(size: 9.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)309                    .padding(.vertical, 2)310                Chip(text: ReferenceTypeInfo.name(entry.type))311                if citations > 0 {312                    Chip(text: citations == 1 ? String(localized: "Cited once") : String(localized: "Cited \(citations)×"), symbol: "quote.opening", color: ORIX.Palette.accent)313                } else {314                    Chip(text: String(localized: "Not cited"))315                }316                if !missing.isEmpty {317                    Chip(text: String(localized: "\(missing.count) missing"), symbol: "exclamationmark.triangle.fill", color: ORIX.Palette.warning)318                        .help(Text(verbatim: ReferenceLibrary.missingSummary(missing)))319                        .accessibilityLabel(Text(verbatim: ReferenceLibrary.missingSummary(missing)))320                }321            }322            HStack(spacing: 10) {323                Button(action: onCite) { Label("Cite", systemImage: "quote.opening") }.help("Insert a citation to this work at the caret")324                Button(action: onEdit) { Label("Edit Reference", systemImage: "pencil") }325                Spacer()326                Button(role: .destructive, action: onDelete) { Image(systemName: "trash") }327                    .help("Delete this entry").accessibilityLabel(Text("Delete \(entry.key)"))328            }329            .buttonStyle(.borderless).controlSize(.small).font(.system(size: 10.5))330        }331        .padding(8)332        .frame(maxWidth: .infinity, alignment: .leading)333        .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.surface))334        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(hover ? ORIX.Palette.accent.opacity(0.45) : ORIX.Palette.hairline))335        .onHover { hover = $0 }336        .accessibilityElement(children: .contain)337        .accessibilityIdentifier("reference-\(entry.key)")338    }339}340
Files main
Menu

Theme