Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraUI/Portfolio.swift8// Module : Qyvora UI9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// Last Modified : 2026-12-0513//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI4243// MARK: - Synchronisation state4445/// State of the synchronisation of a chain (or of the whole wallet).46public enum QSyncState: Sendable, Equatable {47 /// Up to date; `updated` is the time of the last successful refresh, when known.48 case idle(updated: Date?)49 /// A refresh is running; `progress` is a fraction from 0 to 1 when the service can measure it.50 case syncing(progress: Double?)51 /// The figures shown were saved by a previous session and have not been refreshed yet.52 case stale(since: Date?)53 /// The last refresh failed; the reason is shown as given.54 case failed(reason: String)5556 /// Rows stay quiet when everything is up to date.57 public var isVisibleInRow: Bool {58 if case .idle = self { return false }59 return true60 }6162 public var tone: QTone {63 switch self {64 case .idle: return .positive65 case .syncing: return .info66 case .stale: return .neutral67 case .failed: return .critical68 }69 }7071 public var systemImage: String {72 switch self {73 case .idle: return "checkmark.circle"74 case .syncing: return "arrow.triangle.2.circlepath"75 case .stale: return "clock.arrow.circlepath"76 case .failed: return "exclamationmark.triangle"77 }78 }7980 /// Progress clamped to 0…1, or nil.81 public var fraction: Double? {82 if case .syncing(let progress) = self, let progress, progress.isFinite { return min(1, max(0, progress)) }83 return nil84 }8586 /// Short label: "Up to date", "Syncing 42%", "From previous session", "Sync failed".87 public var shortLabel: String {88 switch self {89 case .idle: return "Up to date"90 case .syncing: return fraction.map { "Syncing \(Int(($0 * 100).rounded(.down)))%" } ?? "Syncing"91 case .stale: return "From previous session"92 case .failed: return "Sync failed"93 }94 }9596 /// The label used inside a row, where the balance needs the width: "Saved earlier" instead of "From previous session".97 public var rowLabel: String {98 if case .stale = self { return "Saved earlier" }99 return shortLabel100 }101102 /// One sentence for a banner.103 public func detail(now: Date = Date()) -> String {104 switch self {105 case .idle(let updated):106 return updated.map { "Updated \(RelativeTime.text(for: $0, now: now))." } ?? "Balances are up to date."107 case .syncing:108 return "Balances and history are being refreshed."109 case .stale(let since):110 return "These figures were saved " + (since.map { RelativeTime.text(for: $0, now: now) } ?? "earlier") + " and have not been refreshed yet."111 case .failed(let reason):112 return reason113 }114 }115}116117/// Sync state of one chain, as a small label: a glyph (or a spinner), a few words and, when it failed, a retry control.118public struct SyncPill: View {119 public enum Style: Sendable { case pill, inline }120121 let state: QSyncState122 let style: Style123 let onRetry: (() -> Void)?124125 public init(_ state: QSyncState, style: Style = .pill, onRetry: (() -> Void)? = nil) {126 self.state = state127 self.style = style128 self.onRetry = onRetry129 }130131 var color: Color { state.tone == .neutral ? QColor.textSecondary : state.tone.color }132133 var canRetry: Bool {134 guard onRetry != nil, style == .pill else { return false }135 switch state {136 case .failed, .stale: return true137 default: return false138 }139 }140141 public var body: some View {142 HStack(spacing: 5) {143 if case .syncing = state {144 ProgressView().controlSize(.mini).tint(color)145 } else {146 Image(systemName: state.systemImage).imageScale(.small)147 }148 Text(style == .inline ? state.rowLabel : state.shortLabel).lineLimit(1).qNumericTransition()149 if canRetry, let onRetry {150 Button(action: onRetry) {151 Text("Retry").underline()152 .frame(minHeight: QMetric.minTap)153 .contentShape(Rectangle())154 }155 .buttonStyle(.plain)156 .foregroundStyle(QColor.textPrimary)157 .padding(.leading, 3)158 // the control keeps a 44-point target without making this pill taller than its neighbours159 .padding(.vertical, -8)160 }161 }162 .font(style == .pill ? QFont.captionStrong : QFont.caption)163 .foregroundStyle(color)164 .padding(.horizontal, style == .pill ? 10 : 0)165 .padding(.vertical, style == .pill ? 6 : 0)166 .background {167 if style == .pill {168 Capsule().fill(QColor.surface)169 Capsule().strokeBorder(QColor.stroke, lineWidth: 1)170 }171 }172 .qAnimation(value: state)173 .accessibilityElement(children: canRetry ? .contain : .ignore)174 .accessibilityLabel(state.shortLabel)175 }176}177178/// Sync state of the wallet as a full-width strip above the content: what is happening, a progress line while it179/// runs, and a retry control when it failed or when the figures come from a previous session.180public struct SyncBanner: View {181 let state: QSyncState182 let title: String?183 let onRetry: (() -> Void)?184185 public init(_ state: QSyncState, title: String? = nil, onRetry: (() -> Void)? = nil) {186 self.state = state187 self.title = title188 self.onRetry = onRetry189 }190191 var color: Color { state.tone == .neutral ? QColor.textSecondary : state.tone.color }192193 var showsRetry: Bool {194 guard onRetry != nil else { return false }195 switch state {196 case .failed, .stale: return true197 default: return false198 }199 }200201 public var body: some View {202 VStack(alignment: .leading, spacing: 0) {203 HStack(alignment: .firstTextBaseline, spacing: QSpace.m) {204 Group {205 if case .syncing = state {206 ProgressView().controlSize(.small).tint(color)207 } else {208 Image(systemName: state.systemImage).font(.callout.weight(.semibold)).foregroundStyle(color)209 }210 }211 .frame(width: 22)212 .accessibilityHidden(true)213 VStack(alignment: .leading, spacing: 2) {214 Text(title ?? state.shortLabel).font(QFont.subheadline).foregroundStyle(QColor.textPrimary).qNumericTransition()215 Text(state.detail()).font(QFont.caption).foregroundStyle(QColor.textSecondary)216 }217 .fixedSize(horizontal: false, vertical: true)218 Spacer(minLength: QSpace.s)219 if showsRetry, let onRetry {220 Button(action: onRetry) {221 Label("Retry", systemImage: "arrow.clockwise")222 .font(QFont.captionStrong)223 .foregroundStyle(QColor.textPrimary)224 .padding(.horizontal, 12)225 .frame(minHeight: 34)226 .background(QColor.surfaceRaised, in: Capsule())227 .overlay(Capsule().strokeBorder(QColor.stroke, lineWidth: 1))228 .frame(minHeight: QMetric.minTap)229 .contentShape(Rectangle())230 }231 .buttonStyle(.plain)232 }233 }234 .padding(.horizontal, 14)235 .padding(.vertical, 10)236 if let fraction = state.fraction {237 GeometryReader { geo in238 ZStack(alignment: .leading) {239 Rectangle().fill(QColor.stroke)240 Rectangle().fill(QColor.accentLine).frame(width: geo.size.width * fraction)241 }242 }243 .frame(height: 2)244 .qAnimation(QMotion.numeric, value: fraction)245 .accessibilityHidden(true)246 }247 }248 .frame(maxWidth: .infinity, alignment: .leading)249 .background(QColor.surface)250 .clipShape(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))251 .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))252 .qAnimation(value: state)253 .accessibilityElement(children: showsRetry ? .contain : .combine)254 }255}256257// MARK: - Change258259/// A change of value over a period, as the caller computed it.260public struct QChange: Sendable, Equatable {261 /// The change as a fraction (0.0241 = +2.41%).262 public let fraction: Double263 /// The same change as an already formatted amount ("$12.40"), without sign, or nil.264 public let amount: String?265 /// The period in a few characters ("24 h").266 public let period: String267268 public init(fraction: Double, amount: String? = nil, period: String = "24 h") {269 self.fraction = fraction270 self.amount = amount271 self.period = period272 }273274 public enum Direction: Sendable { case up, down, flat }275276 public var direction: Direction {277 guard let text = FiatFormat.percentChange(fraction), text.first == "+" || text.first == "−" else { return .flat }278 return fraction > 0 ? .up : .down279 }280281 public var percentText: String { FiatFormat.percentChange(fraction) ?? "—" }282283 public var spoken: String {284 let magnitude = percentText.trimmingCharacters(in: CharacterSet(charactersIn: "+−"))285 switch direction {286 case .up: return "Up \(magnitude) over \(period)"287 case .down: return "Down \(magnitude) over \(period)"288 case .flat: return "Unchanged over \(period)"289 }290 }291}292293/// A change written with an arrow, a sign and the figure: the direction is readable without colour.294public struct ChangeLabel: View {295 let change: QChange296 let showsPeriod: Bool297 let hidden: Bool298299 public init(_ change: QChange, showsPeriod: Bool = false, hidden: Bool = false) {300 self.change = change301 self.showsPeriod = showsPeriod302 self.hidden = hidden303 }304305 var color: Color {306 switch change.direction {307 case .up: return QColor.positive308 case .down: return QColor.negative309 case .flat: return QColor.textSecondary310 }311 }312313 var arrow: String {314 switch change.direction {315 case .up: return "arrow.up.right"316 case .down: return "arrow.down.right"317 case .flat: return "arrow.right"318 }319 }320321 public var body: some View {322 HStack(spacing: 4) {323 Image(systemName: arrow).font(.caption2.weight(.bold))324 Text(change.percentText).qNumericTransition()325 if let amount = change.amount {326 Text(hidden ? "••••" : "(" + (change.direction == .down ? "−" : (change.direction == .up ? "+" : "")) + amount + ")")327 .foregroundStyle(QColor.textSecondary)328 }329 if showsPeriod {330 Text(change.period).foregroundStyle(QColor.textSecondary)331 }332 }333 .font(QFont.figure)334 .foregroundStyle(color)335 .lineLimit(1)336 .accessibilityElement(children: .ignore)337 .accessibilityLabel(change.spoken)338 }339}340341// MARK: - Portfolio header342343/// Top of the wallet: the total value, its change over 24 hours and the hide-amounts control. When the total is a344/// sum over test networks it carries a reference-value label; the slot under it receives the unaudited-mainnet345/// notice when one applies.346public struct PortfolioHeader<Notice: View>: View {347 let title: String348 let total: String?349 let change: QChange?350 let isHidden: Bool351 let referenceLabel: String?352 let onToggleHidden: (() -> Void)?353 let notice: Notice354 @State private var toggles = 0355356 /// - Parameters:357 /// - total: the already formatted total, or nil when no price is known (a dash is shown, never a zero).358 /// - referenceLabel: when the figure is not real money (test networks), the sentence that says so.359 /// - notice: a view shown under the figures (`WarningBanner`, the unaudited-mainnet notice…).360 public init(title: String = "Total balance", total: String?, change: QChange? = nil, isHidden: Bool = false,361 referenceLabel: String? = nil, onToggleHidden: (() -> Void)? = nil, @ViewBuilder notice: () -> Notice) {362 self.title = title363 self.total = total364 self.change = change365 self.isHidden = isHidden366 self.referenceLabel = referenceLabel367 self.onToggleHidden = onToggleHidden368 self.notice = notice()369 }370371 public var body: some View {372 VStack(alignment: .leading, spacing: QSpace.m) {373 VStack(alignment: .leading, spacing: QSpace.xs) {374 HStack(alignment: .center, spacing: QSpace.s) {375 QEyebrow(title)376 Spacer(minLength: QSpace.s)377 if let onToggleHidden {378 Button {379 toggles += 1380 onToggleHidden()381 } label: {382 Image(systemName: isHidden ? "eye.slash" : "eye")383 .font(.callout.weight(.medium))384 .foregroundStyle(QColor.textSecondary)385 .contentTransition(.symbolEffect(.replace))386 .frame(width: QMetric.minTap, height: QMetric.minTap, alignment: .trailing)387 .contentShape(Rectangle())388 }389 .buttonStyle(.plain)390 .qHaptic(.toggled, trigger: toggles)391 .accessibilityLabel(isHidden ? "Show amounts" : "Hide amounts")392 }393 }394 .frame(minHeight: onToggleHidden == nil ? nil : QMetric.minTap)395 Text(isHidden ? "••••••" : (total ?? "—"))396 .font(QFont.display)397 .foregroundStyle(total == nil && !isHidden ? QColor.textTertiary : QColor.textPrimary)398 .lineLimit(1)399 .minimumScaleFactor(0.45)400 .qNumericTransition()401 .qAnimation(QMotion.numeric, value: total)402 .qAnimation(QMotion.numeric, value: isHidden)403 .accessibilityLabel(isHidden ? "Amounts hidden" : (total.map { "\(title): \($0)" } ?? "\(title) not available"))404 if let change {405 ChangeLabel(change, showsPeriod: true, hidden: isHidden).padding(.top, 2)406 }407 }408 if let referenceLabel {409 HStack(alignment: .firstTextBaseline, spacing: QSpace.s) {410 QTestTag()411 Text(referenceLabel).font(QFont.caption).foregroundStyle(QColor.textSecondary)412 .fixedSize(horizontal: false, vertical: true)413 }414 .accessibilityElement(children: .combine)415 }416 notice417 }418 .frame(maxWidth: .infinity, alignment: .leading)419 }420}421422public extension PortfolioHeader where Notice == EmptyView {423 init(title: String = "Total balance", total: String?, change: QChange? = nil, isHidden: Bool = false,424 referenceLabel: String? = nil, onToggleHidden: (() -> Void)? = nil) {425 self.init(title: title, total: total, change: change, isHidden: isHidden, referenceLabel: referenceLabel,426 onToggleHidden: onToggleHidden) { EmptyView() }427 }428}429430// MARK: - Allocation431432/// One part of a whole: a chain's or an asset's share of the portfolio.433public struct AllocationItem: Identifiable, Sendable {434 public let id: String435 public let label: String436 public let value: Double437 public let detail: String?438 public let color: Color439440 /// - Parameters:441 /// - value: any non-negative measure (fiat value); only the proportions matter.442 /// - detail: already formatted value shown in the legend, or nil.443 public init(id: String? = nil, label: String, value: Double, detail: String? = nil, color: Color) {444 self.id = id ?? label445 self.label = label446 self.value = value447 self.detail = detail448 self.color = color449 }450451 /// The share of a chain, in its name and tint.452 public init(chain: QChain, value: Double, detail: String? = nil) {453 self.init(id: chain.rawValue, label: chain.name, value: value, detail: detail, color: chain.tintColor)454 }455}456457/// The segments actually drawn: the largest entries, the rest folded into "Other", each with a fill pattern so that458/// two segments never differ by colour only.459struct AllocationSegments {460 struct Segment: Identifiable {461 let id: String462 let label: String463 let detail: String?464 let color: Color465 let pattern: SegmentedSummaryBar.Pattern466 let share: Double467 let percent: String468 }469470 // hollow is kept for "Other", so that it never sits next to a hollow neighbour471 static let patterns: [SegmentedSummaryBar.Pattern] = [.solid, .striped, .dotted]472473 static func resolve(_ items: [AllocationItem], maxSegments: Int, otherLabel: String) -> [Segment] {474 let values = items.map(\.value)475 let grouping = AllocationMath.grouping(values, maxSegments: maxSegments)476 var rows: [(id: String, label: String, detail: String?, color: Color, value: Double)] = grouping.kept.map {477 (items[$0].id, items[$0].label, items[$0].detail, items[$0].color, items[$0].value)478 }479 if !grouping.other.isEmpty {480 let sum = grouping.other.reduce(0) { $0 + values[$1] }481 rows.append(("__other", "\(otherLabel) (\(grouping.other.count))", nil, QColor.textSecondary, sum))482 }483 let shares = AllocationMath.shares(rows.map(\.value))484 let percents = AllocationMath.wholePercents(shares)485 return rows.enumerated().map { index, row in486 Segment(id: row.id, label: row.label, detail: row.detail, color: row.color,487 pattern: row.id == "__other" ? .hollow : patterns[index % patterns.count],488 share: shares[index], percent: AllocationMath.percentText(share: shares[index], wholePercent: percents[index]))489 }490 }491}492493struct AllocationLegend: View {494 let segments: [AllocationSegments.Segment]495 let hidden: Bool496 var showsDetail = true497 @ScaledMetric(relativeTo: .caption) private var swatch: CGFloat = 12498 @Environment(\.dynamicTypeSize) private var typeSize499500 var body: some View {501 let large = typeSize.isAccessibilitySize502 VStack(alignment: .leading, spacing: QSpace.s) {503 ForEach(segments) { segment in504 HStack(alignment: .firstTextBaseline, spacing: QSpace.s) {505 PatternFill(color: segment.color, pattern: segment.pattern)506 .frame(width: swatch, height: swatch)507 .clipShape(RoundedRectangle(cornerRadius: 3, style: .continuous))508 .alignmentGuide(.firstTextBaseline) { $0[.bottom] - 1 }509 VStack(alignment: .leading, spacing: 2) {510 Text(segment.label).font(QFont.footnote).foregroundStyle(QColor.textPrimary).lineLimit(large ? 2 : 1)511 // at accessibility sizes the value goes under its label instead of being cut512 if large, showsDetail, let detail = segment.detail {513 Text(hidden ? "••••" : detail).font(QFont.figure).foregroundStyle(QColor.textSecondary)514 }515 }516 Spacer(minLength: QSpace.s)517 if !large, showsDetail, let detail = segment.detail {518 Text(hidden ? "••••" : detail).font(QFont.figure).foregroundStyle(QColor.textSecondary).lineLimit(1)519 }520 Text(segment.percent).font(QFont.figure).foregroundStyle(QColor.textPrimary)521 .frame(minWidth: 38, alignment: .trailing)522 }523 .accessibilityElement(children: .ignore)524 .accessibilityLabel("\(segment.label), \(segment.percent)" + (hidden ? "" : (segment.detail.map { ", " + $0 } ?? "")))525 }526 }527 }528}529530/// Shares of the portfolio as one horizontal bar and a legend. The legend carries every label and percentage in531/// text, and each segment has its own fill pattern.532public struct AllocationBar: View {533 let items: [AllocationItem]534 let maxSegments: Int535 let showsLegend: Bool536 let hidden: Bool537 let emptyLabel: String538539 /// - Parameters:540 /// - maxSegments: at most this many segments are drawn; smaller entries are folded into "Other".541 /// - hidden: hides the formatted values of the legend (the percentages stay).542 public init(items: [AllocationItem], maxSegments: Int = 5, showsLegend: Bool = true, hidden: Bool = false,543 emptyLabel: String = "Nothing to show yet") {544 self.items = items545 self.maxSegments = maxSegments546 self.showsLegend = showsLegend547 self.hidden = hidden548 self.emptyLabel = emptyLabel549 }550551 public var body: some View {552 let segments = AllocationSegments.resolve(items, maxSegments: maxSegments, otherLabel: "Other")553 VStack(alignment: .leading, spacing: QSpace.m) {554 if segments.isEmpty {555 Capsule().strokeBorder(QColor.strokeStrong, style: StrokeStyle(lineWidth: 1, dash: [4, 3])).frame(height: 10)556 Text(emptyLabel).font(QFont.caption).foregroundStyle(QColor.textSecondary)557 } else {558 GeometryReader { geo in559 let gap: CGFloat = 2560 let available = max(0, geo.size.width - gap * CGFloat(segments.count - 1))561 HStack(spacing: gap) {562 ForEach(segments) { segment in563 PatternFill(color: segment.color, pattern: segment.pattern)564 .frame(width: max(4, available * segment.share))565 }566 }567 .frame(width: geo.size.width, alignment: .leading)568 .clipShape(Capsule())569 }570 .frame(height: 10)571 .accessibilityHidden(true)572 if showsLegend { AllocationLegend(segments: segments, hidden: hidden) }573 }574 }575 .accessibilityElement(children: .contain)576 .accessibilityLabel("Allocation")577 }578}579580/// The same shares as a ring with a centre label, for the portfolio detail.581public struct AllocationRing: View {582 let items: [AllocationItem]583 let maxSegments: Int584 let centerTitle: String?585 let centerValue: String?586 let showsLegend: Bool587 let hidden: Bool588 @ScaledMetric(relativeTo: .body) private var diameter: CGFloat = 128589 @Environment(\.dynamicTypeSize) private var typeSize590591 public init(items: [AllocationItem], maxSegments: Int = 5, centerTitle: String? = nil, centerValue: String? = nil,592 showsLegend: Bool = true, hidden: Bool = false) {593 self.items = items594 self.maxSegments = maxSegments595 self.centerTitle = centerTitle596 self.centerValue = centerValue597 self.showsLegend = showsLegend598 self.hidden = hidden599 }600601 func ring(_ segments: [AllocationSegments.Segment]) -> some View {602 let d = min(diameter, 190)603 return Canvas { context, size in604 let side = min(size.width, size.height)605 let width = side * 0.13606 let radius = (side - width) / 2607 let center = CGPoint(x: size.width / 2, y: size.height / 2)608 guard !segments.isEmpty else {609 let empty = Path(ellipseIn: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2))610 context.stroke(empty, with: .color(QColor.strokeStrong), style: StrokeStyle(lineWidth: 1, dash: [4, 3]))611 return612 }613 let gap = segments.count > 1 ? 2.4 : 0.0614 var start = -90.0615 for segment in segments {616 let sweep = 360 * segment.share617 let from = start + gap / 2, to = start + max(gap / 2 + 0.6, sweep - gap / 2)618 var arc = Path()619 arc.addArc(center: center, radius: radius, startAngle: .degrees(from), endAngle: .degrees(to), clockwise: false)620 let band = arc.strokedPath(StrokeStyle(lineWidth: width, lineCap: .butt))621 var layer = context622 layer.clip(to: band)623 QPatternPainter.paint(&layer, rect: CGRect(origin: .zero, size: size), color: segment.color, pattern: segment.pattern)624 if segment.pattern == .hollow {625 context.stroke(band, with: .color(segment.color), lineWidth: 1.2)626 }627 start += sweep628 }629 }630 .frame(width: d, height: d)631 .overlay {632 VStack(spacing: 1) {633 if let centerTitle {634 Text(centerTitle.uppercased()).font(QFont.eyebrow).kerning(0.8).foregroundStyle(QColor.textSecondary)635 }636 if let centerValue {637 Text(hidden ? "••••" : centerValue).font(QFont.headline.monospacedDigit()).foregroundStyle(QColor.textPrimary)638 .minimumScaleFactor(0.6)639 }640 }641 .lineLimit(1)642 .padding(.horizontal, d * 0.2)643 }644 .accessibilityElement(children: .ignore)645 .accessibilityLabel([centerTitle, hidden ? nil : centerValue].compactMap { $0 }.joined(separator: ": "))646 }647648 public var body: some View {649 let segments = AllocationSegments.resolve(items, maxSegments: maxSegments, otherLabel: "Other")650 Group {651 if typeSize >= .xxLarge || !showsLegend {652 VStack(alignment: .leading, spacing: QSpace.l) {653 ring(segments).frame(maxWidth: .infinity)654 if showsLegend { AllocationLegend(segments: segments, hidden: hidden) }655 }656 } else {657 HStack(alignment: .center, spacing: QSpace.xl) {658 ring(segments)659 // beside the ring there is room for the label and the share; the values belong to the bar660 AllocationLegend(segments: segments, hidden: hidden, showsDetail: false)661 }662 }663 }664 .accessibilityElement(children: .contain)665 .accessibilityLabel("Allocation")666 }667}668669/// Paints a fill pattern into a graphics context (shared by the bar, the ring and the legend swatches).670enum QPatternPainter {671 static func paint(_ context: inout GraphicsContext, rect: CGRect, color: Color, pattern: SegmentedSummaryBar.Pattern) {672 switch pattern {673 case .solid:674 context.fill(Path(rect), with: .color(color))675 case .striped:676 context.fill(Path(rect), with: .color(color.opacity(0.28)))677 var stripes = Path()678 var x = rect.minX - rect.height679 while x < rect.maxX {680 stripes.move(to: CGPoint(x: x, y: rect.maxY))681 stripes.addLine(to: CGPoint(x: x + rect.height, y: rect.minY))682 x += 5683 }684 context.stroke(stripes, with: .color(color), lineWidth: 1.6)685 case .dotted:686 context.fill(Path(rect), with: .color(color.opacity(0.22)))687 var dots = Path()688 var x = rect.minX + 2689 while x < rect.maxX {690 var y = rect.minY + 2691 while y < rect.maxY {692 dots.addEllipse(in: CGRect(x: x, y: y, width: 2, height: 2))693 y += 4694 }695 x += 4696 }697 context.fill(dots, with: .color(color))698 case .hollow:699 context.fill(Path(rect), with: .color(color.opacity(0.12)))700 }701 }702}703704// MARK: - Sparkline705706/// Trend line for a row or a header: the line, a dashed reference at the first value (so that "above" and "below"707/// the start read without colour) and a point on the last value. It draws only what it is given; with fewer than708/// two values it shows a dash.709public struct ValueSparkline: View {710 let values: [Double]711 let tint: Color?712 let showsReference: Bool713 let showsEndPoint: Bool714715 /// - Parameter tint: line colour; by default green when the series rose, red when it fell, grey when flat.716 public init(values: [Double], tint: Color? = nil, showsReference: Bool = true, showsEndPoint: Bool = true) {717 self.values = values718 self.tint = tint719 self.showsReference = showsReference720 self.showsEndPoint = showsEndPoint721 }722723 /// Points of the series in a unit square (x and y from 0 to 1, y up), or nil when it cannot be drawn.724 nonisolated static func unitPoints(_ values: [Double]) -> [CGPoint]? {725 guard let series = SeriesMath.drawable(values), series.count >= 2 else { return nil }726 let low = series.min() ?? 0, high = series.max() ?? 1727 let span = high - low728 return series.enumerated().map { index, value in729 CGPoint(x: Double(index) / Double(series.count - 1), y: span == 0 ? 0.5 : (value - low) / span)730 }731 }732733 public var body: some View {734 if let points = Self.unitPoints(values), let series = SeriesMath.drawable(values) {735 let change = SeriesMath.change(series) ?? 0736 let color = tint ?? (change > 0 ? QColor.positive : (change < 0 ? QColor.negative : QColor.textSecondary))737 Canvas { context, size in738 let inset: CGFloat = 3739 let w = max(1, size.width - inset * 2), h = max(1, size.height - inset * 2)740 func place(_ p: CGPoint) -> CGPoint { CGPoint(x: inset + p.x * w, y: inset + (1 - p.y) * h) }741 if showsReference, let first = points.first {742 var reference = Path()743 reference.move(to: CGPoint(x: 0, y: place(first).y))744 reference.addLine(to: CGPoint(x: size.width, y: place(first).y))745 context.stroke(reference, with: .color(QColor.strokeStrong.opacity(0.7)), style: StrokeStyle(lineWidth: 1, dash: [2, 3]))746 }747 var line = Path()748 line.addLines(points.map(place))749 context.stroke(line, with: .color(color), style: StrokeStyle(lineWidth: 1.6, lineCap: .round, lineJoin: .round))750 if showsEndPoint, let last = points.last {751 let p = place(last)752 context.fill(Path(ellipseIn: CGRect(x: p.x - 3.5, y: p.y - 3.5, width: 7, height: 7)), with: .color(QColor.background))753 context.fill(Path(ellipseIn: CGRect(x: p.x - 2.25, y: p.y - 2.25, width: 4.5, height: 4.5)), with: .color(color))754 }755 }756 .accessibilityElement(children: .ignore)757 .accessibilityLabel("Trend")758 .accessibilityValue(change > 0 ? "Up \(SeriesMath.percentText(change))" : (change < 0 ? "Down \(SeriesMath.percentText(change))" : "Flat"))759 } else {760 Text("–")761 .font(QFont.caption)762 .foregroundStyle(QColor.textTertiary)763 .frame(maxWidth: .infinity, maxHeight: .infinity)764 .accessibilityLabel("No trend data")765 }766 }767}768769// MARK: - Quick actions770771/// One action of the quick action bar.772public struct QuickAction: Identifiable {773 public let id: String774 public let title: String775 public let systemImage: String776 public let isEnabled: Bool777 public let action: () -> Void778779 public init(id: String? = nil, title: String, systemImage: String, isEnabled: Bool = true, action: @escaping () -> Void) {780 self.id = id ?? title781 self.title = title782 self.systemImage = systemImage783 self.isEnabled = isEnabled784 self.action = action785 }786787 public static func send(isEnabled: Bool = true, _ action: @escaping () -> Void) -> QuickAction {788 QuickAction(id: "send", title: "Send", systemImage: "arrow.up.right", isEnabled: isEnabled, action: action)789 }790791 public static func receive(isEnabled: Bool = true, _ action: @escaping () -> Void) -> QuickAction {792 QuickAction(id: "receive", title: "Receive", systemImage: "arrow.down.left", isEnabled: isEnabled, action: action)793 }794795 public static func scan(isEnabled: Bool = true, _ action: @escaping () -> Void) -> QuickAction {796 QuickAction(id: "scan", title: "Scan", systemImage: "qrcode.viewfinder", isEnabled: isEnabled, action: action)797 }798799 public static func more(isEnabled: Bool = true, _ action: @escaping () -> Void) -> QuickAction {800 QuickAction(id: "more", title: "More", systemImage: "ellipsis", isEnabled: isEnabled, action: action)801 }802}803804struct QuickActionButtonStyle: ButtonStyle {805 let stacked: Bool806 @Environment(\.isEnabled) private var enabled807808 func makeBody(configuration: Configuration) -> some View {809 configuration.label810 .opacity(enabled ? 1 : 0.38)811 .scaleEffect(configuration.isPressed ? 0.96 : 1)812 .opacity(configuration.isPressed ? 0.7 : 1)813 .qAnimation(value: configuration.isPressed)814 }815}816817/// Send, Receive, Scan and More as one consistent control: equal columns, a square key and a caption. The first818/// action is the primary one (filled); the others are outlined. At accessibility sizes the actions stack as rows.819public struct QuickActionBar: View {820 let actions: [QuickAction]821 @ScaledMetric(relativeTo: .body) private var key: CGFloat = 52822 @Environment(\.dynamicTypeSize) private var typeSize823 @State private var taps = 0824825 public init(_ actions: [QuickAction]) { self.actions = actions }826827 func keyShape(_ action: QuickAction, primary: Bool) -> some View {828 let side = min(key, 64)829 let shape = RoundedRectangle(cornerRadius: side * 0.32, style: .continuous)830 return Image(systemName: action.systemImage)831 .font(.system(size: side * 0.38, weight: .semibold))832 .foregroundStyle(primary ? QColor.onAccent : QColor.textPrimary)833 .frame(width: side, height: side)834 .background {835 if primary { shape.fill(QColor.accentGradient) } else { shape.fill(QColor.surface) }836 }837 .overlay { if !primary { shape.strokeBorder(QColor.stroke, lineWidth: 1) } }838 }839840 public var body: some View {841 Group {842 if typeSize.isAccessibilitySize {843 VStack(spacing: QSpace.s) {844 ForEach(Array(actions.enumerated()), id: \.element.id) { index, action in845 Button {846 taps += 1847 action.action()848 } label: {849 HStack(spacing: QSpace.m) {850 keyShape(action, primary: index == 0)851 Text(action.title).font(QFont.headline).foregroundStyle(QColor.textPrimary)852 Spacer(minLength: 0)853 }854 .contentShape(Rectangle())855 }856 .buttonStyle(QuickActionButtonStyle(stacked: true))857 .disabled(!action.isEnabled)858 }859 }860 } else {861 HStack(alignment: .top, spacing: 0) {862 ForEach(Array(actions.enumerated()), id: \.element.id) { index, action in863 Button {864 taps += 1865 action.action()866 } label: {867 VStack(spacing: QSpace.s) {868 keyShape(action, primary: index == 0)869 Text(action.title).font(QFont.captionStrong).foregroundStyle(QColor.textPrimary).lineLimit(1)870 .minimumScaleFactor(0.8)871 }872 .frame(maxWidth: .infinity)873 .contentShape(Rectangle())874 }875 .buttonStyle(QuickActionButtonStyle(stacked: false))876 .disabled(!action.isEnabled)877 }878 }879 }880 }881 .qHaptic(.tap, trigger: taps)882 }883}884