Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraUI/Feedback.swift8// Module : Qyvora UI9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//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#if canImport(UIKit)44import UIKit45import UniformTypeIdentifiers46#elseif canImport(AppKit)47import AppKit48#endif4950/// Clipboard access in one place. Every value copied by the application stays on this device (it is not offered to51/// the Universal Clipboard of the user's other devices) and expires: a sensitive one after a minute, any other one52/// (addresses, transaction identifiers, public keys) after ten minutes (MASTG-TEST-0278 and 0280). The recovery53/// phrase and private keys are never copied at all: the views that show them offer no copy action.54public enum QClipboard {55 /// Seconds after which a sensitive value leaves the clipboard (iOS).56 public static let sensitiveLifetime: TimeInterval = 6057 /// Seconds after which any other copied value leaves the clipboard (iOS).58 public static let standardLifetime: TimeInterval = 6005960 /// How long a copied value stays in the clipboard.61 public static func lifetime(sensitive: Bool) -> TimeInterval { sensitive ? sensitiveLifetime : standardLifetime }6263 @MainActor64 public static func copy(_ text: String, sensitive: Bool = false) {65 #if canImport(UIKit)66 UIPasteboard.general.setItems(67 [[UTType.utf8PlainText.identifier: text]],68 options: [.localOnly: true, .expirationDate: Date().addingTimeInterval(lifetime(sensitive: sensitive))])69 #elseif canImport(AppKit)70 NSPasteboard.general.clearContents()71 NSPasteboard.general.setString(text, forType: .string)72 #endif73 }74}7576/// Semantic tone shared by banners, dots and pills. Each tone has its own glyph, so colour is never the only cue.77public enum QTone: String, Sendable, CaseIterable {78 case neutral, info, positive, warning, critical7980 public var color: Color {81 switch self {82 case .neutral: return QColor.textSecondary83 case .info: return QColor.blue84 case .positive: return QColor.positive85 case .warning: return QColor.warning86 case .critical: return QColor.negative87 }88 }8990 public var systemImage: String {91 switch self {92 case .neutral: return "circle.dashed"93 case .info: return "info.circle"94 case .positive: return "checkmark.circle"95 case .warning: return "exclamationmark.triangle"96 case .critical: return "xmark.octagon"97 }98 }99100 var badgeTone: QBadge.Tone {101 switch self {102 case .neutral: return .neutral103 case .info: return .accent104 case .positive: return .positive105 case .warning: return .warning106 case .critical: return .negative107 }108 }109}110111/// Copies a value and confirms with a glyph change, a spoken label and a haptic.112public struct CopyButton: View {113 public enum Style: Sendable { case icon, labelled }114115 let value: String116 let title: String117 let sensitive: Bool118 let style: Style119 @State private var copied = false120 @State private var feedback = 0121122 public init(_ value: String, title: String = "Copy", sensitive: Bool = false, style: Style = .icon) {123 self.value = value124 self.title = title125 self.sensitive = sensitive126 self.style = style127 }128129 public var body: some View {130 Button {131 QClipboard.copy(value, sensitive: sensitive)132 feedback += 1133 withAnimation(.snappy(duration: 0.2)) { copied = true }134 Task { @MainActor in135 try? await Task.sleep(for: .seconds(1.6))136 withAnimation(.snappy(duration: 0.2)) { copied = false }137 }138 } label: {139 HStack(spacing: 6) {140 Image(systemName: copied ? "checkmark" : "doc.on.doc")141 .contentTransition(.symbolEffect(.replace))142 if style == .labelled { Text(copied ? "Copied" : title) }143 }144 .font(.callout.weight(.medium))145 .foregroundStyle(copied ? QColor.positive : QColor.violet)146 .frame(minWidth: 44, minHeight: 44)147 .contentShape(Rectangle())148 }149 .buttonStyle(.plain)150 .sensoryFeedback(.success, trigger: feedback)151 .accessibilityLabel(copied ? "Copied" : title)152 .accessibilityHint(sensitive ? "Copies to this device only; the clipboard is cleared after one minute." : "")153 }154}155156/// Information, warning or critical message with an icon and text.157public struct WarningBanner: View {158 public typealias Severity = QTone159160 let severity: QTone161 let title: String?162 let message: String163 let actionTitle: String?164 let action: (() -> Void)?165166 public init(_ severity: QTone = .warning, title: String? = nil, message: String, actionTitle: String? = nil, action: (() -> Void)? = nil) {167 self.severity = severity168 self.title = title169 self.message = message170 self.actionTitle = actionTitle171 self.action = action172 }173174 var spokenSeverity: String {175 switch severity {176 case .neutral: return "Note"177 case .info: return "Information"178 case .positive: return "Confirmed"179 case .warning: return "Warning"180 case .critical: return "Critical"181 }182 }183184 public var body: some View {185 HStack(alignment: .firstTextBaseline, spacing: 12) {186 Image(systemName: severity.systemImage)187 .font(.body.weight(.semibold))188 .foregroundStyle(severity.color)189 .accessibilityHidden(true)190 VStack(alignment: .leading, spacing: 4) {191 if let title {192 Text(title).font(QFont.headline).foregroundStyle(QColor.textPrimary)193 }194 Text(message).font(QFont.callout).foregroundStyle(title == nil ? QColor.textPrimary : QColor.textSecondary)195 if let actionTitle, let action {196 Button(actionTitle, action: action)197 .font(.callout.weight(.semibold))198 .foregroundStyle(QColor.violet)199 .padding(.top, 4)200 }201 }202 .fixedSize(horizontal: false, vertical: true)203 Spacer(minLength: 0)204 }205 .padding(14)206 .frame(maxWidth: .infinity, alignment: .leading)207 .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))208 .overlay(alignment: .leading) {209 UnevenRoundedRectangle(topLeadingRadius: QMetric.radiusSmall, bottomLeadingRadius: QMetric.radiusSmall, style: .continuous)210 .fill(severity.color)211 .frame(width: 3)212 }213 .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))214 .accessibilityElement(children: .combine)215 .accessibilityLabel("\(spokenSeverity). \(title.map { $0 + ". " } ?? "")\(message)")216 }217}218219/// Small state mark. The shape changes with the tone (disc, ring, triangle, square) and a label is spoken.220public struct StatusDot: View {221 let tone: QTone222 let label: String223 let showsLabel: Bool224 @ScaledMetric(relativeTo: .caption) private var size: CGFloat = 9225226 public init(_ tone: QTone, label: String, showsLabel: Bool = true) {227 self.tone = tone228 self.label = label229 self.showsLabel = showsLabel230 }231232 @ViewBuilder var mark: some View {233 switch tone {234 case .positive: Circle().fill(tone.color)235 case .info: Circle().strokeBorder(tone.color, lineWidth: 2)236 case .neutral: Circle().strokeBorder(tone.color, style: StrokeStyle(lineWidth: 1.5, dash: [2, 2]))237 case .warning: QTriangle().fill(tone.color)238 case .critical: Rectangle().fill(tone.color)239 }240 }241242 public var body: some View {243 HStack(spacing: 6) {244 mark.frame(width: size, height: size)245 if showsLabel {246 Text(label).font(QFont.caption).foregroundStyle(QColor.textSecondary)247 }248 }249 .accessibilityElement(children: .ignore)250 .accessibilityLabel(label)251 }252}253254struct QTriangle: Shape {255 func path(in rect: CGRect) -> Path {256 var p = Path()257 p.move(to: CGPoint(x: rect.midX, y: rect.minY))258 p.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))259 p.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))260 p.closeSubpath()261 return p262 }263}264265/// Section title with an optional trailing action.266public struct SectionHeader: View {267 let title: String268 let subtitle: String?269 let actionTitle: String?270 let action: (() -> Void)?271272 public init(_ title: String, subtitle: String? = nil, actionTitle: String? = nil, action: (() -> Void)? = nil) {273 self.title = title274 self.subtitle = subtitle275 self.actionTitle = actionTitle276 self.action = action277 }278279 public var body: some View {280 HStack(alignment: .firstTextBaseline, spacing: 12) {281 VStack(alignment: .leading, spacing: 3) {282 Text(title).font(QFont.headline).foregroundStyle(QColor.textPrimary).accessibilityAddTraits(.isHeader)283 if let subtitle {284 Text(subtitle).font(QFont.caption).foregroundStyle(QColor.textSecondary)285 }286 }287 Spacer(minLength: 8)288 if let actionTitle, let action {289 Button(actionTitle, action: action)290 .font(.callout.weight(.medium))291 .foregroundStyle(QColor.violet)292 }293 }294 }295}296297/// Nothing to show yet: a glyph, a title, one sentence and an optional action.298public struct EmptyStateView: View {299 let systemImage: String300 let title: String301 let message: String302 let actionTitle: String?303 let action: (() -> Void)?304305 public init(systemImage: String, title: String, message: String, actionTitle: String? = nil, action: (() -> Void)? = nil) {306 self.systemImage = systemImage307 self.title = title308 self.message = message309 self.actionTitle = actionTitle310 self.action = action311 }312313 public var body: some View {314 VStack(spacing: 14) {315 Image(systemName: systemImage)316 .font(.system(.largeTitle, weight: .light))317 .foregroundStyle(QColor.textTertiary)318 .accessibilityHidden(true)319 VStack(spacing: 6) {320 Text(title).font(QFont.headline).foregroundStyle(QColor.textPrimary)321 Text(message).font(QFont.callout).foregroundStyle(QColor.textSecondary).multilineTextAlignment(.center)322 }323 .fixedSize(horizontal: false, vertical: true)324 if let actionTitle, let action {325 Button(actionTitle, action: action)326 .buttonStyle(.qSecondary)327 .padding(.top, 6)328 }329 }330 .padding(.horizontal, 24)331 .padding(.vertical, 28)332 .frame(maxWidth: .infinity)333 }334}335336/// Says that data could not be obtained and why. Used wherever a figure or a chart would otherwise be invented.337public struct UnavailableDataView: View {338 let reason: String339 let title: String340 let retry: (() -> Void)?341 let compact: Bool342343 public init(reason: String, title: String = "Data unavailable", compact: Bool = false, retry: (() -> Void)? = nil) {344 self.reason = reason345 self.title = title346 self.compact = compact347 self.retry = retry348 }349350 public var body: some View {351 if compact {352 HStack(alignment: .firstTextBaseline, spacing: 8) {353 Image(systemName: "icloud.slash").foregroundStyle(QColor.textTertiary).accessibilityHidden(true)354 Text(reason).font(QFont.caption).foregroundStyle(QColor.textSecondary)355 .fixedSize(horizontal: false, vertical: true)356 Spacer(minLength: 0)357 if let retry {358 Button("Retry", action: retry).font(.caption.weight(.semibold)).foregroundStyle(QColor.violet)359 }360 }361 .accessibilityElement(children: .combine)362 .accessibilityLabel("\(title). \(reason)")363 } else {364 EmptyStateView(systemImage: "icloud.slash", title: title, message: reason,365 actionTitle: retry == nil ? nil : "Try again", action: retry)366 }367 }368}369370/// The states of an action that takes time.371public enum LoadingButtonState: Sendable, Equatable {372 case idle373 case loading374 case success375 case failure376}377378/// Primary or secondary action that shows progress in place and reports its outcome with a glyph and a haptic.379public struct LoadingButton: View {380 public enum Prominence: Sendable { case primary, secondary }381382 let title: String383 let loadingTitle: String?384 let systemImage: String?385 let state: LoadingButtonState386 let prominence: Prominence387 let action: () -> Void388389 public init(_ title: String, loadingTitle: String? = nil, systemImage: String? = nil, state: LoadingButtonState = .idle,390 prominence: Prominence = .primary, action: @escaping () -> Void) {391 self.title = title392 self.loadingTitle = loadingTitle393 self.systemImage = systemImage394 self.state = state395 self.prominence = prominence396 self.action = action397 }398399 @ViewBuilder var label: some View {400 HStack(spacing: 8) {401 switch state {402 case .idle:403 if let systemImage { Image(systemName: systemImage) }404 Text(title)405 case .loading:406 ProgressView().tint(prominence == .primary ? QColor.onAccent : QColor.textPrimary)407 Text(loadingTitle ?? title)408 case .success:409 Image(systemName: "checkmark")410 Text(title)411 case .failure:412 Image(systemName: "exclamationmark.triangle")413 Text(title)414 }415 }416 .padding(.horizontal, 12)417 .multilineTextAlignment(.center)418 }419420 public var body: some View {421 Group {422 switch prominence {423 case .primary: Button(action: action) { label }.buttonStyle(.qPrimary)424 case .secondary: Button(action: action) { label }.buttonStyle(.qSecondary)425 }426 }427 .allowsHitTesting(state != .loading)428 .sensoryFeedback(trigger: state) { _, new in429 switch new {430 case .success: return .success431 case .failure: return .error432 default: return nil433 }434 }435 .accessibilityLabel(state == .loading ? (loadingTitle ?? title) : title)436 .accessibilityValue(accessibilityState)437 }438439 var accessibilityState: String {440 switch state {441 case .idle: return ""442 case .loading: return "In progress"443 case .success: return "Done"444 case .failure: return "Failed"445 }446 }447}448449/// Title block of a sheet, with an explicit close control.450public struct SheetHeader: View {451 let title: String452 let subtitle: String?453 let onClose: (() -> Void)?454455 public init(_ title: String, subtitle: String? = nil, onClose: (() -> Void)? = nil) {456 self.title = title457 self.subtitle = subtitle458 self.onClose = onClose459 }460461 public var body: some View {462 HStack(alignment: .top, spacing: 12) {463 VStack(alignment: .leading, spacing: 4) {464 Text(title).font(QFont.title).foregroundStyle(QColor.textPrimary).accessibilityAddTraits(.isHeader)465 if let subtitle {466 Text(subtitle).font(QFont.callout).foregroundStyle(QColor.textSecondary)467 }468 }469 .fixedSize(horizontal: false, vertical: true)470 Spacer(minLength: 8)471 if let onClose {472 Button(action: onClose) {473 Image(systemName: "xmark")474 .font(.footnote.weight(.bold))475 .foregroundStyle(QColor.textSecondary)476 .frame(width: 32, height: 32)477 .background(QColor.surfaceRaised, in: Circle())478 .frame(minWidth: 44, minHeight: 44)479 .contentShape(Rectangle())480 }481 .buttonStyle(.plain)482 .accessibilityLabel("Close")483 }484 }485 }486}487488/// Proportions of a whole with a legend. Segments differ by fill pattern as well as colour, and the legend489/// carries the label and the share in text.490public struct SegmentedSummaryBar: View {491 public enum Pattern: Sendable, CaseIterable { case solid, striped, dotted, hollow }492493 public struct Segment: Identifiable, Sendable {494 public let id: String495 public let label: String496 public let value: Double497 public let detail: String?498 public let color: Color499 public let pattern: Pattern500501 public init(id: String? = nil, label: String, value: Double, detail: String? = nil, color: Color, pattern: Pattern = .solid) {502 self.id = id ?? label503 self.label = label504 self.value = value505 self.detail = detail506 self.color = color507 self.pattern = pattern508 }509 }510511 let segments: [Segment]512 let emptyLabel: String513 @ScaledMetric(relativeTo: .caption) private var swatch: CGFloat = 12514515 public init(segments: [Segment], emptyLabel: String = "Nothing to show") {516 self.segments = segments517 self.emptyLabel = emptyLabel518 }519520 var fractions: [Double] { Proportions.fractions(segments.map(\.value)) }521522 public var body: some View {523 let shares = fractions524 VStack(alignment: .leading, spacing: 12) {525 if shares.allSatisfy({ $0 == 0 }) {526 Capsule().strokeBorder(QColor.stroke, style: StrokeStyle(lineWidth: 1, dash: [4, 3])).frame(height: 12)527 Text(emptyLabel).font(QFont.caption).foregroundStyle(QColor.textSecondary)528 } else {529 GeometryReader { geo in530 let gap: CGFloat = 2531 let visible = shares.filter { $0 > 0 }.count532 let available = max(0, geo.size.width - gap * CGFloat(max(0, visible - 1)))533 HStack(spacing: gap) {534 ForEach(Array(segments.enumerated()), id: \.element.id) { index, segment in535 if shares[index] > 0 {536 PatternFill(color: segment.color, pattern: segment.pattern)537 .frame(width: max(3, available * shares[index]))538 }539 }540 }541 .clipShape(Capsule())542 }543 .frame(height: 12)544 .accessibilityHidden(true)545 VStack(alignment: .leading, spacing: 8) {546 ForEach(Array(segments.enumerated()), id: \.element.id) { index, segment in547 HStack(alignment: .firstTextBaseline, spacing: 8) {548 PatternFill(color: segment.color, pattern: segment.pattern)549 .frame(width: swatch, height: swatch)550 .clipShape(RoundedRectangle(cornerRadius: 3, style: .continuous))551 .alignmentGuide(.firstTextBaseline) { $0[.bottom] - 1 }552 Text(segment.label).font(QFont.callout).foregroundStyle(QColor.textPrimary)553 Spacer(minLength: 8)554 if let detail = segment.detail {555 Text(detail).font(QFont.callout.monospacedDigit()).foregroundStyle(QColor.textSecondary)556 }557 Text(Proportions.percentText(shares[index]))558 .font(QFont.callout.monospacedDigit().weight(.medium))559 .foregroundStyle(QColor.textPrimary)560 }561 .accessibilityElement(children: .ignore)562 .accessibilityLabel("\(segment.label), \(Proportions.percentText(shares[index]))\(segment.detail.map { ", " + $0 } ?? "")")563 }564 }565 }566 }567 }568}569570struct PatternFill: View {571 let color: Color572 let pattern: SegmentedSummaryBar.Pattern573574 var body: some View {575 Canvas { context, size in576 let rect = CGRect(origin: .zero, size: size)577 switch pattern {578 case .solid:579 context.fill(Path(rect), with: .color(color))580 case .striped:581 context.fill(Path(rect), with: .color(color.opacity(0.28)))582 var x = -size.height583 var stripes = Path()584 while x < size.width {585 stripes.move(to: CGPoint(x: x, y: size.height))586 stripes.addLine(to: CGPoint(x: x + size.height, y: 0))587 x += 5588 }589 context.stroke(stripes, with: .color(color), lineWidth: 1.6)590 case .dotted:591 context.fill(Path(rect), with: .color(color.opacity(0.22)))592 var dots = Path()593 var x: CGFloat = 2594 while x < size.width {595 var y: CGFloat = 2596 while y < size.height {597 dots.addEllipse(in: CGRect(x: x, y: y, width: 2, height: 2))598 y += 4599 }600 x += 4601 }602 context.fill(dots, with: .color(color))603 case .hollow:604 context.fill(Path(rect), with: .color(color.opacity(0.12)))605 context.stroke(Path(rect.insetBy(dx: 0.75, dy: 0.75)), with: .color(color), lineWidth: 1.5)606 }607 }608 }609}610611#if DEBUG612#Preview("Feedback components") {613 ScrollView {614 VStack(alignment: .leading, spacing: 20) {615 SectionHeader("Preview section", subtitle: "Illustrative inputs only", actionTitle: "Action") {}616 WarningBanner(.info, title: "Information", message: "Preview text for an informational banner.")617 WarningBanner(.warning, message: "Preview text for a warning banner.", actionTitle: "Review") {}618 WarningBanner(.critical, title: "Critical", message: "Preview text for a critical banner.")619 HStack(spacing: 16) {620 ForEach(QTone.allCases, id: \.self) { StatusDot($0, label: $0.rawValue) }621 }622 SegmentedSummaryBar(segments: [623 .init(label: "Preview A", value: 5, color: QColor.violet, pattern: .solid),624 .init(label: "Preview B", value: 3, color: QColor.blue, pattern: .striped),625 .init(label: "Preview C", value: 1, color: QColor.warning, pattern: .dotted),626 .init(label: "Preview D", value: 0.05, color: QColor.textSecondary, pattern: .hollow),627 ])628 LoadingButton("Preview action", state: .loading) {}629 LoadingButton("Preview action", systemImage: "arrow.up", prominence: .secondary) {}630 HStack { CopyButton("preview-value", style: .labelled); CopyButton("preview-value") }631 SheetHeader("Preview sheet", subtitle: "Subtitle") {}632 UnavailableDataView(reason: "Preview reason: the endpoint did not answer.", compact: true) {}633 EmptyStateView(systemImage: "tray", title: "Preview empty state", message: "One sentence that explains what will appear here.")634 }635 .padding()636 }637 .qScreen()638}639#endif640