Repository Public
1//2// VQuant iOS3// File: VQuant/Charts/PriceChartView.swift4// Description: Interactive native price chart (candles, OHLC, line, area) with overlays and sub-panels: pinch to zoom,5// drag to pan, long-press or pointer crosshair, double-tap to reset; plus PNG export of a chart.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Accessibility12import SwiftUI1314/// Why a SwiftUI `Canvas` and not Metal: a frame only draws the visible window, and the window is reduced to at15/// most one mark per few horizontal points (exact OHLC aggregation, announced on screen, when there are more bars16/// than room). The drawing cost therefore follows the width of the screen, not the length of the series, and the17/// indicator series are computed once per data set, not per frame. A Metal renderer would be warranted for18/// tick-level data or many simultaneous panes; nothing the VQuant backend serves today is of that kind.19struct PriceChartView: View {20 private let bars: [Bar]21 private let configuration: ChartConfiguration22 private let intraday: Bool23 private let previousClose: Double?24 private let interactive: Bool25 private let onInspect: ((Bar?) -> Void)?26 /// Drawn over the plot with the frame's own geometry (drawings anchored to time and price).27 private let overlay: ((PriceChartScene) -> AnyView)?28 /// Told the visible window whenever it changes ("ask the agent about what I am looking at").29 private let onViewport: ((Range<Int>) -> Void)?3031 @State private var viewport: ChartViewport32 @State private var panStart: ChartViewport?33 @State private var magnifyStart: ChartViewport?34 @State private var dragMode = DragMode.undecided35 @State private var crosshair: Int?36 @State private var touchInspecting = false37 @State private var cache = ChartDataCache()38 @State private var touch = TouchTracker()39 @GestureState private var pressActive = false40 @ScaledMetric(relativeTo: .caption2) private var axisWidth: CGFloat = 5441 @ScaledMetric(relativeTo: .caption2) private var xAxisHeight: CGFloat = 184243 private enum DragMode { case undecided, pan, ignore }44 /// Last touch position, kept outside the view state so that tracking it does not redraw the chart.45 @MainActor private final class TouchTracker { var location = CGPoint.zero }46 private struct DataIdentity: Equatable { var count: Int; var first: Date? }4748 init(bars: [Bar], configuration: ChartConfiguration, intraday: Bool, previousClose: Double? = nil, interactive: Bool = true,49 overlay: ((PriceChartScene) -> AnyView)? = nil, onViewport: ((Range<Int>) -> Void)? = nil, onInspect: ((Bar?) -> Void)? = nil) {50 self.overlay = overlay51 self.onViewport = onViewport52 self.bars = bars53 self.configuration = configuration54 self.intraday = intraday55 self.previousClose = previousClose56 self.interactive = interactive57 self.onInspect = onInspect58 _viewport = State(initialValue: ChartViewport(count: bars.count))59 }6061 /// The stored window, or the opening window when the data set changed since it was stored.62 private var currentViewport: ChartViewport {63 viewport.count == bars.count ? viewport : ChartViewport(count: bars.count)64 }6566 var body: some View {67 Group {68 if bars.isEmpty {69 ContentUnavailableView("Aucune donnée", systemImage: "chart.xyaxis.line", description: Text("Le serveur n’a renvoyé aucune observation pour cette période."))70 } else {71 GeometryReader { geo in72 let layout = ChartLayout(size: geo.size, panels: configuration.panels, axisWidth: axisWidth, xAxisHeight: xAxisHeight)73 let scene = PriceChartScene(bars: bars, data: cache.data(for: bars, configuration: configuration), configuration: configuration, intraday: intraday,74 previousClose: previousClose, viewport: currentViewport, layout: layout, crosshair: crosshair.flatMap { $0 < bars.count ? $0 : nil })75 chart(scene)76 }77 }78 }79 .dynamicTypeSize(.xSmall ... .xxLarge)80 .onChange(of: currentViewport.range, initial: true) { _, r in onViewport?(r) }81 .onChange(of: DataIdentity(count: bars.count, first: bars.first?.date)) { _, _ in82 viewport = ChartViewport(count: bars.count)83 endInspection()84 }85 .accessibilityElement(children: .ignore)86 .accessibilityLabel("Graphique de prix")87 .accessibilityValue(summary)88 .accessibilityChartDescriptor(PriceChartDescriptor(bars: Array(bars[currentViewport.range]), intraday: intraday, summary: summary))89 }9091 @ViewBuilder private func chart(_ scene: PriceChartScene) -> some View {92 let base = ZStack(alignment: .topLeading) {93 Canvas { context, _ in94 scene.draw(in: &context)95 }96 if let overlay { overlay(scene) }97 legend(scene)98 .padding(.leading, 6).padding(.top, 4)99 .allowsHitTesting(false)100 if let index = scene.crosshair, let k = scene.markIndex(containing: index) {101 tooltip(scene, markIndex: k)102 .allowsHitTesting(false)103 }104 }105 .contentShape(Rectangle())106107 if interactive {108 base109 .gesture(inspectGesture(scene))110 .simultaneousGesture(panGesture(scene))111 .simultaneousGesture(magnifyGesture(scene))112 .onTapGesture(count: 2) { viewport = ChartViewport(count: bars.count); endInspection() }113 .onContinuousHover(coordinateSpace: .local) { phase in114 switch phase {115 case .active(let p):116 if p.x <= scene.layout.plot.maxX { inspect(scene, x: p.x) } else if !touchInspecting { endInspection() }117 case .ended:118 if !touchInspecting { endInspection() }119 }120 }121 .onChange(of: pressActive) { _, active in if !active, touchInspecting { endInspection() } }122 .sensoryFeedback(trigger: touchInspecting) { _, now in now ? .impact(weight: .light) : nil }123 } else {124 base125 }126 }127128 // MARK: legend and tooltip129130 @ViewBuilder private func legend(_ scene: PriceChartScene) -> some View {131 let overlays = ChartOverlay.allCases.filter { configuration.overlays.contains($0) }132 VStack(alignment: .leading, spacing: 3) {133 if !overlays.isEmpty {134 HStack(spacing: 8) {135 ForEach(overlays) { o in136 HStack(spacing: 3) {137 RoundedRectangle(cornerRadius: 1).fill(o.color).frame(width: 10, height: 3)138 Text(o.label)139 }140 }141 }142 }143 if scene.factor > 1 {144 Text("Agrégé ×\(scene.factor) pour l’affichage (données brutes inchangées)")145 }146 }147 .font(.caption2)148 .foregroundStyle(Theme.textSecondary)149 .lineLimit(1)150 .minimumScaleFactor(0.7)151 .padding(.horizontal, overlays.isEmpty && scene.factor == 1 ? 0 : 5)152 .padding(.vertical, overlays.isEmpty && scene.factor == 1 ? 0 : 3)153 .background(Theme.surface.opacity(0.82), in: RoundedRectangle(cornerRadius: 5))154 .frame(maxWidth: max(0, scene.layout.plot.width - 12), alignment: .leading)155 }156157 private func tooltip(_ scene: PriceChartScene, markIndex k: Int) -> some View {158 let m = scene.marks[k]159 let reference: Double? = k > 0 ? scene.marks[k - 1].bar.close : (m.first > 0 ? bars[m.first - 1].close : nil)160 let change: Double? = reference.flatMap { $0 != 0 ? (m.bar.close / $0 - 1) * 100 : nil }161 let onLeft = scene.x(m) > scene.layout.plot.midX162 return VStack(alignment: .leading, spacing: 2) {163 Text(ChartDates.full(m.bar.date, intraday: intraday)).fontWeight(.semibold)164 if m.last > m.first {165 Text("Agrégat de \(m.last - m.first + 1) barres").foregroundStyle(Theme.textSecondary)166 }167 Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 1) {168 row("Ouv.", Fmt.price(m.bar.open))169 row("Haut", Fmt.price(m.bar.high))170 row("Bas", Fmt.price(m.bar.low))171 row("Clôt.", Fmt.price(m.bar.close))172 row("Vol.", Fmt.compact(m.bar.volume))173 GridRow {174 Text("Var.").foregroundStyle(Theme.textSecondary)175 Text(Fmt.percent(change)).foregroundStyle(Theme.direction(change)).gridColumnAlignment(.trailing)176 }177 }178 }179 .font(.caption2.monospacedDigit())180 .padding(7)181 .background(Theme.surface, in: RoundedRectangle(cornerRadius: 8))182 .overlay(RoundedRectangle(cornerRadius: 8).stroke(Theme.border, lineWidth: 0.5))183 .shadow(color: .black.opacity(0.18), radius: 6, y: 2)184 .fixedSize()185 .padding(6)186 .frame(width: scene.layout.plot.width, height: scene.layout.plot.height, alignment: onLeft ? .topLeading : .topTrailing)187 }188189 private func row(_ name: String, _ value: String) -> some View {190 GridRow {191 Text(name).foregroundStyle(Theme.textSecondary)192 Text(value).gridColumnAlignment(.trailing)193 }194 }195196 // MARK: gestures197198 private func inspect(_ scene: PriceChartScene, x: CGFloat) {199 guard let index = scene.index(atX: x) else { return }200 let before = crosshair.flatMap { scene.markIndex(containing: $0) }201 crosshair = index202 if let k = scene.markIndex(containing: index), k != before || before == nil { onInspect?(scene.marks[k].bar) }203 }204205 private func endInspection() {206 let was = crosshair != nil207 touchInspecting = false208 crosshair = nil209 if was { onInspect?(nil) }210 }211212 /// Long press, then drag: the crosshair follows the finger. While the press is not yet recognised the parent213 /// scroll view keeps its gesture; once it is, the drag belongs to the chart.214 private func inspectGesture(_ scene: PriceChartScene) -> some Gesture {215 LongPressGesture(minimumDuration: 0.25, maximumDistance: 10)216 .sequenced(before: DragGesture(minimumDistance: 0, coordinateSpace: .local))217 .updating($pressActive) { value, state, _ in218 if case .second(true, _) = value { state = true }219 }220 .onChanged { value in221 guard case .second(true, let drag) = value else { return }222 touchInspecting = true223 inspect(scene, x: drag?.location.x ?? touch.location.x)224 }225 .onEnded { _ in endInspection() }226 }227228 /// Horizontal drag pans. A drag that starts mostly vertical is left to the enclosing scroll view.229 private func panGesture(_ scene: PriceChartScene) -> some Gesture {230 DragGesture(minimumDistance: 0, coordinateSpace: .local)231 .onChanged { value in232 touch.location = value.location233 guard !touchInspecting, magnifyStart == nil else { return }234 if dragMode == .undecided {235 let dx = abs(value.translation.width), dy = abs(value.translation.height)236 guard max(dx, dy) >= 10 else { return }237 dragMode = dx > dy ? .pan : .ignore238 panStart = currentViewport239 }240 guard dragMode == .pan, let start = panStart else { return }241 let slot = start.slot(width: scene.plotWidth)242 guard slot > 0 else { return }243 viewport = start.panned(byBars: -Double(value.translation.width) / slot)244 }245 .onEnded { _ in dragMode = .undecided; panStart = nil }246 }247248 private func magnifyGesture(_ scene: PriceChartScene) -> some Gesture {249 MagnifyGesture(minimumScaleDelta: 0.01)250 .onChanged { value in251 let start = magnifyStart ?? currentViewport252 if magnifyStart == nil { magnifyStart = start; panStart = nil; dragMode = .ignore }253 let anchor = scene.plotWidth > 0 ? Double(value.startLocation.x) / scene.plotWidth : 0.5254 viewport = start.zoomed(by: Double(value.magnification), anchor: anchor)255 }256 .onEnded { _ in magnifyStart = nil; dragMode = .undecided }257 }258259 // MARK: accessibility260261 /// What a reader of the visible window would say: period, first and last close, change, extremes.262 private var summary: String {263 let window = bars[currentViewport.range]264 guard let first = window.first, let last = window.last else { return "Aucune donnée." }265 let high = window.map(\.high).max() ?? last.high, low = window.map(\.low).min() ?? last.low266 let change: Double? = first.close != 0 ? (last.close / first.close - 1) * 100 : nil267 var parts = ["Du \(ChartDates.full(first.date, intraday: intraday)) au \(ChartDates.full(last.date, intraday: intraday)), \(window.count) observations."]268 parts.append("Clôture de \(Fmt.price(first.close)) à \(Fmt.price(last.close)), variation \(Fmt.percent(change)).")269 parts.append("Plus haut \(Fmt.price(high)), plus bas \(Fmt.price(low)).")270 if !configuration.overlays.isEmpty {271 parts.append("Indicateurs : " + ChartOverlay.allCases.filter { configuration.overlays.contains($0) }.map(\.label).joined(separator: ", ") + ".")272 }273 return parts.joined(separator: " ")274 }275}276277/// Audio-graph description of the visible closes (VoiceOver "Describe chart" / "Play audio graph").278private struct PriceChartDescriptor: AXChartDescriptorRepresentable {279 let bars: [Bar]280 let intraday: Bool281 let summary: String282283 func makeChartDescriptor() -> AXChartDescriptor {284 let step = max(1, bars.count / 200)285 let sampled = stride(from: 0, to: bars.count, by: step).map { bars[$0] }286 let labels = sampled.map { ChartDates.full($0.date, intraday: intraday) }287 let closes = sampled.map(\.close)288 let lo = closes.min() ?? 0, hi = closes.max() ?? 1289 let x = AXNumericDataAxisDescriptor(title: "Date", range: 0...Double(max(1, sampled.count - 1)), gridlinePositions: []) { v in290 let i = Int(v.rounded())291 return labels.indices.contains(i) ? labels[i] : ""292 }293 let y = AXNumericDataAxisDescriptor(title: "Clôture", range: lo...(hi > lo ? hi : lo + 1), gridlinePositions: []) { Fmt.price($0) }294 let series = AXDataSeriesDescriptor(name: "Clôture", isContinuous: true, dataPoints: closes.enumerated().map { AXDataPoint(x: Double($0.offset), y: $0.element) })295 return AXChartDescriptor(title: "Graphique de prix", summary: summary, xAxis: x, yAxis: y, additionalAxes: [], series: [series])296 }297298 func updateChartDescriptor(_ descriptor: AXChartDescriptor) {299 let fresh = makeChartDescriptor()300 descriptor.summary = fresh.summary301 descriptor.xAxis = fresh.xAxis302 descriptor.yAxis = fresh.yAxis303 descriptor.series = fresh.series304 }305}306307/// A chart as an image, for sharing. The picture is drawn by the same renderer as the screen.308@MainActor309enum ChartSnapshot {310 static func png(bars: [Bar], configuration: ChartConfiguration, intraday: Bool, title: String, subtitle: String,311 size: CGSize = CGSize(width: 1200, height: 750), colorScheme: ColorScheme = .dark) -> Data? {312 guard !bars.isEmpty, size.width >= 64, size.height >= 64 else { return nil }313 // Laid out at half size and rendered at scale 2: the labels keep the proportions they have on screen.314 let logical = CGSize(width: size.width / 2, height: size.height / 2)315 let content = VStack(alignment: .leading, spacing: 6) {316 HStack(alignment: .firstTextBaseline, spacing: 8) {317 SparkleMark().frame(width: 18, height: 18)318 Text(title).font(.headline)319 Spacer(minLength: 8)320 Text("VQuant").font(.caption.weight(.semibold)).foregroundStyle(Theme.textSecondary)321 }322 if !subtitle.isEmpty {323 Text(subtitle).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2)324 }325 PriceChartView(bars: bars, configuration: configuration, intraday: intraday, interactive: false)326 }327 .padding(14)328 .frame(width: logical.width, height: logical.height)329 .background(Theme.background)330 .environment(\.colorScheme, colorScheme)331332 let renderer = ImageRenderer(content: content)333 renderer.scale = 2334 renderer.proposedSize = ProposedViewSize(logical)335 renderer.isOpaque = true336 return renderer.uiImage?.pngData()337 }338}339