SPB Git

Repository Public

DesignSystem.swift 16.1 KB 349 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Components/DesignSystem.swift4//  Description: Visual System V2 « Graphite & Iris · Lumen » — tokens (type, shape, motion), floating material,5//               ModelMark / ModelChip / route badge, the lumen presence line and the small shared controls.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213// MARK: tokens1415extension Color {16    static let bgElev = Color("BgElev")17    static let borderStrong = Color("BorderStrong")18    static let accentSoft = Color("AccentSoft")19    static let userBubble = Color("UserBubble")20    static let lumenMid = Color("LumenMid")21    static let floatFill = Color("FloatFill")22}2324enum Radius {25    static let chip: CGFloat = 626    static let control: CGFloat = 1027    static let card: CGFloat = 1428    static let float: CGFloat = 2029    static let bubble: CGFloat = 1830}3132/// Type roles of the system, all on Dynamic Type text styles.33extension Font {34    static let spDisplay = Font.system(.title, design: .default, weight: .semibold)35    static let spTitle = Font.system(.title3, design: .default, weight: .semibold)36    static let spHeading = Font.system(.headline, design: .default, weight: .semibold)37    static let spUI = Font.system(.subheadline, design: .default, weight: .medium)38    static let spCaption = Font.system(.caption, design: .default, weight: .medium)39    static let spMicro = Font.system(.caption2, design: .default, weight: .semibold)40}4142/// Motion tokens. Every animation of the app goes through `Motion.*(reduce)` so Reduce Motion turns springs into a short fade.43enum Motion {44    static let snappy = Animation.spring(response: 0.28, dampingFraction: 0.86)45    static let smooth = Animation.spring(response: 0.42, dampingFraction: 0.88)46    static let fade = Animation.easeOut(duration: 0.14)47    static func snappy(_ reduce: Bool) -> Animation { reduce ? fade : snappy }48    static func smooth(_ reduce: Bool) -> Animation { reduce ? fade : smooth }49    /// 24 ms per item, 8 items at most.50    static func stagger(_ index: Int) -> Double { Double(min(index, 8)) * 0.024 }51}5253// MARK: surfaces5455struct FloatSurface: ViewModifier {56    var cornerRadius: CGFloat = Radius.float57    var highlighted = false58    @Environment(\.accessibilityReduceTransparency) private var reduceTransparency59    @Environment(\.colorSchemeContrast) private var contrast60    @Environment(\.colorScheme) private var scheme6162    func body(content: Content) -> some View {63        let shape = RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)64        content65            .background {66                // Increase Contrast / Reduce Transparency: the material becomes an opaque surface67                if reduceTransparency || contrast == .increased { shape.fill(Color.surface) }68                else { shape.fill(.regularMaterial).overlay(shape.fill(Color.floatFill.opacity(0.35))) }69            }70            .overlay(shape.strokeBorder(highlighted ? Color.accentColor : (contrast == .increased ? Color.borderStrong : Color.hairline), lineWidth: highlighted ? 1.5 : 0.75))71            .shadow(color: .black.opacity(scheme == .dark ? 0.5 : 0.14), radius: 22, y: 12)72    }73}7475extension View {76    /// The floating layer of the system: translucent material, hairline, soft elevation (composer, pills, palettes).77    func floatSurface(cornerRadius: CGFloat = Radius.float, highlighted: Bool = false) -> some View { modifier(FloatSurface(cornerRadius: cornerRadius, highlighted: highlighted)) }78    /// An opaque card: surface fill + hairline.79    func cardSurface(cornerRadius: CGFloat = Radius.card, fill: Color = .surface) -> some View {80        background(fill, in: .rect(cornerRadius: cornerRadius, style: .continuous))81            .overlay(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous).strokeBorder(Color.hairline, lineWidth: 0.75))82    }83}8485// MARK: model identity8687/// Maker logo (monochrome template, text colour) — or a neutral monogram when the registry has no logo. Never drawn by hand.88struct ModelMark: View {89    var logo: String?90    var name: String91    var size: CGFloat = 1892    /// Colour variant: only in the Explorer hero and the model sheet.93    var color = false94    /// Streaming Presence: the mark breathes while its model generates.95    var breathing = false96    @Environment(\.accessibilityReduceMotion) private var reduceMotion97    @State private var dim = false9899    init(logo: String?, name: String, size: CGFloat = 18, color: Bool = false, breathing: Bool = false) { self.logo = logo; self.name = name; self.size = size; self.color = color; self.breathing = breathing }100    init(_ model: AIModel?, size: CGFloat = 18, color: Bool = false, breathing: Bool = false) {101        self.init(logo: model?.logo, name: model?.creatorName ?? "?", size: size, color: color, breathing: breathing)102    }103104    var body: some View {105        Group {106            if let asset = LogoRegistry.asset(logo, color: color) {107                Image(asset).resizable().interpolation(.high).scaledToFit().foregroundStyle(Color.textPrimary)108            } else {109                Text(String(name.trimmingCharacters(in: .whitespaces).prefix(1)).uppercased())110                    .font(.system(size: size * 0.56, weight: .semibold, design: .rounded)).foregroundStyle(Color.textSecondary)111                    .frame(width: size, height: size)112                    .background(Color.surface2, in: .rect(cornerRadius: size * 0.26, style: .continuous))113            }114        }115        .frame(width: size, height: size)116        .opacity(breathing && !reduceMotion && dim ? 0.55 : 1)117        .onChange(of: breathing, initial: true) { _, on in118            if on && !reduceMotion { withAnimation(.easeInOut(duration: 1.2).repeatForever(autoreverses: true)) { dim = true } }119            else { withAnimation(Motion.fade) { dim = false } }120        }121        .accessibilityHidden(true)122    }123}124125/// « OPENROUTER » micro badge — shown only when the route is not direct.126struct RouteBadge: View {127    var route: String?128    var body: some View {129        if route == "openrouter" || route == "local" {130            Text(verbatim: route == "local" ? "LOCAL" : "OPENROUTER")131                .font(.system(size: 9, weight: .semibold)).tracking(0.5).foregroundStyle(Color.muted)132                .padding(.horizontal, 5).padding(.vertical, 2)133                .overlay(Capsule().strokeBorder(Color.hairline, lineWidth: 0.75))134                .fixedSize()135                .accessibilityLabel(route == "local" ? String(localized: "inférence locale MacLustr") : String(localized: "via OpenRouter"))136        }137    }138}139140/// `[logo] Exact name [OPENROUTER]`. Changing `model` morphs in place: the frame stays, the logo cross-scales, the name rolls.141struct ModelChip: View {142    var logo: String?143    var creatorName: String144    var name: String145    var route: String?146    var markSize: CGFloat = 16147    var font: Font = .spUI148    var breathing = false149    var showsChevron = false150    @Environment(\.accessibilityReduceMotion) private var reduceMotion151152    init(model: AIModel?, fallback: String = String(localized: "Modèle"), markSize: CGFloat = 16, font: Font = .spUI, breathing: Bool = false, showsChevron: Bool = false) {153        logo = model?.logo; creatorName = model?.creatorName ?? fallback; name = model?.displayName ?? fallback; route = model?.route154        self.markSize = markSize; self.font = font; self.breathing = breathing; self.showsChevron = showsChevron155    }156    init(logo: String?, creatorName: String, name: String, route: String?, markSize: CGFloat = 16, font: Font = .spUI, breathing: Bool = false, showsChevron: Bool = false) {157        self.logo = logo; self.creatorName = creatorName; self.name = name; self.route = route; self.markSize = markSize; self.font = font; self.breathing = breathing; self.showsChevron = showsChevron158    }159160    var body: some View {161        HStack(spacing: 6) {162            ModelMark(logo: logo, name: creatorName, size: markSize, breathing: breathing)163                .id(logo ?? creatorName)164                .transition(reduceMotion ? .opacity : .scale(scale: 0.6).combined(with: .opacity))165            Text(name).font(font).foregroundStyle(Color.textPrimary).lineLimit(1)166                .contentTransition(reduceMotion ? .opacity : .numericText())167            RouteBadge(route: route)168            if showsChevron { Image(systemName: "chevron.down").font(.system(size: 9, weight: .bold)).foregroundStyle(Color.muted) }169        }170        .animation(Motion.smooth(reduceMotion), value: name)171        .animation(Motion.smooth(reduceMotion), value: logo)172        .accessibilityElement(children: .ignore)173        .accessibilityLabel(route == "openrouter" ? String(localized: "\(name), \(creatorName), via OpenRouter") : route == "local" ? String(localized: "\(name), \(creatorName), inférence locale") : String(localized: "\(name), \(creatorName)"))174    }175}176177/// Capability glyphs of a model (vision, reasoning, tools…), verified `true` only.178struct CapabilityGlyphs: View {179    let model: AIModel180    var body: some View {181        HStack(spacing: 6) {182            ForEach(ModelCapability.allCases.filter { $0.holds(for: model) }) { c in183                Image(systemName: c.symbol).accessibilityLabel(c.label)184            }185        }186        .font(.system(size: 11, weight: .medium)).foregroundStyle(Color.muted)187    }188}189190extension AIModel {191    /// « 3 $ / 15 $ » per million tokens, « gratuit », or nil when no price is published.192    var priceLabel: String? {193        guard let i = priceInput, let o = priceOutput else { return nil }194        if i == 0 && o == 0 { return String(localized: "gratuit") }195        return "\(Format.price(i)) / \(Format.price(o)) $"196    }197    var contextLabel: String? { contextWindow.map { Format.tokens($0) } }198}199200extension Format {201    /// A per-million price without noise: 3 · 0.15 · 0.075 · 12.5202    static func price(_ v: Double) -> String {203        if v == 0 { return "0" }204        if v >= 100 { return String(format: "%.0f", v) }205        var s = String(format: v < 0.1 ? "%.3f" : "%.2f", v)206        while s.hasSuffix("0") { s.removeLast() }207        if s.hasSuffix(".") { s.removeLast() }208        return s.replacingOccurrences(of: ".", with: Locale.current.decimalSeparator ?? ".")209    }210}211212// MARK: lumen213214/// Streaming Presence: a soft iris light travelling along a hairline (2 pt, ~2.4 s loop). The timeline only runs215/// while `active`; under Reduce Motion it is a static iris hairline. The only gradient of the system.216struct LumenLine: View {217    var active: Bool218    var cornerRadius: CGFloat = Radius.float219    @Environment(\.accessibilityReduceMotion) private var reduceMotion220    @Environment(\.colorScheme) private var scheme221222    var body: some View {223        if active {224            Group {225                if reduceMotion {226                    Capsule().fill(Color.accentColor.opacity(0.7)).frame(height: 1.5)227                } else {228                    TimelineView(.animation) { ctx in229                        let t = ctx.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 2.4) / 2.4230                        GeometryReader { geo in231                            let w = geo.size.width, band = max(w * 0.42, 90)232                            Capsule()233                                .fill(LinearGradient(colors: [.accentColor.opacity(0), .accentColor, .lumenMid, .accentColor, .accentColor.opacity(0)], startPoint: .leading, endPoint: .trailing))234                                .frame(width: band, height: 2)235                                .offset(x: -band + (w + band) * t)236                                .blur(radius: 1.2)237                                .opacity(scheme == .dark ? 0.9 : 0.75)238                        }239                        .frame(height: 2)240                    }241                }242            }243            .padding(.horizontal, cornerRadius * 0.7)244            .clipped()245            .allowsHitTesting(false)246            .transition(.opacity)247            .accessibilityHidden(true)248        }249    }250}251252/// Quiet « working » indicator used where no model mark is on screen yet: three iris dots breathing in place.253struct PresenceDots: View {254    @Environment(\.accessibilityReduceMotion) private var reduceMotion255    var body: some View {256        TimelineView(.animation(minimumInterval: 1 / 20, paused: reduceMotion)) { ctx in257            let t = ctx.date.timeIntervalSinceReferenceDate258            HStack(spacing: 5) {259                ForEach(0..<3, id: \.self) { i in260                    Circle().fill(Color.accentColor).frame(width: 5, height: 5)261                        .opacity(reduceMotion ? 0.7 : 0.3 + 0.7 * (0.5 + 0.5 * sin(t * 3.2 - Double(i) * 0.8)))262                }263            }264        }265        .frame(height: 18)266        .accessibilityLabel(String(localized: "Réponse en cours"))267    }268}269270// MARK: controls271272/// A filter / option chip: `surface-2` at rest, iris-soft with an iris hairline when selected.273struct ChipLabel: View {274    var text: String275    var systemImage: String?276    var selected = false277    var body: some View {278        HStack(spacing: 5) {279            if let systemImage { Image(systemName: systemImage).font(.system(size: 11, weight: .semibold)) }280            Text(text).font(.spCaption).lineLimit(1)281        }282        .foregroundStyle(selected ? Color.accentColor : Color.textSecondary)283        .padding(.horizontal, 11).frame(minHeight: 32)284        .background(selected ? Color.accentSoft : Color.surface2, in: .capsule)285        .overlay(Capsule().strokeBorder(selected ? Color.accentColor.opacity(0.5) : .clear, lineWidth: 0.75))286        .contentShape(.capsule)287    }288}289290/// Pressed state shared by the custom buttons: a quick scale, no colour flash.291struct PressScale: ButtonStyle {292    var scale: CGFloat = 0.94293    @Environment(\.accessibilityReduceMotion) private var reduceMotion294    func makeBody(configuration: Configuration) -> some View {295        configuration.label296            .scaleEffect(configuration.isPressed && !reduceMotion ? scale : 1)297            .opacity(configuration.isPressed ? 0.75 : 1)298            .animation(Motion.snappy(reduceMotion), value: configuration.isPressed)299    }300}301302/// A small caption + value pair used in fact grids (Explorer detail, Arena metrics, context inspector).303struct FactCell: View {304    var title: String305    var value: String306    var note: String?307    var body: some View {308        VStack(alignment: .leading, spacing: 3) {309            Text(title).font(.spMicro).foregroundStyle(Color.muted).textCase(.uppercase).tracking(0.3).lineLimit(1)310            Text(value).font(.system(.subheadline, design: .default, weight: .semibold).monospacedDigit()).foregroundStyle(Color.textPrimary).lineLimit(1).minimumScaleFactor(0.7)311                .contentTransition(.numericText())312            if let note { Text(note).font(.caption2).foregroundStyle(Color.muted).lineLimit(1) }313        }314        .frame(maxWidth: .infinity, alignment: .leading)315        .accessibilityElement(children: .combine)316    }317}318319/// « source : … » line under a block of figures. Every figure of the app says where it comes from.320struct SourceNote: View {321    var text: String322    var body: some View {323        Label(text, systemImage: "info.circle").font(.caption2).foregroundStyle(Color.muted).labelStyle(.titleAndIcon)324            .frame(maxWidth: .infinity, alignment: .leading)325    }326}327328/// Sheet header used by the contextual sheets: title, optional subtitle and a close button with a 44 pt target.329struct SheetHeader: View {330    var title: String331    var subtitle: String?332    var onClose: () -> Void333    var body: some View {334        HStack(alignment: .firstTextBaseline) {335            VStack(alignment: .leading, spacing: 2) {336                Text(title).font(.spTitle).foregroundStyle(Color.textPrimary)337                if let subtitle { Text(subtitle).font(.footnote).foregroundStyle(Color.muted).lineLimit(2) }338            }339            Spacer(minLength: 8)340            Button(action: onClose) {341                Image(systemName: "xmark").font(.system(size: 13, weight: .bold)).foregroundStyle(Color.textSecondary)342                    .frame(width: 30, height: 30).background(Color.surface2, in: .circle).frame(width: 44, height: 44).contentShape(.rect)343            }344            .buttonStyle(PressScale()).accessibilityLabel(String(localized: "Fermer"))345        }346        .padding(.leading, 20).padding(.trailing, 8).padding(.top, 10)347    }348}349
Files main
Menu

Theme