Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Quant/LabJSONField.swift3// Description: The editor of a `json` parameter (legs, positions, shocks, grids): a monospaced editor with live validation against the parameter's schema hint, pretty-print and an error line, plus a row editor where the hint describes an array of objects.4import AppKit5import SwiftUI6import VQuantCore7import VQuantKit8import VQuantUI910private typealias P = VQTokens.Palette11private typealias S = VQTokens.Space12private typealias T = VQTokens.Typography1314struct LabJSONField: View {15 enum Mode: String { case rows, json }16 let param: VQLabParam17 @Binding var text: String18 /// The alternative of the hint that applies (the backtest's strategy for `strategy_params`).19 var selectedLabel: String?20 var startInRows = true21 /// Required now (always, or because of the other fields: `VQLabForm.isRequired`).22 var isRequired = false23 @State private var mode: Mode?2425 private var columns: [LabJSONHint.Column]? { LabJSONHint.rowColumns(param.schemaHint) }26 private var alternatives: [LabJSONHint.Alternative] { LabJSONHint.alternatives(param.schemaHint) }27 private var check: LabJSONHint.Check { LabJSONHint.check(text, hint: param.schemaHint, selected: selectedLabel) }28 private var rows: [[String: String]]? { LabJSONHint.rows(text) }29 private var effectiveMode: Mode {30 if columns == nil { return .json }31 if let mode { return mode == .rows && rows == nil ? .json : mode }32 return startInRows && rows != nil ? .rows : .json33 }3435 var body: some View {36 let c = check37 VStack(alignment: .leading, spacing: 6) {38 HStack(spacing: S.s2) {39 if columns != nil {40 VQSegmentedControl("Editor", selection: Binding(get: { effectiveMode }, set: { mode = $0 }), options: [.init(.rows, "Rows"), .init(.json, "JSON")])41 .scaleEffect(0.88, anchor: .leading).frame(height: 26)42 .accessibilityIdentifier("lab.json.\(param.name).mode")43 }44 Spacer(minLength: 0)45 if alternatives.count == 1 || selectedExample != nil {46 small("Example", "text.insert") { if let e = selectedExample ?? alternatives.first?.example { text = String(decoding: e.data(pretty: true), as: UTF8.self) } }47 .help("Replace the value with the hint's example")48 } else if alternatives.count > 1 {49 Menu {50 ForEach(Array(alternatives.enumerated()), id: \.offset) { i, a in51 Button(a.label ?? "Example \(i + 1)") { text = String(decoding: a.example.data(pretty: true), as: UTF8.self) }52 }53 } label: { Label("Example", systemImage: "text.insert").vqFont(T.caption) }54 .menuStyle(.borderlessButton).fixedSize().help("Replace the value with one of the hint's examples")55 }56 small("Format", "text.alignleft") { if let p = LabJSONHint.pretty(text) { text = p } }.disabled(LabJSONHint.pretty(text) == nil)57 .help("Pretty-print").accessibilityIdentifier("lab.json.\(param.name).format")58 small("Clear", "xmark") { text = "" }.disabled(text.isEmpty).help("Empty the value: the engine's default applies")59 }60 if effectiveMode == .rows, let columns { LabRowEditor(columns: columns, text: $text, name: param.name) }61 else {62 LabCodeEditor(text: $text, identifier: "lab.json.\(param.name)")63 .frame(height: min(220, max(84, CGFloat(text.split(separator: "\n", omittingEmptySubsequences: false).count) * 16 + 18)))64 .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(P.ink2))65 .overlay { RoundedRectangle(cornerRadius: 6, style: .continuous).strokeBorder(c.error != nil ? P.critical : P.line, lineWidth: 1) }66 }67 status(c)68 if let hint = param.schemaHint, !hint.isEmpty {69 VStack(alignment: .leading, spacing: 2) {70 Text("Expected shape").vqFont(T.overline).foregroundStyle(P.text3)71 Text(shownHint(hint)).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(P.text2).lineLimit(4).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)72 }73 }74 }75 }7677 private var selectedExample: JSONValue? { selectedLabel.flatMap { LabJSONHint.example(param.schemaHint, labelled: $0) } }7879 /// With a selected alternative only its example is shown (the full hint of `strategy_params` lists nine strategies).80 private func shownHint(_ hint: String) -> String {81 if let l = selectedLabel, let e = selectedExample { return "\(l) \(String(decoding: e.data(), as: UTF8.self))" }82 return hint83 }8485 private func small(_ title: String, _ symbol: String, _ action: @escaping () -> Void) -> some View {86 Button(action: action) { Label(title, systemImage: symbol).vqFont(T.caption) }.buttonStyle(.borderless).controlSize(.small)87 }8889 @ViewBuilder private func status(_ c: LabJSONHint.Check) -> some View {90 VStack(alignment: .leading, spacing: 2) {91 if let e = c.error {92 Label(e, systemImage: "xmark.octagon.fill").foregroundStyle(P.critical).accessibilityIdentifier("lab.json.\(param.name).error")93 } else if c.isEmpty {94 Label(isRequired ? "Empty — a value is required." : "Empty — the engine's default applies.", systemImage: "circle.dotted").foregroundStyle(P.text3)95 } else {96 Label("Valid JSON · \(c.summary)", systemImage: "checkmark.circle").foregroundStyle(P.text2).accessibilityIdentifier("lab.json.\(param.name).valid")97 }98 ForEach(c.notes, id: \.self) { n in99 Label(n, systemImage: "exclamationmark.triangle").foregroundStyle(P.warn).help("Advisory: compared with the example in the hint. The engine decides.")100 }101 }102 .vqFont(T.caption).labelStyle(LabTightLabel())103 .fixedSize(horizontal: false, vertical: true)104 }105}106107private struct LabTightLabel: LabelStyle {108 func makeBody(configuration: Configuration) -> some View {109 HStack(alignment: .firstTextBaseline, spacing: 4) { configuration.icon.font(.system(size: 10, weight: .medium)); configuration.title }110 }111}112113/// An array of objects as a small table: one row per item, one column per key of the hint.114private struct LabRowEditor: View {115 let columns: [LabJSONHint.Column]116 @Binding var text: String117 let name: String118119 private var rows: [[String: String]] { LabJSONHint.rows(text) ?? [] }120 private func write(_ rows: [[String: String]]) { text = LabJSONHint.text(rows: rows, columns: columns) }121 private func cell(_ row: Int, _ column: String) -> Binding<String> {122 Binding(get: { let r = rows; return r.indices.contains(row) ? r[row][column] ?? "" : "" },123 set: { v in var r = rows; guard r.indices.contains(row) else { return }; r[row][column] = v; write(r) })124 }125 private func width(_ c: LabJSONHint.Column) -> CGFloat {126 switch c.kind { case .choice: 74; case .number: 58; case .bool: 50; default: 92 }127 }128129 var body: some View {130 ScrollView(.horizontal, showsIndicators: false) {131 VStack(alignment: .leading, spacing: 3) {132 HStack(spacing: 4) {133 ForEach(columns) { c in Text(c.name.replacingOccurrences(of: "_", with: " ")).font(.system(size: 9.5, weight: .semibold)).foregroundStyle(P.text3).lineLimit(1).frame(width: width(c), alignment: c.kind == .number ? .trailing : .leading) }134 }135 ForEach(Array(rows.enumerated()), id: \.offset) { i, _ in136 HStack(spacing: 4) {137 ForEach(columns) { c in138 Group {139 if case .choice(let list) = c.kind {140 Picker("", selection: cell(i, c.name)) {141 if !list.contains(cell(i, c.name).wrappedValue) { Text(cell(i, c.name).wrappedValue.isEmpty ? "—" : cell(i, c.name).wrappedValue).tag(cell(i, c.name).wrappedValue) }142 ForEach(list, id: \.self) { Text($0).tag($0) }143 }.labelsHidden().controlSize(.mini)144 } else {145 TextField(LabJSONHint.cellText(c.example), text: cell(i, c.name)).textFieldStyle(.plain)146 .font(.system(size: 11.5, design: .monospaced)).multilineTextAlignment(c.kind == .number ? .trailing : .leading)147 .padding(.horizontal, 4).padding(.vertical, 3)148 .background(RoundedRectangle(cornerRadius: 4, style: .continuous).fill(P.ink2))149 .overlay { RoundedRectangle(cornerRadius: 4, style: .continuous).strokeBorder(P.line, lineWidth: 1) }150 }151 }152 .frame(width: width(c))153 .accessibilityLabel("\(c.name), row \(i + 1)").accessibilityIdentifier("lab.json.\(name).\(i).\(c.name)")154 }155 Button { var r = rows; r.remove(at: i); write(r) } label: { Image(systemName: "minus.circle").foregroundStyle(P.text3) }156 .buttonStyle(.plain).help("Remove this row").accessibilityLabel("Remove row \(i + 1)")157 }158 }159 Button { var r = rows; r.append(LabJSONHint.newRow(columns)); write(r) } label: { Label("Add a row", systemImage: "plus.circle").vqFont(T.caption) }160 .buttonStyle(.borderless).controlSize(.small).padding(.top, 2)161 .accessibilityIdentifier("lab.json.\(name).add")162 }163 .padding(.vertical, 2)164 }165 }166}167168/// A plain monospaced text editor without the system's text substitutions (curly quotes and dashes would break JSON).169struct LabCodeEditor: NSViewRepresentable {170 @Binding var text: String171 var identifier: String172173 func makeCoordinator() -> Coordinator { Coordinator(self) }174175 func makeNSView(context: Context) -> NSScrollView {176 let scroll = NSTextView.scrollableTextView()177 scroll.drawsBackground = false; scroll.hasVerticalScroller = true; scroll.autohidesScrollers = true; scroll.borderType = .noBorder178 guard let tv = scroll.documentView as? NSTextView else { return scroll }179 tv.delegate = context.coordinator180 tv.isRichText = false; tv.allowsUndo = true; tv.drawsBackground = false181 tv.isAutomaticQuoteSubstitutionEnabled = false; tv.isAutomaticDashSubstitutionEnabled = false; tv.isAutomaticTextReplacementEnabled = false182 tv.isAutomaticSpellingCorrectionEnabled = false; tv.isContinuousSpellCheckingEnabled = false; tv.isGrammarCheckingEnabled = false183 tv.font = .monospacedSystemFont(ofSize: 11.5, weight: .regular); tv.textColor = .labelColor184 tv.textContainerInset = NSSize(width: 4, height: 6)185 tv.string = text186 tv.setAccessibilityIdentifier(identifier)187 return scroll188 }189190 func updateNSView(_ scroll: NSScrollView, context: Context) {191 context.coordinator.parent = self192 guard let tv = scroll.documentView as? NSTextView, tv.string != text else { return }193 let selection = tv.selectedRanges194 tv.string = text195 if (selection.first?.rangeValue.upperBound ?? 0) <= (text as NSString).length { tv.selectedRanges = selection }196 }197198 final class Coordinator: NSObject, NSTextViewDelegate {199 var parent: LabCodeEditor200 init(_ parent: LabCodeEditor) { self.parent = parent }201 func textDidChange(_ notification: Notification) {202 guard let tv = notification.object as? NSTextView else { return }203 if parent.text != tv.string { parent.text = tv.string }204 }205 }206}207