Repository Public
1//2// VQuant iOS3// File: VQuant/Next/WorkspaceViews.swift4// Description: Workspaces on the iPad: a synced `workspace` object's layout tree rendered with native split5// containers (rows and columns, draggable dividers, two-, three-pane layouts and deeper), each leaf a6// panel — chart, watchlist, quote, statements, research, quant, portfolio, note. The same object opens7// on the web and the Mac; keys this app does not use are preserved.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11//1213import SwiftUI14import VQuantKit15import VQuantUI1617enum WorkspaceTemplates {18 struct Template: Identifiable, Sendable { var id: String; var name: String; var detail: String; var systemImage: String; var build: @Sendable (String) -> VQWorkspace }1920 private static func panel(_ t: KitPanel.PanelType, _ title: String, _ config: VQJSONObject = [:]) -> KitPanel { KitPanel(type: t, title: title, config: config) }21 /// Sizes are percentages of the split (sum 100): the web client's convention.22 private static func split(_ d: VQLayoutNode.Direction, _ sizes: [Double], _ children: [VQLayoutNode]) -> VQLayoutNode { .split(d, sizes: sizes, children: children) }2324 static let all: [Template] = [25 Template(id: "two", name: "Graphique et liste", detail: "Deux panneaux : le graphique suit le symbole choisi dans la liste.", systemImage: "rectangle.split.2x1") { name in26 var w = VQWorkspace(name: name, icon: "chart", layout: split(.row, [68, 32], [.panel("chart"), .panel("watch")]),27 panels: ["chart": panel(.chart, "Graphique"), "watch": panel(.watchlist, "Liste de suivi")])28 w.raw["activeSymbol"] = "AAPL"; w.raw["template"] = "ios-two"29 return w30 },31 Template(id: "three", name: "Poste d’analyse", detail: "Trois panneaux : liste, graphique, cotation et états financiers.", systemImage: "rectangle.split.3x1") { name in32 var w = VQWorkspace(name: name, icon: "terminal",33 layout: split(.row, [22, 50, 28], [.panel("watch"), .panel("chart"), split(.column, [38, 62], [.panel("quote"), .panel("statements")])]),34 panels: ["watch": panel(.watchlist, "Liste de suivi"), "chart": panel(.chart, "Graphique"), "quote": panel(.quote, "Cotation"), "statements": panel(.statements, "États financiers")])35 w.raw["activeSymbol"] = "AAPL"; w.raw["template"] = "ios-three"36 return w37 },38 Template(id: "research", name: "Poste de recherche", detail: "L’agent, une note et le portefeuille côte à côte.", systemImage: "sparkles.rectangle.stack") { name in39 var w = VQWorkspace(name: name, icon: "research",40 layout: split(.row, [45, 55], [.panel("chat"), split(.column, [50, 50], [.panel("note"), split(.row, [50, 50], [.panel("portfolio"), .panel("quant")])])]),41 panels: ["chat": panel(.chat, "Recherche"), "note": panel(.note, "Note"), "portfolio": panel(.portfolio, "Portefeuille"), "quant": panel(.quant, "Quant Lab")])42 w.raw["template"] = "ios-research"43 return w44 },45 ]46}4748struct WorkspacesView: View {49 @Environment(AppModel.self) private var model50 @State private var creating = false51 @State private var name = ""52 @State private var pendingDelete: VQObject<VQWorkspace>?5354 var body: some View {55 List {56 Section {57 let list = model.next.sync.workspaces.items.sorted { $0.updatedAt > $1.updatedAt }58 if list.isEmpty { Text(model.next.sync.workspaces.isLoaded ? "Aucun espace de travail." : "Chargement…").foregroundStyle(Theme.textSecondary) }59 ForEach(list) { w in60 RouteLink(.workspace(w.id)) {61 VStack(alignment: .leading, spacing: 2) {62 Text(w.data.name.isEmpty ? "Sans nom" : w.data.name).font(.body.weight(.medium))63 Text("\(w.data.layout.panelIds.count) panneau\(w.data.layout.panelIds.count > 1 ? "x" : "") · \(Fmt.relative(w.updatedAt))").font(.caption).foregroundStyle(Theme.textSecondary)64 }65 }66 .accessibilityIdentifier("workspace-\(w.id)")67 .swipeActions { Button("Supprimer", role: .destructive) { pendingDelete = w } }68 }69 } footer: { Text("Les espaces de travail sont synchronisés avec le web et le Mac : la disposition faite sur un appareil s’ouvre sur les autres.").foregroundStyle(Theme.textSecondary) }70 Section("Créer depuis un modèle") {71 ForEach(WorkspaceTemplates.all) { t in72 Button {73 Task {74 let id = model.next.sync.newId()75 await model.next.sync.workspaces.save(t.build(model.next.sync.objectPrefix == "ios-test-" ? "ios-test — \(t.name)" : t.name), id: id)76 model.router.open(.workspace(id), compact: UIDevice.current.userInterfaceIdiom == .phone)77 }78 } label: {79 Label { VStack(alignment: .leading, spacing: 2) { Text(t.name).foregroundStyle(Color.primary); Text(t.detail).font(.caption).foregroundStyle(Theme.textSecondary) } } icon: { Image(systemName: t.systemImage) }80 }81 .accessibilityIdentifier("workspace-template-\(t.id)")82 }83 }84 }85 .navigationTitle("Espaces de travail")86 .refreshable { await model.next.sync.syncNow() }87 .confirmationDialog("Supprimer « \(pendingDelete?.data.name ?? "") » ?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), titleVisibility: .visible) {88 Button("Supprimer l’espace de travail", role: .destructive) { if let w = pendingDelete { Task { await model.next.sync.workspaces.delete(w.id) } } }89 } message: { Text("Il est effacé du compte, sur tous vos appareils.") }90 .accessibilityIdentifier("workspaces")91 }92}9394/// Layout arithmetic of a split, kept apart from the views so it can be tested.95enum SplitMath {96 static let minimumFraction = 0.1297 /// Moves the divider after child `index` by `delta` (a fraction of the split's length), keeping both neighbours98 /// above the minimum and the total unchanged.99 static func moved(_ fractions: [Double], divider index: Int, by delta: Double) -> [Double] {100 guard index >= 0, index + 1 < fractions.count else { return fractions }101 var f = fractions102 let pair = f[index] + f[index + 1]103 let lo = min(minimumFraction, pair / 2)104 let a = min(max(f[index] + delta, lo), pair - lo)105 f[index] = a; f[index + 1] = pair - a106 return f107 }108 /// Fractions as the percentages the web client stores (one decimal, sum 100).109 static func percentages(_ fractions: [Double]) -> [Double] {110 let total = fractions.reduce(0, +)111 guard total > 0 else { return fractions }112 var p = fractions.map { ($0 / total * 1000).rounded() / 10 }113 if let last = p.indices.last { p[last] = ((100 - p.dropLast().reduce(0, +)) * 10).rounded() / 10 }114 return p115 }116 /// The node at `path` (child indices from the root) with its sizes replaced.117 static func setting(_ sizes: [Double], at path: [Int], in node: VQLayoutNode) -> VQLayoutNode {118 var n = node119 guard let first = path.first else { n.sizes = sizes; return n }120 var children = n.children121 guard children.indices.contains(first) else { return n }122 children[first] = setting(sizes, at: Array(path.dropFirst()), in: children[first])123 n.children = children124 return n125 }126}127128struct WorkspaceView: View {129 let workspaceId: String130 @Environment(AppModel.self) private var model131 @Environment(\.horizontalSizeClass) private var sizeClass132 @State private var renaming = false133 @State private var name = ""134 @State private var symbolEntry = ""135 @State private var askingSymbol = false136137 private var object: VQObject<VQWorkspace>? { model.next.sync.workspaces[workspaceId] }138 private var activeSymbol: String? { object?.data.raw["activeSymbol"]?.stringValue.flatMap(WatchlistFile.normalise) }139140 var body: some View {141 Group {142 if let w = object {143 GeometryReader { geo in144 if w.data.layout.panelIds.isEmpty {145 ContentUnavailableView { Label("Espace de travail vide", systemImage: "rectangle.dashed") } description: { Text("Ajoutez un panneau avec le bouton +.") }146 } else if geo.size.width < 620 {147 // Narrow window (iPhone, Slide Over, a small Stage Manager window): the panels one under the other.148 ScrollView {149 VStack(spacing: 10) {150 ForEach(w.data.layout.panelIds, id: \.self) { id in panelView(id, w).frame(height: 380) }151 }152 .padding(10)153 }154 } else {155 LayoutNodeView(node: w.data.layout, path: [], panel: { id in AnyView(panelView(id, w)) }) { path, fractions in156 Task { await model.next.sync.workspaces.update(workspaceId) { $0.layout = SplitMath.setting(SplitMath.percentages(fractions), at: path, in: $0.layout) } }157 }158 .padding(8)159 }160 }161 } else if model.next.sync.workspaces.isLoaded {162 StateView(kind: .empty, title: "Espace de travail introuvable", message: "Il a peut-être été supprimé sur un autre appareil.", systemImage: "rectangle.split.3x1")163 } else { StateView(kind: .loading, title: "Chargement…") }164 }165 .background(Theme.background)166 .navigationTitle(object?.data.name ?? "Espace de travail").navigationBarTitleDisplayMode(.inline)167 .toolbar {168 ToolbarItem(placement: .principal) {169 Button { symbolEntry = activeSymbol ?? ""; askingSymbol = true } label: {170 HStack(spacing: 6) { Image(systemName: "link"); Text(activeSymbol ?? "Symbole").font(.mono(.subheadline, weight: .semibold)) }171 }172 .accessibilityLabel("Symbole actif : \(activeSymbol ?? "aucun"). Modifier")173 .accessibilityIdentifier("workspace-symbol")174 }175 ToolbarItemGroup(placement: .primaryAction) {176 if model.next.sync.workspaces.pendingIDs.contains(workspaceId) { Image(systemName: "arrow.up.circle").foregroundStyle(Theme.orange).accessibilityLabel("En attente d’envoi") }177 Menu {178 Section("Ajouter un panneau") {179 ForEach(PanelCatalog.addable, id: \.type) { p in180 Button { add(p.type, p.title) } label: { Label(p.title, systemImage: p.systemImage) }181 }182 }183 Button { name = object?.data.name ?? ""; renaming = true } label: { Label("Renommer", systemImage: "pencil") }184 OpenWindowButton(route: .workspace(workspaceId))185 } label: { Label("Panneaux", systemImage: "plus.rectangle.on.rectangle") }186 .accessibilityIdentifier("workspace-add")187 }188 }189 .alert("Renommer", isPresented: $renaming) {190 TextField("Nom", text: $name)191 Button("Enregistrer") { let n = name; Task { await model.next.sync.workspaces.update(workspaceId) { $0.name = n } } }192 Button("Annuler", role: .cancel) {}193 }194 .alert("Symbole actif", isPresented: $askingSymbol) {195 TextField("AAPL", text: $symbolEntry).textInputAutocapitalization(.characters)196 Button("Appliquer") { if let s = WatchlistFile.normalise(symbolEntry) { setActive(s) } }197 Button("Annuler", role: .cancel) {}198 } message: { Text("Les panneaux liés (graphique, cotation, états financiers) suivent ce symbole.") }199 .symbolDrop { setActive($0) }200 .accessibilityElement(children: .contain).accessibilityIdentifier("workspace")201 }202203 private func setActive(_ s: String) {204 Task { await model.next.sync.workspaces.update(workspaceId) { $0.raw["activeSymbol"] = .string(s) }; await model.market.refreshQuotes([s]) }205 }206 private func add(_ type: KitPanel.PanelType, _ title: String) {207 let id = "p" + String(VQObjectID.make().prefix(8))208 Task { await model.next.sync.workspaces.update(workspaceId) { w in209 let wide = w.layout.kind == .split && w.layout.direction == .row && w.layout.children.count >= 3210 w.addPanel(KitPanel(type: type, title: title), id: id, direction: wide ? .column : .row)211 } }212 }213 private func remove(_ id: String) { Task { await model.next.sync.workspaces.update(workspaceId) { $0.removePanel(id) } } }214215 @ViewBuilder private func panelView(_ id: String, _ w: VQObject<VQWorkspace>) -> some View {216 if let p = w.data.panels[id] {217 // `config.symbol` is the panel's own symbol; a linked panel (the default) follows the workspace's.218 let linked = p.config["linked"]?.boolValue ?? true219 let symbol = (linked ? activeSymbol : nil) ?? p.config["symbol"]?.stringValue.flatMap(WatchlistFile.normalise) ?? activeSymbol220 PanelChrome(title: p.title ?? PanelCatalog.title(p.type), type: p.type, symbol: PanelCatalog.usesSymbol(p.type) ? symbol : nil, linked: linked, onRemove: { remove(id) }, onToggleLink: {221 Task { await model.next.sync.workspaces.update(workspaceId) { ws in222 var panels = ws.panels223 guard var q = panels[id] else { return }224 var c = q.config; c["linked"] = .bool(!linked); if linked, let s = symbol { c["symbol"] = .string(s) }225 q.config = c; panels[id] = q; ws.panels = panels226 } }227 }) {228 PanelContent(panel: p, panelId: id, symbol: symbol, workspaceId: workspaceId, onPick: { setActive($0) })229 }230 .accessibilityElement(children: .contain).accessibilityIdentifier("panel-\(p.type.rawValue)")231 } else {232 Text("Panneau « \(id) » absent de l’espace de travail.").font(.caption).foregroundStyle(Theme.textSecondary).frame(maxWidth: .infinity, maxHeight: .infinity)233 }234 }235}236237/// A node of the layout tree: a panel, or a split whose children are separated by draggable dividers.238struct LayoutNodeView: View {239 let node: VQLayoutNode240 let path: [Int]241 let panel: (String) -> AnyView242 /// Called when a drag ends, with the split's path and its new fractions.243 let onResize: ([Int], [Double]) -> Void244 @State private var live: [Double]?245 @State private var dragStart: [Double]?246247 static let dividerThickness: CGFloat = 10248249 var body: some View {250 switch node.kind {251 case .panel: if let id = node.panelId { panel(id) }252 case .split:253 GeometryReader { geo in254 let row = node.direction != .column255 let children = node.children256 let fractions = live ?? node.fractions257 let gaps = CGFloat(max(0, children.count - 1)) * Self.dividerThickness258 let length = max(1, (row ? geo.size.width : geo.size.height) - gaps)259 let layout = row ? AnyLayout(HStackLayout(spacing: 0)) : AnyLayout(VStackLayout(spacing: 0))260 layout {261 ForEach(Array(children.enumerated()), id: \.offset) { i, child in262 LayoutNodeView(node: child, path: path + [i], panel: panel, onResize: onResize)263 .frame(width: row ? length * CGFloat(i < fractions.count ? fractions[i] : 0) : nil, height: row ? nil : length * CGFloat(i < fractions.count ? fractions[i] : 0))264 if i < children.count - 1 { divider(i, row: row, length: length, fractions: fractions) }265 }266 }267 }268 case nil:269 Color.clear270 }271 }272273 private func divider(_ i: Int, row: Bool, length: CGFloat, fractions: [Double]) -> some View {274 ZStack {275 Color.clear276 Capsule().fill(live == nil ? Theme.border : Theme.orange).frame(width: row ? 4 : 36, height: row ? 36 : 4)277 }278 .frame(width: row ? Self.dividerThickness : nil, height: row ? nil : Self.dividerThickness)279 .contentShape(Rectangle().inset(by: -8))280 .hoverEffect(.highlight)281 .gesture(DragGesture(minimumDistance: 1, coordinateSpace: .global)282 .onChanged { v in283 let start = dragStart ?? fractions284 if dragStart == nil { dragStart = start }285 live = SplitMath.moved(start, divider: i, by: Double((row ? v.translation.width : v.translation.height) / length))286 }287 .onEnded { _ in288 if let f = live { onResize(path, f) }289 dragStart = nil290 // keep showing the dragged sizes until the saved object comes back with them291 DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { live = nil }292 })293 .accessibilityElement()294 .accessibilityLabel("Séparateur \(i + 1)")295 .accessibilityValue("\(Int((fractions.prefix(i + 1).reduce(0, +) * 100).rounded())) %")296 .accessibilityAdjustableAction { direction in297 let f = SplitMath.moved(fractions, divider: i, by: direction == .increment ? 0.05 : -0.05)298 onResize(path, f)299 }300 .accessibilityIdentifier("divider-\(path.map(String.init).joined(separator: "-"))-\(i)")301 }302}303304enum PanelCatalog {305 static let addable: [(type: KitPanel.PanelType, title: String, systemImage: String)] = [306 (.chart, "Graphique", "chart.xyaxis.line"), (.watchlist, "Liste de suivi", "star"), (.quote, "Cotation", "dollarsign.circle"), (.statements, "États financiers", "tablecells"),307 (.chat, "Recherche", "sparkles"), (.quant, "Quant Lab", "function"), (.portfolio, "Portefeuille", "briefcase"), (.note, "Note", "note.text"),308 ]309 static func title(_ t: VQOpen<KitPanel.PanelType>) -> String { addable.first { $0.type == t.known }?.title ?? Fmt.label(t.rawValue) }310 static func icon(_ t: VQOpen<KitPanel.PanelType>) -> String { addable.first { $0.type == t.known }?.systemImage ?? "square.dashed" }311 static func usesSymbol(_ t: VQOpen<KitPanel.PanelType>) -> Bool { [.chart, .quote, .statements].contains(t.known) }312}313314struct PanelChrome<Content: View>: View {315 var title: String316 var type: VQOpen<KitPanel.PanelType>317 var symbol: String?318 var linked: Bool319 var onRemove: () -> Void320 var onToggleLink: () -> Void321 @ViewBuilder var content: Content322323 var body: some View {324 VStack(spacing: 0) {325 HStack(spacing: 6) {326 Image(systemName: PanelCatalog.icon(type)).font(.caption).foregroundStyle(Theme.orange)327 Text(title.uppercased()).font(.caption2.weight(.semibold)).tracking(0.8).foregroundStyle(Theme.textSecondary).lineLimit(1)328 if let symbol { Text(symbol).font(.mono(.caption, weight: .semibold)).draggableSymbol(symbol) }329 Spacer(minLength: 4)330 Menu {331 if symbol != nil { Button(action: onToggleLink) { Label(linked ? "Détacher du symbole actif" : "Lier au symbole actif", systemImage: linked ? "link.badge.plus" : "link") } }332 Button(role: .destructive, action: onRemove) { Label("Retirer le panneau", systemImage: "xmark.rectangle") }333 } label: { Image(systemName: "ellipsis").frame(width: 44, height: 30).contentShape(Rectangle()) }334 .accessibilityLabel("Actions du panneau \(title)")335 }336 .padding(.leading, 10).frame(height: 32)337 .background(Theme.surface2.opacity(0.6))338 Divider()339 content.frame(maxWidth: .infinity, maxHeight: .infinity).clipped()340 }341 .background(Theme.surface)342 .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))343 .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Theme.border, lineWidth: 1))344 }345}346347struct PanelContent: View {348 let panel: KitPanel349 let panelId: String350 let symbol: String?351 let workspaceId: String352 var onPick: (String) -> Void353 @Environment(AppModel.self) private var model354355 var body: some View {356 switch panel.type.known {357 case .chart:358 if let symbol { ChartWorkstation(symbol: symbol, compact: true).id(symbol) } else { needSymbol }359 case .watchlist:360 ScrollView {361 LazyVStack(spacing: 0) {362 ForEach(model.watchlist.symbols, id: \.self) { s in363 Button { onPick(s) } label: {364 // a narrow pane: symbol, price and change on short lines that never wrap365 let q = model.market.quotes[s]?.value366 HStack(spacing: 6) {367 Text(s.replacingOccurrences(of: "^", with: "")).font(.subheadline.weight(.semibold)).lineLimit(1)368 Spacer(minLength: 4)369 VStack(alignment: .trailing, spacing: 1) {370 Text(Fmt.price(q?.price)).font(.mono(.footnote, weight: .medium)).lineLimit(1).minimumScaleFactor(0.7)371 ChangeLabel(percent: q?.changePercent, font: .caption2).lineLimit(1).fixedSize()372 }373 }374 .padding(.horizontal, 10).frame(minHeight: 44).contentShape(Rectangle())375 .background(s == symbol ? Theme.surface2 : .clear)376 .accessibilityElement(children: .combine)377 }378 .buttonStyle(.plain).draggableSymbol(s).hoverEffect(.highlight)379 .accessibilityIdentifier("panel-watch-\(s)")380 Divider()381 }382 if model.watchlist.symbols.isEmpty { Text("Liste de suivi vide.").font(.caption).foregroundStyle(Theme.textSecondary).padding() }383 }384 }385 .symbolDrop { model.watchlist.add($0, name: nil) }386 .task { await model.market.refreshQuotes(model.watchlist.symbols) }387 case .quote:388 if let symbol { QuotePanel(symbol: symbol) } else { needSymbol }389 case .statements:390 if let symbol { StatementsPanel(symbol: symbol).id(symbol) } else { needSymbol }391 case .chat:392 ScrollView {393 VStack(alignment: .leading, spacing: 10) {394 Button { model.router.compose(mode: .research, draft: symbol.map { "Étudie \($0) : " } ?? "") } label: { Label("Nouvelle recherche", systemImage: "sparkles").frame(maxWidth: .infinity) }395 .buttonStyle(EmberButtonStyle()).accessibilityIdentifier("panel-ask")396 ForEach(model.research.running) { g in RouteLink(.run(g.id)) { GenerationRow(generation: g) }.buttonStyle(.plain); Divider() }397 ForEach((model.next.hub.sessions.value?.sessions ?? []).prefix(6)) { s in RouteLink(.researchSession(s.id)) { StudyRow(session: s) }.buttonStyle(.plain); Divider() }398 }399 .padding(10)400 }401 case .quant:402 ScrollView {403 VStack(alignment: .leading, spacing: 8) {404 if let symbol {405 RouteLink(.quantTool("volatility_lab|\(symbol)")) { Label("Volatilité de \(symbol)", systemImage: "waveform.path.ecg").font(.subheadline) }406 RouteLink(.quantTool("risk_lab|\(symbol)")) { Label("Risque de \(symbol)", systemImage: "exclamationmark.shield").font(.subheadline) }407 Divider()408 }409 ForEach((model.next.lab.jobs.value?.jobs ?? []).prefix(8)) { j in RouteLink(.quantJob(j.id)) { LabJobRow(job: j) }.buttonStyle(.plain); Divider() }410 }411 .padding(10)412 }413 .task { if model.next.lab.catalog.value == nil { await model.next.lab.refreshCatalog() } }414 case .portfolio:415 let lines = PortfolioMath.lines(positions: model.positions, quotes: model.market.quotes.mapValues(\.value))416 ScrollView {417 VStack(alignment: .leading, spacing: 6) {418 let t = PortfolioMath.totals(lines)419 Text(Fmt.money(t.value)).font(.mono(.title3, weight: .medium)).privacySensitive()420 ChangeLabel(percent: t.dayGainPercent.map { $0 * 100 }, absolute: t.dayGain, font: .caption)421 ForEach(lines) { l in Button { onPick(l.symbol) } label: { HoldingRow(line: l) }.buttonStyle(.plain); Divider() }422 if lines.isEmpty { Text("Aucune position.").font(.caption).foregroundStyle(Theme.textSecondary) }423 }424 .padding(10)425 }426 case .note:427 NotePanel(panel: panel, panelId: panelId, workspaceId: workspaceId)428 default:429 VStack(spacing: 6) {430 Image(systemName: "square.dashed").font(.title2).foregroundStyle(Theme.textSecondary)431 Text("Le panneau « \(panel.type.rawValue) » n’a pas encore de rendu natif sur iPad. Il est conservé tel quel et s’affiche sur le web.").font(.caption).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center)432 }433 .padding()434 }435 }436 private var needSymbol: some View { Text("Choisissez un symbole actif (en haut), ou glissez un titre ici.").font(.caption).foregroundStyle(Theme.textSecondary).padding() }437}438439struct QuotePanel: View {440 let symbol: String441 @Environment(AppModel.self) private var model442 var body: some View {443 ScrollView {444 VStack(alignment: .leading, spacing: 6) {445 if let q = model.market.quotes[symbol]?.value {446 if let n = q.name { Text(n).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(1) }447 Text(Fmt.price(q.price)).font(.mono(.title, weight: .medium)).minimumScaleFactor(0.6).lineLimit(1)448 ChangeLabel(percent: q.changePercent, absolute: q.change, font: .footnote)449 if let f = model.market.quoteFreshness[symbol] { ProvenanceChip(f) }450 Divider()451 KeyValueRow(key: "Ouverture", value: Fmt.price(q.open))452 KeyValueRow(key: "Séance", value: "\(Fmt.price(q.dayLow)) – \(Fmt.price(q.dayHigh))")453 KeyValueRow(key: "52 semaines", value: "\(Fmt.price(q.yearLow)) – \(Fmt.price(q.yearHigh))")454 KeyValueRow(key: "Volume", value: Fmt.compact(q.volume))455 KeyValueRow(key: "Capitalisation", value: Fmt.compact(q.marketCap))456 } else if let e = model.market.quoteErrors[symbol] { Text(e.message).font(.caption).foregroundStyle(Theme.down) } else { ProgressView() }457 }458 .padding(10).frame(maxWidth: .infinity, alignment: .leading)459 }460 .task(id: symbol) { await model.market.refreshQuotes([symbol]) }461 }462}463464struct StatementsPanel: View {465 let symbol: String466 @Environment(AppModel.self) private var model467 @State private var state = NextState<VQStatements>()468 @State private var table = "income"469 var body: some View {470 VStack(alignment: .leading, spacing: 6) {471 Picker("Tableau", selection: $table) { Text("Résultat").tag("income"); Text("Bilan").tag("balance"); Text("Flux").tag("cashflow"); Text("Ratios").tag("ratios") }.pickerStyle(.segmented)472 ScrollView {473 if let s = state.value { StatementGrid(statements: s, rows: StatementsView.rows(s, table), compact: true) { _ in } }474 else if let e = state.error { Text(e).font(.caption).foregroundStyle(Theme.down) } else { ProgressView() }475 }476 }477 .padding(8)478 .task { state.begin(); do { state.succeed(try await model.next.terminal.statements(symbol, period: "annual", limit: 5)) } catch { state.fail(error) } }479 }480}481482/// A note panel: the text lives in the panel's `config.text` (it travels with the workspace), or shows the synced483/// note `config.noteId` when the panel points at one.484struct NotePanel: View {485 let panel: KitPanel486 let panelId: String487 let workspaceId: String488 @Environment(AppModel.self) private var model489 @State private var text = ""490 @State private var dirty = false491492 var body: some View {493 if let id = panel.config["noteId"]?.stringValue, let n = model.next.sync.notes[id] {494 ScrollView { VStack(alignment: .leading, spacing: 6) { Text(n.data.title).font(.serif(.headline)); MarkdownView(text: n.data.body); RouteLink(.note(id)) { Label("Ouvrir la note", systemImage: "arrow.up.right.square").font(.caption) } }.padding(10) }495 } else {496 TextEditor(text: $text).font(.callout).scrollContentBackground(.hidden).padding(6)497 .accessibilityLabel("Texte de la note du panneau").accessibilityIdentifier("panel-note-text")498 .onAppear { text = panel.config["text"]?.stringValue ?? "" }499 .onChange(of: text) { _, new in dirty = new != (panel.config["text"]?.stringValue ?? "") }500 .task(id: text) {501 // saved a moment after typing stops: one write per pause, not one per keystroke502 guard dirty else { return }503 try? await Task.sleep(for: .seconds(1.2))504 if Task.isCancelled { return }505 let t = text506 await model.next.sync.workspaces.update(workspaceId) { ws in507 var panels = ws.panels508 guard var q = panels[panelId] else { return }509 var c = q.config; c["text"] = .string(t); q.config = c; panels[panelId] = q; ws.panels = panels510 }511 dirty = false512 }513 }514 }515}516