SPB Git

Repository Public

Components.swift 16.2 KB 308 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Design/Components.swift3// Description: Reusable Local Chat components: cards, pills, metric tiles, buttons, empty states, progress, sparkline, section headers.4import SwiftUI5import LocalChatCore67// MARK: Surfaces89public struct CardModifier: ViewModifier {10    var padding: CGFloat; var radius: CGFloat; var elevated: Bool11    public func body(content: Content) -> some View {12        content.padding(padding)13            .background(elevated ? DS.C.surface2 : DS.C.surface, in: RoundedRectangle(cornerRadius: radius, style: .continuous))14            .overlay(RoundedRectangle(cornerRadius: radius, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))15    }16}17public extension View {18    func card(padding: CGFloat = DS.S.lg, radius: CGFloat = DS.R.card, elevated: Bool = false) -> some View {19        modifier(CardModifier(padding: padding, radius: radius, elevated: elevated))20    }21    /// Translucent floating panel (command palette, composer).22    func glassPanel(radius: CGFloat = DS.R.panel) -> some View {23        background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: radius, style: .continuous))24            .overlay(RoundedRectangle(cornerRadius: radius, style: .continuous).strokeBorder(DS.G.hairline, lineWidth: 1))25            .shadow(color: .black.opacity(0.18), radius: 24, y: 10)26    }27    /// Page background shared by every screen.28    func screenBackground() -> some View { background(DS.C.bg.ignoresSafeArea()) }29}3031// MARK: Labels3233public struct Pill: View {34    public enum Tone { case neutral, accent, ok, warn, danger }35    let text: String; var symbol: String?; var tone: Tone36    public init(_ text: String, symbol: String? = nil, tone: Tone = .neutral) { self.text = text; self.symbol = symbol; self.tone = tone }37    var color: Color { switch tone { case .neutral: DS.C.text2; case .accent: DS.C.accent; case .ok: DS.C.ok; case .warn: DS.C.warn; case .danger: DS.C.danger } }38    public var body: some View {39        HStack(spacing: 4) {40            if let symbol { Image(systemName: symbol).font(.system(size: 9.5, weight: .semibold)) }41            Text(text).font(DS.F.micro).lineLimit(1)42        }43        .foregroundStyle(color)44        .padding(.horizontal, 7).padding(.vertical, 3)45        .background(color.opacity(tone == .neutral ? 0.1 : 0.14), in: Capsule())46    }47}4849public struct BackendBadge: View {50    let backend: BackendKind51    public init(_ backend: BackendKind) { self.backend = backend }52    public var body: some View {53        Pill(backend.displayName, symbol: backend == .remote ? "network" : backend == .appleFoundation ? "apple.logo" : "cpu",54             tone: backend == .remote ? .warn : .accent)55    }56}5758public struct FitBadge: View {59    let verdict: CompatibilityVerdict60    public init(_ verdict: CompatibilityVerdict) { self.verdict = verdict }61    public var body: some View {62        let tone: Pill.Tone = switch verdict.fit { case .comfortable: .ok; case .tight: .warn; case .tooLarge, .unsupported: .danger; case .unknown: .neutral }63        let symbol = switch verdict.fit { case .comfortable: "checkmark.circle.fill"; case .tight: "exclamationmark.triangle.fill"; case .tooLarge: "xmark.octagon.fill"; case .unsupported: "nosign"; case .unknown: "questionmark.circle" }64        Pill(verdict.fit.label, symbol: symbol, tone: tone).help(verdict.reasons.joined(separator: "\n"))65    }66}6768public struct SectionHeader: View {69    let title: String; var subtitle: String?; var symbol: String?70    public init(_ title: String, subtitle: String? = nil, symbol: String? = nil) { self.title = title; self.subtitle = subtitle; self.symbol = symbol }71    public var body: some View {72        HStack(alignment: .firstTextBaseline, spacing: 8) {73            if let symbol { Image(systemName: symbol).foregroundStyle(DS.G.accent).font(.system(size: 14, weight: .semibold)) }74            VStack(alignment: .leading, spacing: 2) {75                Text(title).font(DS.F.headline).foregroundStyle(DS.C.text)76                if let subtitle { Text(subtitle).font(DS.F.caption).foregroundStyle(DS.C.muted) }77            }78            Spacer(minLength: 0)79        }80    }81}8283/// Large screen title with the aurora underline used at the top of every studio.84public struct ScreenTitle<Trailing: View>: View {85    let title: String; let subtitle: String; @ViewBuilder var trailing: Trailing86    public init(_ title: String, subtitle: String, @ViewBuilder trailing: () -> Trailing = { EmptyView() }) { self.title = title; self.subtitle = subtitle; self.trailing = trailing() }87    public var body: some View {88        HStack(alignment: .bottom) {89            VStack(alignment: .leading, spacing: 4) {90                Text(title).font(DS.F.largeTitle).foregroundStyle(DS.C.text)91                Text(subtitle).font(DS.F.callout).foregroundStyle(DS.C.text2)92            }93            Spacer(minLength: 12)94            trailing95        }96    }97}9899// MARK: Metrics100101public struct MetricTile: View {102    let title: String; let value: String; var unit: String?; var symbol: String?; var tint: Color; var footnote: String?103    public init(_ title: String, value: String, unit: String? = nil, symbol: String? = nil, tint: Color = DS.C.accent, footnote: String? = nil) {104        self.title = title; self.value = value; self.unit = unit; self.symbol = symbol; self.tint = tint; self.footnote = footnote105    }106    public var body: some View {107        VStack(alignment: .leading, spacing: 6) {108            HStack(spacing: 5) {109                if let symbol { Image(systemName: symbol).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(tint) }110                Text(title.uppercased()).font(DS.F.micro).kerning(0.4).foregroundStyle(DS.C.muted).lineLimit(1)111            }112            HStack(alignment: .firstTextBaseline, spacing: 3) {113                Text(value).font(DS.F.metric).foregroundStyle(DS.C.text).contentTransition(.numericText()).lineLimit(1).minimumScaleFactor(0.6)114                if let unit { Text(unit).font(DS.F.caption).foregroundStyle(DS.C.muted) }115            }116            if let footnote { Text(footnote).font(DS.F.micro).foregroundStyle(DS.C.muted).lineLimit(2) }117        }118        .frame(maxWidth: .infinity, alignment: .leading)119        .card(padding: DS.S.md)120    }121}122123public enum MetricFormat {124    public static func rate(_ v: Double?) -> String { v.map { $0 >= 100 ? String(format: "%.0f", $0) : String(format: "%.1f", $0) } ?? "—" }125    public static func seconds(_ v: TimeInterval?) -> String {126        guard let v else { return "—" }127        return v < 1 ? String(format: "%.0f ms", v * 1000) : String(format: "%.2f s", v)128    }129    public static func count(_ v: Int?) -> String { v.map { $0.formatted() } ?? "—" }130    public static func memory(_ v: Int64?) -> String { v.map { ByteFormat.memory($0) } ?? "—" }131    public static func bytes(_ v: Int64?) -> String { v.map { ByteFormat.string($0) } ?? "—" }132    public static func duration(_ v: TimeInterval?) -> String {133        guard let v, v.isFinite else { return "—" }134        if v < 60 { return "\(Int(v)) s" }135        if v < 3600 { return "\(Int(v) / 60) min \(Int(v) % 60) s" }136        return "\(Int(v) / 3600) h \((Int(v) % 3600) / 60) min"137    }138}139140/// A dependency-free sparkline for small time series (tokens/s history, memory).141public struct Sparkline: View {142    let values: [Double]; var tint: Color143    public init(_ values: [Double], tint: Color = DS.C.accent) { self.values = values; self.tint = tint }144    public var body: some View {145        GeometryReader { geo in146            let lo = values.min() ?? 0, hi = values.max() ?? 1, span = max(hi - lo, 0.0001)147            let points = values.enumerated().map { i, v in148                CGPoint(x: values.count > 1 ? geo.size.width * CGFloat(i) / CGFloat(values.count - 1) : geo.size.width / 2,149                        y: geo.size.height - geo.size.height * CGFloat((v - lo) / span) * 0.86 - geo.size.height * 0.07)150            }151            if points.count > 1 {152                Path { p in p.move(to: CGPoint(x: points[0].x, y: geo.size.height)); for pt in points { p.addLine(to: pt) }; p.addLine(to: CGPoint(x: points.last!.x, y: geo.size.height)); p.closeSubpath() }153                    .fill(LinearGradient(colors: [tint.opacity(0.28), tint.opacity(0)], startPoint: .top, endPoint: .bottom))154                Path { p in p.move(to: points[0]); for pt in points.dropFirst() { p.addLine(to: pt) } }155                    .stroke(tint, style: StrokeStyle(lineWidth: 1.6, lineCap: .round, lineJoin: .round))156            } else if let only = points.first {157                Circle().fill(tint).frame(width: 5, height: 5).position(only)158            }159        }160        .accessibilityHidden(true)161    }162}163164public struct ProgressBar: View {165    let fraction: Double; var tint: AnyShapeStyle; var height: CGFloat166    public init(_ fraction: Double, height: CGFloat = 5) { self.fraction = fraction; tint = AnyShapeStyle(DS.G.aurora); self.height = height }167    public init(_ fraction: Double, tint: Color, height: CGFloat = 5) { self.fraction = fraction; self.tint = AnyShapeStyle(tint); self.height = height }168    public var body: some View {169        GeometryReader { geo in170            ZStack(alignment: .leading) {171                Capsule().fill(DS.C.surface3)172                Capsule().fill(tint).frame(width: max(height, geo.size.width * min(1, max(0, fraction))))173            }174        }175        .frame(height: height)176        .animation(DS.M.smooth, value: fraction)177    }178}179180// MARK: Buttons181182public struct PrimaryButtonStyle: ButtonStyle {183    @Environment(\.isEnabled) private var enabled184    var compact: Bool185    public init(compact: Bool = false) { self.compact = compact }186    public func makeBody(configuration: Configuration) -> some View {187        configuration.label.font(.system(size: compact ? 12.5 : 14, weight: .semibold)).foregroundStyle(.white)188            .padding(.horizontal, compact ? 12 : 16).padding(.vertical, compact ? 6 : 9)189            .background(DS.G.accent, in: RoundedRectangle(cornerRadius: DS.R.control + 2, style: .continuous))190            .opacity(enabled ? (configuration.isPressed ? 0.8 : 1) : 0.4)191            .scaleEffect(configuration.isPressed ? 0.97 : 1).animation(DS.M.snappy, value: configuration.isPressed)192    }193}194public struct SecondaryButtonStyle: ButtonStyle {195    @Environment(\.isEnabled) private var enabled196    var compact: Bool; var tint: Color197    public init(compact: Bool = false, tint: Color = DS.C.text) { self.compact = compact; self.tint = tint }198    public func makeBody(configuration: Configuration) -> some View {199        configuration.label.font(.system(size: compact ? 12.5 : 14, weight: .medium)).foregroundStyle(tint)200            .padding(.horizontal, compact ? 11 : 15).padding(.vertical, compact ? 6 : 9)201            .background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control + 2, style: .continuous))202            .overlay(RoundedRectangle(cornerRadius: DS.R.control + 2, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))203            .opacity(enabled ? (configuration.isPressed ? 0.7 : 1) : 0.4)204            .scaleEffect(configuration.isPressed ? 0.97 : 1).animation(DS.M.snappy, value: configuration.isPressed)205    }206}207public extension ButtonStyle where Self == PrimaryButtonStyle {208    static var lcPrimary: PrimaryButtonStyle { PrimaryButtonStyle() }209    static var lcPrimaryCompact: PrimaryButtonStyle { PrimaryButtonStyle(compact: true) }210}211public extension ButtonStyle where Self == SecondaryButtonStyle {212    static var lcSecondary: SecondaryButtonStyle { SecondaryButtonStyle() }213    static var lcSecondaryCompact: SecondaryButtonStyle { SecondaryButtonStyle(compact: true) }214    static var lcDestructive: SecondaryButtonStyle { SecondaryButtonStyle(compact: true, tint: DS.C.danger) }215}216217/// Small icon-only button used in toolbars and message actions.218public struct IconButton: View {219    let symbol: String; let label: String; var tint: Color; let action: () -> Void220    public init(_ symbol: String, label: String, tint: Color = DS.C.text2, action: @escaping () -> Void) { self.symbol = symbol; self.label = label; self.tint = tint; self.action = action }221    public var body: some View {222        Button(action: action) { Image(systemName: symbol).font(.system(size: 13, weight: .medium)).frame(width: 28, height: 28).contentShape(Rectangle()) }223            .buttonStyle(.plain).foregroundStyle(tint).help(label).accessibilityLabel(label)224    }225}226227// MARK: States228229public struct EmptyStateView<Actions: View>: View {230    let symbol: String; let title: String; let message: String; @ViewBuilder var actions: Actions231    public init(symbol: String, title: String, message: String, @ViewBuilder actions: () -> Actions = { EmptyView() }) {232        self.symbol = symbol; self.title = title; self.message = message; self.actions = actions()233    }234    public var body: some View {235        VStack(spacing: 14) {236            ZStack {237                Circle().fill(DS.G.soft).frame(width: 84, height: 84)238                Image(systemName: symbol).font(.system(size: 32, weight: .medium)).foregroundStyle(DS.G.accent).symbolRenderingMode(.hierarchical)239            }240            Text(title).font(DS.F.title).foregroundStyle(DS.C.text).multilineTextAlignment(.center)241            Text(message).font(DS.F.callout).foregroundStyle(DS.C.text2).multilineTextAlignment(.center).frame(maxWidth: 420)242            actions243        }244        .padding(DS.S.xl).frame(maxWidth: .infinity, maxHeight: .infinity)245    }246}247248public struct InlineNotice: View {249    public enum Kind { case info, warning, error, privacy }250    let kind: Kind; let text: String251    public init(_ kind: Kind, _ text: String) { self.kind = kind; self.text = text }252    public var body: some View {253        let (symbol, color): (String, Color) = switch kind {254        case .info: ("info.circle.fill", DS.C.accent); case .warning: ("exclamationmark.triangle.fill", DS.C.warn)255        case .error: ("xmark.octagon.fill", DS.C.danger); case .privacy: ("lock.shield.fill", DS.C.ok)256        }257        HStack(alignment: .firstTextBaseline, spacing: 8) {258            Image(systemName: symbol).foregroundStyle(color).font(.system(size: 12.5))259            Text(text).font(DS.F.caption).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true)260            Spacer(minLength: 0)261        }262        .padding(10).background(color.opacity(0.09), in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))263    }264}265266/// Three dots pulsing while a model loads or thinks.267public struct ThinkingDots: View {268    @State private var phase = 0.0269    public init() {}270    public var body: some View {271        HStack(spacing: 4) {272            ForEach(0..<3, id: \.self) { i in273                Circle().fill(DS.G.accent).frame(width: 6, height: 6)274                    .opacity(0.35 + 0.65 * max(0, sin(phase + Double(i) * 0.9)))275                    .scaleEffect(0.8 + 0.3 * max(0, sin(phase + Double(i) * 0.9)))276            }277        }278        .onAppear { withAnimation(.linear(duration: 1.3).repeatForever(autoreverses: false)) { phase = .pi * 2 } }279        .accessibilityLabel("Working")280    }281}282283/// A labelled row for forms that must look the same on macOS and iOS.284public struct SettingRow<Control: View>: View {285    let title: String; var detail: String?; @ViewBuilder var control: Control286    public init(_ title: String, detail: String? = nil, @ViewBuilder control: () -> Control) { self.title = title; self.detail = detail; self.control = control() }287    public var body: some View {288        HStack(alignment: .center, spacing: 12) {289            VStack(alignment: .leading, spacing: 2) {290                Text(title).font(DS.F.body).foregroundStyle(DS.C.text)291                if let detail { Text(detail).font(DS.F.caption).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true) }292            }293            Spacer(minLength: 8)294            control295        }296        .padding(.vertical, 4)297    }298}299300/// Adaptive grid used for tiles and cards.301public struct TileGrid<Content: View>: View {302    var minimum: CGFloat; @ViewBuilder var content: Content303    public init(minimum: CGFloat = 150, @ViewBuilder content: () -> Content) { self.minimum = minimum; self.content = content() }304    public var body: some View {305        LazyVGrid(columns: [GridItem(.adaptive(minimum: minimum), spacing: DS.S.md)], alignment: .leading, spacing: DS.S.md) { content }306    }307}308
Files main
Menu

Theme