Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Components/VQControls.swift3// Description: Segmented control, empty state, skeletons, the AI activity indicator, the sparkline.4import SwiftUI5import VQuantKit67/// A radio group with a sliding thumb. Arrow keys move the selection where there is a keyboard.8public struct VQSegmentedControl<Value: Hashable>: View {9 public struct Option: Identifiable {10 public var value: Value11 public var label: String12 public var id: Value { value }13 public init(_ value: Value, _ label: String) { self.value = value; self.label = label }14 }15 private let label: String16 private let options: [Option]17 @Binding private var selection: Value18 @Namespace private var thumb19 @Environment(\.accessibilityReduceMotion) private var systemReduceMotion20 @Environment(\.vqTheme) private var theme2122 public init(_ label: String, selection: Binding<Value>, options: [Option]) {23 self.label = label; self._selection = selection; self.options = options24 }2526 private func select(_ value: Value) {27 withAnimation(VQTokens.Motion.spring(reduceMotion: systemReduceMotion || theme.reduceMotion)) { selection = value }28 }29 private func step(_ by: Int) {30 guard let i = options.firstIndex(where: { $0.value == selection }) else { return }31 select(options[min(options.count - 1, max(0, i + by))].value)32 }3334 public var body: some View {35 HStack(spacing: 2) {36 ForEach(options) { option in37 let isOn = option.value == selection38 Button { select(option.value) } label: {39 Text(option.label)40 .vqFont(VQTokens.Typography.bodySm).fontWeight(isOn ? .semibold : .regular)41 .foregroundStyle(isOn ? VQP.text1 : VQP.text2)42 .padding(.horizontal, VQS.s3).padding(.vertical, 5)43 .frame(minHeight: 28)44 .background {45 if isOn {46 RoundedRectangle(cornerRadius: VQTokens.Radius.sm - 1, style: .continuous).fill(VQP.ink2)47 .overlay { RoundedRectangle(cornerRadius: VQTokens.Radius.sm - 1, style: .continuous).strokeBorder(VQP.lineStrong, lineWidth: VQTokens.hairline) }48 .matchedGeometryEffect(id: "thumb", in: thumb)49 }50 }51 .contentShape(Rectangle())52 }53 .buttonStyle(.plain)54 .accessibilityAddTraits(isOn ? [.isSelected] : [])55 }56 }57 .padding(2)58 .background(RoundedRectangle(cornerRadius: VQTokens.Radius.sm + 1, style: .continuous).fill(VQP.ink3))59 .fixedSize()60 .focusable()61 .onKeyPress(keys: [.leftArrow, .upArrow]) { _ in step(-1); return .handled }62 .onKeyPress(keys: [.rightArrow, .downArrow]) { _ in step(1); return .handled }63 .accessibilityElement(children: .contain)64 .accessibilityLabel(label)65 }66}6768/// Honest "nothing here, and why". A symbol (SF Symbols name), a serif title, a sentence, real actions only.69public struct VQEmptyState<Actions: View>: View {70 private let systemImage: String?71 private let title: String72 private let message: String?73 private let actions: Actions7475 public init(systemImage: String? = nil, title: String, message: String? = nil, @ViewBuilder actions: () -> Actions = { EmptyView() }) {76 self.systemImage = systemImage; self.title = title; self.message = message; self.actions = actions()77 }7879 public var body: some View {80 VStack(spacing: VQS.s3) {81 if let systemImage {82 Image(systemName: systemImage).font(.system(size: 22, weight: .regular)).foregroundStyle(VQP.text3).accessibilityHidden(true)83 }84 Text(title).vqFont(VQTokens.Typography.title).foregroundStyle(VQP.text1).multilineTextAlignment(.center)85 if let message {86 Text(message).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text2).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true).frame(maxWidth: 420)87 }88 actions89 }90 .padding(VQS.s8)91 .frame(maxWidth: .infinity)92 .accessibilityElement(children: .contain)93 }94}9596/// A placeholder shaped like the content it stands for. It pulses gently, and not at all under reduced motion.97public struct VQSkeleton: View {98 private let width: CGFloat?99 private let height: CGFloat100 private let radius: CGFloat101 @State private var dim = false102 @Environment(\.accessibilityReduceMotion) private var systemReduceMotion103 @Environment(\.vqTheme) private var theme104105 public init(width: CGFloat? = nil, height: CGFloat = 12, radius: CGFloat = 4) { self.width = width; self.height = height; self.radius = radius }106107 public var body: some View {108 let still = systemReduceMotion || theme.reduceMotion109 RoundedRectangle(cornerRadius: radius, style: .continuous)110 .fill(VQP.ink3)111 .frame(width: width, height: height)112 .frame(maxWidth: width == nil ? .infinity : nil, alignment: .leading)113 .opacity(dim ? 0.55 : 1)114 .onAppear {115 guard !still else { return }116 withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) { dim = true }117 }118 .accessibilityHidden(true)119 }120}121122public struct VQSkeletonText: View {123 private let lines: Int124 public init(lines: Int = 3) { self.lines = lines }125 public var body: some View {126 VStack(alignment: .leading, spacing: VQS.s2) {127 ForEach(0..<lines, id: \.self) { i in128 GeometryReader { g in VQSkeleton(width: g.size.width * (i == lines - 1 ? 0.6 : 1), height: 11) }.frame(height: 11)129 }130 }131 }132}133134public struct VQSkeletonRows: View {135 private let rows: Int, columns: Int136 public init(rows: Int = 6, columns: Int = 4) { self.rows = rows; self.columns = columns }137 public var body: some View {138 VStack(spacing: VQS.s3) {139 ForEach(0..<rows, id: \.self) { _ in140 HStack(spacing: VQS.s4) { ForEach(0..<columns, id: \.self) { c in VQSkeleton(height: 11).frame(maxWidth: c == 0 ? .infinity : 72) } }141 }142 }143 }144}145146public struct VQSkeletonChart: View {147 private let height: CGFloat148 public init(height: CGFloat = 220) { self.height = height }149 public var body: some View {150 HStack(alignment: .bottom, spacing: 6) {151 ForEach(Array([0.35, 0.5, 0.42, 0.66, 0.58, 0.8, 0.7, 0.92, 0.76, 0.6, 0.72, 0.5].enumerated()), id: \.offset) { _, f in152 VQSkeleton(height: height * f, radius: 2)153 }154 }155 .frame(height: height, alignment: .bottom)156 }157}158159/// Wraps placeholders in a status region ("Chargement…").160public struct VQLoading<Content: View>: View {161 private let label: String?162 private let content: Content163 @Environment(\.vqTheme) private var theme164 public init(_ label: String? = nil, @ViewBuilder content: () -> Content) { self.label = label; self.content = content() }165 public var body: some View {166 content167 .accessibilityElement(children: .ignore)168 .accessibilityLabel(label ?? theme.l("Loading…"))169 .accessibilityAddTraits(.updatesFrequently)170 }171}172173/// The contextual "the AI is working" indicator: the Ember mark, what it is doing, for how long. A status region.174public struct VQAIActivity: View {175 private let label: String176 private let detail: String?177 @State private var phase = false178 @Environment(\.accessibilityReduceMotion) private var systemReduceMotion179 @Environment(\.vqTheme) private var theme180181 public init(_ label: String, detail: String? = nil) { self.label = label; self.detail = detail }182183 public var body: some View {184 let still = systemReduceMotion || theme.reduceMotion185 HStack(spacing: VQS.s2) {186 ZStack {187 Circle().fill(VQP.accent.opacity(0.22)).frame(width: 14, height: 14).scaleEffect(phase ? 1.25 : 0.85).opacity(still ? 1 : (phase ? 0.2 : 0.9))188 Circle().fill(VQP.accent).frame(width: 7, height: 7)189 }190 .frame(width: 18, height: 18)191 .accessibilityHidden(true)192 Text(label).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).lineLimit(1)193 if let detail { Text(detail).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3) }194 }195 .onAppear {196 guard !still else { return }197 withAnimation(.easeInOut(duration: 1.1).repeatForever(autoreverses: true)) { phase = true }198 }199 .accessibilityElement(children: .ignore)200 .accessibilityLabel([label, detail].compactMap { $0 }.joined(separator: ", "))201 .accessibilityAddTraits(.updatesFrequently)202 }203}204205/// A word-sized line: gaps (nil) are respected, an optional baseline (e.g. the previous close) is drawn as a hairline.206public struct VQSparkline: View {207 private let values: [Double?]208 private let baseline: Double?209 private let label: String210 @Environment(\.vqTheme) private var theme211212 public init(_ values: [Double?], baseline: Double? = nil, label: String) { self.values = values; self.baseline = baseline; self.label = label }213214 public var body: some View {215 let present = values.compactMap { $0 }216 let lo = min(present.min() ?? 0, baseline ?? .greatestFiniteMagnitude), hi = max(present.max() ?? 1, baseline ?? -.greatestFiniteMagnitude)217 let direction: VQDirection = {218 guard let first = baseline ?? present.first, let last = present.last else { return .flat }219 return last > first ? .up : last < first ? .down : .flat220 }()221 Canvas { context, size in222 guard present.count > 1, hi > lo else { return }223 func point(_ i: Int, _ v: Double) -> CGPoint {224 CGPoint(x: size.width * CGFloat(i) / CGFloat(max(1, values.count - 1)), y: 1 + (size.height - 2) * CGFloat(1 - (v - lo) / (hi - lo)))225 }226 if let baseline {227 let y = point(0, baseline).y228 context.stroke(Path { $0.move(to: CGPoint(x: 0, y: y)); $0.addLine(to: CGPoint(x: size.width, y: y)) }, with: .color(VQP.lineStrong), style: StrokeStyle(lineWidth: 1, dash: [2, 2]))229 }230 var path = Path(), pen = false231 for (i, v) in values.enumerated() {232 guard let v else { pen = false; continue }233 if pen { path.addLine(to: point(i, v)) } else { path.move(to: point(i, v)); pen = true }234 }235 context.stroke(path, with: .color(theme.color(direction)), style: StrokeStyle(lineWidth: 1.25, lineCap: .round, lineJoin: .round))236 }237 .frame(width: 64, height: 18)238 .accessibilityElement()239 .accessibilityLabel(label)240 .accessibilityValue(direction == .up ? theme.l("rising") : direction == .down ? theme.l("falling") : theme.l("flat"))241 }242}243244/// The primary action (Ember fill, ink label) and the quiet one (hairline border). Drawn by the package, so they look245/// the same on both platforms and in off-screen renders.246public struct VQButtonStyle: ButtonStyle {247 public enum Kind: Sendable { case primary, secondary }248 private let kind: Kind249 @Environment(\.isEnabled) private var isEnabled250 public init(_ kind: Kind = .secondary) { self.kind = kind }251252 public func makeBody(configuration: Configuration) -> some View {253 let shape = RoundedRectangle(cornerRadius: VQTokens.Radius.sm, style: .continuous)254 configuration.label255 .font(.system(size: 13, weight: kind == .primary ? .semibold : .medium))256 .foregroundStyle(kind == .primary ? VQTokens.Palette.accentFg : VQTokens.Palette.text1)257 .padding(.horizontal, 14).padding(.vertical, 6).frame(minHeight: 30)258 .background { if kind == .primary { shape.fill(VQTokens.Palette.accent) } else { shape.fill(VQTokens.Palette.ink1) } }259 .overlay { if kind == .secondary { shape.strokeBorder(VQTokens.Palette.lineStrong, lineWidth: 1) } }260 .opacity(isEnabled ? (configuration.isPressed ? 0.75 : 1) : 0.4)261 .contentShape(shape)262 }263}264265public extension ButtonStyle where Self == VQButtonStyle {266 static var vqPrimary: VQButtonStyle { VQButtonStyle(.primary) }267 static var vqSecondary: VQButtonStyle { VQButtonStyle(.secondary) }268}269270/// A thin determinate bar (run progress, countdowns).271public struct VQProgressBar: View {272 private let value: Double?273 private let tint: Color274 public init(_ value: Double?, tint: Color = VQTokens.Palette.accent) { self.value = value; self.tint = tint }275 public var body: some View {276 GeometryReader { g in277 ZStack(alignment: .leading) {278 Capsule().fill(VQTokens.Palette.ink3)279 Capsule().fill(tint).frame(width: g.size.width * min(1, max(0, value ?? 0)))280 }281 }282 .frame(height: 4)283 .accessibilityElement()284 .accessibilityValue(value.map { "\(Int(($0 * 100).rounded())) %" } ?? "")285 }286}287