SPB Git

Repository Public

AuditInspector.swift 33.6 KB 589 lines swift

1// ORIX Docs2// File: App/Sources/Inspector/AuditInspector.swift3// Description: The inspector's Auditor tab: profile and check groups, the audit run off the main actor with facts from the layout,4//              findings grouped by severity and check with evidence and a "Show" action, the report, and the rule-based research tools.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import Observation11import UniformTypeIdentifiers12import DocModel13import DocContainer14import DocLayout15import DocReferences16import DocAudit17import DocAutomation1819// MARK: - Model2021enum InspectorAuditProfile: String, CaseIterable, Identifiable {22    case standard, academic, business, minimal23    var id: String { rawValue }24    var title: LocalizedStringKey {25        switch self { case .standard: return "Standard"; case .academic: return "Academic"; case .business: return "Business"; case .minimal: return "Minimal" }26    }27    var summary: LocalizedStringKey {28        switch self {29        case .standard: return "Every check, with the default thresholds."30        case .academic: return "Every check; table captions and keywords required, sentences up to 50 words."31        case .business: return "No bibliography, reference or repetition checks; sentences up to 35 words."32        case .minimal: return "Only what makes a document wrong or unfinished."33        }34    }35    var options: AuditOptions {36        switch self { case .standard: return AuditOptions(); case .academic: return .academic; case .business: return .business; case .minimal: return .minimal }37    }38}3940struct AuditCheckGroup: Identifiable {41    let id: String42    let title: LocalizedStringKey43    let checks: Set<AuditCheck>4445    static let all: [AuditCheckGroup] = [46        AuditCheckGroup(id: "structure", title: "Structure and headings", checks: [.missingHeadings, .headingHierarchy, .emptyHeading, .duplicateHeading]),47        AuditCheckGroup(id: "references", title: "Citations and cross-references", checks: [.brokenCrossReference, .missingBibliographyEntry, .orphanedCitation, .incompleteReference]),48        AuditCheckGroup(id: "figures", title: "Figures and tables", checks: [.missingFigureCaption, .missingTableCaption, .missingAltText, .unreferencedFigure, .unreferencedTable, .overflowingTable]),49        AuditCheckGroup(id: "layout", title: "Layout and formatting", checks: [.unusualPageBreak, .missingPageNumbers, .inconsistentFormatting]),50        AuditCheckGroup(id: "review", title: "Comments and tracked changes", checks: [.unresolvedComment, .pendingTrackedChange]),51        AuditCheckGroup(id: "writing", title: "Writing", checks: [.undefinedAcronym, .repeatedWording, .longSentence, .doubleSpaces]),52        AuditCheckGroup(id: "metadata", title: "Document properties", checks: [.missingMetadata]),53    ]54}5556/// What the rule-based research tools found in the document.57nonisolated struct ResearchResults: Sendable {58    var acronyms: [ResearchAssistant.AcronymFinding] = []59    var captions: [ResearchAssistant.CaptionFinding] = []60    var passages: [ResearchAssistant.CitedPassage] = []61    var repetitions: [ResearchAssistant.RepetitionFinding] = []62    var actions: [ResearchAssistant.Hit] = []6364    static func compute(_ doc: DocumentModel) -> ResearchResults {65        ResearchResults(acronyms: ResearchAssistant.undefinedAcronyms(in: doc), captions: ResearchAssistant.unreferencedCaptions(in: doc),66                        passages: ResearchAssistant.citedPassages(in: doc), repetitions: ResearchAssistant.repeatedWording(in: doc, language: nil),67                        actions: ResearchAssistant.actionItems(in: doc))68    }69}7071/// A document the user chose to search in.72nonisolated struct ExternalDocument: Sendable, Identifiable {73    var id: URL { url }74    let url: URL75    let name: String76    let document: DocumentModel77}7879/// The auditor's results for one document window. Kept outside the view so they survive a change of inspector tab.80@Observable81final class AuditState {82    var profile: InspectorAuditProfile = .standard83    var disabledGroups: Set<String> = []84    var running = false85    var findings: [AuditFinding]?86    var research: ResearchResults?87    var auditedRevision: Int?88    var auditedDocument: DocumentModel?89    var handledRequest = 090    var seconds: Double = 091    var externals: [ExternalDocument] = []92    var externalErrors: [String] = []93    var loadingExternals = false94    var query = ""95    var wholeWord = false96    var caseSensitive = false97    var hits: [ResearchAssistant.Hit] = []98    var searchedQuery = ""99100    private static let states = NSMapTable<DocumentSession, AuditState>.weakToStrongObjects()101    static func of(_ session: DocumentSession) -> AuditState {102        if let s = states.object(forKey: session) { return s }103        let s = AuditState()104        // A document that cites works is most likely academic.105        if !session.doc.bibliography.isEmpty { s.profile = .academic }106        states.setObject(s, forKey: session)107        return s108    }109110    var options: AuditOptions {111        var o = profile.options112        for g in AuditCheckGroup.all where disabledGroups.contains(g.id) { o.enabled.subtract(g.checks) }113        return o114    }115}116117enum AuditRunner {118    /// Facts only the pagination knows, in the 1-based form the auditor expects.119    static func layoutFacts(_ layout: DocumentLayout, doc: DocumentModel) -> LayoutFacts {120        var nearlyEmpty: [Int] = [], unnumbered: [Int] = []121        var stories: [StoryID: [Block]] = [:]122        for (i, page) in layout.pages.enumerated() where !page.isBlank {123            let lastOfSection = i == layout.pages.count - 1 || layout.pages[i + 1].sectionIndex != page.sectionIndex124            if !lastOfSection, page.contentRect.height > 0 {125                var covered = page.texts.filter { $0.story == .body }.reduce(CGFloat(0)) { $0 + $1.height }126                covered += page.tables.reduce(CGFloat(0)) { $0 + $1.height }127                covered += page.floats.reduce(CGFloat(0)) { $0 + $1.rect.height }128                if covered / (page.contentRect.height * CGFloat(max(1, page.setup.columns))) < 0.15 { nearlyEmpty.append(i + 1) }129            }130            var numbered = false131            for f in page.texts {132                switch f.story {133                case .header, .footer:134                    let blocks = stories[f.story] ?? doc.blocks(in: f.story)135                    stories[f.story] = blocks136                    if let p = blocks.paragraph(at: f.path), p.runs.contains(where: { r in if !r.isDeleted, case .field(.pageNumber)? = r.inline { return true } else { return false } }) { numbered = true }137                default: break138                }139                if numbered { break }140            }141            if !numbered { unnumbered.append(i + 1) }142        }143        return LayoutFacts(pageCount: layout.pageCount, pageOfBlock: layout.pageOfBlock.mapValues { $0 + 1 }, overflowingTableIDs: layout.overflowingTableIDs,144                           nearlyEmptyPages: nearlyEmpty, pagesWithoutPageNumber: unnumbered)145    }146147    static func run(_ session: DocumentSession, state: AuditState) {148        guard !state.running else { return }149        let doc = session.doc150        let facts = layoutFacts(session.layout, doc: doc)151        let options = state.options152        let revision = session.revision153        state.running = true154        Task {155            let start = Date()156            let (findings, research) = await Task.detached(priority: .userInitiated) {157                (DocumentAuditor.audit(doc, layout: facts, options: options, incompleteReference: { ReferenceChecks.missingFields($0) }),158                 ResearchResults.compute(doc))159            }.value160            state.findings = findings161            state.research = research162            state.auditedRevision = revision163            state.auditedDocument = doc164            state.seconds = Date().timeIntervalSince(start)165            state.running = false166        }167    }168}169170// MARK: - View171172struct AuditInspector: View {173    let session: DocumentSession174    @State private var state: AuditState175    @State private var showChecks = false176    @State private var collapsed: Set<String> = []177    @State private var open: Set<String> = ["acronyms"]178179    init(session: DocumentSession) {180        self.session = session181        _state = State(initialValue: AuditState.of(session))182    }183184    private var stale: Bool { state.auditedRevision != nil && state.auditedRevision != session.revision }185186    var body: some View {187        ScrollView {188            VStack(spacing: 0) {189                setupSection190                findingsSection191                researchSection192                searchSection193            }194        }195        .background(ORIX.Palette.chrome)196        .onAppear { answerRequest() }197        .onChange(of: session.auditRequest) { _, _ in answerRequest() }198        .accessibilityIdentifier("inspector-audit")199    }200201    private func answerRequest() {202        guard session.auditRequest != state.handledRequest else { return }203        state.handledRequest = session.auditRequest204        AuditRunner.run(session, state: state)205    }206207    // MARK: Profile and run208209    private var setupSection: some View {210        InspectorSection(title: "Document Audit") {211            InspectorRow(label: "Profile") {212                Picker("Profile", selection: $state.profile) {213                    ForEach(InspectorAuditProfile.allCases) { Text($0.title).tag($0) }214                }215                .labelsHidden().fixedSize().accessibilityLabel(Text("Audit profile")).accessibilityIdentifier("audit-profile")216            }217            Text(state.profile.summary).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)218            CollapsibleGroup(title: String(localized: "Checks"), symbol: "slider.horizontal.3", expanded: $showChecks) {219                let enabledByProfile = state.profile.options.enabled220                VStack(alignment: .leading, spacing: 4) {221                    ForEach(AuditCheckGroup.all) { group in222                        let available = !group.checks.isDisjoint(with: enabledByProfile)223                        Toggle(isOn: Binding(get: { available && !state.disabledGroups.contains(group.id) },224                                             set: { on in if on { state.disabledGroups.remove(group.id) } else { state.disabledGroups.insert(group.id) } })) {225                            (Text(group.title) + (available ? Text(verbatim: "") : Text(" (not in this profile)").foregroundStyle(ORIX.Palette.textTertiary)))226                                .font(ORIX.Font.label)227                        }228                        .toggleStyle(.checkbox).disabled(!available)229                        .accessibilityIdentifier("audit-group-\(group.id)")230                    }231                }232            }233            HStack(spacing: ORIX.Space.s) {234                Button { AuditRunner.run(session, state: state) } label: {235                    HStack(spacing: 6) {236                        if state.running { ProgressView().controlSize(.small).tint(.white) } else { Image(systemName: "checklist") }237                        Text(state.running ? "Auditing…" : (state.findings == nil ? "Run Audit" : "Run Again"))238                    }239                    .frame(maxWidth: .infinity)240                }241                .buttonStyle(ORIXButtonStyle()).disabled(state.running)242                .accessibilityIdentifier("audit-run")243                if let findings = state.findings, let doc = state.auditedDocument {244                    Button {245                        ORIXDocument.openUntitled(DocumentAuditor.reportDocument(findings, for: doc), displayName: String(localized: "Audit Report"))246                    } label: { Label("Open Report", systemImage: "doc.text") }247                        .buttonStyle(ORIXButtonStyle(prominent: false))248                        .help("Opens the findings as a new document you can save or export")249                        .accessibilityIdentifier("audit-report")250                }251            }252            if stale {253                Notice(kind: .warning, text: String(localized: "The document changed since this audit. Run it again to refresh the findings."))254                    .accessibilityIdentifier("audit-stale")255            }256        }257    }258259    // MARK: Findings260261    private static func symbol(_ s: AuditFinding.Severity) -> String {262        switch s { case .error: return "xmark.octagon.fill"; case .warning: return "exclamationmark.triangle.fill"; case .info: return "info.circle.fill" }263    }264    private static func color(_ s: AuditFinding.Severity) -> Color {265        switch s { case .error: return ORIX.Palette.critical; case .warning: return ORIX.Palette.warning; case .info: return ORIX.Palette.accent }266    }267    private static func name(_ s: AuditFinding.Severity, count: Int) -> String {268        switch s {269        case .error: return count == 1 ? String(localized: "1 error") : String(localized: "\(count) errors")270        case .warning: return count == 1 ? String(localized: "1 warning") : String(localized: "\(count) warnings")271        case .info: return count == 1 ? String(localized: "1 note") : String(localized: "\(count) notes")272        }273    }274    private static func heading(_ s: AuditFinding.Severity) -> LocalizedStringKey {275        switch s { case .error: return "Errors"; case .warning: return "Warnings"; case .info: return "Notes" }276    }277278    @ViewBuilder279    private var findingsSection: some View {280        if let findings = state.findings {281            let severities: [AuditFinding.Severity] = [.error, .warning, .info]282            InspectorSection(title: "Findings") {283                HStack(spacing: 6) {284                    ForEach(severities, id: \.self) { s in285                        let n = findings.filter { $0.severity == s }.count286                        HStack(spacing: 4) {287                            Image(systemName: AuditInspector.symbol(s)).font(.system(size: 10.5)).foregroundStyle(n == 0 ? ORIX.Palette.textTertiary : AuditInspector.color(s))288                            Text(verbatim: AuditInspector.name(s, count: n)).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(n == 0 ? ORIX.Palette.textTertiary : ORIX.Palette.text)289                                .lineLimit(1).minimumScaleFactor(0.8)290                        }291                        .padding(.horizontal, 6).padding(.vertical, 5).frame(maxWidth: .infinity)292                        .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))293                        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline))294                        .accessibilityElement(children: .combine)295                    }296                }297                .accessibilityIdentifier("audit-counts")298                Text("Audited \(state.auditedDocument.map { DocumentStatistics($0).words } ?? 0) words in \(String(format: "%.2f", state.seconds)) s with the \(Text(state.profile.title)) profile.")299                    .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)300                if findings.isEmpty {301                    Notice(kind: .success, text: String(localized: "No finding with the checks that are enabled."))302                }303            }304            ForEach(severities, id: \.self) { severity in305                let list = findings.filter { $0.severity == severity }306                if !list.isEmpty {307                    InspectorSection(title: AuditInspector.heading(severity)) {308                        let checks = AuditCheck.allCases.filter { c in list.contains { $0.check == c } }309                        ForEach(checks, id: \.self) { check in310                            let group = list.filter { $0.check == check }311                            let id = severity.rawValue + "." + check.rawValue312                            CollapsibleGroup(title: group[0].title, symbol: AuditInspector.symbol(severity), tint: AuditInspector.color(severity), count: group.count,313                                             expanded: Binding(get: { !collapsed.contains(id) }, set: { if $0 { collapsed.remove(id) } else { collapsed.insert(id) } })) {314                                findingGroup(group)315                            }316                            .accessibilityIdentifier("audit-check-\(check.rawValue)")317                        }318                    }319                }320            }321        } else if !state.running {322            InspectorSection(title: "Findings") {323                Text("Run the audit to check structure, references, figures, layout and writing. Every finding quotes the document; nothing is changed for you.")324                    .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)325            }326        }327    }328329    @ViewBuilder330    private func findingGroup(_ group: [AuditFinding]) -> some View {331        let sharedExplanation = Set(group.map(\.explanation)).count == 1332        let sharedSuggestion = Set(group.map(\.suggestion)).count == 1333        VStack(alignment: .leading, spacing: 6) {334            if sharedExplanation { Text(verbatim: group[0].explanation).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true) }335            ForEach(group.prefix(60)) { f in336                VStack(alignment: .leading, spacing: 4) {337                    if !f.evidence.isEmpty {338                        Text(verbatim: f.evidence).font(.system(size: 11, design: .serif)).foregroundStyle(ORIX.Palette.text)339                            .lineLimit(6).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)340                    }341                    if !sharedExplanation { Text(verbatim: f.explanation).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true) }342                    if !sharedSuggestion { suggestion(f.suggestion) }343                    HStack(spacing: 6) {344                        if let page = f.location?.page { Chip(text: String(localized: "Page \(page)"), symbol: "doc") }345                        Spacer()346                        if canShow(f) {347                            Button { show(f) } label: { Label("Show", systemImage: "scope") }348                                .buttonStyle(.borderless).controlSize(.small).font(.system(size: 10.5, weight: .medium))349                                .help("Shows the place in the document")350                                .accessibilityLabel(Text("Show in the document"))351                        }352                    }353                }354                .padding(7).frame(maxWidth: .infinity, alignment: .leading)355                .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))356                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline))357                .accessibilityElement(children: .contain)358            }359            if group.count > 60 {360                Text("\(group.count - 60) more are in the report.").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)361            }362            if sharedSuggestion { suggestion(group[0].suggestion) }363        }364    }365366    private func suggestion(_ text: String) -> some View {367        HStack(alignment: .firstTextBaseline, spacing: 5) {368            Image(systemName: "lightbulb").font(.system(size: 9.5)).foregroundStyle(ORIX.Palette.secondary).accessibilityHidden(true)369            Text(verbatim: text).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)370        }371        .accessibilityElement(children: .combine)372        .accessibilityLabel(Text("Suggestion: \(text)"))373    }374375    private func canShow(_ f: AuditFinding) -> Bool {376        guard let l = f.location else { return false }377        return l.path != nil || l.paragraphID != nil || l.page != nil378    }379380    /// Reveals a finding. The document may have changed since the audit, so the paragraph is looked up again by its identifier.381    private func show(_ f: AuditFinding) {382        guard let l = f.location else { return }383        if let path = l.path, let p = session.doc.blocks(in: l.story).paragraph(at: path), l.paragraphID == nil || p.id == l.paragraphID {384            session.reveal(story: l.story, path: path)385            return386        }387        if let id = l.paragraphID {388            if session.doc.body.contains(where: { $0.id == id }) { session.revealBlock(id: id); return }389            var found: (StoryID, ParaPath)?390            session.doc.forEachParagraphEverywhere { p, story, path in if found == nil, p.id == id { found = (story, path) } }391            if let found { session.reveal(story: found.0, path: found.1); return }392        }393        if let page = l.page { session.revealPage(max(0, page - 1)) } else { session.statusMessage = String(localized: "This place is no longer in the document. Run the audit again.") }394    }395396    // MARK: Research397398    private func group(_ id: String) -> Binding<Bool> {399        Binding(get: { open.contains(id) }, set: { if $0 { open.insert(id) } else { open.remove(id) } })400    }401402    private func reveal(_ hit: ResearchAssistant.Hit) { reveal(story: hit.story, path: hit.path, range: hit.range) }403404    private func reveal(story: StoryID, path: ParaPath, range: Range<Int>) {405        guard let p = session.doc.blocks(in: story).paragraph(at: path) else { return }406        let r = min(range.lowerBound, p.length)..<min(range.upperBound, p.length)407        session.reveal(story: story, path: path, range: r)408    }409410    @ViewBuilder411    private var researchSection: some View {412        InspectorSection(title: "Research") {413            Text("Rule-based checks that quote the document. Nothing here is generated, and no artificial intelligence is involved.")414                .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)415            if let r = state.research {416                CollapsibleGroup(title: String(localized: "Undefined acronyms"), symbol: "textformat.abc", count: r.acronyms.count, expanded: group("acronyms")) {417                    emptyOr(r.acronyms.isEmpty, "Every acronym is expanded somewhere in the document.")418                    ForEach(r.acronyms.prefix(100)) { a in419                        researchRow(title: a.count == 1 ? a.acronym : "\(a.acronym)  ×\(a.count)", mono: true, detail: a.firstUse.context) { reveal(a.firstUse) }420                    }421                }422                CollapsibleGroup(title: String(localized: "Unreferenced figures and tables"), symbol: "photo.on.rectangle", count: r.captions.count, expanded: group("captions")) {423                    emptyOr(r.captions.isEmpty, "Every caption is referred to in the text.")424                    ForEach(r.captions.prefix(100)) { c in425                        researchRow(title: "\(c.label) \(c.number)", mono: false, detail: c.text) { session.revealBlock(id: c.paragraphID) }426                    }427                }428                CollapsibleGroup(title: String(localized: "Cited passages"), symbol: "quote.opening", count: r.passages.count, expanded: group("passages")) {429                    emptyOr(r.passages.isEmpty, "No sentence contains a citation.")430                    ForEach(r.passages.prefix(100)) { p in431                        researchRow(title: p.keys.joined(separator: "; "), mono: true, detail: p.sentence) { reveal(story: p.story, path: p.path, range: p.range) }432                    }433                    more(r.passages.count)434                }435                CollapsibleGroup(title: String(localized: "Repeated wording"), symbol: "repeat", count: r.repetitions.count, expanded: group("repetitions")) {436                    emptyOr(r.repetitions.isEmpty, "No word or phrase is repeated beyond the thresholds.")437                    ForEach(r.repetitions.prefix(100)) { rep in438                        researchRow(title: "“\(rep.text)”  ×\(rep.count)", mono: false,439                                    detail: (rep.kind == .word ? String(localized: "Word used \(rep.count) times within \(rep.span) words.") : String(localized: "Phrase used \(rep.count) times within \(rep.span) words."))440                                        + (rep.occurrences.first.map { " " + $0.context } ?? "")) {441                            if let first = rep.occurrences.first { reveal(first) }442                        }443                    }444                }445                CollapsibleGroup(title: String(localized: "Action items (rule-based)"), symbol: "checkmark.square", count: r.actions.count, expanded: group("actions")) {446                    Text("Found by fixed markers such as TODO, “must”, “next steps:” or an unchecked box. Rule-based, not AI.")447                        .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)448                    ForEach(r.actions.prefix(100)) { hit in449                        researchRow(title: hit.headingTrail.last ?? String(localized: "Document"), mono: false, detail: hit.context) { reveal(hit) }450                    }451                    more(r.actions.count)452                }453            } else {454                Text("Run the audit to fill this section.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textTertiary)455            }456        }457    }458459    @ViewBuilder460    private func emptyOr(_ empty: Bool, _ text: LocalizedStringKey) -> some View {461        if empty { Text(text).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true) }462    }463464    @ViewBuilder465    private func more(_ count: Int) -> some View {466        if count > 100 { Text("Only the first 100 of \(count) are listed.").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary) }467    }468469    private func researchRow(title: String, mono: Bool, detail: String, action: @escaping () -> Void) -> some View {470        Button(action: action) {471            VStack(alignment: .leading, spacing: 1) {472                Text(verbatim: title).font(.system(size: 11, weight: .medium, design: mono ? .monospaced : .default)).foregroundStyle(ORIX.Palette.text).lineLimit(1)473                Text(verbatim: detail).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(3)474                    .multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)475            }476            .frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 3).contentShape(Rectangle())477        }478        .buttonStyle(.plain)479        .accessibilityHint(Text("Shows the place in the document"))480    }481482    // MARK: Search other documents483484    private func chooseFiles() {485        let panel = NSOpenPanel()486        panel.title = String(localized: "Search Other Documents")487        panel.message = String(localized: "Choose the documents to search. Only the files you choose are read.")488        panel.prompt = String(localized: "Add")489        panel.allowsMultipleSelection = true490        panel.canChooseDirectories = false491        panel.allowedContentTypes = (DocumentConverter.importFormats.map(\.fileExtension) + ["markdown", "htm", "text"]).compactMap { UTType(filenameExtension: $0) }492        guard panel.runModal() == .OK else { return }493        let urls = panel.urls.filter { u in !state.externals.contains { $0.url == u } }494        guard !urls.isEmpty else { return }495        state.loadingExternals = true496        Task {497            let loaded = await Task.detached(priority: .userInitiated) { () -> ([ExternalDocument], [String]) in498                var docs: [ExternalDocument] = [], errors: [String] = []499                for url in urls {500                    do { docs.append(ExternalDocument(url: url, name: url.lastPathComponent, document: try DocumentConverter.importDocument(at: url).document)) }501                    catch { errors.append("\(url.lastPathComponent): \(error.localizedDescription)") }502                }503                return (docs, errors)504            }.value505            state.externals += loaded.0506            state.externalErrors = loaded.1507            state.loadingExternals = false508            search()509        }510    }511512    private func search() {513        let query = state.query.trimmingCharacters(in: .whitespaces)514        let docs = state.externals.map { (name: $0.name, document: $0.document) }515        guard !query.isEmpty, !docs.isEmpty else { state.hits = []; state.searchedQuery = ""; return }516        let options = ResearchAssistant.SearchOptions(caseSensitive: state.caseSensitive, wholeWord: state.wholeWord, contextRadius: 60, maxHits: 300)517        Task {518            let hits = await Task.detached(priority: .userInitiated) { ResearchAssistant.search(query, across: docs, options: options) }.value519            state.hits = hits520            state.searchedQuery = query521        }522    }523524    private var searchSection: some View {525        InspectorSection(title: "Search Other Documents") {526            Text("Look a term up in documents you choose. They are read from disk, searched on this Mac and not modified.")527                .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)528            PanelButton(title: state.externals.isEmpty ? "Choose Documents…" : "Add Documents…", symbol: "folder.badge.plus", isEnabled: !state.loadingExternals) { chooseFiles() }529                .accessibilityIdentifier("research-choose")530            if state.loadingExternals { ProgressView().controlSize(.small) }531            ForEach(state.externalErrors, id: \.self) { Notice(kind: .error, text: $0) }532            ForEach(state.externals) { d in533                HStack(spacing: 5) {534                    Image(systemName: "doc.text").font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)535                    Text(verbatim: d.name).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text).lineLimit(1).truncationMode(.middle)536                    Spacer(minLength: 4)537                    Button { NSDocumentController.shared.openDocument(withContentsOf: d.url, display: true) { _, _, _ in } } label: { Image(systemName: "arrow.up.forward.square") }538                        .buttonStyle(.borderless).help("Open this document").accessibilityLabel(Text("Open \(d.name)"))539                    Button { state.externals.removeAll { $0.url == d.url }; search() } label: { Image(systemName: "xmark.circle.fill") }540                        .buttonStyle(.borderless).foregroundStyle(ORIX.Palette.textTertiary).help("Remove from the search").accessibilityLabel(Text("Remove \(d.name)"))541                }542            }543            if !state.externals.isEmpty {544                HStack(spacing: 6) {545                    Image(systemName: "magnifyingglass").font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)546                    TextField("", text: $state.query, prompt: Text("Search \(state.externals.count) documents")).textFieldStyle(.plain).font(ORIX.Font.label)547                        .onSubmit { search() }548                        .accessibilityLabel(Text("Search the chosen documents")).accessibilityIdentifier("research-query")549                }550                .padding(.horizontal, 7).padding(.vertical, 5)551                .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))552                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline))553                HStack(spacing: ORIX.Space.m) {554                    Toggle("Whole word", isOn: $state.wholeWord).toggleStyle(.checkbox)555                    Toggle("Match case", isOn: $state.caseSensitive).toggleStyle(.checkbox)556                }557                .font(ORIX.Font.label)558                .onChange(of: state.query) { _, _ in search() }559                .onChange(of: state.wholeWord) { _, _ in search() }560                .onChange(of: state.caseSensitive) { _, _ in search() }561                if !state.searchedQuery.isEmpty {562                    Text(state.hits.isEmpty ? String(localized: "No match for “\(state.searchedQuery)”.")563                         : (state.hits.count >= 300 ? String(localized: "First \(state.hits.count) matches for “\(state.searchedQuery)”.") : String(localized: "\(state.hits.count) matches for “\(state.searchedQuery)”.")))564                        .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary)565                    ForEach(state.externals) { d in566                        let hits = state.hits.filter { $0.documentName == d.name }567                        if !hits.isEmpty {568                            Text(verbatim: "\(d.name) · \(hits.count)").font(.system(size: 10.5, weight: .semibold)).foregroundStyle(ORIX.Palette.text).lineLimit(1).truncationMode(.middle)569                                .padding(.top, 2)570                            ForEach(hits.prefix(40)) { hit in571                                VStack(alignment: .leading, spacing: 1) {572                                    if !hit.headingTrail.isEmpty {573                                        Text(verbatim: hit.headingTrail.joined(separator: " › ")).font(.system(size: 9.5)).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)574                                    }575                                    Text(verbatim: hit.context).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(3)576                                        .fixedSize(horizontal: false, vertical: true).textSelection(.enabled)577                                }578                                .padding(6).frame(maxWidth: .infinity, alignment: .leading)579                                .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))580                            }581                            if hits.count > 40 { Text("\(hits.count - 40) more in this document.").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary) }582                        }583                    }584                }585            }586        }587    }588}589
Files main
Menu

Theme