SPB Git

Repository Public

LabViews.swift 42.6 KB 781 lines swift

1//2//  VQuant iOS3//  File: VQuant/Next/LabViews.swift4//  Description: Quant Lab: the catalogue of server engines by category, forms generated from each engine's own5//               parameter description and adapted to touch, jobs with progress and cancellation, results rendered by6//               the shared `LabResultView` (the six engines of 1.0 keep their native result views).7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import SwiftUI13import VQuantKit14import VQuantUI1516enum LabText {17    static func category(_ id: String) -> String {18        switch id {19        case "volatility": "Volatilité"; case "risk": "Risque"; case "econometrics": "Économétrie"; case "options": "Options"20        case "backtest": "Backtests"; case "portfolio": "Portefeuille"; case "simulation": "Simulation"; default: Fmt.label(id)21        }22    }23    static func icon(_ id: String) -> String {24        switch id {25        case "volatility": "waveform.path.ecg"; case "risk": "exclamationmark.shield"; case "econometrics": "chart.dots.scatter"; case "options": "chart.line.uptrend.xyaxis"26        case "backtest": "clock.arrow.circlepath"; case "portfolio": "chart.pie"; case "simulation": "dice"; default: "function"27        }28    }29    /// Group headings come from the engine specs (English); the common ones are shown in French.30    static func group(_ g: String) -> String {31        switch g {32        case "": "Paramètres"; case "Data": "Données"; case "Model": "Modèle"; case "Forecast": "Prévision"; case "Comparison": "Comparaison"33        case "Advanced": "Avancé"; case "Portfolio": "Portefeuille"; case "Backtest": "Backtest"; case "Stress": "Tests de résistance"; case "Correlation": "Corrélation"34        case "Estimation": "Estimation"; case "Contract": "Contrat"; case "Market": "Marché"; case "Strategy": "Stratégie"; case "Chain": "Chaîne d’options"35        case "Numerics": "Méthodes numériques"; case "Valuation": "Valorisation"; case "Risk": "Risque"; case "Optimisation": "Optimisation"; case "Scenarios": "Scénarios"36        case "Series": "Série"; case "Seasonality": "Saisonnalité"; case "Tests": "Tests"; case "Rolling": "Fenêtre glissante"; case "Transforms": "Transformations"37        case "Regressors": "Régresseurs"; case "Implied volatility": "Volatilité implicite"; case "Realized measures": "Mesures réalisées"; case "Impulse responses": "Réponses impulsionnelles"38        case "Cointegration": "Cointégration"; case "Bayesian prior": "A priori bayésien"; default: g39        }40    }41}4243/// The catalogue (by category) and the list of jobs. iPhone: a pushed screen; iPad: the list column of the Lab.44struct LabView: View {45    @Environment(AppModel.self) private var model46    @State private var error: String?47    @State private var filter = ""4849    var body: some View {50        List {51            Section { OfflineBanner().listRowInsets(EdgeInsets()) }52            Section("Calculs rapides") {53                RouteLink(.quickCalc("option")) { Label("Prix et grecques d’une option", systemImage: "chart.line.uptrend.xyaxis") }.accessibilityIdentifier("quick-calc-option")54                RouteLink(.quickCalc("var")) { Label("VaR d’une position", systemImage: "exclamationmark.shield") }.accessibilityIdentifier("quick-calc-var")55                RouteLink(.quickCalc("sizing")) { Label("Taille de position", systemImage: "scalemass") }.accessibilityIdentifier("quick-calc-sizing")56            }57            if let catalog = model.next.lab.catalog.value {58                ForEach(catalog.byCategory, id: \.category) { group in59                    let tools = group.tools.filter { filter.isEmpty || $0.title.localizedCaseInsensitiveContains(filter) || $0.summary.localizedCaseInsensitiveContains(filter) || $0.id.contains(filter.lowercased()) }60                    if !tools.isEmpty {61                        Section {62                            ForEach(tools) { t in63                                RouteLink(.quantTool(t.id)) {64                                    VStack(alignment: .leading, spacing: 3) {65                                        HStack(spacing: 6) {66                                            Text(t.title).font(.body.weight(.medium))67                                            if !t.isLab { Tag(text: "1.0") }68                                        }69                                        Text(t.summary).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(3)70                                    }71                                }72                                .accessibilityIdentifier("tool-\(t.id)")73                            }74                        } header: { Label(LabText.category(group.category), systemImage: LabText.icon(group.category)) }75                    }76                }77                if !catalog.unavailable.isEmpty {78                    Section("Moteurs indisponibles sur le serveur") {79                        ForEach(catalog.unavailable.keys.sorted(), id: \.self) { k in KeyValueRow(key: k, value: catalog.unavailable[k] ?? "") }80                    }81                }82                CachedNotice(at: model.next.lab.catalog.cachedAt)83            } else if model.next.lab.catalog.isUnavailable {84                StateView(kind: .failed, title: "Moteurs indisponibles", message: model.next.lab.catalog.error) { Task { await model.next.lab.refreshCatalog() } }85            } else { ProgressView() }8687            Section {88                let jobs = model.next.lab.jobs.value?.jobs ?? []89                if jobs.isEmpty {90                    if model.next.lab.jobs.isLoading { ProgressView() }91                    else if model.next.lab.jobs.isUnavailable { Text(model.next.lab.jobs.error ?? "Indisponible").font(.footnote).foregroundStyle(Theme.textSecondary) }92                    else { Text("Aucun calcul pour l’instant.").foregroundStyle(Theme.textSecondary) }93                }94                CachedNotice(at: model.next.lab.jobs.cachedAt)95                ForEach(jobs) { j in96                    RouteLink(.quantJob(j.id)) { LabJobRow(job: j) }97                        .accessibilityIdentifier("job-\(j.id)")98                        .swipeActions {99                            if j.isRunning {100                                if j.cancellable { Button("Annuler") { act { _ = try await model.next.lab.cancel(j.id) } }.tint(Theme.warning) }101                            } else {102                                Button("Supprimer", role: .destructive) { act { try await model.next.lab.delete(j.id) } }103                            }104                        }105                }106            } header: { Text("Calculs") } footer: {107                Text("Les calculs s’exécutent en Python sur le serveur VQuant, isolés, avec les mêmes moteurs que l’agent. Ils continuent si l’application est fermée.").foregroundStyle(Theme.textSecondary)108            }109        }110        .listStyle(.insetGrouped)111        .navigationTitle("Quant Lab")112        .searchable(text: $filter, prompt: "Filtrer les moteurs")113        .task { await model.next.lab.refreshCatalog(); await model.next.lab.refreshJobs(); model.next.lab.startPolling() }114        .refreshable { await model.next.lab.refreshCatalog(); await model.next.lab.refreshJobs() }115        .errorAlert($error)116        .accessibilityIdentifier("quant")117    }118119    private func act(_ work: @escaping () async throws -> Void) {120        Task { do { try await work() } catch { self.error = nextMessage(error) } }121    }122}123124/// iPad detail column of the Lab when nothing is selected: the fast entry points.125struct LabLanding: View {126    @Environment(AppModel.self) private var model127    var body: some View {128        ScrollView {129            VStack(alignment: .leading, spacing: 18) {130                EditorialHeader("Quant Lab", overline: "Moteurs du serveur")131                Text("Dix-neuf moteurs : volatilité, risque, économétrie, options, backtests, portefeuille, simulation. Chaque résultat porte ses hypothèses, ses diagnostics, sa méthodologie et la provenance de ses données.")132                    .font(.callout).foregroundStyle(Theme.textSecondary)133                LazyVGrid(columns: [GridItem(.adaptive(minimum: 240), spacing: 12)], spacing: 12) {134                    card("Prix et grecques d’une option", "Black-Scholes-Merton, arbre binomial, Monte Carlo", "chart.line.uptrend.xyaxis", .quickCalc("option"))135                    card("VaR d’une position", "Historique, paramétrique, filtrée par la volatilité courante", "exclamationmark.shield", .quickCalc("var"))136                    card("Taille de position", "À partir d’un budget de risque et de la VaR mesurée", "scalemass", .quickCalc("sizing"))137                }138                let running = model.next.lab.running139                if !running.isEmpty {140                    EditorialHeader("En cours")141                    ForEach(running) { j in RouteLink(.quantJob(j.id)) { LabJobRow(job: j) }.buttonStyle(.plain); Divider() }142                }143            }144            .padding(20).frame(maxWidth: 900, alignment: .leading).frame(maxWidth: .infinity)145        }146        .background(Theme.background)147        .navigationTitle("Quant Lab").navigationBarTitleDisplayMode(.inline)148    }149    private func card(_ title: String, _ detail: String, _ image: String, _ route: Route) -> some View {150        RouteLink(route) {151            VStack(alignment: .leading, spacing: 6) {152                Image(systemName: image).font(.title3).foregroundStyle(Theme.orange)153                Text(title).font(.serif(.headline)).multilineTextAlignment(.leading)154                Text(detail).font(.caption).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.leading)155            }156            .paperCard()157        }158        .buttonStyle(.plain).hoverEffect(.lift)159    }160}161162// MARK: - Form163164struct LabFormView: View {165    /// `toolId`, or `toolId|SYMBOL[,SYMBOL]` to prefill the symbol(s).166    let toolId: String167    var projectId: String?168    @Environment(AppModel.self) private var model169    @Environment(\.horizontalSizeClass) private var sizeClass170    @State private var form: VQLabForm?171    @State private var submitting = false172    @State private var error: String?173    @State private var attempted = false174    @State private var expanded: Set<String> = []175176    private var id: String { String(toolId.split(separator: "|").first ?? "") }177    private var presetSymbol: String? { toolId.split(separator: "|").dropFirst().first.map(String.init) }178179    var body: some View {180        Form {181            if let form {182                Section {183                    Text(form.tool.summary).font(.footnote).foregroundStyle(Theme.textSecondary)184                    if let v = form.tool.version { KeyValueRow(key: "Moteur", value: "\(form.tool.id) · v\(v)") }185                }186                // only the groups and fields that apply to the current choices (`visibleWhen` of the engine's spec)187                let groups = form.visibleGroups188                ForEach(Array(groups.enumerated()), id: \.offset) { index, g in189                    if index == 0 || g.params.contains(where: { form.isRequired($0) }) {190                        Section(LabText.group(g.name)) { ForEach(g.params) { field($0) } }191                    } else {192                        Section {193                            DisclosureGroup(isExpanded: Binding(get: { expanded.contains(g.name) }, set: { if $0 { expanded.insert(g.name) } else { expanded.remove(g.name) } })) {194                                ForEach(g.params) { field($0) }195                            } label: {196                                HStack { Text(LabText.group(g.name)); Spacer(); Text("\(g.params.count)").font(.caption).foregroundStyle(Theme.textSecondary) }197                            }198                            .accessibilityIdentifier("group-\(g.name)")199                        }200                    }201                }202                if let error { Section { Label(error, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.down).accessibilityIdentifier("quant-error") } }203                Section {204                    Button { Task { await submit() } } label: {205                        HStack { if submitting { ProgressView().controlSize(.small) }; Text("Lancer le calcul sur le serveur") }.frame(maxWidth: .infinity)206                    }207                    .buttonStyle(EmberButtonStyle())208                    .listRowInsets(EdgeInsets()).listRowBackground(Color.clear)209                    .disabled(submitting).requiresNetwork(model.network.isOnline)210                    .accessibilityIdentifier("quant-submit")211                } footer: {212                    Text("Jusqu’à \(model.next.lab.catalog.value?.maxRunning ?? 3) calculs simultanés. \(form.tool.isLab ? "Un calcul en cours peut être annulé." : "Ce moteur de la version 1.0 ne peut pas être annulé une fois lancé.") Aucune opération financière n’est engagée.")213                }214            } else if model.next.lab.catalog.isUnavailable {215                StateView(kind: .failed, title: "Moteur indisponible", message: model.next.lab.catalog.error) { Task { await model.next.lab.refreshCatalog(); prepare() } }216            } else if model.next.lab.catalog.value != nil {217                StateView(kind: .empty, title: "Moteur inconnu", message: "« \(id) » n’est pas dans le catalogue du serveur.", systemImage: "questionmark.circle")218            } else { ProgressView() }219        }220        .navigationTitle(form?.tool.title ?? "Calcul").navigationBarTitleDisplayMode(.inline)221        .task {222            if model.next.lab.catalog.value == nil { await model.next.lab.refreshCatalog() }223            prepare()224        }225        .accessibilityIdentifier("lab-form")226    }227228    private func prepare() {229        guard form == nil, let tool = model.next.lab.tool(id) else { return }230        var f = VQLabForm(tool: tool)231        if let s = presetSymbol {232            if tool.params.contains(where: { $0.name == "symbol" }) { f["symbol"] = .string(String(s.split(separator: ",").first ?? "")) }233            if tool.params.contains(where: { $0.name == "symbols" }) { f["symbols"] = VQJSON(s.split(separator: ",").map(String.init)) }234        }235        form = f236    }237238    private func binding(_ name: String) -> Binding<VQJSON?> {239        Binding(get: { form?[name] }, set: { form?[name] = $0 })240    }241242    @ViewBuilder private func field(_ p: VQLabParam) -> some View {243        VStack(alignment: .leading, spacing: 4) {244            LabParamField(param: p, value: binding(p.name), required: form?.isRequired(p) ?? p.required)245            if let h = p.help, !h.isEmpty { Text(h).font(.caption2).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true) }246            if attempted, let issue = form?.issue(for: p.name) { Text(issue).font(.caption2).foregroundStyle(Theme.down).accessibilityIdentifier("issue-\(p.name)") }247        }248    }249250    private func submit() async {251        guard let form else { return }252        attempted = true; error = nil253        switch form.validate() {254        case .failure(let invalid):255            // The same rules and wording as the server: every issue at once, next to its field.256            error = invalid.issues.count == 1 ? invalid.message : "\(invalid.issues.count) paramètres à corriger. " + (invalid.issues.first { $0.name.isEmpty }?.message ?? "")257            for g in form.visibleGroups where g.params.contains(where: { p in invalid.issues.contains { $0.name == p.name } }) { expanded.insert(g.name) }258            Haptics.warning()259        case .success(let params):260            submitting = true; defer { submitting = false }261            do {262                let job = try await model.next.lab.start(tool: form.tool.id, params: params, projectId: projectId)263                Haptics.success()264                Task { _ = await model.notifications.requestAuthorization() }265                model.router.open(.quantJob(job.id), compact: sizeClass == .compact)266            } catch { self.error = nextMessage(error); Haptics.warning() }267        }268    }269}270271/// One parameter of an engine as a touch control chosen from its declared type.272struct LabParamField: View {273    let param: VQLabParam274    @Binding var value: VQJSON?275    /// Required now (always, or because of another field's value: `requiredWhen`).276    var required: Bool? = nil277278    private var title: String { param.label + ((required ?? param.required) ? " *" : "") }279    private var text: Binding<String> {280        Binding(get: {281            switch value {282            case .string(let s)?: s283            case .array(let a)?: a.compactMap(\.displayString).joined(separator: ", ")284            case let v?: v.displayString ?? ""285            case nil: ""286            }287        }, set: { value = $0.isEmpty ? nil : .string($0) })288    }289290    var body: some View {291        switch param.type.known {292        case .bool:293            Toggle(title, isOn: Binding(get: { value == .bool(true) || value == .string("true") }, set: { value = .bool($0) }))294                .accessibilityIdentifier("param-\(param.name)")295        case .choice:296            let selection = Binding(get: { value?.displayString ?? "" }, set: { value = .string($0) })297            if param.choices.count <= 3 {298                VStack(alignment: .leading, spacing: 6) {299                    Text(title).font(.subheadline)300                    Picker(title, selection: selection) { ForEach(param.choices, id: \.self) { Text($0).tag($0) } }.pickerStyle(.segmented)301                }302                .accessibilityIdentifier("param-\(param.name)")303            } else {304                Picker(title, selection: selection) { ForEach(param.choices, id: \.self) { Text($0).tag($0) } }305                    .accessibilityIdentifier("param-\(param.name)")306            }307        case .symbol:308            LabeledContent(title) {309                TextField("AAPL", text: text).textInputAutocapitalization(.characters).autocorrectionDisabled().multilineTextAlignment(.trailing).font(.mono(.body))310                    .accessibilityIdentifier("param-\(param.name)")311            }312            .symbolDrop { value = .string($0) }313        case .symbols:314            SymbolsField(title: title, name: param.name, value: $value)315        case .int:316            let n = value?.looseDouble317            HStack {318                Text(title)319                Spacer(minLength: 8)320                TextField(param.defaultValue?.displayString ?? "—", text: text).keyboardType((param.min ?? 0) < 0 ? .numbersAndPunctuation : .numberPad)321                    .multilineTextAlignment(.trailing).font(.mono(.body)).frame(maxWidth: 110)322                    .accessibilityIdentifier("param-\(param.name)")323                Stepper(title, value: Binding(get: { n ?? param.defaultValue?.doubleValue ?? param.min ?? 0 }, set: { value = .number($0) }),324                        in: (param.min ?? -1e9)...(param.max ?? 1e9), step: Self.step(n ?? param.defaultValue?.doubleValue ?? 1))325                    .labelsHidden()326            }327        case .number:328            LabeledContent(title) {329                TextField(param.defaultValue?.displayString ?? "—", text: text).keyboardType((param.min ?? 0) < 0 ? .numbersAndPunctuation : .decimalPad)330                    .multilineTextAlignment(.trailing).font(.mono(.body))331                    .accessibilityIdentifier("param-\(param.name)")332            }333        case .numbers:334            LabeledContent(title) {335                TextField("0.95, 0.99", text: text).keyboardType(.numbersAndPunctuation).multilineTextAlignment(.trailing).font(.mono(.body))336                    .accessibilityIdentifier("param-\(param.name)")337            }338        case .date:339            OptionalDateField(title: title, name: param.name, value: $value, min: param.minDate, max: param.maxDate)340        case .json:341            JSONParamEditor(param: param, value: $value)342        case .group:343            EmptyView()344        case .text, nil:345            VStack(alignment: .leading, spacing: 4) {346                Text(title).font(.subheadline)347                TextField(param.defaultValue?.displayString ?? "", text: text, axis: param.multiline ? .vertical : .horizontal).lineLimit(param.multiline ? 2...6 : 1...1)348                    .autocorrectionDisabled().textInputAutocapitalization(.never).font(.mono(.footnote))349                    .accessibilityIdentifier("param-\(param.name)")350            }351        }352    }353354    /// A step a person would use: 1 for small integers, a power of ten for large ones (250 → 10, 20 000 → 1 000).355    static func step(_ v: Double) -> Double {356        let a = abs(v)357        if a < 50 { return 1 }358        return pow(10, (log10(a)).rounded(.down) - 1)359    }360}361362/// Several tickers as removable chips, with a field to add one and a drop target.363struct SymbolsField: View {364    var title: String365    var name: String366    @Binding var value: VQJSON?367    @State private var entry = ""368369    private var list: [String] {370        switch value {371        case .array(let a)?: a.compactMap(\.displayString)372        case .string(let s)?: s.split(whereSeparator: { ", ;".contains($0) }).map(String.init)373        default: []374        }375    }376    private func set(_ l: [String]) { value = l.isEmpty ? nil : VQJSON(l) }377    private func add(_ raw: String) {378        var l = list379        for part in raw.split(whereSeparator: { ", ;\n".contains($0) }) { if let s = WatchlistFile.normalise(String(part)), !l.contains(s) { l.append(s) } }380        set(l); entry = ""381    }382383    var body: some View {384        VStack(alignment: .leading, spacing: 8) {385            Text(title).font(.subheadline)386            if !list.isEmpty {387                FlowLayout(spacing: 6) {388                    ForEach(list, id: \.self) { s in389                        Button { set(list.filter { $0 != s }) } label: {390                            HStack(spacing: 4) { Text(s).font(.mono(.footnote, weight: .medium)); Image(systemName: "xmark").font(.caption2) }391                                .padding(.horizontal, 10).frame(minHeight: 32)392                                .background(Theme.surface2, in: Capsule())393                        }394                        .buttonStyle(.plain).frame(minHeight: 44)395                        .accessibilityLabel("Retirer \(s)")396                    }397                }398            }399            HStack {400                TextField("Ajouter : AAPL, MSFT…", text: $entry).textInputAutocapitalization(.characters).autocorrectionDisabled().font(.mono(.body))401                    .onSubmit { add(entry) }.submitLabel(.done)402                    .accessibilityIdentifier("param-\(name)")403                if !entry.isEmpty { Button("Ajouter") { add(entry) }.accessibilityIdentifier("param-\(name)-add") }404            }405        }406        .symbolDrop { add($0) }407    }408}409410struct OptionalDateField: View {411    var title: String412    var name: String413    @Binding var value: VQJSON?414    var min: String?415    var max: String?416417    private var date: Date? { value?.stringValue.flatMap(VQISODate.parse) }418    private var range: ClosedRange<Date> {419        let lo = min.flatMap(VQISODate.parse) ?? Date(timeIntervalSince1970: 0)420        let hi = max.flatMap(VQISODate.parse) ?? Date().addingTimeInterval(86_400 * 3650)421        return lo...Swift.max(lo, hi)422    }423    var body: some View {424        if let date {425            HStack {426                DatePicker(title, selection: Binding(get: { date }, set: { value = .string(VQFormat.dateISO($0, timeZone: TimeZone(identifier: "UTC")!)) }), in: range, displayedComponents: .date)427                    .environment(\.timeZone, TimeZone(identifier: "UTC")!)428                Button { value = nil } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.textSecondary) }429                    .buttonStyle(.plain).frame(minWidth: 44, minHeight: 44).accessibilityLabel("Effacer \(title)")430            }431        } else {432            HStack {433                Text(title)434                Spacer()435                Button("Choisir une date") { value = .string(VQFormat.dateISO(Swift.min(Date(), range.upperBound), timeZone: TimeZone(identifier: "UTC")!)) }436                    .accessibilityIdentifier("param-\(name)")437            }438        }439    }440}441442/// A `json` parameter as a native list when its hint has a regular shape: rows of fields for an array of objects443/// (option legs, positions, shocks, dividends), key–value rows for an object of numbers (cash, target weights), and a444/// monospaced editor for anything else. What is sent is always the JSON the engine documents.445struct JSONParamEditor: View {446    let param: VQLabParam447    @Binding var value: VQJSON?448    @State private var raw = ""449    @State private var rawMode = false450451    enum Shape: Equatable {452        case rows([Field])453        case map(valueIsNumber: Bool, sampleKey: String)454        case raw455    }456    struct Field: Equatable, Identifiable { var key: String; var isNumber: Bool; var choices: [String]; var sample: String; var id: String { key } }457458    /// Reads the first alternative of the engine's `schemaHint`.459    static func shape(hint: String?) -> Shape {460        guard var h = hint?.components(separatedBy: "  or  ").first?.trimmingCharacters(in: .whitespaces), !h.isEmpty else { return .raw }461        h = h.replacingOccurrences(of: ", …", with: "").replacingOccurrences(of: "…", with: "")462        guard let j = try? VQJSON.parse(h) else { return .raw }463        if let first = j.arrayValue?.first?.objectValue, !first.isEmpty {464            // keep the order the hint was written in465            let ordered = first.keys.sorted { (h.range(of: "\"\($0)\"")?.lowerBound ?? h.endIndex) < (h.range(of: "\"\($1)\"")?.lowerBound ?? h.endIndex) }466            return .rows(ordered.map { k in467                let v = first[k]!468                let s = v.stringValue ?? ""469                return Field(key: k, isNumber: v.doubleValue != nil, choices: s.contains("|") ? s.split(separator: "|").map(String.init) : [], sample: v.displayString ?? "")470            })471        }472        if let o = j.objectValue, !o.isEmpty, o.values.allSatisfy({ $0.doubleValue != nil || $0.stringValue != nil }) {473            return .map(valueIsNumber: o.values.allSatisfy { $0.doubleValue != nil }, sampleKey: o.keys.sorted().first ?? "")474        }475        return .raw476    }477478    private var shape: Shape { rawMode ? .raw : Self.shape(hint: param.schemaHint) }479    private var title: String { param.label + (param.required ? " *" : "") }480481    var body: some View {482        VStack(alignment: .leading, spacing: 8) {483            HStack {484                Text(title).font(.subheadline)485                Spacer()486                if Self.shape(hint: param.schemaHint) != .raw {487                    Button(rawMode ? "Liste" : "JSON") { toggleRaw() }.font(.caption).accessibilityIdentifier("param-\(param.name)-mode")488                }489            }490            switch shape {491            case .rows(let fields): rowsEditor(fields)492            case .map(let isNumber, let sampleKey): mapEditor(valueIsNumber: isNumber, sampleKey: sampleKey)493            case .raw:494                TextField(param.schemaHint ?? "{ }", text: Binding(get: { raw.isEmpty ? (value.map { $0.stringValue ?? $0.text(pretty: true) } ?? "") : raw }, set: { raw = $0; value = $0.isEmpty ? nil : .string($0) }), axis: .vertical)495                    .lineLimit(3...10).font(.mono(.caption)).autocorrectionDisabled().textInputAutocapitalization(.never)496                    .accessibilityIdentifier("param-\(param.name)")497                if let h = param.schemaHint { Text("Exemple : \(h)").font(.mono(.caption2)).foregroundStyle(Theme.textSecondary).textSelection(.enabled) }498            }499        }500    }501502    private func toggleRaw() {503        if !rawMode { raw = value.map { $0.stringValue ?? $0.text(pretty: true) } ?? "" }504        else if let parsed = try? VQJSON.parse(raw) { value = parsed }505        rawMode.toggle()506    }507508    // MARK: array of objects509510    private var rows: [VQJSONObject] { (value?.arrayValue ?? []).compactMap(\.objectValue) }511    private func setRows(_ r: [VQJSONObject]) { value = r.isEmpty ? nil : .array(r.map(VQJSON.object)) }512513    @ViewBuilder private func rowsEditor(_ fields: [Field]) -> some View {514        ForEach(Array(rows.enumerated()), id: \.offset) { i, row in515            VStack(alignment: .leading, spacing: 6) {516                HStack {517                    Text("\(i + 1)").font(.mono(.caption, weight: .semibold)).foregroundStyle(Theme.textSecondary)518                    Spacer()519                    Button(role: .destructive) { var r = rows; r.remove(at: i); setRows(r) } label: { Image(systemName: "minus.circle") }520                        .buttonStyle(.plain).foregroundStyle(Theme.down).frame(minWidth: 44, minHeight: 44).accessibilityLabel("Retirer la ligne \(i + 1)")521                }522                ForEach(fields) { f in523                    let b = Binding<String>(get: { row[f.key]?.displayString ?? "" }, set: { new in524                        var r = rows525                        if new.isEmpty { r[i][f.key] = nil }526                        else if f.isNumber, let n = Double(new.replacingOccurrences(of: ",", with: ".")) { r[i][f.key] = .number(n) }527                        else { r[i][f.key] = .string(new) }528                        setRows(r)529                    })530                    if !f.choices.isEmpty {531                        Picker(Fmt.label(f.key), selection: b) { ForEach(f.choices, id: \.self) { Text($0).tag($0) } }.pickerStyle(.segmented)532                    } else {533                        LabeledContent(Fmt.label(f.key)) {534                            TextField(f.sample, text: b).multilineTextAlignment(.trailing).font(.mono(.footnote))535                                .keyboardType(f.isNumber ? .numbersAndPunctuation : .default).autocorrectionDisabled().textInputAutocapitalization(f.key == "symbol" ? .characters : .never)536                                .accessibilityIdentifier("param-\(param.name)-\(i)-\(f.key)")537                        }538                    }539                }540            }541            .padding(10).background(Theme.surface2.opacity(0.6), in: RoundedRectangle(cornerRadius: 10))542        }543        Button {544            var o: VQJSONObject = [:]545            for f in fields where !f.choices.isEmpty { o[f.key] = .string(f.choices[0]) }546            setRows(rows + [o])547        } label: { Label("Ajouter une ligne", systemImage: "plus.circle") }548            .accessibilityIdentifier("param-\(param.name)-add")549    }550551    // MARK: object of scalars552553    private var pairs: [(key: String, value: VQJSON)] { (value?.objectValue ?? [:]).sorted { $0.key < $1.key }.map { ($0.key, $0.value) } }554    @State private var newKey = ""555    @State private var newValue = ""556557    @ViewBuilder private func mapEditor(valueIsNumber: Bool, sampleKey: String) -> some View {558        ForEach(pairs, id: \.key) { pair in559            HStack {560                Text(pair.key).font(.mono(.footnote, weight: .medium))561                Spacer()562                Text(pair.value.displayString ?? "").font(.mono(.footnote))563                Button(role: .destructive) { var o = value?.objectValue ?? [:]; o[pair.key] = nil; value = o.isEmpty ? nil : .object(o) } label: { Image(systemName: "minus.circle") }564                    .buttonStyle(.plain).foregroundStyle(Theme.down).frame(minWidth: 44, minHeight: 44).accessibilityLabel("Retirer \(pair.key)")565            }566        }567        HStack {568            TextField(sampleKey, text: $newKey).font(.mono(.footnote)).autocorrectionDisabled().textInputAutocapitalization(.characters)569                .accessibilityIdentifier("param-\(param.name)-key")570            TextField(valueIsNumber ? "0" : "valeur", text: $newValue).font(.mono(.footnote)).keyboardType(valueIsNumber ? .numbersAndPunctuation : .default).multilineTextAlignment(.trailing).frame(maxWidth: 110)571                .accessibilityIdentifier("param-\(param.name)-value")572            Button("Ajouter") {573                let k = newKey.trimmingCharacters(in: .whitespaces)574                guard !k.isEmpty, !newValue.isEmpty else { return }575                var o = value?.objectValue ?? [:]576                if valueIsNumber, let n = Double(newValue.replacingOccurrences(of: ",", with: ".")) { o[k] = .number(n) } else if !valueIsNumber { o[k] = .string(newValue) } else { return }577                value = .object(o); newKey = ""; newValue = ""578            }579            .disabled(newKey.isEmpty || newValue.isEmpty)580        }581    }582}583584/// Wrapping row of chips.585struct FlowLayout: Layout {586    var spacing: CGFloat = 6587    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {588        let width = proposal.width ?? .infinity589        var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0590        for v in subviews {591            let s = v.sizeThatFits(.unspecified)592            if x > 0, x + s.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }593            x += s.width + spacing; rowHeight = max(rowHeight, s.height); maxX = max(maxX, x - spacing)594        }595        return CGSize(width: proposal.width ?? maxX, height: y + rowHeight)596    }597    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {598        var x = bounds.minX, y = bounds.minY, rowHeight: CGFloat = 0599        for v in subviews {600            let s = v.sizeThatFits(.unspecified)601            if x > bounds.minX, x + s.width > bounds.maxX { x = bounds.minX; y += rowHeight + spacing; rowHeight = 0 }602            v.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(s))603            x += s.width + spacing; rowHeight = max(rowHeight, s.height)604        }605    }606}607608// MARK: - Job609610struct LabJobView: View {611    let jobId: String612    @Environment(AppModel.self) private var model613    @Environment(\.horizontalSizeClass) private var sizeClass614    @State private var job: VQQuantJob?615    @State private var origin: DataOrigin?616    @State private var error: String?617    @State private var alert: String?618    @State private var share: ChartScreen.ShareItem?619620    var body: some View {621        ScrollView {622            if let job {623                VStack(alignment: .leading, spacing: 16) {624                    header(job)625                    if job.isRunning { running(job) }626                    if let e = job.failureMessage, !job.isRunning {627                        Label(e, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.down)628                            .padding(12).frame(maxWidth: .infinity, alignment: .leading).background(Theme.down.opacity(0.1), in: RoundedRectangle(cornerRadius: 10))629                            .accessibilityIdentifier("job-error")630                    }631                    if job.status == .cancelled { Text("Calcul annulé : un calcul annulé ne garde aucun résultat.").font(.footnote).foregroundStyle(Theme.textSecondary) }632                    if let lab = job.labResult, lab.success {633                        LabResultView(lab).accessibilityIdentifier("lab-result")634                    } else if let result = job.result, !result.isNull, job.labResult == nil, let legacy = Self.legacy(result) {635                        QuantResultView(result: legacy).accessibilityIdentifier("legacy-result")636                    }637                    reproducibility(job)638                    if let code = job.code, !code.isEmpty {639                        DisclosureGroup("Code Python exécuté") { CodeBlock(language: "python", code: code) }.font(.subheadline).paperCard(padding: 12)640                    }641                }642                .padding(16)643                .frame(maxWidth: 1100).frame(maxWidth: .infinity)644            } else if let error {645                StateView(kind: .failed, title: "Calcul indisponible", message: error) { Task { await load() } }646            } else { StateView(kind: .loading, title: "Chargement…") }647        }648        .background(Theme.background)649        .navigationTitle(job.map { model.next.lab.title($0.tool) } ?? "Calcul").navigationBarTitleDisplayMode(.inline)650        .toolbar {651            if let job, job.isRunning, job.cancellable {652                ToolbarItem(placement: .primaryAction) {653                    Button("Annuler", role: .destructive) { Task { await cancel() } }.accessibilityIdentifier("job-cancel")654                }655            }656            if let job, job.status == .done {657                ToolbarItem(placement: .primaryAction) {658                    Menu {659                        if let lab = job.labResult {660                            Button { exportImage(lab) } label: { Label("Image du résultat (PNG)", systemImage: "photo") }661                            Button { exportPDF(lab) } label: { Label("Document (PDF)", systemImage: "doc.richtext") }662                        }663                        ShareLink(item: Self.exportJSON(job)) { Label("Données (JSON)", systemImage: "curlybraces") }664                        if !model.next.studio.projects.isEmpty {665                            Menu("Ajouter à un projet") {666                                ForEach(model.next.studio.projects.prefix(12)) { p in667                                    Button(p.data.title) { Task { await model.next.sync.projects.update(p.id) { d in var it = d.items; if !it.contains(where: { $0.ref == job.id }) { it.append(VQProject.Item(type: .quantJob, ref: job.id, title: model.next.lab.title(job.tool), addedAt: Date())) }; d.items = it } } }668                                }669                            }670                        }671                        Button { Task { await review(job) } } label: { Label("Demander une revue automatisée", systemImage: "checkmark.seal") }672                    } label: { Label("Exporter", systemImage: "square.and.arrow.up") }673                    .accessibilityIdentifier("job-export")674                }675            }676        }677        .task {678            if model.next.lab.catalog.value == nil { await model.next.lab.refreshCatalog() }679            model.notifications.visibleJobId = jobId680            await load()681            // Poll this job until it ends; the loop dies with the view.682            while !Task.isCancelled, job?.isRunning == true {683                try? await Task.sleep(for: .milliseconds(1200))684                await load()685            }686        }687        .onDisappear { if model.notifications.visibleJobId == jobId { model.notifications.visibleJobId = nil } }688        .refreshable { await load() }689        .sheet(item: $share) { ActivityView(items: [$0.url]) }690        .errorAlert($alert)691        .accessibilityIdentifier("quant-job")692    }693694    static func legacy(_ v: VQJSON) -> JSONValue? { try? JSONDecoder().decode(JSONValue.self, from: v.data()) }695696    private func load() async {697        do { let l = try await model.next.lab.job(jobId); job = l.value; origin = l.origin; error = nil }698        catch { if job == nil, !(error is CancellationError) { self.error = nextMessage(error) } }699    }700701    private func cancel() async {702        do {703            switch try await model.next.lab.cancel(jobId) {704            case .cancelled(let j): job = j705            case .notCancellable: alert = "Ce moteur de la version 1.0 ne peut pas être annulé."706            case .notRunning: await load()707            }708        } catch { alert = nextMessage(error) }709    }710711    private func review(_ job: VQQuantJob) async {712        do {713            let id = try await model.next.studio.review(VQReview.Target(type: .quantJob, id: job.id), projectId: job.projectId)714            model.router.open(.review(id), compact: sizeClass == .compact)715        } catch { alert = nextMessage(error) }716    }717718    private func header(_ job: VQQuantJob) -> some View {719        HStack(spacing: 8) {720            JobStatusBadge.lab(job.status).accessibilityIdentifier("quant-status")721            if case .cache(let t)? = origin { FreshnessBadge(freshness: .cached(savedAt: t), compact: true) }722            if let v = job.engineVersion { Tag(text: "v\(v)") }723            Spacer()724            if let d = job.durationMs { Text(VQFormat.duration(ms: d)).font(.mono(.caption)).foregroundStyle(Theme.textSecondary) }725        }726    }727728    private func running(_ job: VQQuantJob) -> some View {729        VStack(alignment: .leading, spacing: 8) {730            if let p = job.progress {731                ProgressView(value: min(1, max(0, p))) { Text("Calcul en cours sur le serveur") } currentValueLabel: { Text(VQFormat.percent(p, decimals: 0)) }732                    .tint(Theme.orange).accessibilityIdentifier("job-progress")733            } else {734                HStack(spacing: 10) { ProgressView(); Text("Calcul en cours sur le serveur…").font(.footnote).foregroundStyle(Theme.textSecondary) }735            }736            if let s = job.startedAt { Text("Lancé \(Fmt.relative(s)). Vous pouvez quitter cet écran : le calcul continue.").font(.caption).foregroundStyle(Theme.textSecondary) }737        }738        .paperCard()739    }740741    /// Everything needed to reproduce the number: engine, exact parameters, identifier, timestamps.742    private func reproducibility(_ job: VQQuantJob) -> some View {743        DisclosureGroup("Exécution et paramètres") {744            VStack(spacing: 6) {745                KeyValueRow(key: "Moteur", value: job.tool)746                ForEach(job.params.keys.sorted(), id: \.self) { k in747                    let v = job.params[k]!748                    KeyValueRow(key: Fmt.label(k), value: v.displayString ?? v.arrayValue.map { a in a.compactMap(\.displayString).joined(separator: ", ") }.flatMap { $0.isEmpty ? nil : $0 } ?? v.text())749                }750                if let s = job.startedAt { KeyValueRow(key: "Lancé", value: Fmt.dateTime(s)) }751                if let f = job.finishedAt { KeyValueRow(key: "Terminé", value: Fmt.dateTime(f)) }752                KeyValueRow(key: "Identifiant", value: job.id)753            }754            .textSelection(.enabled).padding(.top, 6)755        }756        .font(.subheadline)757        .paperCard(padding: 12)758    }759760    static func exportJSON(_ job: VQQuantJob) -> String {761        let doc: VQJSON = ["id": .string(job.id), "tool": .string(job.tool), "params": .object(job.params), "startedAt": VQJSON(job.startedAt.map { ISO8601.string($0) }),762                           "finishedAt": VQJSON(job.finishedAt.map { ISO8601.string($0) }), "result": job.result ?? .null, "code": VQJSON(job.code)]763        return doc.text(pretty: true)764    }765766    private func exportImage(_ lab: VQLabResult) {767        var o = LabResultView.Options(); o.expanded = true768        guard let data = VQExport.png(LabResultView(lab, options: o), width: 760, colorScheme: .light, theme: model.preferences.theme) else { alert = "Image impossible à produire."; return }769        write(data, "VQuant-\(lab.engine)-\(jobId.prefix(8)).png")770    }771    private func exportPDF(_ lab: VQLabResult) {772        var o = LabResultView.Options(); o.expanded = true773        guard let data = VQExport.pdf(LabResultView(lab, options: o), width: 760, colorScheme: .light, theme: model.preferences.theme) else { alert = "PDF impossible à produire."; return }774        write(data, "VQuant-\(lab.engine)-\(jobId.prefix(8)).pdf")775    }776    private func write(_ data: Data, _ name: String) {777        let url = FileManager.default.temporaryDirectory.appendingPathComponent(name)778        do { try data.write(to: url, options: .atomic); share = .init(url: url) } catch { alert = "Fichier impossible à écrire." }779    }780}781
Files main
Menu

Theme