SPB Git

Repository Public MIT

HistoryView.swift 8.1 KB 157 lines swift

1// ORIX Calc2// File: App/Sources/HistoryView.swift3// Description: The shared calculation history of all environments — search, filter, reuse, explain, export.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import ORIXUI9import ORIXExpression10import ORIXNumerics1112struct HistoryView: View {13    @Environment(AppModel.self) private var app14    @Environment(\.dismiss) private var dismiss15    var embedded = false16    @State private var query = ""17    @State private var filter: CalcMode?18    @State private var confirmClear = false19    @State private var detail: HistoryItem?2021    private var items: [HistoryItem] {22        app.history.filter { item in23            (filter == nil || item.mode == filter) &&24            (query.isEmpty || item.input.localizedCaseInsensitiveContains(query) || item.display.localizedCaseInsensitiveContains(query))25        }26    }27    private var grouped: [(day: Date, items: [HistoryItem])] {28        let calendar = Calendar.current29        let groups = Dictionary(grouping: items) { calendar.startOfDay(for: $0.date) }30        return groups.keys.sorted(by: >).map { ($0, groups[$0]!) }31    }32    private var csv: String {33        func q(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\"" }34        let rows = items.map { [ISO8601DateFormatter().string(from: $0.date), $0.mode.title, q($0.input), q($0.display), q($0.canonical), $0.isExact ? "exact" : "approximate", $0.status].joined(separator: ",") }35        return (["Date,Environment,Input,Result,FullPrecision,Exactness,Verification"] + rows).joined(separator: "\r\n") + "\r\n"36    }3738    var body: some View {39        NavigationStack {40            Group {41                if app.history.isEmpty {42                    ContentUnavailableView("No history yet", systemImage: "clock.arrow.circlepath",43                                           description: Text("Results from every environment appear here and can be reused anywhere."))44                } else {45                    List {46                        ForEach(grouped, id: \.day) { group in47                            Section(group.day.formatted(date: .abbreviated, time: .omitted)) {48                                ForEach(group.items) { item in row(item) }49                                    .onDelete { offsets in app.deleteHistory(offsets.map { group.items[$0].id }) }50                            }51                        }52                    }53                    .listStyle(.plain)54                    .scrollContentBackground(.hidden)55                    .searchable(text: $query, prompt: "Search history")56                }57            }58            .background(ORIXColor.background)59            .navigationTitle("History")60            #if os(iOS)61            .navigationBarTitleDisplayMode(.inline)62            #endif63            .toolbar {64                if !embedded { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }65                ToolbarItem(placement: .topBarLeading) {66                    Menu {67                        Picker("Environment", selection: $filter) {68                            Text("All Environments").tag(CalcMode?.none)69                            ForEach(CalcMode.allCases) { Label($0.title, systemImage: $0.symbol).tag(CalcMode?.some($0)) }70                        }71                        ShareLink(item: csv, preview: SharePreview("ORIX Calc history.csv")) { Label("Export CSV", systemImage: "square.and.arrow.up") }72                            .disabled(items.isEmpty)73                        Button(role: .destructive) { confirmClear = true } label: { Label("Clear History", systemImage: "trash") }74                            .disabled(app.history.isEmpty)75                    } label: { Image(systemName: filter == nil ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill") }76                    .accessibilityLabel("Filter and export")77                }78            }79            .confirmationDialog("Delete the entire history?", isPresented: $confirmClear, titleVisibility: .visible) {80                Button("Clear History", role: .destructive) { app.clearHistory() }81            } message: { Text("Variables and workspaces are not affected.") }82            .sheet(item: $detail) { HistoryDetail(item: $0) }83        }84    }8586    private func reuse(_ text: String) {87        app.sendToCalculator(text)88        if !embedded { dismiss() }89    }9091    private func row(_ item: HistoryItem) -> some View {92        Button {93            reuse(item.canonical.isEmpty ? item.display : item.canonical)94        } label: {95            HStack(alignment: .top, spacing: ORIXSpacing.m) {96                Image(systemName: item.mode.symbol).font(.caption.weight(.semibold)).foregroundStyle(item.mode.tint).frame(width: 22).padding(.top, 3)97                VStack(alignment: .leading, spacing: 3) {98                    Text(item.input).font(.callout).foregroundStyle(ORIXColor.textSecondary).lineLimit(2)99                    HStack(spacing: 6) {100                        Text(item.display).font(ORIXFont.valueEmphasis).foregroundStyle(ORIXColor.textPrimary).lineLimit(2)101                        if item.status == "verified" { Image(systemName: "checkmark.seal.fill").font(.caption).foregroundStyle(ORIXColor.success).accessibilityLabel("Verified") }102                        if item.status == "warning" { Image(systemName: "exclamationmark.triangle.fill").font(.caption).foregroundStyle(ORIXColor.warning).accessibilityLabel("Has warnings") }103                    }104                }105                Spacer(minLength: 0)106                Text(item.date.formatted(date: .omitted, time: .shortened)).font(.caption2).foregroundStyle(ORIXColor.textTertiary)107            }108            .contentShape(Rectangle())109        }110        .buttonStyle(.plain)111        .listRowBackground(Color.clear)112        .accessibilityElement(children: .combine)113        .accessibilityHint("Reuses the result in the calculator")114        .contextMenu {115            Button { app.copy(item.display) } label: { Label("Copy Result", systemImage: "doc.on.doc") }116            if !item.canonical.isEmpty { Button { reuse(item.canonical) } label: { Label("Reuse Result", systemImage: "arrow.uturn.left") } }117            if item.mode == .standard || item.mode == .scientific {118                Button { reuse(item.input) } label: { Label("Reuse Expression", systemImage: "text.cursor") }119                Button { app.sendToGraph(item.input); if !embedded { dismiss() } } label: { Label("Graph Expression", systemImage: CalcMode.graph.symbol) }120            }121            if !item.canonical.isEmpty {122                Button { app.sendToWorkspace(item.mode == .standard || item.mode == .scientific ? item.input : item.canonical); if !embedded { dismiss() } } label: {123                    Label("Save to Workspace", systemImage: CalcMode.workspace.symbol)124                }125            }126            if !item.detail.isEmpty { Button { detail = item } label: { Label("Explain", systemImage: "text.magnifyingglass") } }127            Button(role: .destructive) { app.deleteHistory([item.id]) } label: { Label("Delete", systemImage: "trash") }128        }129    }130}131132private struct HistoryDetail: View {133    @Environment(\.dismiss) private var dismiss134    let item: HistoryItem135    var body: some View {136        NavigationStack {137            ScrollView {138                VStack(alignment: .leading, spacing: ORIXSpacing.l) {139                    Text(item.input).font(.headline)140                    Text(item.display).font(ORIXFont.display(34)).minimumScaleFactor(0.4).textSelection(.enabled)141                    Text(item.detail).font(ORIXFont.mono).textSelection(.enabled)142                }143                .frame(maxWidth: .infinity, alignment: .leading)144                .padding()145            }146            .navigationTitle(item.mode.title)147            #if os(iOS)148            .navigationBarTitleDisplayMode(.inline)149            #endif150            .toolbar {151                ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } }152                ToolbarItem(placement: .topBarLeading) { ShareLink(item: "\(item.input)\n= \(item.display)\n\n\(item.detail)") { Image(systemName: "square.and.arrow.up") } }153            }154        }155    }156}157
Files main
Menu

Theme