SPB Git

Repository Public

ChartViews.swift 31.9 KB 538 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Charting/ChartViews.swift3// Description: The chart with its controls (interval, range, style, indicators, comparison, drawing tools, provenance, ask the agent, export), as a section of the main window and as a detached window.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910struct ChartPane: View {11    let app: AppEnvironment12    @Bindable var chart: ChartModel13    /// A ticker dropped on the chart (without ⌥) or picked for it: the owner decides what "this chart's symbol" means.14    var onSymbol: (String) -> Void15    /// Hands the prepared question to a Research composer.16    var onAsk: (AskDraft) -> Void17    var onDetach: (() -> Void)?18    @State private var showCompare = false19    @State private var showProvenance = false20    @State private var dropTargeted = false21    @State private var sync: ChartSync?22    @Environment(\.undoManager) private var undo2324    var body: some View {25        VStack(spacing: 0) {26            controls27            Rectangle().fill(VQTokens.Palette.line).frame(height: 1)28            if let e = chart.error, chart.bars.isEmpty {29                EmptyState(symbol: "chart.xyaxis.line", title: "No chart for \(chart.symbol)", detail: e)30            } else {31                HStack(spacing: 0) {32                    ChartToolPalette(chart: chart, undo: undo)33                    Rectangle().fill(VQTokens.Palette.line).frame(width: 1)34                    ZStack(alignment: .topLeading) {35                        ChartCanvas(model: chart, settings: app.settings)36                        ChartInteraction(model: chart)37                        ChartLegend(chart: chart, settings: app.settings).padding(.leading, 8).padding(.top, 6).allowsHitTesting(false)38                        ChartNoteEditor(chart: chart, undo: undo)39                        if chart.loading, chart.bars.isEmpty { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }40                        if dropTargeted {41                            RoundedRectangle(cornerRadius: VQTokens.Radius.sm).strokeBorder(VQTokens.Palette.accent, lineWidth: 2).padding(3).allowsHitTesting(false)42                            Text("Drop to chart this symbol · hold ⌥ to compare").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text1)43                                .padding(.horizontal, 10).padding(.vertical, 5).background(.regularMaterial, in: Capsule())44                                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom).padding(.bottom, 36).allowsHitTesting(false)45                        }46                    }47                    .background(ChartColors.background)48                    .dropDestination(for: String.self) { items, _ in drop(items) } isTargeted: { dropTargeted = $0 }49                }50            }51            Rectangle().fill(VQTokens.Palette.line).frame(height: 1)52            footer53        }54        .background(VQTokens.Palette.ink0)55        .onAppear {56            // DEBUG `-VQXChartNoSync 1` (UI tests): the chart is not bound to the account, nothing is written57            if sync == nil, app.options.extra["ChartNoSync"] != "1" { sync = ChartSync(app: app, chart: chart) }58            sync?.refresh()59            if chart.bars.isEmpty { chart.reload() }60            chart.startRefreshing()61        }62        .onDisappear { sync?.flush(); chart.stopRefreshing() }63        // the account's chart objects changed (another device, the first pull, the echo of a save), or the symbol did64        .onChange(of: app.sync.active?.charts.items) { _, _ in sync?.refresh() }65        .onChange(of: chart.symbol) { _, _ in sync?.refresh() }66        #if DEBUG67        .task { await ChartDebug.applyLaunchOptions(app: app, chart: chart, undo: undo, showProvenance: { showProvenance = true }, ask: ask) }68        #endif69    }7071    /// A ticker dragged from a watchlist row (plain text): the chart switches to it; with ⌥ held it is compared.72    private func drop(_ items: [String]) -> Bool {73        guard let s = items.lazy.compactMap({ Watchlist.normalize($0.trimmingCharacters(in: .whitespacesAndNewlines)) }).first else { return false }74        if NSEvent.modifierFlags.contains(.option) {75            guard s != chart.symbol else { return false }76            chart.addCompare(s)77        } else { onSymbol(s) }78        return true79    }8081    private func ask() { if let d = ChartAsk.draft(chart) { onAsk(d) } }8283    private var controls: some View {84        VStack(spacing: 6) {85            HStack(spacing: 10) {86                Text(chart.symbol).font(.system(size: 17, weight: .semibold, design: .monospaced)).foregroundStyle(VQTokens.Palette.text1).fixedSize()87                    .draggable(chart.symbol).help("Drag this ticker to another chart or to a watchlist")88                if let e = app.market.entry(chart.symbol) {89                    Text(Fmt.price(e.quote.price)).font(VQTokens.Typography.numMd.font).foregroundStyle(VQTokens.Palette.text1).fixedSize()90                    ChangeText(value: e.quote.changePercent, settings: app.settings).font(VQTokens.Typography.numSm.font).fixedSize()91                    FreshnessBadge(freshness: e.freshness, compact: true).fixedSize()92                }93                Spacer(minLength: 4)94                Group {95                    ChartSegment(label: "Chart type", options: ChartStyle.allCases.map { ($0, $0.title, $0.symbol) }, selection: chart.style, prefix: "chart.style") { chart.style = $0 }96                    Menu {97                        Toggle("SMA 20", isOn: $chart.indicators.sma20); Toggle("SMA 50", isOn: $chart.indicators.sma50); Toggle("SMA 200", isOn: $chart.indicators.sma200)98                        Toggle("EMA 20", isOn: $chart.indicators.ema20); Toggle("Bollinger bands (20, 2)", isOn: $chart.indicators.bollinger)99                        Divider()100                        Toggle("Volume", isOn: $chart.indicators.volume); Toggle("RSI (14)", isOn: $chart.indicators.rsi); Toggle("MACD (12, 26, 9)", isOn: $chart.indicators.macd)101                        Divider()102                        Toggle("Logarithmic scale", isOn: $chart.logScale)103                        Picker("Price adjustment", selection: Binding(get: { chart.adjust }, set: { chart.setAdjust($0) })) {104                            ForEach(ChartModel.adjustments, id: \.self) { Text(ChartProvenance.adjustName($0)).tag($0) }105                        }106                        Toggle("Link crosshair with other charts", isOn: $chart.linked)107                        if chart.foreignIndicators > 0 {108                            Divider()109                            Text("\(chart.foreignIndicators) indicator\(chart.foreignIndicators == 1 ? "" : "s") set on another device \(chart.foreignIndicators == 1 ? "is" : "are") kept but not drawn here")110                        }111                        if let layouts = sync?.layouts, !layouts.isEmpty {112                            Divider()113                            Menu("Saved layouts") {114                                ForEach(layouts) { o in Button("\(o.data.string("name") ?? o.id) · \(o.data.symbol)") { sync?.applyLayout(o) } }115                            }116                        }117                    } label: { Text("Indicators") }.fixedSize().help("Indicators are computed on this Mac from the bars shown").accessibilityIdentifier("chart.indicators")118                    Button("Compare") { showCompare = true }119                        .popover(isPresented: $showCompare, arrowEdge: .bottom) { ComparePopover(app: app, chart: chart).vqTheme(app.vqTheme) }120                        .help("Overlay other symbols as percentage change").accessibilityIdentifier("chart.compare")121                    Menu {122                        Button("PNG Image…") { ChartExport.png(chart, app.settings) }123                        Button("PDF Document…") { ChartExport.pdf(chart, app.settings) }124                        Button("CSV of Source Bars…") { ChartExport.csv(chart) }125                    } label: { Text("Export") }.fixedSize()126                    Button(action: ask) { Label("Ask the Agent", systemImage: "sparkles").labelStyle(.titleAndIcon) }127                        .tint(VQTokens.Palette.accent).disabled(chart.bars.isEmpty)128                        .help("Ask the research agent about the visible range: symbol, dates, indicators and the levels you drew are stated in the question")129                        .accessibilityIdentifier("chart.ask")130                    if let onDetach { Button(action: onDetach) { Image(systemName: "rectangle.portrait.on.rectangle.portrait") }.help("Open in its own window").accessibilityLabel("Open in its own window") }131                }132                .controlSize(.small)133            }134            HStack(spacing: 10) {135                ChartSegment(label: "Bar interval", options: BarInterval.allCases.map { ($0, $0.label, nil) }, selection: chart.interval, prefix: "chart.interval") { chart.setInterval($0) }136                ChartSegment(label: "Time range", options: ChartRange.available(for: chart.interval).map { ($0, $0.rawValue, nil) }, selection: chart.range, prefix: "chart.range") { chart.setRange($0) }137                Spacer(minLength: 4)138                if sync?.hasObject == true {139                    Image(systemName: sync?.saving == true ? "arrow.triangle.2.circlepath" : "checkmark.icloud").font(.system(size: 11)).foregroundStyle(VQTokens.Palette.text3)140                        .help("This chart's settings and drawings are saved in your account (object \(sync?.objectID ?? "")) and follow you on your other devices")141                        .accessibilityLabel("Chart saved in your account")142                }143                ChartProvenanceButton(chart: chart, isPresented: $showProvenance, theme: app.vqTheme)144            }145        }146        .padding(.horizontal, 10).padding(.vertical, 7)147        .background(VQTokens.Palette.ink1)148    }149150    private var footer: some View {151        HStack(spacing: 12) {152            Text("\(chart.bars.count) source bars · \(chart.interval.label)").font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text2)153            if chart.dropped > 0 { Text("\(chart.dropped) rows without a close ignored").font(.caption).foregroundStyle(VQTokens.Palette.warn) }154            if chart.foreignDrawings > 0 { Text("\(chart.foreignDrawings) drawing\(chart.foreignDrawings == 1 ? "" : "s") from another device not shown").font(.caption).foregroundStyle(VQTokens.Palette.text3) }155            if !chart.compareOrder.isEmpty {156                HStack(spacing: 8) {157                    ForEach(Array(([chart.symbol] + chart.compareOrder).enumerated()), id: \.element) { n, s in158                        HStack(spacing: 3) { Circle().fill(ChartColors.compare(n)).frame(width: 7, height: 7); Text(s).font(.caption.monospaced()) }159                            .contentShape(Rectangle())160                            .draggable(s)      // a ticker can be dragged to another chart or to a watchlist161                            .accessibilityElement(children: .combine).accessibilityIdentifier("chart.series.\(s)")162                    }163                }164            }165            Spacer()166            if chart.loading { ProgressView().controlSize(.mini) }167            if let f = chart.fetchedAt { Text("Received \(Fmt.time(f))").font(.caption).foregroundStyle(VQTokens.Palette.text3) }168            Text(chart.tool.map { "\($0.title): \($0.pointsNeeded == 1 ? "click in the chart" : "drag, or click twice") · esc cancels" } ?? "Scroll to zoom · drag to pan · double-click to fit")169                .font(.caption2).foregroundStyle(VQTokens.Palette.text3).lineLimit(1)170        }171        .padding(.horizontal, 10).frame(height: 24)172        .background(VQTokens.Palette.ink1)173    }174}175176/// A compact segmented control whose segments are real buttons (each reachable by its identifier in UI tests).177struct ChartSegment<Value: Hashable>: View {178    let label: String179    let options: [(Value, String, String?)]180    let selection: Value181    let prefix: String182    let pick: (Value) -> Void183184    var body: some View {185        HStack(spacing: 1) {186            ForEach(Array(options.enumerated()), id: \.offset) { _, o in187                let on = o.0 == selection188                Button { pick(o.0) } label: {189                    Group { if let icon = o.2 { Image(systemName: icon).font(.system(size: 11, weight: .medium)) } else { Text(o.1).font(.system(size: 11, weight: on ? .semibold : .regular, design: .monospaced)) } }190                        .foregroundStyle(on ? VQTokens.Palette.text1 : VQTokens.Palette.text2)191                        .padding(.horizontal, 7).frame(height: 20)192                        .background(on ? VQTokens.Palette.ink4 : Color.clear, in: RoundedRectangle(cornerRadius: 4))193                        .contentShape(Rectangle())194                }195                .buttonStyle(.plain)196                .help(o.1)197                .accessibilityLabel(o.1)198                .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)199                .accessibilityIdentifier("\(prefix).\(o.1)")200            }201        }202        .padding(2)203        .background(VQTokens.Palette.ink3, in: RoundedRectangle(cornerRadius: 6))204        .fixedSize()205        .accessibilityElement(children: .contain)206        .accessibilityLabel(label)207    }208}209210/// The drawing tools, in a rail on the left of the plot: pointer, the six tools, the colour of new drawings (or of211/// the selected one), delete.212struct ChartToolPalette: View {213    @Bindable var chart: ChartModel214    let undo: UndoManager?215216    static let tools: [(DrawingKind, String)] = [217        (.trend, "line.diagonal"), (.hline, "minus"), (.rect, "rectangle"), (.fib, "line.3.horizontal"), (.text, "character.textbox"), (.measure, "ruler"),218    ]219220    private var colorIndex: Int { chart.selection.flatMap { id in chart.drawings.first { $0.id == id }?.color } ?? chart.drawingColor }221222    var body: some View {223        VStack(spacing: 3) {224            tool(nil, "cursorarrow", "Pointer: select, move and resize drawings; drag the chart to pan", id: "pointer")225            Rectangle().fill(VQTokens.Palette.line).frame(width: 18, height: 1).padding(.vertical, 2)226            ForEach(Self.tools, id: \.0) { kind, icon in tool(kind, icon, kind.title, id: kind.rawValue) }227            Rectangle().fill(VQTokens.Palette.line).frame(width: 18, height: 1).padding(.vertical, 2)228            Menu {229                ForEach(Array(ChartColors.series.enumerated()), id: \.offset) { i, _ in230                    Button { setColor(i) } label: { Label(Self.colorNames[i], systemImage: i == colorIndex ? "checkmark.circle.fill" : "circle.fill").tint(ChartColors.series[i]) }231                }232            } label: {233                Circle().fill(ChartColors.drawing(colorIndex)).frame(width: 13, height: 13).overlay(Circle().strokeBorder(VQTokens.Palette.lineStrong, lineWidth: 1))234            }235            .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().frame(width: 26, height: 24)236            .help(chart.selection == nil ? "Colour of new drawings" : "Colour of the selected drawing")237            .accessibilityLabel("Drawing colour").accessibilityIdentifier("chart.tool.color")238            Button { if let id = chart.selection { chart.delete(id, undo: undo) } } label: { icon("trash", on: false) }239                .buttonStyle(.plain).disabled(chart.selection == nil).opacity(chart.selection == nil ? 0.35 : 1)240                .help("Delete the selected drawing (⌫)").accessibilityLabel("Delete drawing").accessibilityIdentifier("chart.tool.delete")241                .contextMenu { Button("Delete All Drawings", role: .destructive) { chart.deleteAllDrawings(undo: undo) }.disabled(chart.drawings.isEmpty) }242            Spacer(minLength: 0)243            Text("\(chart.drawings.count)").font(.system(size: 10, design: .monospaced)).foregroundStyle(VQTokens.Palette.text3)244                .help("\(chart.drawings.count) drawing\(chart.drawings.count == 1 ? "" : "s") on this chart")245                .accessibilityLabel("Drawings").accessibilityValue("\(chart.drawings.count)").accessibilityIdentifier("chart.drawingCount")246                .padding(.bottom, 26)247        }248        .padding(.top, 6)249        .frame(width: 34)250        .background(VQTokens.Palette.ink1)251    }252253    static let colorNames = ["Blue", "Orange", "Green", "Amber", "Pink", "Leaf", "Violet", "Red"]254255    private func setColor(_ i: Int) {256        if let id = chart.selection { chart.setColor(i, of: id, undo: undo) } else { chart.drawingColor = i }257    }258259    private func icon(_ name: String, on: Bool) -> some View {260        Image(systemName: name).font(.system(size: 12.5, weight: .medium))261            .foregroundStyle(on ? VQTokens.Palette.accentText : VQTokens.Palette.text2)262            .frame(width: 26, height: 24)263            .background(on ? VQTokens.Palette.ink4 : Color.clear, in: RoundedRectangle(cornerRadius: 5))264            .contentShape(Rectangle())265    }266267    private func tool(_ kind: DrawingKind?, _ symbol: String, _ help: String, id: String) -> some View {268        let on = chart.tool == kind269        return Button { chart.tool = kind; chart.draft = nil; if kind != nil { chart.selection = nil } } label: { icon(symbol, on: on) }270            .buttonStyle(.plain)271            .help(help)272            .accessibilityLabel(kind?.title ?? "Pointer")273            .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)274            .accessibilityIdentifier("chart.tool.\(id)")275    }276}277278/// The text field of a note being written, placed on its anchor.279private struct ChartNoteEditor: View {280    let chart: ChartModel281    let undo: UndoManager?282    @State private var text = ""283    @FocusState private var focused: Bool284285    var body: some View {286        GeometryReader { geo in287            if let id = chart.editingText, let d = chart.drawings.first(where: { $0.id == id }), let s = chart.scale, let anchor = d.points.first {288                let L = ChartLayout(size: geo.size, showVolume: chart.indicators.volume, showRSI: chart.indicators.rsi, showMACD: chart.indicators.macd)289                let p = ChartProjection(start: chart.start, step: L.plotWidth / CGFloat(chart.count), times: chart.times, stepSeconds: chart.stepSeconds, scale: s).point(anchor)290                TextField("Note", text: $text)291                    .textFieldStyle(.plain).font(ChartDrawingRender.noteFont)292                    .padding(.horizontal, 6).padding(.vertical, 3)293                    .frame(width: 200)294                    .background(VQTokens.Palette.ink2, in: RoundedRectangle(cornerRadius: 4))295                    .overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(ChartColors.drawing(d.color), lineWidth: 1.5))296                    .focused($focused)297                    .onSubmit { chart.setText(text, of: id, undo: undo) }298                    .onExitCommand { chart.setText(d.text ?? "", of: id, undo: undo) }299                    .accessibilityIdentifier("chart.noteField")300                    .position(x: min(max(p.x + 8 + 100, 104), max(104, L.plotWidth - 104)), y: min(max(p.y, 14), L.price.maxY - 14))301                    .onAppear { text = d.text ?? ""; focused = true }302                    .id(id)303            }304        }305    }306}307308/// O/H/L/C/V of the bar under the pointer (or the last bar), plus the indicator values at that bar.309private struct ChartLegend: View {310    let chart: ChartModel311    let settings: SettingsStore312    var body: some View {313        let i = chart.hover?.index ?? (chart.bars.count - 1)314        if chart.bars.indices.contains(i) {315            let b = chart.bars[i]316            let prev = i > 0 ? chart.bars[i - 1].close : nil317            let chg = prev.map { (b.close / $0 - 1) * 100 }318            VStack(alignment: .leading, spacing: 2) {319                HStack(spacing: 8) {320                    Text(chart.dateText(b.time)).foregroundStyle(VQTokens.Palette.text2)321                    item("O", b.open); item("H", b.high); item("L", b.low); item("C", b.close)322                    Text(Fmt.percent(chg)).foregroundStyle(settings.changeColor(chg))323                    Text("Vol \(Fmt.compact(b.volume))").foregroundStyle(VQTokens.Palette.text2)324                }325                HStack(spacing: 8) {326                    if chart.indicators.sma20 { ind("SMA20", chart.sma20, i, ChartColors.sma20) }327                    if chart.indicators.sma50 { ind("SMA50", chart.sma50, i, ChartColors.sma50) }328                    if chart.indicators.sma200 { ind("SMA200", chart.sma200, i, ChartColors.sma200) }329                    if chart.indicators.ema20 { ind("EMA20", chart.ema20, i, ChartColors.ema20) }330                    if chart.indicators.bollinger { ind("BB↑", chart.bands.upper, i, ChartColors.bollinger); ind("BB↓", chart.bands.lower, i, ChartColors.bollinger) }331                    if chart.indicators.rsi { ind("RSI", chart.rsi, i, ChartColors.rsi) }332                }333            }334            .font(.system(size: 11, design: .monospaced))335            .foregroundStyle(VQTokens.Palette.text1)336            .padding(.horizontal, 6).padding(.vertical, 3)337            .background(ChartColors.background.opacity(0.82), in: RoundedRectangle(cornerRadius: 4))338        }339    }340    private func item(_ l: String, _ v: Double) -> some View { HStack(spacing: 2) { Text(l).foregroundStyle(VQTokens.Palette.text3); Text(Fmt.price(v)) } }341    @ViewBuilder private func ind(_ l: String, _ s: [Double?], _ i: Int, _ c: Color) -> some View {342        if s.indices.contains(i), let v = s[i] { HStack(spacing: 2) { Text(l).foregroundStyle(c); Text(Fmt.price(v)) } }343    }344}345346private struct ComparePopover: View {347    let app: AppEnvironment348    let chart: ChartModel349    var body: some View {350        VStack(alignment: .leading, spacing: 8) {351            Text("Compare with").font(.headline)352            SymbolSearchField(app: app, placeholder: "Add a symbol") { chart.addCompare($0) }.frame(width: 260)353            ForEach(chart.compareOrder, id: \.self) { s in354                HStack { Text(s).font(.body.monospaced()); Spacer(); Button { chart.removeCompare(s) } label: { Image(systemName: "xmark.circle.fill") }.buttonStyle(.borderless) }355            }356            Text("Each series is drawn as its percentage change from the first visible bar, on the dates it shares with \(chart.symbol).").font(.caption).foregroundStyle(.secondary).frame(width: 260, alignment: .leading)357        }358        .padding(12)359    }360}361362enum ChartExport {363    private static func name(_ c: ChartModel, _ ext: String) -> String { "\(c.symbol.replacingOccurrences(of: "^", with: ""))-\(c.interval.label)-\(c.range.rawValue).\(ext)" }364365    private static func renderer(_ c: ChartModel, _ s: SettingsStore) -> ImageRenderer<some View> {366        let v = VStack(alignment: .leading, spacing: 4) {367            Text("\(c.symbol) · \(c.interval.label) · \(c.bars.count) bars · \(c.provenance.map { ChartProvenance.providerName($0.provider) + " · " } ?? "")VQuant").font(.system(size: 12, weight: .medium))368            ChartCanvas(model: c, settings: s, interactive: false)369        }370        .padding(12).frame(width: 1400, height: 800).background(ChartColors.background)371        let r = ImageRenderer(content: v); r.scale = 2372        return r373    }374375    static func pngData(_ c: ChartModel, _ s: SettingsStore) -> Data? {376        guard let img = renderer(c, s).cgImage else { return nil }377        return NSBitmapImageRep(cgImage: img).representation(using: .png, properties: [:])378    }379    static func png(_ c: ChartModel, _ s: SettingsStore) {380        guard let data = pngData(c, s) else { return }381        SavePanel.save(data, name: name(c, "png"), types: [.png])382    }383384    static func pdfData(_ c: ChartModel, _ s: SettingsStore) -> Data {385        let r = renderer(c, s)386        let data = NSMutableData()387        r.render { size, draw in388            var box = CGRect(origin: .zero, size: size)389            guard let consumer = CGDataConsumer(data: data as CFMutableData), let ctx = CGContext(consumer: consumer, mediaBox: &box, nil) else { return }390            ctx.beginPDFPage(nil); draw(ctx); ctx.endPDFPage(); ctx.closePDF()391        }392        return data as Data393    }394    static func pdf(_ c: ChartModel, _ s: SettingsStore) { SavePanel.save(pdfData(c, s), name: name(c, "pdf"), types: [.pdf]) }395396    /// The source bars as received from the server — never the visually merged ones.397    static func csvText(_ c: ChartModel) -> String { CSV.bars(c.bars, intraday: c.isIntraday) }398    static func csv(_ c: ChartModel) { SavePanel.save(Data(csvText(c).utf8), name: name(c, "csv"), types: [.commaSeparatedText]) }399}400401// MARK: - As a section of the main window402403struct ChartSection: View {404    let app: AppEnvironment405    let model: WindowModel406    @State private var chart: ChartModel?407    @Environment(\.openWindow) private var openWindow408409    var body: some View {410        HStack(spacing: 0) {411            Group {412                if let chart {413                    ChartPane(app: app, chart: chart, onSymbol: { model.show(.charting, symbol: $0) }, onAsk: { model.ask($0) }) {414                        openWindow(id: "chart", value: ChartSpec(symbol: chart.symbol, interval: chart.interval, range: chart.range.rawValue, compare: chart.compareOrder))415                    }416                }417            }418                .frame(minWidth: 420, maxWidth: .infinity)419                .layoutPriority(1)420            Divider()421            QuoteSidebar(app: app, model: model).frame(width: 240)422        }423        .onAppear {424            if chart == nil { chart = ChartModel(app: app, symbol: model.symbol) }; app.market.watch([model.symbol])425            #if DEBUG426            ChartBench.run(app: app)427            #endif428        }429        .onDisappear { app.market.unwatch([model.symbol]) }430        .onChange(of: model.symbol) { old, new in chart?.setSymbol(new); app.market.unwatch([old]); app.market.watch([new]) }431    }432}433434/// Quote detail and company profile of the charted symbol.435private struct QuoteSidebar: View {436    let app: AppEnvironment437    let model: WindowModel438    @State private var profile: CompanyProfile?439440    var body: some View {441        ScrollView {442            VStack(alignment: .leading, spacing: 10) {443                if let e = app.market.entry(model.symbol) {444                    let q = e.quote445                    Text(q.name).font(.headline).lineLimit(2)446                    FreshnessBadge(freshness: e.freshness)447                    Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 5) {448                        row("Open", Fmt.price(q.open)); row("Previous close", Fmt.price(q.previousClose))449                        row("Day range", "\(Fmt.price(q.dayLow)) – \(Fmt.price(q.dayHigh))"); row("52-week range", "\(Fmt.price(q.yearLow)) – \(Fmt.price(q.yearHigh))")450                        row("Volume", Fmt.compact(q.volume)); row("Market cap", Fmt.compact(q.marketCap))451                        row("50-day average", Fmt.price(q.priceAvg50)); row("200-day average", Fmt.price(q.priceAvg200))452                        row("Exchange", q.exchange ?? "—")453                    }454                    .font(.callout)455                } else if app.market.unknown.contains(model.symbol) {456                    Text("The data provider has no quote for \(model.symbol).").font(.callout).foregroundStyle(.secondary)457                } else { ProgressView().controlSize(.small) }458                if let p = profile {459                    Divider()460                    Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 5) {461                        row("Sector", p.sector ?? "—"); row("Industry", p.industry ?? "—"); row("Country", p.country ?? "—")462                        row("CEO", p.ceo ?? "—"); row("Employees", p.fullTimeEmployees ?? "—"); row("Beta", Fmt.number(p.beta))463                    }.font(.callout)464                    if let d = p.description { Text(d).font(.caption).foregroundStyle(.secondary).lineLimit(12) }465                    if let w = p.website, let url = URL(string: w) { Link(w, destination: url).font(.caption) }466                }467                Divider()468                VStack(alignment: .leading, spacing: 6) {469                    Button { model.show(.data) } label: { Label("Explore Data", systemImage: "tablecells") }470                    Button { model.quantTool = "risk_metrics"; model.show(.quant) } label: { Label("Run a Computation", systemImage: "function") }471                    Button { model.openConversation(nil) } label: { Label("Ask the Agent", systemImage: "sparkles") }472                    WatchlistAddMenu(app: app, symbol: model.symbol).menuStyle(.borderlessButton)   // the synced lists (the 1.x local store is no longer written)473                }474                .buttonStyle(.link)475            }476            .padding(12)477        }478        .background(VQTokens.Palette.ink1)479        .task(id: model.symbol) {480            profile = nil481            profile = (try? await app.cache.fetch("profile-\(model.symbol)") { [api = app.api, s = model.symbol] in try await api.profile(s) })?.value482        }483    }484    private func row(_ l: String, _ v: String) -> some View { GridRow { Text(l).foregroundStyle(.secondary); Text(v).monospacedDigit().gridColumnAlignment(.trailing) } }485}486487// MARK: - As its own window488489struct ChartWindow: View {490    let app: AppEnvironment491    /// What the window was opened with (never written back: see RootView). Later changes live in scene storage.492    let spec: ChartSpec?493    @State private var chart: ChartModel?494    @State private var holder = SymbolHolder()495    @SceneStorage("vq.chart.symbol") private var storedSymbol = ""496    @SceneStorage("vq.chart.interval") private var storedInterval = ""497    @SceneStorage("vq.chart.range") private var storedRange = ""498    @SceneStorage("vq.chart.compare") private var storedCompare = ""499500    var body: some View {501        Group {502            if !app.session.isSignedIn {503                EmptyState(symbol: "lock", title: "Sign in to VQuant", detail: "This chart opens once the main window is signed in.")504            } else if let chart {505                ChartPane(app: app, chart: chart, onSymbol: { s in chart.setSymbol(s); app.market.watch([s]) }, onAsk: { ChartAsk.route($0, app: app) })506                    .toolbar { ToolbarItem(placement: .principal) { SymbolSearchField(app: app) { s in chart.setSymbol(s); app.market.watch([s]) }.frame(width: 240) } }507                    .navigationTitle(chart.symbol)508                    .onChange(of: chart.symbol, initial: true) { _, v in storedSymbol = v; holder.symbol = v }509                    .onChange(of: chart.interval) { _, v in storedInterval = v.rawValue }510                    .onChange(of: chart.range) { _, v in storedRange = v.rawValue }511                    .onChange(of: chart.compareOrder) { _, v in storedCompare = v.joined(separator: ",") }512            } else {513                // Never an empty Group: modifiers of an empty Group attach to nothing, so the task below never ran and a514                // chart window opened while signed in stayed blank (a defect present since 1.0, found with real pointer515                // events on 2026-11-20; RootView had the same one when a layout re-opened a main window).516                Color.clear517            }518        }519        .task(id: app.session.isSignedIn) {520            guard app.session.isSignedIn, chart == nil else { return }521            let symbol = storedSymbol.isEmpty ? (spec?.symbol ?? "AAPL") : storedSymbol522            let c = ChartModel(app: app, symbol: symbol, interval: BarInterval(rawValue: storedInterval) ?? spec?.interval, range: ChartRange(rawValue: storedRange.isEmpty ? (spec?.range ?? "") : storedRange))523            for x in (storedCompare.isEmpty ? (spec?.compare ?? []) : storedCompare.split(separator: ",").map(String.init)) { c.addCompare(x) }524            chart = c525            app.market.watch([symbol])526        }527        .vqTheme(app.vqTheme)528        .background(WindowAccessor { w in529            if let id = spec?.id { WorkspaceLayouts.place(w, id: id) }530            // the record reads the window's current symbol when a layout is captured531            WorkspaceLayouts.register(w) { [holder] in holder.symbol.map { SavedWorkspace.Window(section: "chart", symbol: $0, frame: nil, kind: "chart") } }532        })533    }534}535536/// What a chart window currently shows, readable from outside SwiftUI (layout capture).537final class SymbolHolder { var symbol: String? }538
Files main
Menu

Theme