SPB Git

Repository Public

ProposalView.swift 13.3 KB 261 lines swift

1// ORIX Docs2// File: App/Sources/Intelligence/ProposalView.swift3// Description: The proposal card: source excerpt, streamed result, word-level changes, the warning for citation-like passages4//              absent from the source, and Accept / Insert below / Copy / New document / Regenerate / Reject / Stop.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocAutomation1011struct ProposalView: View {12    @Bindable var model: IntelligenceModel13    @State private var showChanges = true1415    private var isReplacement: Bool { model.action?.replacesSource ?? false }1617    var body: some View {18        VStack(alignment: .leading, spacing: ORIX.Space.m) {19            header20            if let source = model.source { sourceExcerpt(source) }21            switch model.phase {22            case .running(let stage): running(stage)23            case .proposal: proposal24            case .failed(let message): failure(message)25            case .idle: EmptyView()26            }27        }28        .padding(ORIX.Space.m)29        .background(RoundedRectangle(cornerRadius: ORIX.Radius.l).fill(ORIX.Palette.surface))30        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.l).strokeBorder(ORIX.Palette.hairline))31        .accessibilityElement(children: .contain)32        .accessibilityIdentifier("intelligence.proposal")33    }3435    private var header: some View {36        HStack(spacing: ORIX.Space.s) {37            Image(systemName: model.action?.symbol ?? "sparkles").foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)38            Text(model.action?.title ?? "").font(.system(size: 12.5, weight: .semibold)).foregroundStyle(ORIX.Palette.text)39            Spacer(minLength: 0)40            Pill(text: String(localized: "Proposal"))41        }42        .accessibilityElement(children: .combine)43        .accessibilityAddTraits(.isHeader)44    }4546    private func sourceExcerpt(_ source: IntelligenceSource) -> some View {47        VStack(alignment: .leading, spacing: ORIX.Space.xs) {48            Text("\(source.scope.title) · \(source.words) words").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)49            Text(source.text.replacingOccurrences(of: "\n", with: " "))50                .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(3)51                .frame(maxWidth: .infinity, alignment: .leading)52        }53        .padding(.leading, ORIX.Space.s)54        .overlay(alignment: .leading) { Rectangle().fill(ORIX.Palette.hairline).frame(width: 2) }55        .accessibilityElement(children: .combine)56        .accessibilityLabel(Text("Source text, \(source.words) words"))57    }5859    // MARK: Running6061    private func running(_ stage: IntelligenceEvent.Stage) -> some View {62        VStack(alignment: .leading, spacing: ORIX.Space.s) {63            if !model.proposal.isEmpty {64                Text(model.proposal).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.text)65                    .frame(maxWidth: .infinity, alignment: .leading).textSelection(.enabled)66                    .accessibilityIdentifier("intelligence.result")67            }68            HStack(spacing: ORIX.Space.s) {69                ProgressView().controlSize(.small)70                Text(stage.label).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)71                Spacer(minLength: 0)72                Button(String(localized: "Stop")) { model.stop() }73                    .buttonStyle(ORIXButtonStyle(prominent: false))74                    .keyboardShortcut(".", modifiers: .command)75                    .help("Stop generating (⌘.)")76                    .accessibilityIdentifier("intelligence.stop")77            }78        }79    }8081    // MARK: Proposal8283    @ViewBuilder private var proposal: some View {84        if let outcome = model.outcome {85            if let notice = outcome.strategy.notice { note(notice, symbol: "square.stack.3d.up", color: ORIX.Palette.textSecondary) }86            if !outcome.unsupported.isEmpty { warning(outcome) }87            if isReplacement, let source = model.source {88                Picker("", selection: $showChanges) {89                    Text("Changes").tag(true)90                    Text("Result").tag(false)91                }92                .pickerStyle(.segmented).labelsHidden().controlSize(.small)93                .accessibilityLabel(Text("Show changes or the result"))94                Text(showChanges ? ProposalText.changes(from: source.text, to: outcome) : ProposalText.result(outcome))95                    .font(ORIX.Font.body).frame(maxWidth: .infinity, alignment: .leading).textSelection(.enabled)96                    .accessibilityIdentifier("intelligence.result")97                    .accessibilityLabel(Text(outcome.text))98            } else {99                Text(ProposalText.result(outcome)).font(ORIX.Font.body)100                    .frame(maxWidth: .infinity, alignment: .leading).textSelection(.enabled)101                    .accessibilityIdentifier("intelligence.result")102            }103            Text("\(DocumentWords.count(outcome.text)) words · \(outcome.duration.formatted(.number.precision(.fractionLength(1)))) s on this Mac")104                .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)105            actions106        }107    }108109    private func warning(_ outcome: IntelligenceOutcome) -> some View {110        VStack(alignment: .leading, spacing: ORIX.Space.xs) {111            Label {112                Text("Not found in your text").font(.system(size: 11.5, weight: .semibold))113            } icon: { Image(systemName: "exclamationmark.triangle.fill") }114            .foregroundStyle(ORIX.Palette.warning)115            Text("The result contains \(outcome.unsupported.count) citation-like passage(s) that are not in the source. They are highlighted. The model may have invented them: verify or remove them before accepting.")116                .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text).fixedSize(horizontal: false, vertical: true)117            ForEach(outcome.unsupported) { p in118                HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.xs) {119                    Text(p.kind.title).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary)120                    Text(p.text).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text).lineLimit(2)121                }122            }123        }124        .padding(ORIX.Space.s)125        .frame(maxWidth: .infinity, alignment: .leading)126        .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.warning.opacity(0.12)))127        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.warning.opacity(0.5)))128        .accessibilityElement(children: .combine)129        .accessibilityIdentifier("intelligence.warning")130    }131132    private func note(_ text: String, symbol: String, color: Color) -> some View {133        Label { Text(text).font(ORIX.Font.label).fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: symbol) }134            .foregroundStyle(color)135    }136137    @ViewBuilder private var actions: some View {138        let blocker = isReplacement ? model.replaceBlocker : nil139        VStack(alignment: .leading, spacing: ORIX.Space.s) {140            if isReplacement {141                HStack(spacing: ORIX.Space.s) {142                    Button(String(localized: "Accept")) { model.accept() }143                        .buttonStyle(ORIXButtonStyle())144                        .disabled(blocker != nil).opacity(blocker == nil ? 1 : 0.45)145                        .keyboardShortcut(.return, modifiers: .command)146                        .help(blocker ?? String(localized: "Replace the text with this proposal (⌘↩). One Undo restores the original."))147                        .accessibilityIdentifier("intelligence.accept")148                    Button(String(localized: "Reject")) { model.reject() }149                        .buttonStyle(ORIXButtonStyle(prominent: false))150                        .keyboardShortcut(.cancelAction)151                        .help("Discard the proposal; the text is left as it is (Esc)")152                        .accessibilityIdentifier("intelligence.reject")153                    Spacer(minLength: 0)154                }155                if let blocker { note(blocker, symbol: "info.circle", color: ORIX.Palette.textSecondary) }156            }157            HStack(spacing: ORIX.Space.s) {158                Button(isReplacement ? String(localized: "Insert Below") : String(localized: "Insert After")) { model.insertBelow() }159                    .buttonStyle(ORIXButtonStyle(prominent: !isReplacement))160                    .disabled(model.source == nil)161                    .help("Insert the result as new paragraphs after the source text; the source is not changed")162                    .accessibilityIdentifier("intelligence.insert")163                Button(String(localized: "Copy")) { model.copy() }164                    .buttonStyle(ORIXButtonStyle(prominent: false))165                    .help("Copy the result")166                    .accessibilityIdentifier("intelligence.copy")167                Spacer(minLength: 0)168            }169            HStack(spacing: ORIX.Space.m) {170                if !isReplacement {171                    Button(String(localized: "New Document")) { model.openAsNewDocument() }172                        .help("Open the result as a new document")173                        .accessibilityIdentifier("intelligence.newDocument")174                }175                Button(String(localized: "Regenerate")) { model.regenerate() }176                    .help("Ask the model again; the result may differ")177                    .accessibilityIdentifier("intelligence.regenerate")178                if !isReplacement {179                    Button(String(localized: "Dismiss")) { model.reject() }180                        .keyboardShortcut(.cancelAction)181                        .accessibilityIdentifier("intelligence.reject")182                }183                Spacer(minLength: 0)184            }185            .buttonStyle(.link).font(ORIX.Font.label)186        }187    }188189    private func failure(_ message: String) -> some View {190        VStack(alignment: .leading, spacing: ORIX.Space.s) {191            note(message, symbol: "exclamationmark.circle", color: ORIX.Palette.critical)192                .accessibilityIdentifier("intelligence.error")193            HStack(spacing: ORIX.Space.m) {194                if model.generationEnabled { Button(String(localized: "Try Again")) { model.regenerate() } }195                Button(String(localized: "Dismiss")) { model.reject() }.keyboardShortcut(.cancelAction)196            }197            .buttonStyle(.link).font(ORIX.Font.label)198        }199    }200}201202enum DocumentWords {203    static func count(_ text: String) -> Int { text.split { $0.isWhitespace }.count }204}205206/// Attributed renderings of a proposal: the result with unsupported passages highlighted, and the word-level changes.207enum ProposalText {208    static func result(_ outcome: IntelligenceOutcome) -> AttributedString {209        var out = AttributedString()210        var cursor = outcome.text.startIndex211        for p in outcome.unsupported where p.range.lowerBound >= cursor && p.range.upperBound <= outcome.text.endIndex {212            out += plain(String(outcome.text[cursor..<p.range.lowerBound]))213            var flagged = AttributedString(String(outcome.text[p.range]))214            flagged.backgroundColor = ORIX.Palette.warning.opacity(0.28)215            flagged.foregroundColor = ORIX.Palette.text216            flagged.underlineStyle = .single217            out += flagged218            cursor = p.range.upperBound219        }220        out += plain(String(outcome.text[cursor...]))221        return out222    }223224    private static func plain(_ s: String) -> AttributedString {225        var a = AttributedString(s)226        a.foregroundColor = ORIX.Palette.text227        return a228    }229230    /// Deleted words struck through, inserted words underlined in the positive colour; unsupported passages keep their highlight.231    static func changes(from source: String, to outcome: IntelligenceOutcome) -> AttributedString {232        let flagged = outcome.unsupported.map(\.text)233        var out = AttributedString()234        let old = source.replacingOccurrences(of: "\n", with: "\n\n")235        var segments = WordDiff.diff(old, outcome.text)236        // When little is shared, interleaved words are unreadable: show the old text struck through, then the new one.237        let kept = segments.filter { $0.kind == .equal }.reduce(0) { $0 + $1.text.count }238        if Double(kept) < 0.4 * Double(max(1, min(old.count, outcome.text.count))) {239            segments = [WordDiffSegment(kind: .deleted, text: old), WordDiffSegment(kind: .equal, text: "\n\n"), WordDiffSegment(kind: .inserted, text: outcome.text)]240        }241        for segment in segments {242            var a = AttributedString(segment.text)243            switch segment.kind {244            case .equal:245                a.foregroundColor = ORIX.Palette.text246            case .deleted:247                a.foregroundColor = ORIX.Palette.critical248                a.strikethroughStyle = .single249            case .inserted:250                a.foregroundColor = ORIX.Palette.positive251                a.underlineStyle = .single252                if flagged.contains(where: { $0.contains(segment.text.trimmingCharacters(in: .whitespaces)) && segment.text.trimmingCharacters(in: .whitespaces).count > 2 }) {253                    a.backgroundColor = ORIX.Palette.warning.opacity(0.28)254                }255            }256            out += a257        }258        return out259    }260}261
Files main
Menu

Theme