Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Research/Citations.swift3// Description: The two research views of the editors' atom sheets: `CitationPickerView` (search the references, give a4// locator, return what a `citation` inline node stores) and `BibliographyView` (the references cited in a page,5// resolved through the repository, formatted in APA on the device — another style is said to be shown in APA).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesAPI12import SPNotesDesign13import SPNotesSync14import SwiftUI1516/// What the editor writes in a `citation` node (`CitationInline(refId:label:locator:)`).17public struct CitationChoice: Sendable, Equatable {18 public var refId: String19 /// The cached "Author Year" label.20 public var label: String21 /// « p. 12 », « chap. 3 »… (may be empty).22 public var locator: String2324 public init(refId: String, label: String, locator: String = "") {25 self.refId = refId26 self.label = label27 self.locator = locator28 }29}3031@Observable @MainActor32public final class CitationPickerModel {33 public private(set) var references: [ResearchReference] = []34 public private(set) var phase: LoadPhase = .idle35 public var searchText = ""36 public var locator: String37 public private(set) var selectedId: String?38 /// Only the references attached to this page first (the rest of the library after).39 public let pageId: String?4041 private let repository: ResearchRepository42 private let onPick: (@MainActor (CitationChoice) -> Void)?4344 /// - Parameters:45 /// - pageId: the page being edited: its references are listed first.46 /// - current: the citation being edited (preselected, locator kept).47 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, pageId: String? = nil, current: CitationChoice? = nil,48 now: @escaping @Sendable () -> Date = { Date() }, onPick: (@MainActor (CitationChoice) -> Void)? = nil) {49 repository = repositories.research50 self.pageId = pageId51 selectedId = current?.refId52 locator = current?.locator ?? ""53 self.onPick = onPick54 }5556 /// The device's copy of the library: works offline.57 public func load() async {58 phase = .loading59 do {60 let all = try await repository.localReferences()61 references = all.sorted { a, b in62 let mineA = pageId != nil && a.pageId == pageId, mineB = pageId != nil && b.pageId == pageId63 if mineA != mineB { return mineA }64 return ReferenceFormatter.label(a).localizedCaseInsensitiveCompare(ReferenceFormatter.label(b)) == .orderedAscending65 }66 phase = .loaded67 } catch {68 phase = .failed(FeatureFailure(error))69 }70 }7172 public var filtered: [ResearchReference] { references.filter { ReferenceFormatter.matches($0, searchText) } }73 public var selected: ResearchReference? { references.first { $0.id == selectedId } }74 public func select(_ reference: ResearchReference) { selectedId = reference.id }7576 /// The choice as it would be stored; nil while nothing is selected.77 public var choice: CitationChoice? {78 selected.map { CitationChoice(refId: $0.id, label: ReferenceFormatter.label($0), locator: locator.trimmingCharacters(in: .whitespaces)) }79 }8081 /// Returns the choice to the editor (the explicit « Citer » action).82 @discardableResult83 public func confirm() -> CitationChoice? {84 guard let choice else { return nil }85 onPick?(choice)86 return choice87 }8889 /// « (Doe & Roe, 2021, p. 12) ».90 public nonisolated static func preview(_ choice: CitationChoice) -> String {91 "(" + choice.label + (choice.locator.isEmpty ? "" : ", " + choice.locator) + ")"92 }93}9495public struct CitationPickerView: View {96 @State private var model: CitationPickerModel9798 public init(repositories: NotesRepositories, pageId: String? = nil, current: CitationChoice? = nil, onPick: @escaping @MainActor (CitationChoice) -> Void) {99 _model = State(initialValue: CitationPickerModel(repositories: repositories, pageId: pageId, current: current, onPick: onPick))100 }101102 public init(model: CitationPickerModel) { _model = State(initialValue: model) }103104 public var body: some View {105 FeatureScaffold(title: L("Citer une référence"), phase: model.phase, retry: { Task { await model.load() } }) { sizeClass in106 FeaturePhaseView(phase: model.phase, hasData: !model.references.isEmpty, retry: { Task { await model.load() } }) {107 NVEmptyState(systemImage: "books.vertical", title: L("Bibliothèque vide"), message: L("Ajoutez d'abord des références dans l'écran Recherche."))108 } content: {109 VStack(alignment: .leading, spacing: 0) {110 HStack(spacing: NVSpace.sm) {111 Image(systemName: "magnifyingglass").foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)112 TextField(L("Titre, auteur, année, clé, DOI"), text: $model.searchText).textFieldStyle(.plain).nvFont(.body)113 }114 .padding(.horizontal, NVSpace.md)115 .frame(minHeight: sizeClass.isCompact ? 44 : 36)116 .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.md))117 .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.line, lineWidth: 1))118 .padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)119 .padding(.bottom, NVSpace.sm)120 ScrollView {121 LazyVStack(alignment: .leading, spacing: NVSpace.sm) {122 if model.filtered.isEmpty {123 Text(L("Aucune référence ne correspond à cette recherche.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted).padding(.vertical, NVSpace.lg)124 }125 ForEach(model.filtered) { reference in126 ReferenceRow(reference: reference, isSelected: model.selectedId == reference.id) { model.select(reference) }127 }128 }129 .padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)130 .padding(.bottom, NVSpace.md)131 }132 footer(sizeClass)133 }134 }135 }136 .task { if model.phase == .idle { await model.load() } }137 }138139 private func footer(_ sizeClass: FeatureSizeClass) -> some View {140 VStack(alignment: .leading, spacing: NVSpace.sm) {141 HStack(spacing: NVSpace.sm) {142 TextField(L("Repère (p. 12, chap. 3…), facultatif"), text: $model.locator)143 .textFieldStyle(.plain).nvFont(.body)144 .padding(.horizontal, NVSpace.md)145 .frame(minHeight: sizeClass.isCompact ? 44 : 36)146 .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.md))147 .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.lineStrong, lineWidth: 1))148 .accessibilityLabel(L("Repère dans la source"))149 FeatureButton(L("Citer"), systemImage: "quote.opening", kind: .primary) { model.confirm() }150 .disabled(model.choice == nil).opacity(model.choice == nil ? 0.5 : 1)151 }152 if let choice = model.choice {153 Text(LF("Aperçu : %@", CitationPickerModel.preview(choice))).nvFont(.ui).foregroundStyle(NVColor.fgMuted).lineLimit(2)154 } else {155 Text(L("Choisissez une référence.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)156 }157 }158 .padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)159 .padding(.vertical, NVSpace.md)160 .background(NVColor.bgElevated.opacity(0.6))161 .overlay(alignment: .top) { Rectangle().fill(NVColor.line).frame(height: 1) }162 }163}164165/// One line of a bibliography.166public struct BibliographyEntry: Sendable, Equatable, Identifiable {167 public var id: String168 /// nil = the cited reference does not exist (any more).169 public var reference: ResearchReference?170 /// Inline Markdown of the formatted entry.171 public var markdown: String172 public var plain: String173}174175@Observable @MainActor176public final class BibliographyModel {177 public let citedIds: [String]178 public let style: String179 public let title: String180 public private(set) var entries: [BibliographyEntry] = []181 public private(set) var phase: LoadPhase = .idle182183 private let repository: ResearchRepository184 private weak var router: (any FeatureRouter)?185186 /// - Parameters:187 /// - citedIds: the `refId`s of the page's `citation` nodes (`NoteDocument.citedReferences()`), in reading order.188 /// - style / title: the attributes of the `bibliography` node.189 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, citedIds: [String], style: String = "apa", title: String = "",190 now: @escaping @Sendable () -> Date = { Date() }) {191 repository = repositories.research192 self.router = router193 var seen = Set<String>()194 self.citedIds = citedIds.filter { !$0.isEmpty && seen.insert($0).inserted }195 self.style = style.isEmpty ? "apa" : style196 self.title = title.isEmpty ? L("Références") : title197 }198199 /// True when the node asks for a style the device does not format: the entries are shown in APA and the view says so.200 public var styleIsSubstituted: Bool { !ReferenceFormatter.isSupported(style: style) }201202 /// Resolves the cited references (server, else the device's copy) and sorts them like a reference list.203 public func load() async {204 phase = .loading205 guard !citedIds.isEmpty else { entries = []; phase = .loaded; return }206 do {207 let found = try await repository.resolve(ids: citedIds)208 let resolved = citedIds.compactMap { id in found[id] }.map { reference -> BibliographyEntry in209 let markdown = ReferenceFormatter.apaMarkdown(reference)210 return BibliographyEntry(id: reference.id, reference: reference, markdown: markdown, plain: String(ReferenceFormatter.attributed(markdown).characters))211 }.sorted { $0.plain.localizedCaseInsensitiveCompare($1.plain) == .orderedAscending }212 let missing = citedIds.filter { found[$0] == nil }.map { BibliographyEntry(id: $0, reference: nil, markdown: "", plain: L("Référence introuvable")) }213 entries = resolved + missing214 phase = .loaded215 } catch {216 phase = .failed(FeatureFailure(error))217 }218 }219220 public var missingCount: Int { entries.filter { $0.reference == nil }.count }221222 public func open(_ entry: BibliographyEntry) {223 guard let reference = entry.reference, let url = ResearchModel.link(reference) else { return }224 router?.openURL(url)225 }226}227228/// The computed bibliography of a page (read-only: it is derived from the citations).229public struct BibliographyView: View {230 @State private var model: BibliographyModel231232 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, citedIds: [String], style: String = "apa", title: String = "") {233 _model = State(initialValue: BibliographyModel(repositories: repositories, router: router, citedIds: citedIds, style: style, title: title))234 }235236 public init(model: BibliographyModel) { _model = State(initialValue: model) }237238 public var body: some View {239 FeatureScaffold(title: model.title, subtitle: LF("Style %@ · calculée à partir des citations de la page", model.style.uppercased()), phase: model.phase,240 retry: { Task { await model.load() } }) { sizeClass in241 FeaturePhaseView(phase: model.phase, hasData: !model.entries.isEmpty, retry: { Task { await model.load() } }) {242 NVEmptyState(systemImage: "quote.opening", title: L("Aucune citation"), message: L("La bibliographie se remplit quand la page cite des références."))243 } content: {244 ScrollView {245 VStack(alignment: .leading, spacing: NVSpace.md) {246 if model.styleIsSubstituted {247 Label(LF("Le style %@ n'est pas mis en forme sur cet appareil : les entrées sont affichées en APA.", model.style.uppercased()), systemImage: "info.circle")248 .nvFont(.ui).foregroundStyle(NVColor.warningText).fixedSize(horizontal: false, vertical: true)249 }250 ForEach(model.entries) { entry in251 if let reference = entry.reference {252 Button { model.open(entry) } label: {253 Text(ReferenceFormatter.attributed(entry.markdown))254 .nvFont(.reading).foregroundStyle(NVColor.fg).multilineTextAlignment(.leading)255 .frame(maxWidth: .infinity, alignment: .leading)256 .fixedSize(horizontal: false, vertical: true)257 .contentShape(Rectangle())258 }259 .buttonStyle(.plain)260 .disabled(ResearchModel.link(reference) == nil)261 .accessibilityLabel(entry.plain)262 } else {263 Label(L("Référence introuvable"), systemImage: "questionmark.circle").nvFont(.ui).foregroundStyle(NVColor.dangerText)264 }265 }266 }267 .frame(maxWidth: NVSpace.readingMeasure, alignment: .leading)268 .padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)269 .padding(.bottom, NVSpace.xl)270 .frame(maxWidth: .infinity, alignment: .leading)271 }272 }273 }274 .task { if model.phase == .idle { await model.load() } }275 }276}277