SPB Git

Repository Public

ReferenceFormSheet.swift 17.2 KB 285 lines swift

1// ORIX Docs2// File: App/Sources/Sheets/ReferenceFormSheet.swift3// Description: The form that adds or edits one bibliography entry: fields chosen by entry type, a suggested citation key, the list of4//              fields still missing and a preview in the document's citation style. Every value is typed by the user.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel10import DocReferences1112nonisolated struct ReferenceFieldSpec: Identifiable, Sendable {13    let key: String14    let label: String15    var wide = false16    var id: String { key }17}1819/// An entry type offered by the form, with the fields that matter for it.20nonisolated struct ReferenceTypeInfo: Identifiable, Sendable {21    let id: String22    let name: String23    let usesEditors: Bool24    let fields: [ReferenceFieldSpec]2526    static let all: [ReferenceTypeInfo] = {27        func f(_ key: String, _ label: String, wide: Bool = false) -> ReferenceFieldSpec { ReferenceFieldSpec(key: key, label: label, wide: wide) }28        let volume = f("volume", String(localized: "Volume")), issue = f("issue", String(localized: "Issue")), pages = f("page", String(localized: "Pages"))29        let doi = f("DOI", "DOI"), url = f("URL", "URL", wide: true), publisher = f("publisher", String(localized: "Publisher"))30        let place = f("publisher-place", String(localized: "Place")), edition = f("edition", String(localized: "Edition"))31        let accessed = f("accessed", String(localized: "Accessed (YYYY-MM-DD)"))32        return [33            ReferenceTypeInfo(id: "article-journal", name: String(localized: "Journal article"), usesEditors: false,34                              fields: [f("container-title", String(localized: "Journal"), wide: true), volume, issue, pages, doi, url]),35            ReferenceTypeInfo(id: "book", name: String(localized: "Book"), usesEditors: true,36                              fields: [publisher, place, edition, volume, f("ISBN", "ISBN"), doi, url]),37            ReferenceTypeInfo(id: "chapter", name: String(localized: "Book chapter"), usesEditors: true,38                              fields: [f("container-title", String(localized: "Book title"), wide: true), publisher, place, pages, edition, doi, url]),39            ReferenceTypeInfo(id: "paper-conference", name: String(localized: "Conference paper"), usesEditors: true,40                              fields: [f("container-title", String(localized: "Proceedings"), wide: true), f("event-title", String(localized: "Conference"), wide: true),41                                       publisher, place, pages, doi, url]),42            ReferenceTypeInfo(id: "thesis", name: String(localized: "Thesis"), usesEditors: false,43                              fields: [f("genre", String(localized: "Thesis type")), f("publisher", String(localized: "University")), place, url]),44            ReferenceTypeInfo(id: "report", name: String(localized: "Report"), usesEditors: false,45                              fields: [f("number", String(localized: "Report number")), f("publisher", String(localized: "Institution")), place, doi, url]),46            ReferenceTypeInfo(id: "webpage", name: String(localized: "Web page"), usesEditors: false,47                              fields: [f("container-title", String(localized: "Website"), wide: true), url, accessed]),48            ReferenceTypeInfo(id: "article-magazine", name: String(localized: "Magazine article"), usesEditors: false,49                              fields: [f("container-title", String(localized: "Magazine"), wide: true), volume, issue, pages, url]),50            ReferenceTypeInfo(id: "article-newspaper", name: String(localized: "Newspaper article"), usesEditors: false,51                              fields: [f("container-title", String(localized: "Newspaper"), wide: true), pages, url]),52            ReferenceTypeInfo(id: "manuscript", name: String(localized: "Unpublished manuscript"), usesEditors: false,53                              fields: [f("genre", String(localized: "Description")), f("publisher", String(localized: "Institution")), url]),54            ReferenceTypeInfo(id: "dataset", name: String(localized: "Dataset"), usesEditors: false,55                              fields: [publisher, f("version", String(localized: "Version")), doi, url]),56            ReferenceTypeInfo(id: "software", name: String(localized: "Software"), usesEditors: false,57                              fields: [publisher, f("version", String(localized: "Version")), doi, url]),58            ReferenceTypeInfo(id: "document", name: String(localized: "Other document"), usesEditors: true,59                              fields: [publisher, place, f("genre", String(localized: "Description")), doi, url]),60        ]61    }()6263    static func info(_ id: String) -> ReferenceTypeInfo? { all.first { $0.id == id } }6465    /// Display name of any CSL type, including the ones the form does not offer (kept as imported).66    static func name(_ id: String) -> String { info(id)?.name ?? id }67}6869nonisolated enum ReferenceNames {70    /// "Family, Given; Family, Jr, Given; {Institution}".71    static func text(_ names: [PersonName]) -> String {72        names.map { n in73            if n.isOthers { return "others" }74            if n.isLiteral { return "{\(n.literal ?? "")}" }75            let parts = n.givenAndSuffix76            if parts.given.isEmpty && parts.suffix == nil { return n.family }77            if let suffix = parts.suffix { return "\(n.family), \(suffix), \(parts.given)" }78            return "\(n.family), \(parts.given)"79        }.joined(separator: "; ")80    }8182    static func parse(_ text: String) -> [PersonName] {83        text.split(whereSeparator: { $0 == ";" || $0.isNewline })84            .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }85            .flatMap { NameParser.parseList($0) }86    }87}8889struct ReferenceFormSheet: View {90    let session: DocumentSession91    /// The entry being edited; nil adds a new one.92    let original: BibEntry?93    let onClose: (_ savedKey: String?) -> Void9495    @State private var type: String96    @State private var key: String97    @State private var keyEdited: Bool98    @State private var title: String99    @State private var authors: String100    @State private var editors: String101    @State private var year: String102    @State private var month: String103    @State private var day: String104    @State private var values: [String: String]105    private let otherKeys: Set<String>106    private let citedCount: Int107108    init(session: DocumentSession, original: BibEntry?, onClose: @escaping (_ savedKey: String?) -> Void) {109        self.session = session; self.original = original; self.onClose = onClose110        let e = original ?? BibEntry(key: "")111        _type = State(initialValue: e.type)112        _key = State(initialValue: e.key)113        _keyEdited = State(initialValue: original != nil)114        _title = State(initialValue: e.title)115        _authors = State(initialValue: ReferenceNames.text(e.authors))116        _editors = State(initialValue: ReferenceNames.text(e.editors))117        _year = State(initialValue: e.year.map(String.init) ?? e.fields[ReferenceField.issuedLiteral] ?? "")118        _month = State(initialValue: e.month.map(String.init) ?? "")119        _day = State(initialValue: e.day.map(String.init) ?? "")120        _values = State(initialValue: e.fields)121        otherKeys = Set(session.doc.bibliography.map(\.key)).subtracting(original.map { [$0.key] } ?? [])122        citedCount = original.map { o in session.numbering.citedKeys.contains(o.key) ? 1 : 0 } ?? 0123    }124125    private var typeInfo: ReferenceTypeInfo? { ReferenceTypeInfo.info(type) }126    private var specs: [ReferenceFieldSpec] { (typeInfo?.fields ?? []) + [ReferenceFieldSpec(key: "note", label: String(localized: "Note"), wide: true)] }127128    /// The entry as the form stands, without its key.129    private func draft() -> BibEntry {130        var e = original ?? BibEntry(key: "")131        e.type = type132        e.authors = ReferenceNames.parse(authors)133        if typeInfo?.usesEditors ?? true { e.editors = ReferenceNames.parse(editors) }134        var fields = e.fields135        func set(_ k: String, _ v: String) {136            let t = v.trimmingCharacters(in: .whitespacesAndNewlines)137            if t.isEmpty { fields.removeValue(forKey: k) } else { fields[k] = t }138        }139        set("title", title)140        for spec in specs { set(spec.key, values[spec.key] ?? "") }141        let y = year.trimmingCharacters(in: .whitespaces)142        if let n = Int(y) {143            e.year = n; fields.removeValue(forKey: ReferenceField.issuedLiteral)144            e.month = Int(month.trimmingCharacters(in: .whitespaces)).flatMap { (1...12).contains($0) ? $0 : nil }145            e.day = e.month == nil ? nil : Int(day.trimmingCharacters(in: .whitespaces)).flatMap { (1...31).contains($0) ? $0 : nil }146        } else {147            e.year = nil; e.month = nil; e.day = nil148            if y.isEmpty { fields.removeValue(forKey: ReferenceField.issuedLiteral) } else { fields[ReferenceField.issuedLiteral] = y }149        }150        e.fields = fields151        return e152    }153154    private func suggestedKey(_ e: BibEntry) -> String { ReferenceChecks.suggestedKey(for: e, existing: otherKeys) }155156    private func effectiveKey(_ e: BibEntry) -> String {157        keyEdited ? key.trimmingCharacters(in: .whitespaces) : suggestedKey(e)158    }159160    private func keyProblem(_ k: String) -> String? {161        if k.isEmpty { return String(localized: "A citation key is required.") }162        if k.contains(where: { $0.isWhitespace || $0 == "," || $0 == ";" || $0 == "{" || $0 == "}" }) { return String(localized: "The key cannot contain spaces, commas, semicolons or braces.") }163        if otherKeys.contains(k) { return String(localized: "Another entry already uses this key.") }164        return nil165    }166167    var body: some View {168        let e = draft()169        let k = effectiveKey(e)170        let problem = keyProblem(k)171        let hasContent = !e.title.isEmpty || !e.authors.isEmpty172        var complete = e; complete.key = k173        let missing = ReferenceChecks.missingFields(complete)174        return SheetScaffold(title: original == nil ? "Add Reference" : "Edit Reference", symbol: "text.book.closed",175                             subtitle: "Enter the details as they appear on the work. Nothing is looked up or filled in for you.", width: 600,176                             primaryTitle: original == nil ? "Add" : "Save", primaryEnabled: problem == nil && hasContent,177                             onPrimary: {178                                 ReferenceLibrary.save(complete, replacing: original?.key, in: session)179                                 onClose(k)180                             }, onCancel: { onClose(nil) }) {181            ScrollView {182                VStack(alignment: .leading, spacing: ORIX.Space.m) {183                    HStack(alignment: .bottom, spacing: ORIX.Space.m) {184                        LabeledField(label: "Type") {185                            Picker("Type", selection: $type) {186                                ForEach(ReferenceTypeInfo.all) { Text(verbatim: $0.name).tag($0.id) }187                                if typeInfo == nil { Text(verbatim: type).tag(type) }188                            }189                            .labelsHidden().frame(width: 210).accessibilityIdentifier("reference-type")190                        }191                        LabeledField(label: "Citation key") {192                            HStack(spacing: 4) {193                                TextField("", text: Binding(get: { keyEdited ? key : suggestedKey(e) }, set: { key = $0; keyEdited = true }), prompt: Text("Citation key"))194                                    .textFieldStyle(.roundedBorder).font(.system(size: 12, design: .monospaced))195                                    .accessibilityLabel(Text("Citation key")).accessibilityIdentifier("reference-key")196                                Button { keyEdited = false } label: { Image(systemName: "wand.and.stars") }197                                    .buttonStyle(.borderless).disabled(!keyEdited)198                                    .help("Use the suggested key (author, year, first title word)")199                                    .accessibilityLabel(Text("Use the suggested key"))200                            }201                        }202                    }203                    if let problem, keyEdited || hasContent { Notice(kind: .error, text: problem) }204                    if original != nil, citedCount > 0, k != original?.key, problem == nil {205                        Notice(kind: .info, text: String(localized: "This entry is cited in the document. Its citations will follow the new key."))206                    }207                    LabeledField(label: "Title") {208                        TextField("", text: $title, prompt: Text("Title of the work")).textFieldStyle(.roundedBorder)209                            .accessibilityLabel(Text("Title")).accessibilityIdentifier("reference-title")210                    }211                    LabeledField(label: "Authors") {212                        TextField("", text: $authors, prompt: Text(verbatim: "Family, Given; Family, Given; {Institution}")).textFieldStyle(.roundedBorder)213                            .accessibilityLabel(Text("Authors")).accessibilityIdentifier("reference-authors")214                        Text("Separate authors with semicolons. Put an institution in braces.").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)215                    }216                    if typeInfo?.usesEditors ?? !e.editors.isEmpty {217                        LabeledField(label: "Editors") {218                            TextField("", text: $editors, prompt: Text(verbatim: "Family, Given; Family, Given")).textFieldStyle(.roundedBorder)219                                .accessibilityLabel(Text("Editors"))220                        }221                    }222                    HStack(spacing: ORIX.Space.m) {223                        LabeledField(label: "Year") {224                            TextField("", text: $year, prompt: Text(verbatim: "2024")).textFieldStyle(.roundedBorder).frame(width: 110)225                                .accessibilityLabel(Text("Year")).accessibilityIdentifier("reference-year")226                        }227                        LabeledField(label: "Month") {228                            TextField("", text: $month, prompt: Text(verbatim: "1–12")).textFieldStyle(.roundedBorder).frame(width: 64)229                                .accessibilityLabel(Text("Month")).disabled(Int(year.trimmingCharacters(in: .whitespaces)) == nil)230                        }231                        LabeledField(label: "Day") {232                            TextField("", text: $day, prompt: Text(verbatim: "1–31")).textFieldStyle(.roundedBorder).frame(width: 64)233                                .accessibilityLabel(Text("Day")).disabled(Int(month.trimmingCharacters(in: .whitespaces)) == nil)234                        }235                        Spacer()236                    }237                    fieldGrid238                    VStack(alignment: .leading, spacing: 4) {239                        FieldLabel("Preview in the document's citation style")240                        Text(CitationEngine(styleID: session.doc.settings.citationStyle, language: session.doc.meta.language).formattedEntry(complete, number: nil).attributedText)241                            .font(.system(size: 12, design: .serif)).foregroundStyle(ORIX.Palette.text)242                            .frame(maxWidth: .infinity, alignment: .leading).padding(10).well()243                            .textSelection(.enabled)244                    }245                    if hasContent, !missing.isEmpty {246                        Notice(kind: .warning, text: ReferenceLibrary.missingSummary(missing) + ". " + String(localized: "You can save the entry and complete it later."))247                    }248                }249                .padding(.leading, 2).padding(.trailing, 8).padding(.vertical, 1)250            }251            .frame(maxHeight: 470)252        }253    }254255    private var fieldGrid: some View {256        let rows: [[ReferenceFieldSpec]] = {257            var out: [[ReferenceFieldSpec]] = []258            var pending: ReferenceFieldSpec?259            for s in specs {260                if s.wide { if let p = pending { out.append([p]); pending = nil }; out.append([s]) }261                else if let p = pending { out.append([p, s]); pending = nil }262                else { pending = s }263            }264            if let p = pending { out.append([p]) }265            return out266        }()267        return VStack(alignment: .leading, spacing: ORIX.Space.m) {268            ForEach(Array(rows.enumerated()), id: \.offset) { _, row in269                HStack(alignment: .top, spacing: ORIX.Space.m) {270                    ForEach(row) { spec in271                        VStack(alignment: .leading, spacing: 3) {272                            Text(verbatim: spec.label).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary)273                            TextField("", text: Binding(get: { values[spec.key] ?? "" }, set: { values[spec.key] = $0 }))274                                .textFieldStyle(.roundedBorder)275                                .accessibilityLabel(Text(verbatim: spec.label))276                        }277                        .frame(maxWidth: .infinity)278                    }279                    if row.count == 1 && !(row.first?.wide ?? true) { Color.clear.frame(maxWidth: .infinity, maxHeight: 1) }280                }281            }282        }283    }284}285
Files main
Menu

Theme