SPB Git

Repository Public

ScenarioPanel.swift 15.8 KB 303 lines swift

1import SwiftUI2import SheetCore3import SheetUI4import WhatIf5import AnalysisKit67/// Scenario Manager panel: stored scenarios, capture of a new one, result cells and the comparison summary.8struct ScenarioPanel: View {9    let session: WorkbookSession10    @Environment(\.compactForm) private var compact11    @State private var name = ""12    @State private var comment = ""13    @State private var cellsText = ""14    @State private var resultText = ""15    @State private var resultTextLoaded = false16    @State private var editing: UUID?17    @State private var drafts: [Int: String] = [:]18    @State private var pendingDelete: Scenario?19    @State private var status: String?20    @State private var failure: String?21    @State private var summary: ToolResult?22    @State private var summaryError: String?2324    private var set: ScenarioSet {25        _ = session.revision26        return ScenarioStore.load(session)27    }2829    /// Recompute the summary when the stored set or the workbook content changes.30    private var refreshKey: String { "\(session.contentRevision)|\(set.hashValue)" }3132    var body: some View {33        let current = set34        VStack(alignment: .leading, spacing: compact ? 12 : 14) {35            card { scenarioList(current) }36            card { newScenario(current) }37            card { results(current) }38            card { summarySection(current) }39            feedback40            Text(L("Scenarios are stored in the workbook. Applying a scenario is one step to undo; creating, editing or deleting stored scenarios is saved immediately and cannot be undone."))41                .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)42        }43        .task(id: refreshKey) { await refreshSummary() }44        .onAppear { loadDefaults(current) }45        .confirmationDialog(L("Delete the scenario “%@”?", pendingDelete?.name ?? ""), isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } })) {46            Button(L("Delete Scenario"), role: .destructive) {47                if let s = pendingDelete { run { try ScenarioStore.delete(s.id, session: session); status = L("Scenario “%@” deleted.", s.name) } }48                pendingDelete = nil49            }50            Button(L("Cancel"), role: .cancel) { pendingDelete = nil }51        } message: { Text(L("This cannot be undone.")) }52        .accessibilityIdentifier("scenarios.panel")53    }5455    // MARK: Building blocks5657    @ViewBuilder private func card<C: View>(@ViewBuilder _ content: () -> C) -> some View {58        if compact {59            VStack(alignment: .leading, spacing: 8) { content() }60            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)61        } else {62            VStack(alignment: .leading, spacing: 10) { content() }63                .padding(ORIX.Space.md)64                .frame(maxWidth: .infinity, alignment: .leading)65                .background(RoundedRectangle(cornerRadius: ORIX.Radius.card).fill(ORIX.Palette.surface))66                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.card).strokeBorder(ORIX.Palette.hairline))67        }68    }6970    private func heading(_ text: String) -> some View {71        Text(text.uppercased()).font(.system(size: 10.5, weight: .semibold)).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)72            .accessibilityAddTraits(.isHeader)73    }7475    private func run(_ body: () throws -> Void) {76        failure = nil77        do { try body() } catch { failure = ToolError.describe(error); status = nil }78    }7980    @ViewBuilder private var feedback: some View {81        if let failure {82            Label(failure, systemImage: "exclamationmark.triangle.fill").font(.system(size: 12)).foregroundStyle(ORIX.Palette.danger)83                .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("scenarios.error")84        } else if let status {85            Label(status, systemImage: "checkmark.circle").font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary)86                .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("scenarios.status")87        }88    }8990    private func loadDefaults(_ current: ScenarioSet) {91        let wb = session.workbook92        if cellsText.isEmpty, let first = current.scenarios.first {93            cellsText = first.cells.compactMap { ScenarioStore.address(sheetID: $0.sheetID, cell: $0.cell, in: wb) }.map { WhatIfSupport.label($0, in: wb) }.joined(separator: ", ")94        }95        if !resultTextLoaded {96            resultText = ScenarioStore.resultAddresses(current, in: wb).map { WhatIfSupport.label($0, in: wb) }.joined(separator: ", ")97            resultTextLoaded = true98        }99    }100101    // MARK: Scenario list102103    @ViewBuilder private func scenarioList(_ current: ScenarioSet) -> some View {104        heading(L("Scenarios"))105        if current.scenarios.isEmpty {106            VStack(alignment: .leading, spacing: 4) {107                Label(L("No scenarios yet"), systemImage: "square.stack.3d.up").font(.system(size: 13, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)108                Text(L("A scenario is a named set of values for the input cells of your model. Set the inputs in the sheet, then capture them below; repeat for each case you want to compare."))109                    .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)110            }111            .padding(.vertical, 4)112        }113        ForEach(current.scenarios) { s in scenarioRow(s) }114    }115116    private func scenarioRow(_ s: Scenario) -> some View {117        VStack(alignment: .leading, spacing: 6) {118            HStack(alignment: .firstTextBaseline, spacing: 8) {119                Text(s.name).font(.system(size: 13, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)120                Spacer(minLength: 4)121                Button(L("Apply")) {122                    run { try ScenarioStore.apply(s, session: session); status = L("Scenario “%@” applied. Undo restores the previous values.", s.name) }123                }124                .help(L("Writes the scenario's values into its cells. One step to undo."))125                .accessibilityLabel(L("Apply scenario %@", s.name))126                .accessibilityIdentifier("scenarios.apply.\(s.name)")127                Button { toggleEdit(s) } label: { Image(systemName: editing == s.id ? "chevron.up" : "pencil") }128                    .help(L("Edit the values of this scenario"))129                    .accessibilityLabel(L("Edit scenario %@", s.name))130                    .accessibilityIdentifier("scenarios.edit.\(s.name)")131                Button { pendingDelete = s } label: { Image(systemName: "trash") }132                    .help(L("Delete this scenario"))133                    .accessibilityLabel(L("Delete scenario %@", s.name))134                    .accessibilityIdentifier("scenarios.delete.\(s.name)")135            }136            .controlSize(.small)137            Text(s.comment.isEmpty ? L("%d cells", s.cells.count) : L("%d cells", s.cells.count) + " · " + s.comment)138                .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)139            if editing == s.id { editor(s) }140        }141        .padding(8)142        .background(RoundedRectangle(cornerRadius: ORIX.Radius.control).fill(ORIX.Palette.surfaceRaised.opacity(0.55)))143        .accessibilityElement(children: .contain)144        .accessibilityLabel(s.name)145    }146147    private func toggleEdit(_ s: Scenario) {148        if editing == s.id { editing = nil; return }149        editing = s.id150        drafts = Dictionary(uniqueKeysWithValues: s.cells.enumerated().map { ($0.offset, ScenarioStore.editText($0.element.value, locale: session.locale)) })151    }152153    private func editor(_ s: Scenario) -> some View {154        VStack(alignment: .leading, spacing: 5) {155            ForEach(Array(s.cells.enumerated()), id: \.offset) { i, c in156                let label = ScenarioStore.label(sheetID: c.sheetID, cell: c.cell, in: session.workbook)157                HStack(spacing: 8) {158                    Text(label).font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)159                        .frame(maxWidth: compact ? 130 : 240, alignment: .leading)160                    TextField(L("Value"), text: Binding(get: { drafts[i] ?? "" }, set: { drafts[i] = $0 }))161                        .textFieldStyle(.roundedBorder).monospacedDigit().multilineTextAlignment(.trailing).frame(width: compact ? 96 : 130)162                        .accessibilityLabel(L("Value of %@ in scenario %@", label, s.name))163                        .accessibilityIdentifier("scenarios.value.\(s.name).\(i)")164                }165            }166            HStack(spacing: 8) {167                Button(L("Save Values")) {168                    run {169                        var updated = s170                        for i in updated.cells.indices { updated.cells[i].value = try ScenarioStore.parse(drafts[i] ?? "", session: session) }171                        try ScenarioStore.update(updated, session: session)172                        editing = nil173                        status = L("Scenario “%@” updated.", s.name)174                    }175                }176                .accessibilityIdentifier("scenarios.save.\(s.name)")177                Button(L("Cancel")) { editing = nil }178            }179            .controlSize(.small)180        }181        .padding(.top, 2)182    }183184    // MARK: New scenario185186    @ViewBuilder private func newScenario(_ current: ScenarioSet) -> some View {187        heading(L("New scenario from the current values"))188        field(L("Name")) {189            TextField(L("e.g. Optimistic"), text: $name).textFieldStyle(.roundedBorder).frame(maxWidth: 260)190                .accessibilityLabel(L("Scenario name")).accessibilityIdentifier("scenarios.name")191        }192        field(L("Comment")) {193            TextField(L("optional"), text: $comment).textFieldStyle(.roundedBorder).frame(maxWidth: 360)194                .accessibilityLabel(L("Scenario comment")).accessibilityIdentifier("scenarios.comment")195        }196        field(L("Changing cells")) {197            CellField(L("Changing cells"), text: $cellsText, session: session, multiple: true, identifier: "scenarios.cells")198        }199        HStack(spacing: 8) {200            Button {201                run {202                    guard let cells = RangeReader.cells(cellsText, workbook: session.workbook, sheet: session.sheetIndex) else {203                        throw ToolError(L("Enter the changing cells of the scenario (for example B4:B6)."))204                    }205                    let replaced = current.scenario(named: name.trimmingCharacters(in: .whitespaces)) != nil206                    let s = try ScenarioStore.capture(name: name, comment: comment, cells: cells, session: session)207                    status = replaced ? L("Scenario “%@” replaced with the current values.", s.name) : L("Scenario “%@” captured from the current values (%d cells).", s.name, s.cells.count)208                    name = ""; comment = ""209                }210            } label: { Label(L("Capture Current Values"), systemImage: "camera.metering.matrix") }211                .buttonStyle(PrimaryButtonStyle())212                .help(L("Stores the current content of the changing cells under this name (replaces a scenario of the same name)"))213                .accessibilityIdentifier("scenarios.capture")214        }215    }216217    @ViewBuilder private func field<C: View>(_ label: String, @ViewBuilder _ content: () -> C) -> some View {218        if compact {219            VStack(alignment: .leading, spacing: 3) {220                Text(label).font(.system(size: 11.5, weight: .medium)).foregroundStyle(ORIX.Palette.textSecondary)221                content()222            }223        } else {224            HStack(alignment: .firstTextBaseline, spacing: 12) {225                Text(label).font(.system(size: 12.5)).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 130, alignment: .trailing).accessibilityHidden(true)226                content()227                Spacer(minLength: 0)228            }229        }230    }231232    // MARK: Result cells and summary233234    @ViewBuilder private func results(_ current: ScenarioSet) -> some View {235        heading(L("Result cells"))236        Text(L("The formula cells to compare across scenarios (for example profit or cash flow)."))237            .font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)238        HStack(spacing: 8) {239            CellField(L("Result cells"), text: $resultText, session: session, multiple: true, identifier: "scenarios.results")240            Button(L("Set")) {241                run {242                    let t = resultText.trimmingCharacters(in: .whitespaces)243                    guard t.isEmpty || RangeReader.cells(t, workbook: session.workbook, sheet: session.sheetIndex) != nil else {244                        throw ToolError(L("“%@” is not a valid list of cells.", t))245                    }246                    let cells = t.isEmpty ? [] : (RangeReader.cells(t, workbook: session.workbook, sheet: session.sheetIndex) ?? [])247                    guard cells.count <= 200 else { throw ToolError(L("Choose at most %d result cells.", 200)) }248                    try ScenarioStore.setResultCells(cells, session: session)249                    status = L("%d result cells set.", cells.count)250                }251            }252            .controlSize(.small)253            .accessibilityLabel(L("Set result cells"))254            .accessibilityIdentifier("scenarios.set-results")255        }256    }257258    @ViewBuilder private func summarySection(_ current: ScenarioSet) -> some View {259        let write = Button {260            run {261                let o = try ScenarioStore.writeSummary(session: session)262                status = L("Summary report written to sheet “%@”.", session.workbook.sheets[o.sheet].name)263            }264        } label: { Label(L("Write Summary Report to Sheet"), systemImage: "square.and.arrow.down.on.square") }265            .controlSize(.small)266            .disabled(current.scenarios.isEmpty)267            .help(L("Writes the comparison below as a formatted report on a new sheet. One step to undo."))268            .accessibilityIdentifier("scenarios.write-summary")269        HStack {270            heading(L("Summary"))271            Spacer(minLength: 0)272            if !compact { write }273        }274        if current.scenarios.isEmpty {275            Text(L("The comparison of the result cells across scenarios appears here once a scenario exists."))276                .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)277        } else if let summaryError {278            Label(summaryError, systemImage: "exclamationmark.triangle.fill").font(.system(size: 12)).foregroundStyle(ORIX.Palette.warning)279                .fixedSize(horizontal: false, vertical: true)280        } else if let summary {281            ResultBlocksView(summary)282            if compact { write }283        } else {284            HStack(spacing: 8) { ProgressView().controlSize(.small); Text(L("Computing…")).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary) }285        }286    }287288    private func refreshSummary() async {289        let current = ScenarioStore.load(session)290        guard !current.scenarios.isEmpty else { summary = nil; summaryError = nil; return }291        let cells = ScenarioStore.resultAddresses(current, in: session.workbook)292        let model = WhatIfSupport.snapshot(session)293        let outcome: Result<ToolResult, any Error> = await Task.detached(priority: .userInitiated) {294            Result { ScenarioStore.report(try ScenarioStore.summary(current, resultCells: cells, model: model), set: current, resultCells: cells, workbook: model.workbook) }295        }.value296        guard !Task.isCancelled else { return }297        switch outcome {298        case .success(let r): summary = r; summaryError = nil299        case .failure(let e): summary = nil; summaryError = ToolError.describe(e)300        }301    }302}303
Files main
Menu

Theme