SPB Git

Repository Public

LabFormView.swift 21.8 KB 374 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Quant/LabFormView.swift3// Description: The parameter form of a Quant Lab tool, generated from the shared kit's `VQLabForm` (every parameter type, groups, help, bounds), validated the way the server validates; the options engine's modes and the backtest's strategy parameters shape the same form.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89private typealias P = VQTokens.Palette10private typealias S = VQTokens.Space11private typealias T = VQTokens.Typography1213struct LabFormView: View {14    let app: AppEnvironment15    @Bindable var model: WindowModel16    @Bindable var state: LabWindowState17    let tool: VQLabTool1819    @State private var attempted = false20    @State private var submitting = false21    @State private var failure: LabStartFailure?22    @State private var collapsed: Set<String> = ["Advanced", "Numerics"]23    @State private var showAll = false24    @State private var projectId: String?25    @State private var prefilled = false2627    private var lab: LabStore { app.lab }28    private var form: VQLabForm { lab.forms[tool.id] ?? lab.form(tool) }29    private func set(_ name: String, _ value: VQJSON?) {30        var f = form; f[name] = value; lab.forms[tool.id] = f31        failure = nil32    }33    private var issues: [String: String] {34        guard case .failure(let invalid) = form.validate() else { return [:] }35        return Dictionary(invalid.issues.map { ($0.name, $0.message) }, uniquingKeysWith: { a, _ in a })36    }37    /// An issue is shown once Run was tried, or as soon as the field holds something the server would refuse.38    private func issue(_ p: VQLabParam, _ all: [String: String]) -> String? {39        guard let m = all[p.name] else { return nil }40        return attempted || !form.text(p.name).isEmpty ? m : nil41    }4243    private var optionsMode: LabOptionsMode? { tool.id == "options_lab" ? LabOptionsMode(rawValue: form.text("mode")) ?? .price : nil }44    private var isBacktest: Bool { tool.id == "backtest" }4546    /// The server's own `visibleWhen` first (kit 0.3: fields that do not apply to the current values are hidden),47    /// then the options workbench's narrower selection. "All parameters" shows everything.48    private func shows(_ p: VQLabParam) -> Bool {49        if let m = optionsMode { return showAll ? p.name != "mode" : form.isVisible(p) && m.shows(param: p.name, group: p.group) }50        if isBacktest, p.name == "rule" { return form.text("strategy") == "rule" }51        return form.isVisible(p)52    }53    private var groups: [(name: String, params: [VQLabParam])] {54        var g = tool.groups.map { (name: $0.name, params: $0.params.filter(shows)) }.filter { !$0.params.isEmpty }55        // the group a mode is about comes right after the underlying56        let lead: String? = switch optionsMode { case .strategy?: "Strategy"; case .chain?: "Chain"; case .implied?: "Implied volatility"; default: nil }57        if let lead, let i = g.firstIndex(where: { $0.name == lead }), i > 1 { let x = g.remove(at: i); g.insert(x, at: min(1, g.count)) }58        return g59    }60    private func groupTitle(_ name: String) -> String {61        if isBacktest {62            switch name { case "": return "Strategy"; case "Costs": return "Costs and slippage"; case "Evaluation": return "Benchmark and evaluation"; case "Validation": return "Walk-forward and sensitivity"; default: break }63        }64        if optionsMode != nil, name.isEmpty { return "Underlying" }65        return name.isEmpty ? "Inputs" : name66    }6768    var body: some View {69        let all = issues70        VStack(spacing: 0) {71            ScrollView {72                VStack(alignment: .leading, spacing: S.s5) {73                    Text(tool.summary).vqFont(T.bodySm).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true)74                    if let mode = optionsMode { modePicker(mode) }75                    if isBacktest {76                        note("clock.arrow.2.circlepath", "Signals are traded one bar later by construction: a decision made on bar t is executed on bar t + 1. The result states the engine's own look-ahead test.")77                    }78                    ForEach(groups, id: \.name) { g in group(g.name, g.params, all) }79                    if optionsMode != nil {80                        Toggle("All parameters of the engine", isOn: $showAll).toggleStyle(.checkbox).vqFont(T.caption).foregroundStyle(P.text2)81                            .help("A mode puts forward the parameters it uses. Every parameter is sent either way; this shows them all.")82                    }83                }84                .padding(S.s4)85                .frame(maxWidth: .infinity, alignment: .leading)86            }87            Rectangle().fill(P.line).frame(height: 1)88            footer(all)89        }90        .onAppear { prefill(); consumeLaunchArguments() }91        .onChange(of: model.symbol) { _, _ in prefill(force: true) }92    }9394    // MARK: sections9596    private func modePicker(_ mode: LabOptionsMode) -> some View {97        VStack(alignment: .leading, spacing: S.s2) {98            VQSegmentedControl("Options workbench", selection: Binding(get: { mode }, set: { set("mode", .string($0.rawValue)) }),99                               options: [.init(.price, "Pricer"), .init(.strategy, "Strategy"), .init(.chain, "Chain"), .init(.implied, "Implied vol")])100                .accessibilityIdentifier("lab.options.mode")101            Text(mode.blurb).vqFont(T.caption).foregroundStyle(P.text3).fixedSize(horizontal: false, vertical: true)102        }103    }104105    private func note(_ symbol: String, _ text: String) -> some View {106        HStack(alignment: .firstTextBaseline, spacing: S.s2) {107            Image(systemName: symbol).font(.system(size: 11, weight: .medium)).foregroundStyle(P.info).accessibilityHidden(true)108            Text(text).vqFont(T.caption).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true)109        }110        .padding(S.s3).frame(maxWidth: .infinity, alignment: .leading)111        .overlay(alignment: .leading) { Rectangle().fill(P.info).frame(width: 2) }112        .background(P.ink2)113    }114115    private func group(_ name: String, _ params: [VQLabParam], _ all: [String: String]) -> some View {116        let isCollapsed = collapsed.contains(name) && !params.contains { issue($0, all) != nil }117        return VStack(alignment: .leading, spacing: S.s3) {118            Button { if collapsed.contains(name) { collapsed.remove(name) } else { collapsed.insert(name) } } label: {119                HStack(spacing: S.s2) {120                    Text(groupTitle(name)).vqFont(T.overline).foregroundStyle(P.text2)121                    Rectangle().fill(P.line).frame(height: 1)122                    Image(systemName: isCollapsed ? "chevron.right" : "chevron.down").font(.system(size: 9, weight: .semibold)).foregroundStyle(P.text3)123                }124                .contentShape(Rectangle())125            }126            .buttonStyle(.plain)127            .accessibilityLabel("\(groupTitle(name)), \(isCollapsed ? "collapsed" : "expanded")")128            if !isCollapsed { ForEach(params) { p in field(p, issue(p, all)) } }129        }130    }131132    // MARK: fields133134    private func text(_ p: VQLabParam) -> Binding<String> {135        Binding(get: { form.text(p.name) }, set: { set(p.name, $0.isEmpty ? nil : .string($0)) })136    }137138    private func bounds(_ p: VQLabParam) -> String? {139        func f(_ x: Double) -> String { abs(x) >= 1e12 ? "" : VQJSON.number(x).text() }140        switch p.type.known {141        case .int?, .number?, .numbers?:142            let lo = p.min.map(f) ?? "", hi = p.max.map(f) ?? ""143            if lo.isEmpty && hi.isEmpty { return nil }144            return lo.isEmpty ? "≤ \(hi)" : hi.isEmpty ? "≥ \(lo)" : "\(lo) – \(hi)"145        case .symbols?: return p.max.map { "up to \(Int($0))" }146        case .date?: return [p.minDate.map { "from \($0)" }, p.maxDate.map { "to \($0)" }].compactMap { $0 }.joined(separator: " ").nilIfEmpty147        default: return nil148        }149    }150151    private func placeholder(_ p: VQLabParam) -> String {152        if let d = p.defaultValue { return d.arrayValue.map { $0.compactMap(\.displayString).joined(separator: ", ") } ?? d.displayString ?? "" }153        switch p.type.known {154        case .date?: return "YYYY-MM-DD"155        case .symbol?: return form.isRequired(p) ? "Ticker" : "optional"156        case .symbols?: return "SPY, QQQ, TLT"157        default: return form.isRequired(p) ? "required" : "optional"158        }159    }160161    @ViewBuilder private func field(_ p: VQLabParam, _ issue: String?) -> some View {162        let compact: Bool = { switch p.type.known { case .int?, .number?, .choice?, .bool?, .date?, .symbol?: true; default: false } }()163        VStack(alignment: .leading, spacing: 4) {164            if compact {165                HStack(alignment: .center, spacing: S.s2) {166                    label(p)167                    Spacer(minLength: S.s2)168                    control(p, issue != nil).frame(width: p.type == .choice ? 168 : p.type == .bool ? nil : 132, alignment: .trailing)169                }170            } else {171                HStack(alignment: .firstTextBaseline) { label(p); Spacer(minLength: S.s2); if let b = bounds(p) { Text(b).vqFont(T.numSm).foregroundStyle(P.text3) } }172                control(p, issue != nil)173            }174            if let help = p.help, !help.isEmpty { Text(help).vqFont(T.caption).foregroundStyle(P.text3).fixedSize(horizontal: false, vertical: true) }175            if let issue {176                Label(issue, systemImage: "exclamationmark.circle.fill").vqFont(T.caption).foregroundStyle(P.critical).fixedSize(horizontal: false, vertical: true)177                    .accessibilityIdentifier("lab.issue.\(p.name)")178            }179        }180    }181182    private func label(_ p: VQLabParam) -> some View {183        HStack(alignment: .firstTextBaseline, spacing: 4) {184            Text(p.label).vqFont(T.bodySm).foregroundStyle(P.text1).fixedSize(horizontal: false, vertical: true)185            if form.isRequired(p) { Text("required").vqFont(T.overline).foregroundStyle(P.accentText) }186        }187    }188189    @ViewBuilder private func control(_ p: VQLabParam, _ invalid: Bool) -> some View {190        switch p.type {191        case .known(.bool):192            Toggle("", isOn: Binding(get: { form.bool(p.name) }, set: { set(p.name, .bool($0)) })).labelsHidden().toggleStyle(.switch).controlSize(.small)193                .accessibilityLabel(p.label).accessibilityIdentifier("lab.field.\(p.name)")194        case .known(.choice):195            Picker("", selection: Binding(get: { form.text(p.name) }, set: { set(p.name, .string($0)) })) {196                if !p.choices.contains(form.text(p.name)) { Text(form.text(p.name).isEmpty ? "—" : form.text(p.name)).tag(form.text(p.name)) }197                ForEach(p.choices, id: \.self) { Text($0.replacingOccurrences(of: "_", with: " ")).tag($0) }198            }199            .labelsHidden().controlSize(.small).accessibilityLabel(p.label).accessibilityIdentifier("lab.field.\(p.name)")200        case .known(.int), .known(.number):201            VStack(alignment: .trailing, spacing: 1) {202                boxed(invalid) { TextField(placeholder(p), text: text(p)).textFieldStyle(.plain).multilineTextAlignment(.trailing).font(.system(size: 12.5, design: .monospaced)).accessibilityLabel(p.label).accessibilityIdentifier("lab.field.\(p.name)") }203                if let b = bounds(p) { Text(b).font(.system(size: 9.5, design: .monospaced)).foregroundStyle(P.text3) }204            }205        case .known(.date):206            LabDateField(text: text(p), invalid: invalid, name: p.name, label: p.label)207        case .known(.symbol):208            boxed(invalid) { TextField(placeholder(p), text: Binding(get: { form.text(p.name) }, set: { set(p.name, $0.isEmpty ? nil : .string($0.uppercased())) })).textFieldStyle(.plain).font(.system(size: 12.5, weight: .medium, design: .monospaced)).accessibilityLabel(p.label).accessibilityIdentifier("lab.field.\(p.name)") }209        case .known(.symbols):210            boxed(invalid) { TextField(placeholder(p), text: Binding(get: { form.text(p.name) }, set: { set(p.name, $0.isEmpty ? nil : .string($0.uppercased())) }), axis: .vertical).lineLimit(1...3).textFieldStyle(.plain).font(.system(size: 12.5, weight: .medium, design: .monospaced)).accessibilityLabel(p.label).accessibilityIdentifier("lab.field.\(p.name)") }211        case .known(.numbers):212            boxed(invalid) { TextField(placeholder(p), text: text(p)).textFieldStyle(.plain).font(.system(size: 12.5, design: .monospaced)).accessibilityLabel(p.label).accessibilityIdentifier("lab.field.\(p.name)") }213        case .known(.json):214            LabJSONField(param: p, text: text(p), selectedLabel: isBacktest && p.name == "strategy_params" ? form.text("strategy") : nil,215                         startInRows: app.options.extra["LabRows"] != "0", isRequired: form.isRequired(p))216        case .known(.group): EmptyView()217        case .known(.text), .unknown:218            boxed(invalid) {219                TextField(placeholder(p), text: text(p), axis: .vertical).lineLimit(p.multiline || (p.maxLength ?? 0) > 200 ? 2...6 : 1...2).textFieldStyle(.plain)220                    .font(.system(size: 12.5, design: p.name == "rule" ? .monospaced : .default)).accessibilityLabel(p.label).accessibilityIdentifier("lab.field.\(p.name)")221            }222        }223    }224225    private func boxed<C: View>(_ invalid: Bool, @ViewBuilder _ content: () -> C) -> some View {226        content()227            .padding(.horizontal, 7).padding(.vertical, 5)228            .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(P.ink2))229            .overlay { RoundedRectangle(cornerRadius: 6, style: .continuous).strokeBorder(invalid ? P.critical : P.line, lineWidth: 1) }230    }231232    // MARK: footer and run233234    private func footer(_ all: [String: String]) -> some View {235        VStack(alignment: .leading, spacing: S.s2) {236            if attempted, !all.isEmpty {237                let n = all.count238                Label(all[""] ?? "\(n) parameter\(n == 1 ? "" : "s") to correct above.", systemImage: "exclamationmark.triangle.fill").vqFont(T.caption).foregroundStyle(P.critical)239                    .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("lab.form.issues")240            }241            if let failure {242                Label(failure.message, systemImage: failure.isLimit ? "hourglass" : "exclamationmark.triangle.fill").vqFont(T.caption).foregroundStyle(failure.isLimit ? P.warn : P.critical)243                    .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("lab.form.failure")244            } else if lab.atLimit {245                Label(lab.limitExplanation, systemImage: "hourglass").vqFont(T.caption).foregroundStyle(P.warn).fixedSize(horizontal: false, vertical: true)246                    .accessibilityIdentifier("lab.form.limit")247            }248            HStack(spacing: S.s2) {249                Button { run() } label: {250                    HStack(spacing: 6) { Image(systemName: "play.fill").font(.system(size: 10)); Text("Run on the Server").fontWeight(.semibold) }251                        .vqFont(T.bodySm).foregroundStyle(P.accentFg).padding(.horizontal, S.s3).frame(height: 30)252                        .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(P.accent.opacity(canRun ? 1 : 0.4)))253                        .contentShape(Rectangle())254                }255                .buttonStyle(.plain).disabled(!canRun).keyboardShortcut(.return, modifiers: .command)256                .accessibilityIdentifier("quant.run")257                .help(!app.connectivity.isOnline ? "This Mac is offline" : lab.atLimit ? lab.limitExplanation : "Validate and start the computation (⌘↩)")258                if submitting { ProgressView().controlSize(.small).accessibilityHidden(true) }259                Spacer(minLength: S.s2)260                Menu {261                    projectMenu262                    Divider()263                    Button("Reset to the Engine's Defaults") { lab.forms[tool.id] = VQLabForm(tool: tool); attempted = false; failure = nil; prefill() }264                    Button("Forget the Parameters Last Used on This Mac") { lab.forget(tool); attempted = false; failure = nil; prefill() }.disabled(!lab.hasRemembered(tool.id))265                } label: { Image(systemName: "ellipsis.circle").foregroundStyle(P.text2) }266                .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().help("Project, defaults")267                Text("\(lab.runningCount)/\(lab.maxRunning) running").vqFont(T.numSm).foregroundStyle(lab.atLimit ? P.warn : P.text3)268                    .help("The server runs at most \(lab.maxRunning) computations at once per person.")269            }270            if let pid = projectId, let p = app.sync.active?.projects[pid] {271                Text("Filed in project “\(p.data.title)” when it starts.").vqFont(T.caption).foregroundStyle(P.text3)272            }273        }274        .padding(.horizontal, S.s4).padding(.vertical, S.s3)275        .background(P.ink1)276    }277278    @ViewBuilder private var projectMenu: some View {279        let projects = app.sync.active?.projects.items ?? []280        Menu("File the Job in a Project") {281            Button { projectId = nil } label: { if projectId == nil { Label("None", systemImage: "checkmark") } else { Text("None") } }282            ForEach(projects) { p in Button { projectId = p.id } label: { if projectId == p.id { Label(p.data.title, systemImage: "checkmark") } else { Text(p.data.title) } } }283            if projects.isEmpty { Text("No project yet (Research Studio)") }284        }285    }286287    private var canRun: Bool { !submitting && app.connectivity.isOnline && !lab.atLimit }288289    private func run() {290        attempted = true291        switch form.validate() {292        case .failure: return293        case .success(let params):294            submitting = true; failure = nil295            Task {296                defer { submitting = false }297                do {298                    let j = try await lab.start(tool: tool, params: params, projectId: projectId)299                    attempted = false300                    model.quantJobId = j.id301                } catch let f as LabStartFailure { failure = f }302                catch { failure = LabStartFailure(message: error.localizedDescription) }303            }304        }305    }306307    /// As in 1.x: the window's symbol is proposed for a required symbol, the held positions for a list of symbols —308    /// only where the person has no value of their own yet.309    private func prefill(force: Bool = false) {310        var f = form311        if lab.forms[tool.id] == nil { lab.forms[tool.id] = f }312        let remembered = lab.hasRemembered(tool.id)313        for p in tool.params {314            if p.type == .symbol, p.required, force || (!prefilled && !remembered) || f.text(p.name).isEmpty { f[p.name] = .string(model.symbol) }315            if p.type == .symbols, f.text(p.name).isEmpty {316                let held = app.workspace.positions.map(\.symbol)317                if held.count >= 2 { f[p.name] = VQJSON(Array(held.prefix(12))) }318            }319        }320        prefilled = true321        if f != form { lab.forms[tool.id] = f }322    }323324    /// DEBUG launch arguments: `-VQXLabMode <price|implied|strategy|chain>`, `-VQXLabParams <json object>` (merged325    /// into the form), `-VQXLabAll 1`, `-VQXLabAttempt 1` (validate at once), `-VQXLabRun 1` (run at once).326    private func consumeLaunchArguments() {327        #if DEBUG328        guard app.options.tool == tool.id, !LabLaunchOnce.done else { return }329        LabLaunchOnce.done = true330        let o = app.options.extra331        var f = form332        if let m = o["LabMode"], tool.id == "options_lab" { f["mode"] = .string(m) }333        if let raw = o["LabParams"], let obj = (try? VQJSON.parse(raw))?.objectValue { for (k, v) in obj { f[k] = v.objectValue != nil || (v.arrayValue?.contains { $0.objectValue != nil } ?? false) ? .string(v.text(pretty: true)) : v } }334        lab.forms[tool.id] = f335        if o["LabAll"] != nil { showAll = true; collapsed = [] }336        if o["LabAttempt"] != nil { attempted = true }337        if o["LabRun"] != nil { run() }338        #endif339    }340}341342/// One consumption of the form's launch arguments per process (a second window must not re-run a computation).343@MainActor enum LabLaunchOnce { static var done = false }344345private extension String { var nilIfEmpty: String? { isEmpty ? nil : self } }346347/// An ISO date typed by hand or picked from a calendar.348private struct LabDateField: View {349    @Binding var text: String350    let invalid: Bool351    let name: String352    let label: String353    @State private var open = false354355    private static let iso: DateFormatter = { let f = DateFormatter(); f.calendar = Calendar(identifier: .gregorian); f.locale = Locale(identifier: "en_US_POSIX"); f.timeZone = TimeZone(identifier: "UTC"); f.dateFormat = "yyyy-MM-dd"; return f }()356357    var body: some View {358        HStack(spacing: 4) {359            TextField("YYYY-MM-DD", text: $text).textFieldStyle(.plain).font(.system(size: 12.5, design: .monospaced)).accessibilityLabel(label).accessibilityIdentifier("lab.field.\(name)")360            Button { open = true } label: { Image(systemName: "calendar").font(.system(size: 11)).foregroundStyle(P.text3) }.buttonStyle(.plain).help("Pick a date")361                .popover(isPresented: $open, arrowEdge: .trailing) {362                    VStack(alignment: .trailing, spacing: S.s2) {363                        DatePicker("", selection: Binding(get: { Self.iso.date(from: text) ?? Date() }, set: { text = Self.iso.string(from: $0) }), displayedComponents: .date)364                            .datePickerStyle(.graphical).labelsHidden().environment(\.timeZone, TimeZone(identifier: "UTC")!)365                        Button("Clear") { text = ""; open = false }.controlSize(.small)366                    }.padding(S.s3)367                }368        }369        .padding(.horizontal, 7).padding(.vertical, 5)370        .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(P.ink2))371        .overlay { RoundedRectangle(cornerRadius: 6, style: .continuous).strokeBorder(invalid ? P.critical : P.line, lineWidth: 1) }372    }373}374
Files main
Menu

Theme