SPB Git

Repository Public MIT

Components.swift 19.3 KB 400 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraDesign/Sources/Components.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI8990// MARK: - Surfaces9192/// The standard card: an opaque raised surface with a hairline stroke. Opaque on purpose: no blur cost while scrolling.93public struct AstraCard<Content: View>: View {94    var padding: CGFloat95    var radius: CGFloat96    var tint: Color?97    @ViewBuilder var content: () -> Content98    public init(padding: CGFloat = AstraSpace.lg, radius: CGFloat = AstraRadius.lg, tint: Color? = nil, @ViewBuilder content: @escaping () -> Content) {99        self.padding = padding; self.radius = radius; self.tint = tint; self.content = content100    }101    public var body: some View {102        content()103            .padding(padding)104            .frame(maxWidth: .infinity, alignment: .leading)105            .background(tint ?? AstraColor.surface, in: RoundedRectangle(cornerRadius: radius, style: .continuous))106            .overlay(RoundedRectangle(cornerRadius: radius, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))107    }108}109110public struct SectionTitle: View {111    var title: String; var detail: String?112    public init(_ title: String, detail: String? = nil) { self.title = title; self.detail = detail }113    public var body: some View {114        HStack(alignment: .firstTextBaseline) {115            Text(title).font(AstraFont.headline).foregroundStyle(AstraColor.textPrimary).accessibilityAddTraits(.isHeader)116            Spacer(minLength: AstraSpace.sm)117            if let detail { Text(detail).font(AstraFont.footnote).foregroundStyle(AstraColor.textTertiary) }118        }119    }120}121122// MARK: - Buttons123124public struct AstraPrimaryButtonStyle: ButtonStyle {125    @Environment(\.isEnabled) private var enabled126    var destructive: Bool127    public init(destructive: Bool = false) { self.destructive = destructive }128    public func makeBody(configuration: Configuration) -> some View {129        configuration.label130            .font(AstraFont.bodyEmphasis)131            .foregroundStyle(AstraColor.onAccent)132            .padding(.horizontal, AstraSpace.xl)133            .frame(maxWidth: .infinity, minHeight: 50)134            .background(destructive ? AstraColor.dangerFill : AstraColor.accentFill, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))135            .opacity(enabled ? (configuration.isPressed ? 0.82 : 1) : 0.4)136            .scaleEffect(configuration.isPressed ? 0.985 : 1)137            .animation(AstraMotion.quick, value: configuration.isPressed)138            .contentShape(Rectangle())139    }140}141142public struct AstraSecondaryButtonStyle: ButtonStyle {143    @Environment(\.isEnabled) private var enabled144    var compact: Bool145    public init(compact: Bool = false) { self.compact = compact }146    public func makeBody(configuration: Configuration) -> some View {147        configuration.label148            .font(compact ? AstraFont.subheadline.weight(.semibold) : AstraFont.bodyEmphasis)149            .foregroundStyle(AstraColor.textPrimary)150            .padding(.horizontal, compact ? AstraSpace.md : AstraSpace.xl)151            .frame(maxWidth: compact ? nil : .infinity, minHeight: compact ? AstraSpace.hit : 50)152            .background(AstraColor.surfaceRaised, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))153            .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))154            .opacity(enabled ? (configuration.isPressed ? 0.7 : 1) : 0.4)155            .animation(AstraMotion.quick, value: configuration.isPressed)156            .contentShape(Rectangle())157    }158}159160/// A round icon button with a full 44-point target.161public struct IconButton: View {162    var symbol: String; var label: String; var tint: Color; var filled: Bool; var action: () -> Void163    public init(_ symbol: String, label: String, tint: Color = AstraColor.textSecondary, filled: Bool = false, action: @escaping () -> Void) {164        self.symbol = symbol; self.label = label; self.tint = tint; self.filled = filled; self.action = action165    }166    public var body: some View {167        Button(action: action) {168            Image(systemName: symbol)169                .font(.system(size: 17, weight: .semibold))170                .foregroundStyle(filled ? AstraColor.onAccent : tint)171                .frame(width: 34, height: 34)172                .background(filled ? AnyShapeStyle(AstraColor.accentFill) : AnyShapeStyle(Color.clear), in: Circle())173                .frame(width: AstraSpace.hit, height: AstraSpace.hit)174                .contentShape(Rectangle())175        }176        .buttonStyle(.plain)177        .accessibilityLabel(label)178    }179}180181// MARK: - Badges and pills182183public struct AstraBadge: View {184    public enum Tone { case neutral, accent, success, warning, danger, cyan }185    var text: String; var symbol: String?; var tone: Tone186    public init(_ text: String, symbol: String? = nil, tone: Tone = .neutral) { self.text = text; self.symbol = symbol; self.tone = tone }187    private var colors: (fg: Color, bg: Color) {188        switch tone {189        case .neutral: (AstraColor.textSecondary, AstraColor.surfaceRaised)190        case .accent: (AstraColor.violet, AstraColor.accentSoft)191        case .success: (AstraColor.success, AstraColor.successSoft)192        case .warning: (AstraColor.warning, AstraColor.warningSoft)193        case .danger: (AstraColor.danger, AstraColor.dangerSoft)194        case .cyan: (AstraColor.cyan, AstraColor.surfaceRaised)195        }196    }197    public var body: some View {198        HStack(spacing: 4) {199            if let symbol { Image(systemName: symbol).imageScale(.small) }200            Text(text).lineLimit(1)201        }202        .font(AstraFont.micro)203        .foregroundStyle(colors.fg)204        .padding(.horizontal, 8).padding(.vertical, 4)205        .background(colors.bg, in: Capsule())206        .accessibilityElement(children: .combine)207    }208}209210/// A labelled figure. Shows an em dash, never a made-up number, when the value is unavailable.211public struct MetricTile: View {212    var label: String; var value: String?; var unit: String?; var symbol: String?213    public init(_ label: String, value: String?, unit: String? = nil, symbol: String? = nil) { self.label = label; self.value = value; self.unit = unit; self.symbol = symbol }214    public var body: some View {215        VStack(alignment: .leading, spacing: 4) {216            HStack(spacing: 4) {217                if let symbol { Image(systemName: symbol).imageScale(.small) }218                Text(label)219            }220            .font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary).lineLimit(1)221            HStack(alignment: .firstTextBaseline, spacing: 3) {222                Text(value ?? "—").font(AstraFont.metricSmall).foregroundStyle(value == nil ? AstraColor.textTertiary : AstraColor.textPrimary)223                    .contentTransition(.numericText())224                if let unit, value != nil { Text(unit).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary) }225            }226            .lineLimit(1).minimumScaleFactor(0.7)227        }228        .frame(maxWidth: .infinity, alignment: .leading)229        .accessibilityElement(children: .ignore)230        .accessibilityLabel(label)231        .accessibilityValue(value.map { $0 + (unit.map { " " + $0 } ?? "") } ?? "not available")232    }233}234235/// A monogram tile standing in for a provider. Astra deliberately ships no third-party logos; the name is always in text beside it.236public struct ProviderMark: View {237    var initials: String; var tint: Color; var size: CGFloat; var symbol: String?238    public init(initials: String, tint: Color, size: CGFloat = 34, symbol: String? = nil) { self.initials = initials; self.tint = tint; self.size = size; self.symbol = symbol }239    public var body: some View {240        ZStack {241            RoundedRectangle(cornerRadius: size * 0.28, style: .continuous).fill(tint.opacity(0.16))242            RoundedRectangle(cornerRadius: size * 0.28, style: .continuous).strokeBorder(tint.opacity(0.35), lineWidth: 1)243            if let symbol { Image(systemName: symbol).font(.system(size: size * 0.44, weight: .semibold)).foregroundStyle(tint) }244            else { Text(initials).font(.system(size: size * 0.38, weight: .bold, design: .rounded)).foregroundStyle(tint) }245        }246        .frame(width: size, height: size)247        .accessibilityHidden(true)248    }249}250251// MARK: - States252253public struct EmptyStateView<Actions: View>: View {254    var symbol: String?; var title: String; var message: String255    @ViewBuilder var actions: () -> Actions256    public init(symbol: String? = nil, title: String, message: String, @ViewBuilder actions: @escaping () -> Actions) {257        self.symbol = symbol; self.title = title; self.message = message; self.actions = actions258    }259    public var body: some View {260        VStack(spacing: AstraSpace.lg) {261            if let symbol {262                Image(systemName: symbol).font(.system(size: 34, weight: .light)).foregroundStyle(AstraColor.signature).accessibilityHidden(true)263            } else {264                AstraGlyph().frame(width: 72, height: 72)265            }266            VStack(spacing: AstraSpace.sm) {267                Text(title).font(AstraFont.title).foregroundStyle(AstraColor.textPrimary).multilineTextAlignment(.center)268                Text(message).font(AstraFont.callout).foregroundStyle(AstraColor.textSecondary).multilineTextAlignment(.center)269            }270            actions()271        }272        .padding(AstraSpace.xxl)273        .frame(maxWidth: 460)274    }275}276public extension EmptyStateView where Actions == EmptyView {277    init(symbol: String? = nil, title: String, message: String) { self.init(symbol: symbol, title: title, message: message) { EmptyView() } }278}279280/// An inline notice: information, warning or error, with an optional action.281public struct NoticeCard: View {282    public enum Kind { case info, warning, error, success }283    var kind: Kind; var title: String; var message: String?; var actionTitle: String?; var action: (() -> Void)?284    public init(_ kind: Kind, title: String, message: String? = nil, actionTitle: String? = nil, action: (() -> Void)? = nil) {285        self.kind = kind; self.title = title; self.message = message; self.actionTitle = actionTitle; self.action = action286    }287    private var style: (symbol: String, fg: Color, bg: Color) {288        switch kind {289        case .info: ("info.circle.fill", AstraColor.indigo, AstraColor.accentSoft)290        case .warning: ("exclamationmark.triangle.fill", AstraColor.warning, AstraColor.warningSoft)291        case .error: ("xmark.octagon.fill", AstraColor.danger, AstraColor.dangerSoft)292        case .success: ("checkmark.circle.fill", AstraColor.success, AstraColor.successSoft)293        }294    }295    public var body: some View {296        HStack(alignment: .top, spacing: AstraSpace.md) {297            Image(systemName: style.symbol).foregroundStyle(style.fg).font(.body.weight(.semibold)).accessibilityHidden(true)298            VStack(alignment: .leading, spacing: 4) {299                Text(title).font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)300                if let message { Text(message).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true) }301                if let actionTitle, let action {302                    Button(actionTitle, action: action).font(AstraFont.footnote.weight(.semibold)).foregroundStyle(style.fg)303                        .frame(minHeight: AstraSpace.hit, alignment: .leading)304                }305            }306            Spacer(minLength: 0)307        }308        .padding(AstraSpace.md)309        .background(style.bg, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))310        .accessibilityElement(children: .combine)311    }312}313314/// Determinate progress as a thin signature-gradient bar.315public struct AstraProgressBar: View {316    var fraction: Double317    public init(_ fraction: Double) { self.fraction = fraction }318    public var body: some View {319        GeometryReader { geo in320            ZStack(alignment: .leading) {321                Capsule().fill(AstraColor.surfaceSunken)322                Capsule().fill(AstraColor.signatureHorizontal).frame(width: max(6, geo.size.width * min(1, max(0, fraction))))323            }324        }325        .frame(height: 6)326        .accessibilityElement()327        .accessibilityLabel("Progress")328        .accessibilityValue("\(Int((min(1, max(0, fraction)) * 100).rounded())) percent")329    }330}331332// MARK: - Toast333334public struct Toast: Identifiable, Equatable, Sendable {335    public enum Kind: Sendable { case info, success, error }336    public let id = UUID()337    public var kind: Kind; public var text: String338    public init(_ text: String, kind: Kind = .info) { self.text = text; self.kind = kind }339}340341public struct ToastHost: ViewModifier {342    @Binding var toast: Toast?343    @Environment(\.accessibilityReduceMotion) private var reduceMotion344    public func body(content: Content) -> some View {345        content.overlay(alignment: .top) {346            if let toast {347                HStack(spacing: AstraSpace.sm) {348                    Image(systemName: toast.kind == .success ? "checkmark.circle.fill" : toast.kind == .error ? "exclamationmark.circle.fill" : "info.circle.fill")349                        .foregroundStyle(toast.kind == .success ? AstraColor.success : toast.kind == .error ? AstraColor.danger : AstraColor.cyan)350                    Text(toast.text).font(AstraFont.subheadline.weight(.medium)).foregroundStyle(AstraColor.textPrimary).lineLimit(3)351                }352                .padding(.horizontal, AstraSpace.lg).padding(.vertical, AstraSpace.md)353                .background(AstraColor.surfaceRaised, in: Capsule())354                .overlay(Capsule().strokeBorder(AstraColor.strokeStrong, lineWidth: 1))355                .astraShadow(.mid)356                .padding(.top, AstraSpace.sm).padding(.horizontal, AstraSpace.lg)357                .transition(reduceMotion ? .opacity : .move(edge: .top).combined(with: .opacity))358                .accessibilityAddTraits(.isStaticText)359                .task(id: toast.id) {360                    try? await Task.sleep(nanoseconds: 2_600_000_000)361                    if self.toast?.id == toast.id { withAnimation(AstraMotion.resolve(AstraMotion.gentle, reduceMotion: reduceMotion)) { self.toast = nil } }362                }363                .onTapGesture { self.toast = nil }364            }365        }366        .animation(AstraMotion.resolve(AstraMotion.standard, reduceMotion: reduceMotion), value: toast)367    }368}369public extension View {370    func astraToast(_ toast: Binding<Toast?>) -> some View { modifier(ToastHost(toast: toast)) }371    /// The page backdrop used by every primary screen.372    func astraBackdrop(stars: Double = 0.6) -> some View { background(Starfield(density: stars)) }373}374375/// Wrapping row layout for badges and chips.376public struct FlowLayout: Layout {377    var spacing: CGFloat378    public init(spacing: CGFloat = 6) { self.spacing = spacing }379    public func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {380        arrange(width: proposal.width ?? .infinity, subviews: subviews).size381    }382    public func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {383        let result = arrange(width: bounds.width, subviews: subviews)384        for (i, origin) in result.origins.enumerated() {385            subviews[i].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified)386        }387    }388    private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, origins: [CGPoint]) {389        var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0390        var origins: [CGPoint] = []391        for sub in subviews {392            let s = sub.sizeThatFits(.unspecified)393            if x > 0, x + s.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }394            origins.append(CGPoint(x: x, y: y))395            x += s.width + spacing; rowHeight = max(rowHeight, s.height); maxX = max(maxX, x - spacing)396        }397        return (CGSize(width: maxX, height: y + rowHeight), origins)398    }399}400
Files main
Menu

Theme