Repository Public
1import SwiftUI2import SheetCore3import SheetUI45/// Form → Run → results for one tool. Used in the studio centre and (compact) in the What-If inspector.6public struct ToolPanel: View {7 let tool: ToolDescriptor8 @Bindable var model: ToolSessionModel9 let session: WorkbookSession10 @Environment(\.compactForm) private var compact11 @State private var showInfo = false12 @State private var showConventions = false1314 public init(tool: ToolDescriptor, model: ToolSessionModel, session: WorkbookSession) {15 self.tool = tool; self.model = model; self.session = session16 }1718 private var values: Binding<FormValues> {19 Binding(get: { model.formValues(tool.id) }, set: { model.setValues($0, for: tool.id) })20 }2122 public var body: some View {23 if let custom = tool.customPanel {24 VStack(alignment: .leading, spacing: compact ? 10 : 14) {25 header26 custom(session)27 }28 } else {29 VStack(alignment: .leading, spacing: compact ? 10 : 14) {30 header31 formCard32 resultSection33 }34 .onAppear { model.prepare(tool.id, session: session) }35 .onChange(of: tool.id) { _, id in model.prepare(id, session: session) }36 }37 }3839 // MARK: Header4041 private var header: some View {42 VStack(alignment: .leading, spacing: 4) {43 HStack(alignment: .firstTextBaseline, spacing: 8) {44 Text(tool.title).font(compact ? .system(size: 14, weight: .semibold) : .system(size: 18, weight: .semibold))45 .foregroundStyle(ORIX.Palette.textPrimary)46 .accessibilityAddTraits(.isHeader)47 if !tool.info.isEmpty {48 Button { showInfo.toggle() } label: { Image(systemName: "info.circle") }49 .buttonStyle(.borderless)50 .help(L("Method notes and documented limitations"))51 .accessibilityLabel(L("Method notes and documented limitations"))52 .accessibilityIdentifier("\(tool.id).info")53 .popover(isPresented: $showInfo, arrowEdge: .bottom) { infoPopover }54 }55 Spacer(minLength: 0)56 }57 Text(tool.summary).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)58 }59 }6061 private var infoPopover: some View {62 VStack(alignment: .leading, spacing: 8) {63 Text(L("Method notes")).font(.system(size: 12.5, weight: .semibold))64 ForEach(Array(tool.info.enumerated()), id: \.offset) { _, line in65 HStack(alignment: .firstTextBaseline, spacing: 6) {66 Text("•").foregroundStyle(ORIX.Palette.textTertiary)67 Text(line).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true)68 }69 }70 Text(L("Source: SheetAnalytics validation record (reference tests against SciPy, statsmodels, scikit-learn and arch)."))71 .font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)72 }73 .padding(14)74 .frame(width: 380, alignment: .leading)75 }7677 // MARK: Form7879 private var formCard: some View {80 VStack(alignment: .leading, spacing: compact ? 10 : 12) {81 FormView(tool: tool, values: values, session: session)82 if let extra = tool.extraForm { extra(ToolFormContext(session: session, values: values)) }83 if !tool.conventions.isEmpty { conventions }84 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)85 runBar86 }87 .padding(compact ? 0 : ORIX.Space.md)88 .background(RoundedRectangle(cornerRadius: ORIX.Radius.card).fill(compact ? Color.clear : ORIX.Palette.surface))89 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.card).strokeBorder(compact ? Color.clear : ORIX.Palette.hairline))90 }9192 private var conventions: some View {93 DisclosureGroup(isExpanded: $showConventions) {94 VStack(alignment: .leading, spacing: 4) {95 ForEach(Array(tool.conventions.enumerated()), id: \.offset) { _, line in96 HStack(alignment: .firstTextBaseline, spacing: 6) {97 Text("•").foregroundStyle(ORIX.Palette.textTertiary)98 Text(line).font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)99 .textSelection(.enabled)100 }101 }102 }103 .padding(.top, 5)104 .frame(maxWidth: .infinity, alignment: .leading)105 } label: {106 Label(L("Assumptions & conventions"), systemImage: "text.book.closed")107 .font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.textSecondary)108 }109 .accessibilityIdentifier("\(tool.id).conventions")110 }111112 private var isRunningThis: Bool { model.runningID == tool.id }113114 private var runBar: some View {115 HStack(spacing: 10) {116 Button {117 Task { await model.run(tool.id, session: session) }118 } label: {119 Label(tool.runTitle ?? L("Run"), systemImage: "play.fill")120 }121 .buttonStyle(PrimaryButtonStyle())122 .keyboardShortcut(.return, modifiers: .command)123 .disabled(model.isRunning)124 .help(L("Run (⌘↩)"))125 .accessibilityIdentifier("\(tool.id).run")126 if isRunningThis {127 ProgressView(value: model.progress > 0 ? model.progress : nil)128 .progressViewStyle(.linear).frame(width: compact ? 70 : 160)129 .accessibilityLabel(L("Progress"))130 if model.progress > 0 { Text(Fmt.percent(model.progress, 0)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary) }131 Button(L("Cancel")) { model.cancel() }132 .keyboardShortcut(".", modifiers: .command)133 .accessibilityIdentifier("\(tool.id).cancel")134 }135 Spacer(minLength: 0)136 }137 }138139 // MARK: Results140141 @ViewBuilder private var resultSection: some View {142 switch model.state(tool.id) {143 case .idle:144 if !compact {145 EmptyStateView(systemImage: tool.systemImage, title: L("No results yet"),146 message: L("Choose the inputs above, then press Run. Results are computed from the workbook data and can be written to a sheet."))147 .frame(minHeight: 180)148 }149 case .running:150 HStack(spacing: 8) {151 ProgressView().controlSize(.small)152 Text(L("Computing…")).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)153 }154 .padding(.vertical, 8)155 case .cancelled:156 message(L("The computation was cancelled. The workbook was not modified."), icon: "xmark.circle", tint: ORIX.Palette.textSecondary)157 case .failed(let text):158 message(text, icon: "exclamationmark.triangle.fill", tint: ORIX.Palette.danger)159 .accessibilityIdentifier("\(tool.id).error")160 case .done(let result):161 VStack(alignment: .leading, spacing: compact ? 10 : 12) {162 HStack(alignment: .firstTextBaseline) {163 VStack(alignment: .leading, spacing: 2) {164 Text(L("Results").uppercased()).font(.system(size: 10.5, weight: .semibold)).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)165 if let s = result.subtitle { Text(s).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary) }166 }167 Spacer(minLength: 0)168 }169 .accessibilityAddTraits(.isHeader)170 ResultBlocksView(result) { chart in171 let o = ReportWriter.insertChart(chart, to: .newSheet, session: session)172 model.status = L("Chart inserted on sheet “%@”", session.workbook.sheets[o.sheet].name)173 }174 outputBar(result)175 }176 .padding(compact ? 0 : ORIX.Space.md)177 .background(RoundedRectangle(cornerRadius: ORIX.Radius.card).fill(compact ? Color.clear : ORIX.Palette.surface))178 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.card).strokeBorder(compact ? Color.clear : ORIX.Palette.hairline))179 .accessibilityIdentifier("\(tool.id).results")180 }181 }182183 private func message(_ text: String, icon: String, tint: Color) -> some View {184 HStack(alignment: .firstTextBaseline, spacing: 8) {185 Image(systemName: icon).foregroundStyle(tint).accessibilityHidden(true)186 Text(text).font(.system(size: 12.5)).foregroundStyle(ORIX.Palette.textPrimary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)187 Spacer(minLength: 0)188 }189 .padding(10)190 .background(RoundedRectangle(cornerRadius: ORIX.Radius.control).fill(tint.opacity(0.09)))191 }192193 @ViewBuilder private func outputBar(_ result: ToolResult) -> some View {194 VStack(alignment: .leading, spacing: 8) {195 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)196 if !result.actions.isEmpty {197 FlowLayout(spacing: 8) {198 ForEach(result.actions) { action in199 actionButton(action)200 }201 }202 }203 if result.canWriteReport {204 let layout = compact ? AnyLayout(VStackLayout(alignment: .leading, spacing: 6)) : AnyLayout(HStackLayout(spacing: 10))205 layout {206 Picker(L("Report destination"), selection: $model.writeToNewSheet) {207 Text(L("New sheet")).tag(true)208 Text(L("At cell")).tag(false)209 }210 .pickerStyle(.segmented).labelsHidden().fixedSize()211 .accessibilityLabel(L("Report destination"))212 .accessibilityIdentifier("\(tool.id).destination")213 if !model.writeToNewSheet {214 CellField(L("Top-left cell of the report"), text: $model.destinationCell, session: session, identifier: "\(tool.id).destination-cell")215 }216 if !result.charts.isEmpty {217 Toggle(L("Include charts"), isOn: $model.includeCharts).toggleStyle(.checkbox).font(.system(size: 12))218 .accessibilityIdentifier("\(tool.id).include-charts")219 }220 if !compact { Spacer(minLength: 0) }221 Button { model.writeReport(tool.id, session: session) } label: { Label(L("Write Report to Sheet"), systemImage: "square.and.arrow.down.on.square") }222 .help(L("Writes the tables above as a formatted report. One step to undo."))223 .accessibilityIdentifier("\(tool.id).write-report")224 }225 }226 if let status = model.status {227 Label(status, systemImage: "checkmark.circle").font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary)228 .accessibilityIdentifier("\(tool.id).status")229 }230 }231 }232233 @ViewBuilder private func actionButton(_ action: ResultAction) -> some View {234 let button = Button { model.perform(action, session: session) } label: { Label(action.title, systemImage: action.systemImage) }235 .help(action.help.isEmpty ? action.title : action.help)236 .accessibilityIdentifier("\(tool.id).action.\(action.id)")237 if action.isPrimary { button.buttonStyle(PrimaryButtonStyle()) } else { button }238 }239}240241/// Accent-filled button for the primary command of a panel (keeps its colour when the window is inactive).242public struct PrimaryButtonStyle: ButtonStyle {243 @Environment(\.isEnabled) private var enabled244 public init() {}245 public func makeBody(configuration: Configuration) -> some View {246 configuration.label247 .font(.system(size: 12.5, weight: .semibold))248 .foregroundStyle(Color(light: 0xFFFFFF, dark: 0x0A0D18))249 .padding(.horizontal, 12).padding(.vertical, 5)250 .background(RoundedRectangle(cornerRadius: ORIX.Radius.chip).fill(ORIX.Palette.accent.opacity(enabled ? (configuration.isPressed ? 0.75 : 1) : 0.4)))251 .contentShape(Rectangle())252 }253}254