Repository Public
1// ORIX Docs2// File: App/Sources/Sheets/CitationSheet.swift3// Description: The citation picker: searches the document's reference library, cites one or several works with locator, prefix,4// suffix and author suppression, and previews the in-text citation. Only entries of the library can be cited.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel10import DocReferences1112struct CitationSheet: View {13 let session: DocumentSession14 private let story: StoryID15 /// Position of the citation being edited (the selection covers it); nil inserts a new one.16 private let existing: Position?1718 @State private var query = ""19 @State private var items: [CitationItem]20 @State private var addBibliography = false21 @State private var report: ReferenceImportReport?22 @State private var showForm = false23 @FocusState private var searchFocused: Bool2425 init(session: DocumentSession) {26 self.session = session27 let sel = session.selection28 story = sel.story29 var found: Position?30 var initial: [CitationItem] = []31 if !sel.isCaret, sel.start.path == sel.end.path, sel.end.offset - sel.start.offset == 1,32 case .citation(let c)? = session.editor.inline(at: sel.start, in: sel.story) {33 found = sel.start; initial = c.items34 }35 existing = found36 _items = State(initialValue: initial)37 }3839 private func close() { session.activeSheet = nil }4041 private func cleaned(_ items: [CitationItem]) -> [CitationItem] {42 items.map { i in43 func tidy(_ s: String?) -> String? { let t = (s ?? "").trimmingCharacters(in: .whitespaces); return t.isEmpty ? nil : t }44 return CitationItem(key: i.key, locator: tidy(i.locator), prefix: tidy(i.prefix), suffix: tidy(i.suffix), suppressAuthor: i.suppressAuthor)45 }46 }4748 /// The in-text citation as the document's style will print it, computed on a copy of the document that already holds it.49 private func preview(_ library: Set<String>) -> String {50 let citation = Citation(items: cleaned(items))51 guard !citation.items.isEmpty else { return "" }52 var e = session.editor53 if let existing { let s = story; e.updateInline(at: existing, in: s) { $0 = .citation(citation) } } else { e.insertInline(.citation(citation)) }54 let doc = e.doc55 return CitationEngine(document: doc).citationText(citation, document: doc, numbering: Numbering(doc))56 }5758 private func commit() {59 let citation = Citation(items: cleaned(items))60 guard !citation.items.isEmpty else { return }61 let appendBibliography = addBibliography62 let title = session.doc.meta.language.hasPrefix("fr") ? "Références" : String(localized: "References")63 if let existing {64 let s = story65 session.perform(String(localized: "Edit Citation")) { e in e.updateInline(at: existing, in: s) { $0 = .citation(citation) } }66 } else {67 session.perform(String(localized: "Insert Citation")) { e in68 e.insertInline(.citation(citation))69 if appendBibliography {70 e.doc.body.append(.bibliography(BibliographyBlock(title: title)))71 e.doc.body.append(.paragraph(Paragraph()))72 }73 }74 }75 close()76 }7778 private func toggle(_ key: String) {79 if let i = items.firstIndex(where: { $0.key == key }) { items.remove(at: i) } else { items.append(CitationItem(key: key)) }80 }8182 private func importReferences() {83 if let r = ReferenceLibrary.importReferences(into: session) { report = r }84 }8586 var body: some View {87 let _ = session.revision88 let library = session.doc.bibliography89 let keys = Set(library.map(\.key))90 let hasBibliography = session.doc.body.contains { if case .bibliography = $0 { return true } else { return false } }91 let engine = CitationEngine(styleID: session.doc.settings.citationStyle, language: session.doc.meta.language)92 SheetScaffold(title: existing == nil ? "Insert Citation" : "Edit Citation", symbol: "quote.opening",93 subtitle: "Cite works from this document's reference library. Style: \(engine.info.name).", width: 760,94 primaryTitle: existing == nil ? "Insert" : "Update", primaryEnabled: !items.isEmpty && items.allSatisfy { keys.contains($0.key) },95 onPrimary: commit, onCancel: close,96 accessory: {97 Button { importReferences() } label: { Label("Import References…", systemImage: "square.and.arrow.down") }98 .buttonStyle(ORIXButtonStyle(prominent: false)).accessibilityIdentifier("citation-import")99 Button { showForm = true } label: { Label("Add Reference…", systemImage: "plus") }100 .buttonStyle(ORIXButtonStyle(prominent: false)).accessibilityIdentifier("citation-add")101 }) {102 VStack(alignment: .leading, spacing: ORIX.Space.m) {103 if let report { ImportReportView(report: report) { self.report = nil } }104 if library.isEmpty {105 VStack(spacing: ORIX.Space.s) {106 EmptyState(symbol: "books.vertical", title: "The reference library is empty",107 message: "A citation always points to an entry of the document's library. Import a BibTeX, RIS or CSL-JSON file, or add a reference by hand, then cite it here.")108 HStack(spacing: ORIX.Space.s) {109 Button("Import References…") { importReferences() }.buttonStyle(ORIXButtonStyle())110 Button("Add Reference…") { showForm = true }.buttonStyle(ORIXButtonStyle(prominent: false))111 }112 .padding(.bottom, ORIX.Space.xl)113 }114 .frame(maxWidth: .infinity).frame(height: 300)115 } else {116 HStack(alignment: .top, spacing: ORIX.Space.l) {117 libraryColumn(library, engine: engine).frame(width: 370)118 selectionColumn(library: library, keys: keys, hasBibliography: hasBibliography)119 }120 }121 }122 }123 .sheet(isPresented: $showForm) {124 ReferenceFormSheet(session: session, original: nil) { saved in125 showForm = false126 if let saved, !items.contains(where: { $0.key == saved }) { items.append(CitationItem(key: saved)) }127 }128 }129 .onAppear { searchFocused = true }130 }131132 private func matches(_ e: BibEntry, _ needle: String) -> Bool {133 if needle.isEmpty { return true }134 var hay = e.key + " " + e.title + " " + (e.year.map(String.init) ?? "") + " " + (e.fields["container-title"] ?? "")135 for n in e.authors + e.editors { hay += " " + n.family + " " + n.given + " " + (n.literal ?? "") }136 let folded = hay.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)137 return needle.split(separator: " ").allSatisfy { folded.contains($0) }138 }139140 private func libraryColumn(_ library: [BibEntry], engine: CitationEngine) -> some View {141 let needle = query.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil).trimmingCharacters(in: .whitespaces)142 let shown = library.filter { matches($0, needle) }143 return VStack(alignment: .leading, spacing: ORIX.Space.s) {144 HStack(spacing: 6) {145 Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)146 TextField("", text: $query, prompt: Text("Search author, title, year or key")).textFieldStyle(.plain).font(ORIX.Font.body)147 .focused($searchFocused).accessibilityLabel(Text("Search the library")).accessibilityIdentifier("citation-search")148 Text("\(shown.count) of \(library.count)").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).monospacedDigit()149 }150 .padding(.horizontal, 8).padding(.vertical, 6).well()151 ScrollView {152 LazyVStack(alignment: .leading, spacing: 2) {153 ForEach(shown) { e in154 let index = items.firstIndex { $0.key == e.key }155 Button { toggle(e.key) } label: {156 HStack(alignment: .top, spacing: 8) {157 Image(systemName: index == nil ? "circle" : "checkmark.circle.fill").font(.system(size: 13))158 .foregroundStyle(index == nil ? ORIX.Palette.textTertiary : ORIX.Palette.accent).padding(.top, 1)159 VStack(alignment: .leading, spacing: 2) {160 Text(engine.formattedEntry(e, number: nil).attributedText).font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.text)161 .lineLimit(3).multilineTextAlignment(.leading)162 Text(verbatim: e.key).font(.system(size: 10, design: .monospaced)).foregroundStyle(ORIX.Palette.textTertiary)163 }164 Spacer(minLength: 0)165 }166 .padding(.horizontal, 8).padding(.vertical, 6)167 .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(index == nil ? Color.clear : ORIX.Palette.accent.opacity(0.11)))168 .contentShape(Rectangle())169 }170 .buttonStyle(.plain)171 .accessibilityAddTraits(index == nil ? [] : .isSelected)172 .accessibilityHint(Text(index == nil ? "Adds this work to the citation" : "Removes this work from the citation"))173 }174 if shown.isEmpty {175 Text("No reference matches “\(query)”.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).padding(ORIX.Space.l)176 }177 }178 .padding(4)179 }180 .frame(height: 320).well()181 .accessibilityIdentifier("citation-library")182 }183 }184185 private func selectionColumn(library: [BibEntry], keys: Set<String>, hasBibliography: Bool) -> some View {186 VStack(alignment: .leading, spacing: ORIX.Space.s) {187 FieldLabel("In-text citation")188 Group {189 if items.isEmpty {190 Text("Select one or more works on the left.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textTertiary)191 } else {192 Text(verbatim: preview(keys)).font(.system(size: 14, design: .serif)).foregroundStyle(ORIX.Palette.text).textSelection(.enabled)193 .accessibilityIdentifier("citation-preview")194 }195 }196 .frame(maxWidth: .infinity, minHeight: 34, alignment: .leading).padding(.horizontal, 10).padding(.vertical, 6)197 .background(ORIX.Palette.surfaceRaised).well()198199 FieldLabel(items.count > 1 ? "Cited works, in order" : "Cited work")200 ScrollView {201 VStack(alignment: .leading, spacing: 6) {202 if items.isEmpty {203 Text("Locator, prefix and suffix are set here for each work you select.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textTertiary)204 .fixedSize(horizontal: false, vertical: true).padding(6)205 }206 ForEach($items, id: \.key) { $item in207 let entry = library.first { $0.key == item.key }208 VStack(alignment: .leading, spacing: 6) {209 HStack(spacing: 6) {210 Text(verbatim: entry.map(shortLabel) ?? item.key).font(.system(size: 11.5, weight: .semibold)).foregroundStyle(ORIX.Palette.text).lineLimit(1)211 Spacer(minLength: 4)212 if items.count > 1, let i = items.firstIndex(where: { $0.key == item.key }) {213 Button { items.swapAt(i, i - 1) } label: { Image(systemName: "chevron.up") }214 .buttonStyle(.borderless).disabled(i == 0).accessibilityLabel(Text("Move up"))215 Button { items.swapAt(i, i + 1) } label: { Image(systemName: "chevron.down") }216 .buttonStyle(.borderless).disabled(i == items.count - 1).accessibilityLabel(Text("Move down"))217 }218 Button { toggle(item.key) } label: { Image(systemName: "xmark.circle.fill") }219 .buttonStyle(.borderless).foregroundStyle(ORIX.Palette.textTertiary)220 .help("Remove from the citation").accessibilityLabel(Text("Remove from the citation"))221 }222 if entry == nil {223 Notice(kind: .error, text: String(localized: "“\(item.key)” is not in the library. Remove it or import the entry."))224 } else {225 HStack(spacing: 6) {226 optionField("Prefix", prompt: "see", text: Binding(get: { item.prefix ?? "" }, set: { item.prefix = $0 }))227 optionField("Locator", prompt: "p. 12", text: Binding(get: { item.locator ?? "" }, set: { item.locator = $0 }))228 optionField("Suffix", prompt: "emphasis added", text: Binding(get: { item.suffix ?? "" }, set: { item.suffix = $0 }))229 }230 Toggle("Suppress author", isOn: $item.suppressAuthor).toggleStyle(.checkbox).font(ORIX.Font.label)231 .help("Prints the year only, for when the author is named in the sentence.")232 }233 }234 .padding(8)235 .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))236 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline))237 }238 }239 .padding(6).frame(maxWidth: .infinity, alignment: .leading)240 }241 .frame(height: existing == nil && !hasBibliography ? 216 : 246).well()242243 if existing == nil && !hasBibliography {244 Toggle("Add the bibliography at the end of the document", isOn: $addBibliography).toggleStyle(.checkbox).font(ORIX.Font.label)245 .help("The document has no bibliography yet. The generated list shows the works that are cited.")246 .accessibilityIdentifier("citation-add-bibliography")247 }248 }249 }250251 private func optionField(_ label: LocalizedStringKey, prompt: String, text: Binding<String>) -> some View {252 VStack(alignment: .leading, spacing: 2) {253 Text(label).font(.system(size: 9.5, weight: .medium)).foregroundStyle(ORIX.Palette.textTertiary)254 TextField("", text: text, prompt: Text(verbatim: prompt)).textFieldStyle(.roundedBorder).controlSize(.small)255 .accessibilityLabel(Text(label))256 }257 }258259 /// "Boucher & Roy (2024)" style label for the list of cited works; taken from the entry, never invented.260 private func shortLabel(_ e: BibEntry) -> String {261 let people = (e.authors.isEmpty ? e.editors : e.authors).filter { !$0.isOthers }262 func name(_ p: PersonName) -> String { p.isLiteral ? (p.literal ?? "") : p.family }263 var who: String264 switch people.count {265 case 0: who = e.title.isEmpty ? e.key : e.title266 case 1: who = name(people[0])267 case 2: who = name(people[0]) + " & " + name(people[1])268 default: who = name(people[0]) + " et al."269 }270 if let y = e.year { who += " (\(y))" }271 return who272 }273}274275/// What an import read, skipped and renamed, file by file.276struct ImportReportView: View {277 let report: ReferenceImportReport278 let onDismiss: () -> Void279 var body: some View {280 VStack(alignment: .leading, spacing: 6) {281 HStack {282 Image(systemName: "square.and.arrow.down").font(.system(size: 11, weight: .semibold)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)283 Text("Import report: \(report.added) added").font(.system(size: 11.5, weight: .semibold)).foregroundStyle(ORIX.Palette.text)284 Spacer()285 Button(action: onDismiss) { Image(systemName: "xmark") }.buttonStyle(.borderless)286 .help("Dismiss the report").accessibilityLabel(Text("Dismiss the import report"))287 }288 ScrollView {289 VStack(alignment: .leading, spacing: 6) {290 ForEach(report.files) { f in291 VStack(alignment: .leading, spacing: 2) {292 Text("\(f.name): \(f.parsed) entries read").font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.text)293 ForEach(Array(f.issues.enumerated()), id: \.offset) { _, line in294 Label { Text(verbatim: line) } icon: { Image(systemName: "exclamationmark.triangle").foregroundStyle(ORIX.Palette.warning) }295 .font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textSecondary)296 }297 ForEach(Array(f.log.enumerated()), id: \.offset) { _, line in298 Text(verbatim: line).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textSecondary)299 }300 }301 .textSelection(.enabled)302 }303 }304 .frame(maxWidth: .infinity, alignment: .leading)305 }306 .frame(maxHeight: 110)307 }308 .padding(10)309 .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.accent.opacity(0.07)))310 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.accent.opacity(0.25)))311 .accessibilityIdentifier("import-report")312 }313}314