SPB Git

Repository Public

WatchlistsView.swift 27.9 KB 488 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Terminal/WatchlistsView.swift3// Description: Watchlists of the account (synced `watchlist` objects): create, rename and delete lists, add symbols, select several rows (click, ⌘-click, ⇧-click, arrows), reorder by dragging, drag a ticker out to a chart, quotes of the data layer with their freshness, and a mark on lists whose last change has not reached the server yet.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910struct WatchlistsView: View {11    let app: AppEnvironment12    @Bindable var model: WindowModel1314    @State private var selection = RowSelection()15    @State private var creating = false16    @State private var newName = ""17    @State private var renaming: String?18    @State private var renameText = ""19    @State private var deleting: VQObject<VQWatchlist>?20    /// Tickers being dragged out of this list (the dragged row, or the whole selection when the row is part of it).21    @State private var dragging: [String] = []22    @State private var dropTarget: DropTarget?23    @State private var launchApplied = false24    @FocusState private var tableFocused: Bool25    @FocusState private var nameFocused: Bool2627    struct DropTarget: Equatable { var symbol: String; var below: Bool }2829    private var lists: [VQObject<VQWatchlist>] { app.syncedWatchlists }30    private var current: VQObject<VQWatchlist>? { lists.first { $0.id == model.watchlistId } ?? lists.first }3132    var body: some View {33        Group {34            if let session = app.sync.active {35                HStack(spacing: 0) {36                    sidebar(session)37                    Rectangle().fill(TP.line).frame(width: VQTokens.hairline)38                    detail(session)39                }40            } else {41                // an overlay: the empty state never takes part in the layout of the window42                Color.clear.overlay {43                    VQEmptyState(systemImage: "icloud.slash", title: "Watchlists are not loaded yet", message: "They are part of your account and appear as soon as synchronisation has started.")44                }45                .frame(maxWidth: .infinity, maxHeight: .infinity)46            }47        }48        .background(TP.ink0)49        .onChange(of: current?.data.symbols) { _, new in selection.prune(to: new ?? []) }50        .onChange(of: current?.id) { _, _ in selection.clear() }51        .onAppear { if !launchApplied, let id = app.options.extra["Watchlist"] { model.watchlistId = id } }52        .task(id: current?.data.symbols) {53            applyLaunchArguments()54            let symbols = current?.data.symbols ?? []55            guard !symbols.isEmpty else { return }56            // quotes are polled, never streamed: the cadence is the person's setting (0 = on demand only)57            while !Task.isCancelled {58                await app.terminal.loadQuotes(symbols)59                let every = app.settings.quoteRefresh60                try? await Task.sleep(for: .seconds(every > 0 ? max(10, every) : 3600))61            }62        }63        .confirmationDialog("Delete “\(deleting?.data.name ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {64            Button("Delete Watchlist", role: .destructive) { if let d = deleting { delete(d) } }65            Button("Cancel", role: .cancel) {}66        } message: { Text("The list is deleted on every device signed in to your account. This cannot be undone.") }67    }6869    /// DEBUG launch arguments for captures: `-VQXWatchlist <id>` opens a list, `-VQXWatchSelect AAPL,NVDA` selects rows.70    private func applyLaunchArguments() {71        guard !launchApplied, !lists.isEmpty else { return }72        launchApplied = true73        if let pick = app.options.extra["WatchSelect"], let symbols = current?.data.symbols {74            for s in pick.split(separator: ",").map(String.init) where symbols.contains(s) { selection.toggle(s) }75        }76    }7778    // MARK: lists7980    private func sidebar(_ session: SyncSession) -> some View {81        VStack(alignment: .leading, spacing: 0) {82            HStack {83                Text("Watchlists").font(TT.overline.font).tracking(TT.overline.tracking).textCase(.uppercase).foregroundStyle(TP.text3)84                Spacer()85                Button { newName = ""; creating = true; nameFocused = true } label: { Image(systemName: "plus") }86                    .buttonStyle(.borderless).help("New watchlist").accessibilityLabel("New watchlist").accessibilityIdentifier("watchlist.new")87            }88            .padding(.horizontal, TS.s4).padding(.top, TS.s4).padding(.bottom, TS.s2)89            ScrollView {90                VStack(spacing: 1) {91                    ForEach(lists) { w in92                        if renaming == w.id {93                            nameField($renameText, id: "watchlist.rename.field") { commitRename(w.id) } cancel: { renaming = nil }94                        } else {95                            listRow(w, pending: session.watchlists.pendingIDs.contains(w.id))96                        }97                    }98                    if creating { nameField($newName, id: "watchlist.new.field") { commitCreate(session) } cancel: { creating = false } }99                }100                .padding(.horizontal, TS.s2)101            }102            if let e = session.watchlists.lastError {103                Label(e.userMessage, systemImage: "exclamationmark.triangle").font(TT.caption.font).foregroundStyle(TP.critical).padding(TS.s3).fixedSize(horizontal: false, vertical: true)104            }105        }106        .frame(width: 232)107        .background(TP.ink1)108    }109110    private func listRow(_ w: VQObject<VQWatchlist>, pending: Bool) -> some View {111        let on = w.id == current?.id112        return Button { model.watchlistId = w.id } label: {113            HStack(spacing: 6) {114                Rectangle().fill(on ? TP.accent : Color.clear).frame(width: 2, height: 16)115                Text(w.data.name.isEmpty ? "Untitled" : w.data.name).font(TT.bodySm.font.weight(on ? .semibold : .regular)).foregroundStyle(TP.text1).lineLimit(1)116                Spacer(minLength: 4)117                if pending {118                    Image(systemName: "arrow.up.circle").font(.system(size: 11)).foregroundStyle(TP.text3)119                        .help("A change to this list is waiting to reach the server").accessibilityLabel("Pending sync")120                }121                Text("\(w.data.symbols.count)").font(.system(size: 11, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text3)122            }123            .padding(.trailing, TS.s2).frame(height: 28)124            .background(RoundedRectangle(cornerRadius: 5, style: .continuous).fill(on ? TP.ink3 : Color.clear))125            .contentShape(Rectangle())126        }127        .buttonStyle(.plain)128        .contextMenu {129            Button("Rename…") { beginRename(w) }130            Button("Delete…", role: .destructive) { deleting = w }131        }132        .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)133        .accessibilityIdentifier("watchlist.list.\(w.data.name)")134    }135136    private func nameField(_ text: Binding<String>, id: String, commit: @escaping () -> Void, cancel: @escaping () -> Void) -> some View {137        TextField("Name", text: text)138            .textFieldStyle(.roundedBorder).font(TT.bodySm.font)139            .focused($nameFocused)140            .onSubmit(commit)141            .onExitCommand(perform: cancel)142            .padding(.vertical, 2).padding(.horizontal, 2)143            .accessibilityIdentifier(id)144    }145146    private func commitCreate(_ session: SyncSession) {147        let name = newName.trimmingCharacters(in: .whitespacesAndNewlines)148        creating = false149        guard !name.isEmpty else { return }150        // objects written by automated checks are recognisable on the test backend151        let id = app.options.isUITest ? "mac-test-" + VQObjectID.make().prefix(18) : VQObjectID.make()152        Task {153            await session.watchlists.save(VQWatchlist(name: name, symbols: []), id: id)154            if let e = session.watchlists.lastError { app.toasts.show(e.userMessage, error: true) } else { model.watchlistId = id }155        }156    }157158    private func beginRename(_ w: VQObject<VQWatchlist>) { renameText = w.data.name; renaming = w.id; nameFocused = true }159160    private func commitRename(_ id: String) {161        let name = renameText.trimmingCharacters(in: .whitespacesAndNewlines)162        renaming = nil163        guard !name.isEmpty, let lists = app.sync.active?.watchlists, lists[id]?.data.name != name else { return }164        Task { await lists.update(id) { $0.name = name } }165    }166167    private func delete(_ w: VQObject<VQWatchlist>) {168        guard let lists = app.sync.active?.watchlists else { return }169        deleting = nil170        if model.watchlistId == w.id { model.watchlistId = nil }171        Task {172            await lists.delete(w.id)173            if let e = lists.lastError { app.toasts.show(e.userMessage, error: true) } else { app.toasts.show("“\(w.data.name)” deleted.") }174        }175    }176177    // MARK: the open list178179    @ViewBuilder private func detail(_ session: SyncSession) -> some View {180        if let w = current {181            let symbols = w.data.symbols182            VStack(spacing: 0) {183                header(w, pending: session.watchlists.pendingIDs.contains(w.id))184                if symbols.isEmpty {185                    // an overlay: the empty state never takes part in the layout of the window186                    Color.clear.overlay {187                        VQEmptyState(systemImage: "star", title: "This watchlist is empty", message: "Add symbols with the field above, or drop tickers here. The list follows your account on every device.")188                    }189                    .frame(maxWidth: .infinity, maxHeight: .infinity)190                        .onDrop(of: [.plainText], isTargeted: nil) { providers in drop(providers, onto: nil, below: true); return true }191                } else {192                    columnHeader193                    Hairline(strong: true)194                    table(w)195                }196                Hairline()197                footer(w)198            }199        } else if !session.watchlists.isLoaded {200            ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)201        } else {202            // an overlay: the empty state never takes part in the layout of the window203            Color.clear.overlay {204                VQEmptyState(systemImage: "star", title: "No watchlist yet", message: "A watchlist belongs to your account: it appears on the web, the Mac and the iPhone.") {205                    Button("New Watchlist") { newName = ""; creating = true; nameFocused = true }206                }207            }208            .frame(maxWidth: .infinity, maxHeight: .infinity)209        }210    }211212    private func header(_ w: VQObject<VQWatchlist>, pending: Bool) -> some View {213        HStack(alignment: .center, spacing: TS.s3) {214            Text(w.data.name.isEmpty ? "Untitled" : w.data.name).font(TT.displayMd.font).tracking(TT.displayMd.tracking).foregroundStyle(TP.text1).lineLimit(1)215                .accessibilityIdentifier("watchlist.title")216            if pending {217                HStack(spacing: 4) { Image(systemName: "arrow.up.circle"); Text("Pending sync") }218                    .font(.system(size: 10.5, weight: .medium)).foregroundStyle(TP.text2)219                    .padding(.horizontal, 7).padding(.vertical, 2.5).overlay { Capsule(style: .continuous).strokeBorder(TP.lineStrong, style: StrokeStyle(lineWidth: 1, dash: [3, 2])) }220                    .help("This Mac has a change to this list that the server has not accepted yet. It is kept and sent as soon as possible.")221                    .accessibilityIdentifier("watchlist.pending")222            }223            Spacer(minLength: TS.s3)224            SymbolSearchField(app: app, placeholder: "Add a symbol") { s in add([s], to: w.id) }.frame(width: 240)225            Menu {226                Button("Rename…") { beginRename(w) }227                Button("Copy Symbols") { VQPasteboard.copy(w.data.symbols.joined(separator: "\n")) }.disabled(w.data.symbols.isEmpty)228                Divider()229                Button("Delete Watchlist…", role: .destructive) { deleting = w }230            } label: { Image(systemName: "ellipsis.circle") }231                .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().help("Rename or delete this watchlist")232                .accessibilityLabel("Watchlist actions").accessibilityIdentifier("watchlist.actions")233        }234        .padding(.horizontal, TS.s6).padding(.top, TS.s5).padding(.bottom, TS.s4)235    }236237    private var columnHeader: some View {238        HStack(spacing: WatchColumns.spacing) {239            Text("Symbol").frame(width: WatchColumns.symbol, alignment: .leading)240            Text("Name").frame(maxWidth: .infinity, alignment: .leading)241            Text("Day range").frame(width: WatchColumns.range, alignment: .leading)242            Text("Volume").frame(width: WatchColumns.volume, alignment: .trailing)243            Text("Last").frame(width: WatchColumns.price, alignment: .trailing)244            Text("Change").frame(width: WatchColumns.change, alignment: .trailing)245            Text("%").frame(width: WatchColumns.percent, alignment: .trailing)246            Text("Freshness").frame(width: WatchColumns.chip, alignment: .leading)247        }248        .font(TT.overline.font).tracking(TT.overline.tracking).textCase(.uppercase).foregroundStyle(TP.text3)249        .padding(.horizontal, TS.s6).padding(.bottom, 6)250    }251252    private func table(_ w: VQObject<VQWatchlist>) -> some View {253        let symbols = w.data.symbols254        let store = app.terminal255        let locale = app.vqTheme.numberLocale256        return ScrollView {257            LazyVStack(spacing: 0) {258                ForEach(symbols, id: \.self) { s in259                    WatchRow(symbol: s, quote: store.quotes[s], missing: store.missing.contains(s), selected: selection.contains(s), locale: locale,260                             dropEdge: dropTarget?.symbol == s ? (dropTarget?.below == true ? .bottom : .top) : nil)261                        .contentShape(Rectangle())262                        .onTapGesture { click(s, in: symbols) }263                        .simultaneousGesture(TapGesture(count: 2).onEnded { model.show(.charting, symbol: s) })264                        .onDrag {265                            dragging = selection.contains(s) ? selection.ordered(in: symbols) : [s]266                            // one plain-text ticker: what a chart (or any text field) accepts267                            return NSItemProvider(object: s as NSString)268                        } preview: {269                            Text(selection.contains(s) && selection.count > 1 ? "\(s) +\(selection.count - 1)" : s)270                                .font(.system(size: 12, weight: .semibold, design: .monospaced)).padding(.horizontal, 10).padding(.vertical, 5)271                                .background(TP.ink2, in: Capsule()).overlay { Capsule().strokeBorder(TP.lineStrong) }272                        }273                        .onDrop(of: [.plainText], delegate: RowDrop(symbol: s, target: $dropTarget) { providers, below in drop(providers, onto: s, below: below) })274                        .contextMenu { rowMenu(s, in: w) }275                        .accessibilityElement(children: .combine)276                        .accessibilityAddTraits(selection.contains(s) ? [.isButton, .isSelected] : .isButton)277                        .accessibilityValue(selection.contains(s) ? "selected" : "")278                        .accessibilityIdentifier("watchlist.row.\(s)")279                    Hairline().padding(.horizontal, TS.s6)280                }281            }282            .padding(.bottom, TS.s4)283            // the space under the last row takes drops too (append)284            .frame(maxWidth: .infinity, minHeight: 200, alignment: .top)285            .contentShape(Rectangle())286            .onTapGesture { selection.clear(); tableFocused = true }287        }288        .onDrop(of: [.plainText], isTargeted: nil) { providers in drop(providers, onto: nil, below: true); return true }289        .focusable().focused($tableFocused).focusEffectDisabled()290        .onKeyPress(keys: [.upArrow, .downArrow]) { press in291            selection.move(by: press.key == .upArrow ? -1 : 1, in: symbols, extending: press.modifiers.contains(.shift)); return .handled292        }293        .onKeyPress(keys: [.delete, .deleteForward]) { _ in removeSelection(from: w.id); return .handled }294        .onKeyPress(.return) { if let s = selection.ordered(in: symbols).first { model.show(.charting, symbol: s); return .handled }; return .ignored }295        .onKeyPress(.escape) { guard !selection.isEmpty else { return .ignored }; selection.clear(); return .handled }296        .onKeyPress(characters: CharacterSet(charactersIn: "a")) { press in297            guard press.modifiers.contains(.command) else { return .ignored }298            selection.selectAll(symbols); return .handled299        }300        .accessibilityIdentifier("watchlist.table")301    }302303    @ViewBuilder private func rowMenu(_ s: String, in w: VQObject<VQWatchlist>) -> some View {304        // a right-click on a row outside the selection acts on that row; inside it, on the whole selection305        let targets = selection.contains(s) && selection.count > 1 ? selection.ordered(in: w.data.symbols) : [s]306        if targets.count == 1 {307            SymbolContextMenu(app: app, model: model, symbol: s, name: app.terminal.quotes[s]?.name, context: "From the watchlist “\(w.data.name)”.")308        } else {309            Button("Chart \(targets[0])") { model.show(.charting, symbol: targets[0]) }310            Button("Copy \(targets.count) Symbols") { VQPasteboard.copy(targets.joined(separator: "\n")) }311            Button("Ask the Agent to Compare Them") {312                model.ask(AskDraft(text: "Compare \(targets.joined(separator: ", ")): performance, valuation and risk.", context: "Symbols selected in the watchlist “\(w.data.name)”."))313            }314        }315        Divider()316        Button(targets.count == 1 ? "Remove from Watchlist" : "Remove \(targets.count) Symbols", role: .destructive) { remove(Set(targets), from: w.id) }317    }318319    private func footer(_ w: VQObject<VQWatchlist>) -> some View {320        let store = app.terminal321        let n = w.data.symbols.count322        return HStack(spacing: TS.s3) {323            Text("\(n) symbol\(n == 1 ? "" : "s")").font(TT.caption.font).monospacedDigit().foregroundStyle(TP.text2)324            Text(selection.isEmpty ? "No selection" : "\(selection.count) selected").font(TT.caption.font.weight(selection.isEmpty ? .regular : .semibold)).monospacedDigit()325                .foregroundStyle(selection.isEmpty ? TP.text3 : TP.text1)326                .accessibilityValue("\(selection.count)")327                .accessibilityIdentifier("watchlist.selection")328            if !selection.isEmpty {329                Button("Remove") { removeSelection(from: w.id) }.controlSize(.small).accessibilityIdentifier("watchlist.remove")330                    .help("Remove the selected symbols from this list (⌫)")331                Button("Clear") { selection.clear() }.controlSize(.small).buttonStyle(.borderless)332            }333            Spacer(minLength: TS.s3)334            if let e = store.quotesError, store.quotes.isEmpty { Label(e, systemImage: "exclamationmark.triangle").font(TT.caption.font).foregroundStyle(TP.critical).lineLimit(1) }335            if store.quotesFromCache, let t = store.quotesReceived { CachedChip(received: t) }336            else if let f = store.quotesFreshness, n > 0 { VQProvenanceChip(f) }337            Text(app.settings.quoteRefresh > 0 ? "Polled every \(max(10, app.settings.quoteRefresh)) s" : "Polled on demand").font(TT.caption.font).foregroundStyle(TP.text3)338                .help("Quotes are requested from the server over HTTPS at this cadence. There is no streaming feed.")339            Button { Task { await store.loadQuotes(w.data.symbols) } } label: { Image(systemName: "arrow.clockwise") }340                .buttonStyle(.borderless).disabled(store.quotesLoading || n == 0).help("Ask for the quotes again").accessibilityLabel("Refresh quotes")341        }342        .padding(.horizontal, TS.s6).frame(height: 34)343        .background(TP.ink1)344    }345346    // MARK: actions347348    private func click(_ s: String, in symbols: [String]) {349        let flags = NSEvent.modifierFlags350        if flags.contains(.command) { selection.toggle(s) }351        else if flags.contains(.shift) { selection.extend(to: s, in: symbols) }352        else { selection.click(s) }353        tableFocused = true354    }355356    private func add(_ raw: [String], to id: String) {357        guard let lists = app.sync.active?.watchlists, let list = lists[id] else { return }358        let symbols = raw.compactMap(Watchlist.normalize)359        let fresh = symbols.filter { !list.data.symbols.contains($0) }360        guard !fresh.isEmpty else { if let s = symbols.first { app.toasts.show("\(s) is already in this watchlist.") }; return }361        guard list.data.symbols.count + fresh.count <= VQWatchlist.maxSymbols else { app.toasts.show("A watchlist holds at most \(VQWatchlist.maxSymbols) symbols.", error: true); return }362        Task {363            await lists.update(id) { w in for s in fresh { w.add(s) } }364            if let e = lists.lastError { app.toasts.show(e.userMessage, error: true) }365        }366    }367368    private func remove(_ symbols: Set<String>, from id: String) {369        guard !symbols.isEmpty, let lists = app.sync.active?.watchlists else { return }370        Task {371            await lists.update(id) { w in w.symbols = w.symbols.filter { !symbols.contains($0) } }372            if let e = lists.lastError { app.toasts.show(e.userMessage, error: true) }373        }374    }375376    private func removeSelection(from id: String) { remove(selection.ids, from: id); selection.clear() }377378    /// A drop on a row (or under the last one): rows dragged from this list are moved there; a ticker coming from379    /// elsewhere (a chart, a text) is added to the list.380    private func drop(_ providers: [NSItemProvider], onto row: String?, below: Bool) {381        let moving = dragging382        dragging = []; dropTarget = nil383        guard let w = current, let lists = app.sync.active?.watchlists else { return }384        let id = w.id385        Task {386            var texts: [String] = []387            for p in providers where p.canLoadObject(ofClass: NSString.self) {388                if let s = await Self.string(from: p) { texts.append(s) }389            }390            let tickers = texts.flatMap { $0.split(whereSeparator: { $0 == "\n" || $0 == "," || $0 == " " || $0 == "\t" }).map(String.init) }.compactMap(Watchlist.normalize)391            guard let first = tickers.first else { return }392            if moving.contains(first), let live = lists[id]?.data.symbols {393                let set = Set(moving)394                let next = row.map { ListReorder.move(live, moving: set, onto: $0, below: below) } ?? ListReorder.move(live, moving: set, before: nil)395                guard next != live else { return }396                await lists.update(id) { $0.symbols = next }397                if let e = lists.lastError { app.toasts.show(e.userMessage, error: true) }398            } else { add(tickers, to: id) }399        }400    }401402    private static func string(from provider: NSItemProvider) async -> String? {403        await withCheckedContinuation { c in404            _ = provider.loadObject(ofClass: NSString.self) { value, _ in c.resume(returning: value as? String) }405        }406    }407}408409private enum WatchColumns {410    static let spacing: CGFloat = 10411    static let symbol: CGFloat = 84, range: CGFloat = 104, volume: CGFloat = 76, price: CGFloat = 92, change: CGFloat = 84, percent: CGFloat = 84, chip: CGFloat = 112412}413414private struct RowDrop: DropDelegate {415    let symbol: String416    @Binding var target: WatchlistsView.DropTarget?417    let perform: ([NSItemProvider], Bool) -> Void418    private func below(_ info: DropInfo) -> Bool { info.location.y > WatchRow.height / 2 }419420    func validateDrop(info: DropInfo) -> Bool { info.hasItemsConforming(to: [.plainText]) }421    func dropUpdated(info: DropInfo) -> DropProposal? {422        let t = WatchlistsView.DropTarget(symbol: symbol, below: below(info))423        if target != t { target = t }424        return DropProposal(operation: .move)425    }426    func dropExited(info: DropInfo) { if target?.symbol == symbol { target = nil } }427    func performDrop(info: DropInfo) -> Bool { let b = below(info); target = nil; perform(info.itemProviders(for: [.plainText]), b); return true }   // the indicator line must not outlive the drop428}429430private struct WatchRow: View {431    static let height: CGFloat = 32432    let symbol: String433    let quote: VQQuote?434    let missing: Bool435    let selected: Bool436    let locale: VQNumberLocale437    let dropEdge: VerticalEdge?438    @State private var over = false439440    var body: some View {441        HStack(spacing: WatchColumns.spacing) {442            Text(symbol).font(.system(size: 13, weight: .semibold, design: .monospaced)).foregroundStyle(TP.text1).lineLimit(1).frame(width: WatchColumns.symbol, alignment: .leading)443            Text(quote?.name ?? (missing ? "No provider quotes this symbol" : "")).font(TT.bodySm.font).foregroundStyle(missing ? TP.text3 : TP.text2).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading)444            if let q = quote {445                DayRangeBar(low: q.dayLow, high: q.dayHigh, price: q.price, locale: locale).frame(width: WatchColumns.range)446                Text(TerminalFormat.compact(q.volume, locale: locale)).font(.system(size: 12, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text2).frame(width: WatchColumns.volume, alignment: .trailing)447                Text(TerminalFormat.price(q.price, locale: locale)).font(.system(size: 13, weight: .medium, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text1).frame(width: WatchColumns.price, alignment: .trailing)448                TDelta(value: q.change, text: VQFormat.number(q.change, decimals: TerminalFormat.changeDecimals(level: q.price, unit: nil), signed: true, locale: locale)).frame(width: WatchColumns.change, alignment: .trailing)449                TDelta(value: q.changePct, text: VQFormat.percentValue(q.changePct, signed: true, locale: locale)).frame(width: WatchColumns.percent, alignment: .trailing)450                // each quote has its own kind (polled, or delayed when it comes from the secondary provider) and provider time451                VQProvenanceChip(kind: q.freshness?.known ?? .polled, provider: nil, asOf: q.providerTimestamp).frame(width: WatchColumns.chip, alignment: .leading)452                    .help("\(VQFreshness.providerName(q.provider) ?? "Provider") · \(q.exchange ?? "") \(q.currency ?? "")")453            } else if missing {454                Text("Unavailable").font(.system(size: 10.5, weight: .medium)).foregroundStyle(TP.text3).frame(width: WatchColumns.chip, alignment: .leading)455            } else {456                VQSkeleton(width: 220, height: 10).frame(maxWidth: 440, alignment: .trailing)457            }458        }459        .padding(.horizontal, TS.s6)460        .frame(height: Self.height)461        .background(selected ? TP.ink4 : over ? TP.ink3.opacity(0.6) : Color.clear)462        .overlay(alignment: .leading) { if selected { Rectangle().fill(TP.accent).frame(width: 2) } }463        .overlay(alignment: dropEdge == .bottom ? .bottom : .top) { if dropEdge != nil { Rectangle().fill(TP.accent).frame(height: 2).padding(.horizontal, TS.s4) } }464        .onHover { over = $0 }465    }466}467468/// Where the last price sits in the day's range.469private struct DayRangeBar: View {470    let low: Double?, high: Double?, price: Double?471    let locale: VQNumberLocale472    var body: some View {473        GeometryReader { g in474            if let low, let high, let price, high > low {475                let x = max(0, min(1, (price - low) / (high - low)))476                ZStack(alignment: .leading) {477                    Capsule().fill(TP.lineStrong).frame(height: 2)478                    Circle().fill(TP.text1).frame(width: 6, height: 6).offset(x: x * (g.size.width - 6))479                }480                .frame(maxHeight: .infinity)481            }482        }483        .frame(height: 12)484        .help("Day range \(TerminalFormat.price(low, locale: locale)) – \(TerminalFormat.price(high, locale: locale))")485        .accessibilityHidden(true)486    }487}488
Files main
Menu

Theme