SPB Git

Repository Public

TextToolsView.swift 15.6 KB 319 lines swift

1// ORIX Docs2// File: App/Sources/Intelligence/TextToolsView.swift3// Description: The rule-based part of the intelligence panel: readability, repeated wording, undefined acronyms, languages and4//              related paragraphs. No language model is involved; the section says so and is always available.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import Observation10import DocModel11import DocAudit1213nonisolated enum TextTool: String, CaseIterable, Identifiable, Sendable {14    case readability, repetition, acronyms, languages, related15    var id: String { rawValue }16    var title: String {17        switch self {18        case .readability: return String(localized: "Readability")19        case .repetition: return String(localized: "Repeated Wording")20        case .acronyms: return String(localized: "Undefined Acronyms")21        case .languages: return String(localized: "Languages")22        case .related: return String(localized: "Related Paragraphs")23        }24    }25    var symbol: String {26        switch self {27        case .readability: return "chart.bar.xaxis"28        case .repetition: return "repeat"29        case .acronyms: return "textformat.abc"30        case .languages: return "globe"31        case .related: return "point.3.connected.trianglepath.dotted"32        }33    }34    var help: String {35        switch self {36        case .readability: return String(localized: "Sentence lengths, long sentences and reading time")37        case .repetition: return String(localized: "Words and phrases repeated close together")38        case .acronyms: return String(localized: "Acronyms used without being spelled out first")39        case .languages: return String(localized: "The language of each paragraph, and paragraphs that differ from the rest")40        case .related: return String(localized: "Paragraphs on the same topic as the selection")41        }42    }43}4445@Observable46final class TextToolsModel {47    nonisolated enum Result: Sendable {48        case readability(ReadabilityReport)49        case repetition([ResearchAssistant.RepetitionFinding])50        case acronyms([ResearchAssistant.AcronymFinding])51        case languages(LanguageReport)52        case related(RelatedReport, query: String)53        case message(String)54    }55    @ObservationIgnored unowned let session: DocumentSession56    private(set) var open: TextTool?57    private(set) var result: Result?58    private(set) var busy = false59    /// Document revision the result was computed for.60    private(set) var computedRevision = -161    @ObservationIgnored private var task: Task<Void, Never>?6263    init(session: DocumentSession) { self.session = session }6465    var isStale: Bool { result != nil && computedRevision != session.revision }6667    func toggle(_ tool: TextTool) {68        if open == tool, !isStale { open = nil; result = nil; return }69        run(tool)70    }7172    func run(_ tool: TextTool) {73        task?.cancel()74        open = tool75        result = nil76        busy = true77        let doc = session.doc78        let revision = session.revision79        var query = ""80        var excluded = Set<ParaPath>()81        if tool == .related {82            let slices = session.selection.isCaret ? [] : session.editor.selectedParagraphs()83            if session.selection.story == .body, !slices.isEmpty {84                query = session.editor.selectedText85                excluded = Set(slices.map(\.path))86            } else if let p = session.blocks.paragraph(at: session.selection.start.path) {87                query = p.visibleText88                if session.selection.story == .body { excluded = [session.selection.start.path] }89            }90            query = query.replacingOccurrences(of: objectReplacementCharacter, with: "")91            guard query.trimmingCharacters(in: .whitespacesAndNewlines).count >= 12 else {92                busy = false93                result = .message(String(localized: "Select a sentence or place the caret in a paragraph of text first."))94                return95            }96        }97        // The analyses are pure functions of the document value: they run off the main thread.98        task = Task { [weak self] in99            let computed = await TextToolsModel.compute(tool, doc: doc, query: query, excluding: excluded)100            guard let self, !Task.isCancelled else { return }101            self.result = computed102            self.computedRevision = revision103            self.busy = false104        }105    }106107    @concurrent nonisolated private static func compute(_ tool: TextTool, doc: DocumentModel, query: String, excluding: Set<ParaPath>) async -> Result {108        switch tool {109        case .readability: return .readability(TextTools.readability(doc))110        case .repetition: return .repetition(ResearchAssistant.repeatedWording(in: doc, language: doc.meta.language))111        case .acronyms: return .acronyms(ResearchAssistant.undefinedAcronyms(in: doc))112        case .languages: return .languages(TextTools.languages(doc))113        case .related: return .related(TextTools.related(to: query, in: doc, excluding: excluding), query: query)114        }115    }116117    func reveal(_ location: TextLocation) { session.reveal(story: location.story, path: location.path, range: location.range) }118    func reveal(_ hit: ResearchAssistant.Hit) { session.reveal(story: hit.story, path: hit.path, range: hit.range) }119}120121struct TextToolsView: View {122    @Bindable var model: TextToolsModel123124    var body: some View {125        VStack(alignment: .leading, spacing: ORIX.Space.s) {126            Label {127                Text("Rules and statistics, not a language model. Always available, same result every time.")128                    .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)129            } icon: { Image(systemName: "function").foregroundStyle(ORIX.Palette.textTertiary) }130            ForEach(TextTool.allCases) { tool in131                VStack(alignment: .leading, spacing: ORIX.Space.s) {132                    ToolRow(tool: tool, isOpen: model.open == tool) { model.toggle(tool) }133                    if model.open == tool { results.padding(.leading, ORIX.Space.xs) }134                }135            }136        }137    }138139    @ViewBuilder private var results: some View {140        if model.busy {141            HStack(spacing: ORIX.Space.s) { ProgressView().controlSize(.small); Text("Analysing…").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary) }142        } else if let result = model.result {143            VStack(alignment: .leading, spacing: ORIX.Space.s) {144                if model.isStale, let tool = model.open {145                    Button(String(localized: "The document changed — analyse again")) { model.run(tool) }.buttonStyle(.link).font(ORIX.Font.label)146                }147                switch result {148                case .readability(let r): readability(r)149                case .repetition(let items): repetition(items)150                case .acronyms(let items): acronyms(items)151                case .languages(let r): languages(r)152                case .related(let r, _): related(r)153                case .message(let text): caption(text)154                }155            }156        }157    }158159    private func caption(_ text: String) -> some View {160        Text(text).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)161    }162163    private func metric(_ label: LocalizedStringKey, _ value: String) -> some View {164        HStack {165            Text(label).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)166            Spacer(minLength: ORIX.Space.s)167            Text(value).font(ORIX.Font.label.monospacedDigit()).foregroundStyle(ORIX.Palette.text)168        }169        .accessibilityElement(children: .combine)170    }171172    // MARK: Readability173174    @ViewBuilder private func readability(_ r: ReadabilityReport) -> some View {175        if r.sentences == 0 { caption(String(localized: "The document has no sentences to measure yet.")) } else {176            metric("Sentences", "\(r.sentences)")177            metric("Words per sentence (average)", r.averageWords.formatted(.number.precision(.fractionLength(1))))178            metric("Words per sentence (median)", "\(r.medianWords)")179            metric("Longest sentence", String(localized: "\(r.longestWords) words"))180            metric("Estimated reading time", String(localized: "\(r.readingMinutes) min"))181            let peak = max(1, r.buckets.map(\.count).max() ?? 1)182            VStack(alignment: .leading, spacing: 3) {183                Text("Sentence length distribution").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)184                ForEach(r.buckets) { b in185                    HStack(spacing: ORIX.Space.s) {186                        Text(b.label).font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 38, alignment: .leading)187                        GeometryReader { geo in188                            RoundedRectangle(cornerRadius: 2).fill(ORIX.Palette.accent.opacity(0.75))189                                .frame(width: max(b.count > 0 ? 2 : 0, geo.size.width * CGFloat(b.count) / CGFloat(peak)))190                        }191                        .frame(height: 8)192                        Text("\(b.count)").font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.text).frame(width: 30, alignment: .trailing)193                    }194                    .accessibilityElement(children: .ignore)195                    .accessibilityLabel(Text("\(b.count) sentences of \(b.label) words"))196                }197            }198            if r.long.isEmpty { caption(String(localized: "No sentence is longer than \(r.threshold) words.")) } else {199                Text("\(r.long.count) sentence(s) longer than \(r.threshold) words").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)200                ForEach(r.long.prefix(12)) { s in201                    LocationRow(badge: "\(s.words)", text: s.location.excerpt) { model.reveal(s.location) }202                }203            }204        }205    }206207    // MARK: Repetition and acronyms208209    @ViewBuilder private func repetition(_ items: [ResearchAssistant.RepetitionFinding]) -> some View {210        if items.isEmpty { caption(String(localized: "No word or phrase is repeated unusually often in a short span.")) } else {211            ForEach(items.prefix(20)) { f in212                LocationRow(badge: "×\(f.count)", text: f.kind == .phrase ? "“\(f.text)”" : f.text,213                            detail: f.occurrences.first.map { $0.context }) { if let hit = f.occurrences.first { model.reveal(hit) } }214            }215        }216    }217218    @ViewBuilder private func acronyms(_ items: [ResearchAssistant.AcronymFinding]) -> some View {219        if items.isEmpty { caption(String(localized: "Every acronym is spelled out where it first appears, or the document uses none.")) } else {220            ForEach(items.prefix(30)) { f in221                LocationRow(badge: "×\(f.count)", text: f.acronym, detail: f.firstUse.context) { model.reveal(f.firstUse) }222            }223        }224    }225226    // MARK: Languages227228    @ViewBuilder private func languages(_ r: LanguageReport) -> some View {229        if r.shares.isEmpty { caption(String(localized: "No paragraph is long enough to identify its language.")) } else {230            ForEach(r.shares) { s in metric(LocalizedStringKey(TextTools.languageName(s.code)), String(localized: "\(s.paragraphs) paragraph(s)")) }231            if r.undetermined > 0 { caption(String(localized: "\(r.undetermined) short paragraph(s) were not identified.")) }232            if r.outliers.isEmpty {233                if r.shares.count == 1 { caption(String(localized: "Every identified paragraph is in the same language.")) }234            } else {235                Text("Paragraphs in another language").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)236                ForEach(r.outliers.prefix(15)) { o in237                    LocationRow(badge: o.code.uppercased(), text: o.location.excerpt) { model.reveal(o.location) }238                }239            }240        }241    }242243    // MARK: Related244245    @ViewBuilder private func related(_ r: RelatedReport) -> some View {246        switch r.method {247        case .sentenceEmbedding(let language):248            caption(String(localized: "Ranked by meaning, with the system's sentence embeddings for \(TextTools.languageName(language))."))249        case .lexical(let reason):250            caption(reason == "unknown"251                    ? String(localized: "Ranked by shared vocabulary: the language of the selection could not be identified, so sentence embeddings were not used.")252                    : String(localized: "Ranked by shared vocabulary: no sentence embedding is available on this Mac for \(TextTools.languageName(reason))."))253        }254        if r.items.isEmpty { caption(String(localized: "No other paragraph is related to this text.")) } else {255            ForEach(r.items) { item in256                LocationRow(badge: "\(Int((item.score * 100).rounded()))", text: item.location.excerpt) { model.reveal(item.location) }257            }258        }259    }260}261262private struct ToolRow: View {263    let tool: TextTool264    let isOpen: Bool265    let action: () -> Void266    @State private var hover = false267268    var body: some View {269        Button(action: action) {270            HStack(spacing: ORIX.Space.s) {271                Image(systemName: tool.symbol).font(.system(size: 12, weight: .medium)).frame(width: 18).foregroundStyle(isOpen ? ORIX.Palette.accent : ORIX.Palette.textSecondary)272                Text(tool.title).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.text)273                Spacer(minLength: 0)274                Image(systemName: isOpen ? "chevron.down" : "chevron.right").font(.system(size: 9, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary)275            }276            .padding(.horizontal, ORIX.Space.s).padding(.vertical, 6)277            .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(isOpen ? ORIX.Palette.accent.opacity(0.1) : (hover ? ORIX.Palette.text.opacity(0.06) : .clear)))278            .contentShape(Rectangle())279        }280        .buttonStyle(.plain)281        .onHover { hover = $0 }282        .help(tool.help)283        .accessibilityLabel(Text(tool.title))284        .accessibilityHint(Text(tool.help))285        .accessibilityAddTraits(isOpen ? .isSelected : [])286        .accessibilityIdentifier("intelligence.tool.\(tool.rawValue)")287    }288}289290/// One result that jumps to its place in the document.291struct LocationRow: View {292    let badge: String293    let text: String294    var detail: String?295    let action: () -> Void296    @State private var hover = false297298    var body: some View {299        Button(action: action) {300            HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.s) {301                Text(badge).font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.accent).frame(minWidth: 26, alignment: .trailing)302                VStack(alignment: .leading, spacing: 1) {303                    Text(text).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text).lineLimit(2).multilineTextAlignment(.leading)304                    if let detail, !detail.isEmpty { Text(detail).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(2).multilineTextAlignment(.leading) }305                }306                Spacer(minLength: 0)307            }308            .padding(.vertical, 3).padding(.horizontal, ORIX.Space.xs)309            .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(hover ? ORIX.Palette.text.opacity(0.06) : .clear))310            .contentShape(Rectangle())311        }312        .buttonStyle(.plain)313        .onHover { hover = $0 }314        .help("Show in the document")315        .accessibilityLabel(Text("\(text), \(badge)"))316        .accessibilityHint(Text("Shows this place in the document"))317    }318}319
Files main
Menu

Theme