Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Components/DesignSystem.swift3// Description: Colours, number and date formatting, and the small shared views (freshness badge, change text, banners, empty states).4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore78enum Palette {9 static let green = Color(red: 0.13, green: 0.72, blue: 0.47)10 static let red = Color(red: 0.92, green: 0.30, blue: 0.30)11 static let amber = Color(red: 0.95, green: 0.62, blue: 0.10)12 static let brand = LinearGradient(colors: [Color(red: 1, green: 0.54, blue: 0.16), Color(red: 1, green: 0.24, blue: 0.43), Color(red: 0.66, green: 0.33, blue: 0.97)], startPoint: .topLeading, endPoint: .bottomTrailing)13 static let series: [Color] = [.accentColor, .blue, .purple, .teal, .orange, .pink, .indigo, .mint, .brown, .cyan]14 static let hairline = Color.primary.opacity(0.10)15 static let panel = Color(nsColor: .controlBackgroundColor)16}1718enum Fmt {19 static func price(_ v: Double?, digits: Int? = nil) -> String {20 guard let v, v.isFinite else { return "—" }21 let d = digits ?? (abs(v) >= 1000 ? 2 : abs(v) >= 1 ? 2 : 4)22 return v.formatted(.number.precision(.fractionLength(d)).grouping(.automatic))23 }24 static func signed(_ v: Double?, digits: Int = 2) -> String {25 guard let v, v.isFinite else { return "—" }26 return v.formatted(.number.precision(.fractionLength(digits)).sign(strategy: .always(includingZero: false)))27 }28 static func percent(_ v: Double?, digits: Int = 2) -> String {29 guard let v, v.isFinite else { return "—" }30 return v.formatted(.number.precision(.fractionLength(digits)).sign(strategy: .always(includingZero: false))) + " %"31 }32 static func plainPercent(_ v: Double?, digits: Int = 2) -> String { v.map { $0.formatted(.number.precision(.fractionLength(digits))) + " %" } ?? "—" }33 /// 5.12 T, 33.4 M — for market capitalisation and volume.34 static func compact(_ v: Double?) -> String {35 guard let v, v.isFinite else { return "—" }36 let a = abs(v)37 let (d, s): (Double, String) = a >= 1e12 ? (1e12, " T") : a >= 1e9 ? (1e9, " B") : a >= 1e6 ? (1e6, " M") : a >= 1e3 ? (1e3, " K") : (1, "")38 return (v / d).formatted(.number.precision(.fractionLength(d == 1 ? 0 : 2))) + s39 }40 static func number(_ v: Double?, digits: Int = 2) -> String { v.map { $0.isFinite ? $0.formatted(.number.precision(.fractionLength(0...digits))) : "—" } ?? "—" }41 static func money(_ v: Double?) -> String { v.map { $0.formatted(.number.precision(.fractionLength(2)).grouping(.automatic)) } ?? "—" }42 static func time(_ d: Date?) -> String { d.map { $0.formatted(date: .omitted, time: .standard) } ?? "—" }43 static func dateTime(_ d: Date?) -> String { d.map { $0.formatted(date: .abbreviated, time: .shortened) } ?? "—" }44 static func relative(_ d: Date?) -> String { d.map { $0.formatted(.relative(presentation: .named)) } ?? "—" }45 static func duration(_ s: TimeInterval?) -> String {46 guard let s else { return "—" }47 return s < 60 ? String(format: "%.1f s", s) : "\(Int(s) / 60) min \(Int(s) % 60) s"48 }49 /// A market timestamp (exchange wall time, see BarParser) for chart axes and tooltips.50 static func marketDate(_ d: Date, intraday: Bool) -> String {51 var s = Date.FormatStyle(date: .abbreviated, time: intraday ? .shortened : .omitted)52 s.timeZone = BarParser.calendar.timeZone53 return d.formatted(s)54 }55 /// Cell text of a provider table: big numbers grouped, ratios kept precise.56 static func cell(_ v: JSONValue?) -> String {57 switch v {58 case .number(let n)?:59 if n.rounded() == n, abs(n) < 9e15 { return Int64(n).formatted(.number.grouping(.automatic)) }60 return n.formatted(.number.precision(.significantDigits(1...6)))61 default: return DataTable.text(v)62 }63 }64}6566/// States the age of a value in words and colour. "Recent" is reserved for a provider timestamp under two minutes old;67/// the word "live" is never used because the backend has no streaming feed.68struct FreshnessBadge: View {69 let freshness: Freshness70 var compact = false7172 var body: some View {73 HStack(spacing: 4) {74 Circle().fill(color).frame(width: 6, height: 6)75 Text(compact ? freshness.label : text).font(.caption2).foregroundStyle(.secondary).lineLimit(1)76 }77 .help(help)78 .accessibilityElement(children: .ignore)79 .accessibilityLabel("Data freshness: \(text)")80 }81 private var color: Color {82 switch freshness { case .recent: Palette.green; case .delayed: Palette.amber; case .historical: .secondary; case .cached: .orange; case .unavailable: Palette.red }83 }84 private var text: String {85 switch freshness {86 case .recent(let d): "Recent · \(Fmt.time(d))"87 case .delayed(let d): "Delayed · \(Fmt.dateTime(d))"88 case .historical(let d): d.map { "Historical · through \(Fmt.marketDate($0, intraday: false))" } ?? "Historical"89 case .cached(let d): "Cached · received \(Fmt.relative(d))"90 case .unavailable: "Unavailable"91 }92 }93 private var help: String {94 switch freshness {95 case .recent: "Quote timestamped by the data provider less than two minutes ago. Quotes are polled over HTTPS; this is not a streaming feed."96 case .delayed: "The provider's timestamp for this quote is older than two minutes (closed market or delayed feed)."97 case .historical: "End-of-day or past data: a historical record, not a current price."98 case .cached: "The server could not be reached. This is the last value this Mac received."99 case .unavailable(let why): why100 }101 }102}103104struct ChangeText: View {105 let value: Double?106 var percent = true107 let settings: SettingsStore108 var body: some View {109 Text(percent ? Fmt.percent(value) : Fmt.signed(value)).monospacedDigit().foregroundStyle(settings.changeColor(value))110 }111}112113struct EmptyState: View {114 let symbol: String115 let title: String116 var detail: String?117 var body: some View {118 VStack(spacing: 8) {119 Image(systemName: symbol).font(.system(size: 34, weight: .light)).foregroundStyle(.tertiary)120 Text(title).font(.headline)121 if let detail { Text(detail).font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center).frame(maxWidth: 440) }122 }123 .padding(24).frame(maxWidth: .infinity, maxHeight: .infinity)124 }125}126127/// A strip above content: offline notice, cached-data notice, or an error with a retry.128struct NoticeBar: View {129 enum Kind { case offline, cached, error }130 let kind: Kind131 let text: String132 var retry: (() -> Void)?133 var body: some View {134 HStack(spacing: 8) {135 Image(systemName: kind == .error ? "exclamationmark.triangle.fill" : kind == .offline ? "wifi.slash" : "clock.arrow.circlepath")136 .foregroundStyle(kind == .error ? Palette.red : .orange)137 Text(text).font(.callout).lineLimit(2)138 Spacer()139 if let retry { Button("Retry", action: retry).controlSize(.small) }140 }141 .padding(.horizontal, 12).padding(.vertical, 6)142 .background((kind == .error ? Palette.red : Color.orange).opacity(0.10))143 .overlay(alignment: .bottom) { Divider() }144 }145}146147struct Panel<Content: View>: View {148 var title: String?149 var trailing: AnyView?150 @ViewBuilder var content: Content151 init(_ title: String? = nil, trailing: AnyView? = nil, @ViewBuilder content: () -> Content) { self.title = title; self.trailing = trailing; self.content = content() }152 var body: some View {153 VStack(alignment: .leading, spacing: 8) {154 if title != nil || trailing != nil {155 HStack { if let title { Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(.secondary) }; Spacer(); trailing }156 }157 content158 }159 .padding(12)160 .frame(maxWidth: .infinity, alignment: .leading)161 .background(Palette.panel, in: RoundedRectangle(cornerRadius: 8))162 .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Palette.hairline))163 }164}165166struct Stat: View {167 let label: String168 let value: String169 var color: Color = .primary170 var body: some View {171 VStack(alignment: .leading, spacing: 2) {172 Text(label).font(.caption).foregroundStyle(.secondary).lineLimit(1)173 Text(value).font(.system(.body, design: .rounded).weight(.medium)).monospacedDigit().foregroundStyle(color).lineLimit(1).minimumScaleFactor(0.7)174 }175 .frame(maxWidth: .infinity, alignment: .leading)176 .accessibilityElement(children: .combine)177 }178}179180struct ToastOverlay: View {181 let center: ToastCenter182 var body: some View {183 if let t = center.current {184 HStack(spacing: 8) {185 Image(systemName: t.isError ? "exclamationmark.triangle.fill" : "checkmark.circle.fill").foregroundStyle(t.isError ? Palette.red : Palette.green)186 Text(t.text).font(.callout).lineLimit(3)187 }188 .padding(.horizontal, 14).padding(.vertical, 9)189 .background(.regularMaterial, in: Capsule())190 .overlay(Capsule().strokeBorder(Palette.hairline))191 .shadow(radius: 8, y: 2)192 .padding(.bottom, 34)193 .transition(.opacity)194 .id(t.id)195 }196 }197}198199/// Gives SwiftUI code the NSWindow it is hosted in (frame save and restore, titles).200struct WindowAccessor: View {201 let onWindow: (NSWindow) -> Void202 /// A zero-sized, non-interactive probe: a full-size AppKit view behind SwiftUI content can take pointer events203 /// meant for AppKit-backed controls above it (the sidebar list).204 var body: some View { Probe(onWindow: onWindow).frame(width: 0, height: 0).allowsHitTesting(false).accessibilityHidden(true) }205206 private struct Probe: NSViewRepresentable {207 let onWindow: (NSWindow) -> Void208 func makeNSView(context: Context) -> PassthroughView {209 let v = PassthroughView()210 v.onWindow = onWindow211 return v212 }213 func updateNSView(_ nsView: PassthroughView, context: Context) { nsView.onWindow = onWindow }214 }215216 /// Reports the window when the view really enters one. The 1.x probe asked once, one run-loop turn after the view217 /// was created: when the view was not attached yet by then (a main window whose content is inserted after its218 /// model exists), the callback never ran — the window was never registered for layouts ("No window to save."),219 /// and `WindowModel.window` stayed nil. Found with real pointer events on 2026-11-20.220 final class PassthroughView: NSView {221 var onWindow: ((NSWindow) -> Void)?222 private weak var reported: NSWindow?223 override func hitTest(_ point: NSPoint) -> NSView? { nil }224 override func viewDidMoveToWindow() {225 super.viewDidMoveToWindow()226 guard let w = window, w !== reported else { return }227 reported = w228 // after the current layout pass: handlers set observable state and frames229 DispatchQueue.main.async { [weak self, weak w] in if let w, self?.window === w { self?.onWindow?(w) } }230 }231 }232}233234enum SavePanel {235 /// Asks where to save and writes the data there (the sandbox grants access to the chosen file only).236 @discardableResult static func save(_ data: Data, name: String, types: [UTType]) -> URL? {237 let p = NSSavePanel()238 p.nameFieldStringValue = name; p.allowedContentTypes = types; p.canCreateDirectories = true239 guard p.runModal() == .OK, let url = p.url else { return nil }240 do { try data.write(to: url, options: .atomic); return url } catch { NSAlert(error: error).runModal(); return nil }241 }242}243244/// A list row that selects on click by its own action. The app does not rely on `List(selection:)`: on macOS 27 its245/// outline-backed lists receive the click but do not select the row (observed with the UI tests, 2026-11-18).246struct SelectableRow<Content: View>: View {247 let isSelected: Bool248 let action: () -> Void249 @ViewBuilder var content: Content250251 var body: some View {252 Button(action: action) {253 content.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())254 }255 .buttonStyle(.plain)256 .listRowBackground(RoundedRectangle(cornerRadius: 6).fill(isSelected ? Color.accentColor.opacity(0.22) : Color.clear).padding(.horizontal, 6))257 .accessibilityAddTraits(isSelected ? [.isSelected, .isButton] : .isButton)258 }259}260