SPB Git

Repository Public

ComparisonWindow.swift 29.0 KB 608 lines swift

1// ORIX Docs2// File: App/Sources/Sheets/ComparisonWindow.swift3// Description: The comparison window: summary, change list, and the aligned side-by-side view of the original and revised documents4//              (one scroll view, so both sides always move together), with the merged-document and report actions.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import UniformTypeIdentifiers11import DocModel12import DocReview1314struct ComparisonPayload {15    let result: DocumentComparison16    let options: ComparisonOptions17    let original: DocumentModel18    let revised: DocumentModel19    let originalName: String20    let revisedName: String21}2223/// Owns one comparison window. Windows stay alive until closed.24final class ComparisonWindowController: NSObject, NSWindowDelegate {25    private static var open: [ComparisonWindowController] = []26    private let window: NSWindow27    private let payload: ComparisonPayload2829    static func present(_ payload: ComparisonPayload) {30        let controller = ComparisonWindowController(payload)31        open.append(controller)32        controller.window.makeKeyAndOrderFront(nil)33        // Automated runs (`-ORIXCompareSnapshot <png>`): capture the window and leave.34        if let path = UserDefaults.standard.string(forKey: "ORIXCompareSnapshot") {35            let window = controller.window36            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {37                LaunchOptions.snapshot(window: window, to: URL(fileURLWithPath: path))38                exit(0)39            }40        }41    }4243    private init(_ payload: ComparisonPayload) {44        self.payload = payload45        window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1180, height: 760), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)46        super.init()47        window.title = String(localized: "Comparison: \(payload.originalName) → \(payload.revisedName)")48        window.isReleasedWhenClosed = false49        window.minSize = NSSize(width: 860, height: 480)50        window.delegate = self51        let model = ComparisonModel(payload)52        window.contentView = NSHostingView(rootView: ComparisonView(model: model, openMerged: { [weak self] in self?.openMerged() },53                                                                    saveReport: { [weak self] in self?.saveReport() }, openReport: { [weak self] in self?.openReport() }))54        window.center()55    }5657    func windowWillClose(_ notification: Notification) {58        ComparisonWindowController.open.removeAll { $0 === self }59    }6061    private func openMerged() {62        ORIXDocument.openUntitled(payload.result.merged, displayName: String(localized: "\(baseName(payload.revisedName)) (compared)"))63    }6465    private func openReport() {66        let report = payload.result.reportDocument(originalName: payload.originalName, revisedName: payload.revisedName)67        ORIXDocument.openUntitled(report, displayName: String(localized: "Comparison Report"))68    }6970    private func saveReport() {71        let panel = NSSavePanel()72        panel.allowedContentTypes = [UTType(filenameExtension: "md") ?? .plainText]73        panel.nameFieldStringValue = String(localized: "Comparison Report") + ".md"74        panel.canCreateDirectories = true75        let markdown = payload.result.reportMarkdown(originalName: payload.originalName, revisedName: payload.revisedName)76        let host = window77        panel.beginSheetModal(for: host) { response in78            guard response == .OK, let url = panel.url else { return }79            do { try markdown.write(to: url, atomically: true, encoding: .utf8) } catch {80                let alert = NSAlert()81                alert.messageText = String(localized: "The report could not be saved.")82                alert.informativeText = error.localizedDescription83                alert.beginSheetModal(for: host)84            }85        }86    }8788    private func baseName(_ name: String) -> String { (name as NSString).deletingPathExtension }89}9091// MARK: - Model9293/// What one aligned row shows on each side. Built on demand for the rows that scroll into view and kept.94struct ComparisonRowContent {95    var left: AttributedString?96    var right: AttributedString?97    var leftNumber: Int?98    var rightNumber: Int?99    var leftNote: String?100    var rightNote: String?101}102103@Observable104final class ComparisonModel {105    let payload: ComparisonPayload106    let rows: [AlignedRow]107    let changedRows: [Int]108    var selectedChange: String?109    var highlightedRow: Int?110    var changesOnly = false111    @ObservationIgnored private var cache: [Int: ComparisonRowContent] = [:]112    @ObservationIgnored private var rowOfOriginal: [Int: Int] = [:]113    @ObservationIgnored private var rowOfRevised: [Int: Int] = [:]114115    init(_ payload: ComparisonPayload) {116        self.payload = payload117        rows = payload.result.rows118        changedRows = rows.indices.filter { payload.result.rows[$0].kind != .equal }119        for (i, row) in rows.enumerated() {120            if let o = row.original, row.kind != .movedTo, rowOfOriginal[o] == nil { rowOfOriginal[o] = i }121            if let r = row.revised, row.kind != .movedFrom, rowOfRevised[r] == nil { rowOfRevised[r] = i }122        }123        // Formatting, style and structure changes sit on rows whose text is equal: those rows count as changed too.124        var extra = Set(changedRows)125        for change in payload.result.changes where change.story == .body { if let i = row(of: change) { extra.insert(i) } }126        rowsWithChanges = extra127    }128129    @ObservationIgnored private(set) var rowsWithChanges: Set<Int> = []130131    var visibleRows: [Int] { changesOnly ? rows.indices.filter { rowsWithChanges.contains($0) } : Array(rows.indices) }132133    func row(of change: DocumentChange) -> Int? {134        if let r = change.revisedBlock, let i = rowOfRevised[r] { return i }135        if let o = change.originalBlock, let i = rowOfOriginal[o] { return i }136        return nil137    }138139    func content(_ index: Int) -> ComparisonRowContent {140        if let c = cache[index] { return c }141        let c = build(rows[index])142        cache[index] = c143        return c144    }145146    private func block(_ index: Int?, in doc: DocumentModel) -> Block? {147        guard let index, doc.body.indices.contains(index) else { return nil }148        return doc.body[index]149    }150151    private func build(_ row: AlignedRow) -> ComparisonRowContent {152        let a = block(row.original, in: payload.original), b = block(row.revised, in: payload.revised)153        var c = ComparisonRowContent()154        switch row.kind {155        case .equal:156            c.left = a.map { ComparisonText.plain($0, in: payload.original) }157            c.right = b.map { ComparisonText.plain($0, in: payload.revised) }158            c.leftNumber = row.original; c.rightNumber = row.revised159        case .modified:160            c.leftNumber = row.original; c.rightNumber = row.revised161            if let pa = a?.paragraph, let pb = b?.paragraph {162                let runs = DocumentComparer.inlineDiff(pa, pb, options: payload.options)163                c.left = ComparisonText.side(runs, original: true, style: pa.style)164                c.right = ComparisonText.side(runs, original: false, style: pb.style)165            } else {166                c.left = a.map { ComparisonText.plain($0, in: payload.original) }167                c.right = b.map { ComparisonText.plain($0, in: payload.revised) }168            }169        case .inserted:170            c.right = b.map { ComparisonText.plain($0, in: payload.revised) }171            c.rightNumber = row.revised172        case .deleted:173            c.left = a.map { ComparisonText.plain($0, in: payload.original) }174            c.leftNumber = row.original175        case .movedFrom:176            c.left = a.map { ComparisonText.plain($0, in: payload.original) }177            c.leftNumber = row.original178            if let to = row.revised { c.leftNote = String(localized: "Moved to block \(to + 1)") }179        case .movedTo:180            c.right = b.map { ComparisonText.plain($0, in: payload.revised) }181            c.rightNumber = row.revised182            if let from = row.original { c.rightNote = String(localized: "Moved from block \(from + 1)") }183        }184        return c185    }186187    /// Moves the selection to the next or previous change of the list.188    func step(_ delta: Int) -> DocumentChange? {189        let changes = payload.result.changes190        guard !changes.isEmpty else { return nil }191        let current = changes.firstIndex { $0.id == selectedChange }192        let next = current.map { ($0 + delta + changes.count) % changes.count } ?? (delta > 0 ? 0 : changes.count - 1)193        return changes[next]194    }195}196197/// Styled text of blocks for the side-by-side view.198enum ComparisonText {199    static func label(_ inline: Inline) -> String {200        switch inline {201        case .image: return String(localized: "[image]")202        case .shape: return String(localized: "[shape]")203        case .equation(let e): return "[\(e.latex)]"204        case .note: return String(localized: "[note]")205        case .citation: return String(localized: "[citation]")206        case .crossRef: return String(localized: "[cross-reference]")207        case .field: return String(localized: "[field]")208        case .bookmark: return ""209        }210    }211212    static func text(_ run: Run) -> String {213        if let inline = run.inline { return label(inline) }214        return run.text.replacingOccurrences(of: "\u{2028}", with: "\n")215    }216217    static func text(_ p: Paragraph) -> String { p.runs.filter { !$0.isDeleted }.map(text).joined() }218219    static func font(style: String) -> Font {220        if style == StyleID.title { return .system(size: 15, weight: .bold) }221        if style == StyleID.heading(1) { return .system(size: 14, weight: .bold) }222        if style.hasPrefix("Heading") { return .system(size: 12.5, weight: .semibold) }223        if style == StyleID.code { return .system(size: 11.5, design: .monospaced) }224        return .system(size: 12.5)225    }226227    static func plain(_ block: Block, in doc: DocumentModel) -> AttributedString {228        switch block {229        case .paragraph(let p):230            var s = AttributedString(text(p))231            s.font = font(style: p.style)232            return s233        case .table(let t):234            let lines = t.rows.map { row in row.cells.map { cell in cell.paragraphs.map(text).joined(separator: " ") }.joined(separator: "  │  ") }235            var s = AttributedString(lines.joined(separator: "\n"))236            s.font = .system(size: 11.5)237            return s238        case .pageBreak(let b): return marker(b.kind == .page ? String(localized: "Page break") : String(localized: "Column break"))239        case .sectionBreak: return marker(String(localized: "Section break"))240        case .toc(let t):241            switch t.kind {242            case .contents: return marker(String(localized: "Table of contents"))243            case .figures: return marker(String(localized: "List of figures"))244            case .tables: return marker(String(localized: "List of tables"))245            }246        case .bibliography: return marker(String(localized: "Bibliography"))247        }248    }249250    private static func marker(_ name: String) -> AttributedString {251        var s = AttributedString("— \(name) —")252        s.font = .system(size: 11, weight: .medium)253        s.foregroundColor = ORIX.Palette.textTertiary254        return s255    }256257    /// One side of a word-level diff. The original side keeps deletions (struck through), the revised side keeps insertions258    /// (underlined); text whose formatting changed gets a dotted underline on both.259    static func side(_ runs: [Run], original: Bool, style: String) -> AttributedString {260        var out = AttributedString()261        let base = font(style: style)262        for run in runs {263            if let rev = run.revision, (rev.kind == .insertion) == original { continue }264            var piece = AttributedString(text(run))265            piece.font = base266            if run.revision != nil {267                let color = original ? ORIX.Palette.critical : ORIX.Palette.positive268                piece.foregroundColor = color269                piece.backgroundColor = color.opacity(0.14)270                if original { piece.strikethroughStyle = Text.LineStyle(pattern: .solid, color: color) }271                else { piece.underlineStyle = Text.LineStyle(pattern: .solid, color: color) }272            } else if run.formatRevision != nil {273                piece.underlineStyle = Text.LineStyle(pattern: .dot, color: ORIX.Palette.warning)274                piece.backgroundColor = ORIX.Palette.warning.opacity(0.12)275            }276            out.append(piece)277        }278        return out279    }280}281282extension AlignedRow.Kind {283    var label: String? {284        switch self {285        case .equal: return nil286        case .modified: return String(localized: "Modified")287        case .inserted: return String(localized: "Inserted")288        case .deleted: return String(localized: "Deleted")289        case .movedFrom, .movedTo: return String(localized: "Moved")290        }291    }292    var symbol: String {293        switch self {294        case .equal: return "equal"295        case .modified: return "pencil"296        case .inserted: return "plus"297        case .deleted: return "minus"298        case .movedFrom, .movedTo: return "arrow.up.arrow.down"299        }300    }301    var color: Color {302        switch self {303        case .equal: return ORIX.Palette.textTertiary304        case .modified: return ORIX.Palette.warning305        case .inserted: return ORIX.Palette.positive306        case .deleted: return ORIX.Palette.critical307        case .movedFrom, .movedTo: return ORIX.Palette.accent308        }309    }310}311312extension DocumentChange.Kind {313    var localizedLabel: String {314        switch self {315        case .inserted: return String(localized: "Inserted")316        case .deleted: return String(localized: "Deleted")317        case .modified: return String(localized: "Modified")318        case .moved: return String(localized: "Moved")319        case .formatting: return String(localized: "Formatting")320        case .style: return String(localized: "Style")321        case .structure: return String(localized: "Structure")322        }323    }324    var symbol: String {325        switch self {326        case .inserted: return "plus"327        case .deleted: return "minus"328        case .modified: return "pencil"329        case .moved: return "arrow.up.arrow.down"330        case .formatting: return "textformat"331        case .style: return "paragraphsign"332        case .structure: return "square.split.2x2"333        }334    }335    var color: Color {336        switch self {337        case .inserted: return ORIX.Palette.positive338        case .deleted: return ORIX.Palette.critical339        case .modified: return ORIX.Palette.warning340        case .moved: return ORIX.Palette.accent341        case .formatting, .style, .structure: return ORIX.Palette.textSecondary342        }343    }344}345346// MARK: - Views347348struct ComparisonView: View {349    @Bindable var model: ComparisonModel350    let openMerged: () -> Void351    let saveReport: () -> Void352    let openReport: () -> Void353354    var body: some View {355        let summary = model.payload.result.summary356        VStack(spacing: 0) {357            header(summary)358            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)359            ScrollViewReader { proxy in360                HStack(spacing: 0) {361                    changeList(proxy: proxy).frame(width: 286)362                    Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)363                    sideBySide364                }365            }366        }367        .background(ORIX.Palette.chrome)368        .frame(minWidth: 860, minHeight: 480)369        .accessibilityIdentifier("comparison-view")370    }371372    private func header(_ summary: ComparisonSummary) -> some View {373        VStack(alignment: .leading, spacing: ORIX.Space.s) {374            HStack(alignment: .center, spacing: ORIX.Space.m) {375                HStack(spacing: 6) {376                    Text(model.payload.originalName).lineLimit(1).truncationMode(.middle)377                    Image(systemName: "arrow.right").font(.system(size: 10, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityLabel(Text("compared with"))378                    Text(model.payload.revisedName).lineLimit(1).truncationMode(.middle)379                }380                .font(ORIX.Font.title).foregroundStyle(ORIX.Palette.text)381                Spacer(minLength: ORIX.Space.m)382                Menu {383                    Button("Save as Markdown…", action: saveReport)384                    Button("Open as Document", action: openReport)385                } label: { Text("Export Report…") }386                    .menuStyle(.borderlessButton).fixedSize()387                    .accessibilityIdentifier("comparison-export-report")388                Button(action: openMerged) { Text("Open Merged Document with Tracked Changes").fixedSize() }389                    .buttonStyle(ORIXButtonStyle())390                    .help("Opens the revised document with every difference as a tracked change you can accept or reject.")391                    .accessibilityIdentifier("comparison-open-merged")392            }393            ScrollView(.horizontal, showsIndicators: false) {394                HStack(spacing: ORIX.Space.s) {395                    if summary.isIdentical {396                        Label("The documents are identical", systemImage: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.positive)397                    } else {398                        ForEach(DocumentChange.Kind.allCases, id: \.self) { kind in399                            if summary.count(kind) > 0 {400                                Label("\(summary.count(kind)) \(kind.localizedLabel.lowercased())", systemImage: kind.symbol)401                                    .labelStyle(.titleAndIcon).foregroundStyle(kind.color)402                                    .padding(.horizontal, 7).padding(.vertical, 2)403                                    .background(Capsule().fill(kind.color.opacity(0.12)))404                            }405                        }406                    }407                    Text("+\(summary.wordsInserted) / −\(summary.wordsDeleted) words").foregroundStyle(ORIX.Palette.textSecondary)408                        .accessibilityLabel(Text("\(summary.wordsInserted) words inserted, \(summary.wordsDeleted) words deleted"))409                    if summary.wordsMoved > 0 { Text("\(summary.wordsMoved) words moved").foregroundStyle(ORIX.Palette.textSecondary) }410                    Text("Similarity \(summary.similarity.formatted(.percent.precision(.fractionLength(1))))").foregroundStyle(ORIX.Palette.textSecondary)411                }412                .font(ORIX.Font.caption.monospacedDigit()).lineLimit(1).fixedSize()413            }414            .accessibilityIdentifier("comparison-summary")415        }416        .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.m)417    }418419    private func select(_ change: DocumentChange, proxy: ScrollViewProxy) {420        model.selectedChange = change.id421        guard let row = model.row(of: change) else { model.highlightedRow = nil; return }422        if model.changesOnly && !model.rowsWithChanges.contains(row) { model.changesOnly = false }423        model.highlightedRow = row424        withAnimation(ORIX.Motion.quick) {425            proxy.scrollTo("row-\(row)", anchor: .center)426            proxy.scrollTo("change-\(change.id)")427        }428    }429430    private func changeList(proxy: ScrollViewProxy) -> some View {431        let changes = model.payload.result.changes432        return VStack(spacing: 0) {433            HStack(spacing: 2) {434                Text("Changes").font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary).accessibilityAddTraits(.isHeader)435                Text("\(changes.count)").font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary).padding(.leading, 4)436                Spacer()437                BarButton(symbol: "chevron.up", help: "Previous Change", isEnabled: !changes.isEmpty) { if let c = model.step(-1) { select(c, proxy: proxy) } }438                    .accessibilityIdentifier("comparison-previous")439                BarButton(symbol: "chevron.down", help: "Next Change", isEnabled: !changes.isEmpty) { if let c = model.step(1) { select(c, proxy: proxy) } }440                    .accessibilityIdentifier("comparison-next")441            }442            .padding(.leading, ORIX.Space.m).padding(.trailing, ORIX.Space.s).frame(height: 34)443            Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1)444            if changes.isEmpty {445                EmptyState(symbol: "equal.circle", title: "No differences", message: "Both documents have the same content with these options.")446            } else {447                ScrollView {448                    LazyVStack(alignment: .leading, spacing: 1) {449                        ForEach(changes) { change in450                            ComparisonChangeRow(change: change, isSelected: change.id == model.selectedChange, hasRow: model.row(of: change) != nil) { select(change, proxy: proxy) }451                                .id("change-\(change.id)")452                        }453                    }454                    .padding(ORIX.Space.s)455                }456            }457        }458    }459460    private var sideBySide: some View {461        VStack(spacing: 0) {462            HStack(spacing: 0) {463                columnTitle("Original", name: model.payload.originalName)464                Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)465                columnTitle("Revised", name: model.payload.revisedName)466                    .overlay(alignment: .trailing) {467                        Toggle("Changes only", isOn: $model.changesOnly)468                            .toggleStyle(.checkbox).controlSize(.small).font(ORIX.Font.label)469                            .padding(.leading, ORIX.Space.s).padding(.trailing, ORIX.Space.m)470                            .frame(maxHeight: .infinity).background(ORIX.Palette.chrome)471                            .accessibilityIdentifier("comparison-changes-only")472                    }473            }474            .frame(height: 34)475            Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1)476            ScrollView {477                LazyVStack(spacing: 0) {478                    ForEach(model.visibleRows, id: \.self) { index in479                        ComparisonRowView(kind: model.rows[index].kind, content: model.content(index), isHighlighted: index == model.highlightedRow,480                                          hasQuietChange: model.rows[index].kind == .equal && model.rowsWithChanges.contains(index))481                            .id("row-\(index)")482                    }483                }484            }485            .background(ORIX.Palette.surface)486            .accessibilityIdentifier("comparison-rows")487        }488    }489490    private func columnTitle(_ title: LocalizedStringKey, name: String) -> some View {491        HStack(spacing: 6) {492            Text(title).font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)493            Text(name).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).truncationMode(.middle)494            Spacer(minLength: 0)495        }496        .padding(.horizontal, ORIX.Space.m)497        .frame(maxWidth: .infinity, alignment: .leading)498        .accessibilityElement(children: .combine).accessibilityAddTraits(.isHeader)499    }500}501502private struct ComparisonChangeRow: View {503    let change: DocumentChange504    let isSelected: Bool505    let hasRow: Bool506    let action: () -> Void507    @State private var hover = false508509    private var location: String {510        var parts: [String] = []511        switch change.story {512        case .body: break513        case .header: parts.append(String(localized: "Header"))514        case .footer: parts.append(String(localized: "Footer"))515        case .note: parts.append(String(localized: "Note"))516        }517        switch (change.originalBlock, change.revisedBlock) {518        case let (o?, r?): parts.append(o == r ? String(localized: "Block \(o + 1)") : String(localized: "Block \(o + 1) → \(r + 1)"))519        case let (o?, nil): parts.append(String(localized: "Original block \(o + 1)"))520        case let (nil, r?): parts.append(String(localized: "Revised block \(r + 1)"))521        default: if change.story == .body { parts.append(String(localized: "Document")) }522        }523        return parts.joined(separator: " · ")524    }525526    var body: some View {527        Button(action: action) {528            VStack(alignment: .leading, spacing: 3) {529                HStack(spacing: 5) {530                    Label(change.kind.localizedLabel, systemImage: change.kind.symbol)531                        .labelStyle(.titleAndIcon).font(.system(size: 11, weight: .semibold)).foregroundStyle(change.kind.color)532                    Spacer(minLength: 4)533                    Text(location).font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)534                }535                if !change.detail.isEmpty {536                    Text(change.detail).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text).lineLimit(3).multilineTextAlignment(.leading)537                }538                if !change.before.isEmpty {539                    Text(change.before).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2).multilineTextAlignment(.leading)540                }541                if !change.after.isEmpty && change.after != change.before {542                    HStack(alignment: .firstTextBaseline, spacing: 4) {543                        Image(systemName: "arrow.turn.down.right").font(.system(size: 8, weight: .bold)).foregroundStyle(ORIX.Palette.textTertiary)544                        Text(change.after).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2).multilineTextAlignment(.leading)545                    }546                }547            }548            .padding(.horizontal, 8).padding(.vertical, 6)549            .frame(maxWidth: .infinity, alignment: .leading)550            .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(isSelected ? ORIX.Palette.accent.opacity(0.13) : (hover ? ORIX.Palette.text.opacity(0.06) : .clear)))551            .overlay(alignment: .leading) {552                if isSelected { RoundedRectangle(cornerRadius: 1).fill(ORIX.Palette.accent).frame(width: 2.5).padding(.vertical, 4) }553            }554            .contentShape(Rectangle())555        }556        .buttonStyle(.plain)557        .onHover { hover = $0 }558        .help(hasRow ? Text("Show in the side-by-side view") : Text("This change is not in the body text; see the report for details."))559        .accessibilityAddTraits(isSelected ? .isSelected : [])560    }561}562563private struct ComparisonRowView: View {564    let kind: AlignedRow.Kind565    let content: ComparisonRowContent566    let isHighlighted: Bool567    let hasQuietChange: Bool568569    var body: some View {570        HStack(alignment: .top, spacing: 0) {571            cell(text: content.left, number: content.leftNumber, note: content.leftNote, active: kind == .deleted || kind == .movedFrom || kind == .modified)572            Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)573            cell(text: content.right, number: content.rightNumber, note: content.rightNote, active: kind == .inserted || kind == .movedTo || kind == .modified)574        }575        .fixedSize(horizontal: false, vertical: true)576        .overlay { if isHighlighted { Rectangle().strokeBorder(ORIX.Palette.accent, lineWidth: 1.5) } }577        .overlay(alignment: .bottom) { Rectangle().fill(ORIX.Palette.hairline.opacity(0.45)).frame(height: 1) }578    }579580    @ViewBuilder581    private func cell(text: AttributedString?, number: Int?, note: String?, active: Bool) -> some View {582        HStack(alignment: .top, spacing: ORIX.Space.s) {583            Text(number.map { String($0 + 1) } ?? "")584                .font(.system(size: 10).monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary)585                .frame(width: 30, alignment: .trailing).padding(.top, 2)586                .accessibilityHidden(true)587            if let text {588                VStack(alignment: .leading, spacing: 3) {589                    if active, let label = kind.label {590                        Label(note ?? label, systemImage: kind.symbol)591                            .labelStyle(.titleAndIcon).font(.system(size: 10, weight: .semibold)).foregroundStyle(kind.color)592                    } else if hasQuietChange {593                        Label("Formatting or structure", systemImage: "textformat")594                            .labelStyle(.titleAndIcon).font(.system(size: 10, weight: .semibold)).foregroundStyle(ORIX.Palette.textSecondary)595                    }596                    Text(text).foregroundStyle(ORIX.Palette.text).textSelection(.enabled)597                        .fixedSize(horizontal: false, vertical: true)598                }599            }600            Spacer(minLength: 0)601        }602        .padding(.trailing, ORIX.Space.m).padding(.vertical, 6)603        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)604        .background(text == nil ? AnyShapeStyle(ORIX.Palette.canvas.opacity(0.7)) : (active ? AnyShapeStyle(kind.color.opacity(0.07)) : AnyShapeStyle(Color.clear)))605        .overlay(alignment: .leading) { if active && text != nil { Rectangle().fill(kind.color).frame(width: 2.5) } }606    }607}608
Files main
Menu

Theme