SPB Git

Repository Public

Theme.swift 15.3 KB 281 lines swift

1// SP Drive iOS2// File: Components/Theme.swift3// Description: Visual identity shared by every screen: the indigo-to-violet gradient of SP Drive, file-kind colours, small reusable views.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import UIKit910/// SP Drive design system v2 — the token set shared by the three clients (`docs/next/DESIGN-SYSTEM-V2.md` of the macOS repository is the11/// contract: same names, same values; CSS variables on the web, `SPDTheme` in Swift). This is the iOS rendering: colours as dynamic12/// colours (light, dark, Increase Contrast), type tokens mapped to text styles so Dynamic Type scales them.13enum SPDTheme {14    /// One colour role: light / dark, and their Increase Contrast forms. For translucent roles the HC alpha is ×1.6 (capped at 1).15    struct Role: Sendable {16        let light: UInt32, dark: UInt32, hcLight: UInt32, hcDark: UInt3217        let alphaLight: Double, alphaDark: Double18        init(_ light: UInt32, _ dark: UInt32, hc hcLight: UInt32? = nil, _ hcDark: UInt32? = nil, alpha alphaLight: Double = 1, _ alphaDark: Double = 1) {19            self.light = light; self.dark = dark; self.hcLight = hcLight ?? light; self.hcDark = hcDark ?? dark; self.alphaLight = alphaLight; self.alphaDark = alphaDark20        }21        var color: Color {22            Color(uiColor: UIColor { t in23                let dark = t.userInterfaceStyle == .dark, hc = t.accessibilityContrast == .high24                let hex = dark ? (hc ? hcDark : self.dark) : (hc ? hcLight : light)25                let alpha = min(1, (dark ? alphaDark : alphaLight) * (hc && (alphaLight < 1 || alphaDark < 1) ? 1.6 : 1))26                return UIColor(red: CGFloat((hex >> 16) & 0xFF) / 255, green: CGFloat((hex >> 8) & 0xFF) / 255, blue: CGFloat(hex & 0xFF) / 255, alpha: alpha)27            })28        }29    }3031    /// Colour roles (§2 of the contract).32    enum Palette {33        static let brand = Role(0x6D3DF2, 0x9882FF, hc: 0x4F22C9, 0xB7A8FF).color34        static let brandIndigo = Role(0x4A55E0, 0x8E97FF, hc: 0x2F39B8, 0xAEB5FF).color35        static let brandWash = Role(0x6D3DF2, 0x9882FF, hc: 0x4F22C9, 0xB7A8FF, alpha: 0.10, 0.18).color36        static let selection = Role(0x6D3DF2, 0x9882FF, hc: 0x4F22C9, 0xB7A8FF, alpha: 0.16, 0.30).color37        static let canvas = Role(0xFFFFFF, 0x1B1B1F, hc: 0xFFFFFF, 0x000000).color38        static let surface = Role(0xF6F6F9, 0x232328, hc: 0xF2F2F6, 0x101013).color39        static let surfaceRaised = Role(0xFFFFFF, 0x2B2B31, hc: 0xFFFFFF, 0x1A1A1E).color40        static let sunken = Role(0xEEEEF3, 0x161619, hc: 0xE6E6EC, 0x000000).color41        static let hairline = Role(0x000000, 0xFFFFFF, alpha: 0.10, 0.12).color42        static let textPrimary = Role(0x16161A, 0xF2F2F5, hc: 0x000000, 0xFFFFFF).color43        static let textSecondary = Role(0x5C5C66, 0xA6A6B0, hc: 0x33333A, 0xD4D4DC).color44        static let textTertiary = Role(0x8A8A94, 0x7C7C86, hc: 0x55555E, 0xB0B0BA).color45        static let onBrand = Role(0xFFFFFF, 0x14102B, hc: 0xFFFFFF, 0x000000).color46        static let positive = Role(0x1E8E5A, 0x4CC38A, hc: 0x116B41, 0x7BE0AE).color47        static let warning = Role(0xB76E00, 0xF0B454, hc: 0x8A5200, 0xFFD084).color48        static let critical = Role(0xC8322B, 0xFF6B63, hc: 0x9E1C16, 0xFF9A94).color49    }50    /// Corner radii (§4), continuous corners everywhere.51    enum Radius {52        static let xs: CGFloat = 4, sm: CGFloat = 6, md: CGFloat = 10, lg: CGFloat = 14, xl: CGFloat = 2053    }54    /// Spacing on a 4-point grid (§4).55    enum Space {56        static let xxs: CGFloat = 2, xs: CGFloat = 4, sm: CGFloat = 8, md: CGFloat = 12, lg: CGFloat = 16, xl: CGFloat = 24, xxl: CGFloat = 32, xxxl: CGFloat = 4857    }58    /// Type scale (§3): each token is the text style the contract assigns to iOS, so everything follows Dynamic Type.59    enum Typo {60        static let display = Font.system(.title, design: .serif).weight(.semibold)61        static let title = Font.system(.title3, design: .serif).weight(.semibold)62        static let headline = Font.headline63        static let body = Font.body64        static let bodyStrong = Font.body.weight(.medium)65        static let callout = Font.callout66        static let caption = Font.caption67        static let eyebrow = Font.caption2.weight(.semibold)68        static let mono = Font.system(.caption, design: .monospaced)69        static let figure = Font.system(.title2, design: .rounded).weight(.semibold).monospacedDigit()70    }71    /// Elevation (§5): black shadow, ×1.7 opacity in dark mode. A raised element also has a hairline border.72    enum Elevation {73        case e0, e1, e2, e374        var radius: CGFloat { switch self { case .e0: 0; case .e1: 3; case .e2: 24; case .e3: 40 } }75        var y: CGFloat { switch self { case .e0: 0; case .e1: 1; case .e2: 8; case .e3: 16 } }76        func opacity(_ scheme: ColorScheme) -> Double { min(1, (scheme == .dark ? 1.7 : 1) * { switch self { case .e0: 0; case .e1: 0.07; case .e2: 0.16; case .e3: 0.24 } }()) }77    }78    /// Motion (§6): named motions with their duration and curve. `resolve` gives the Reduce Motion form (nil = the state changes at once).79    enum Motion {80        static let instant = 0.10, quick = 0.18, standard = 0.28, slow = 0.4581        static let select = Animation.timingCurve(0.2, 0, 0, 1, duration: instant)82        static let hover = Animation.timingCurve(0.2, 0, 0, 1, duration: quick)83        static let navigate = Animation.timingCurve(0.05, 0.7, 0.1, 1, duration: standard)84        static let reveal = Animation.spring(response: 0.45, dampingFraction: 0.82)85        static let dismiss = Animation.timingCurve(0.3, 0, 0.8, 0.15, duration: quick)86        static let drop = Animation.spring(response: 0.28, dampingFraction: 0.86)87        static let progress = Animation.linear(duration: 0.20)88        static func resolve(_ animation: Animation, reduceMotion: Bool) -> Animation? { reduceMotion ? nil : animation }89    }90    /// The app mark's two stops (indigo → violet). Per the contract it belongs to the mark; on iOS it also fills the primary button and folder tiles.91    static let gradient = LinearGradient(colors: [Palette.brandIndigo, Palette.brand], startPoint: .topLeading, endPoint: .bottomTrailing)92}9394enum Theme {95    static let gradient = SPDTheme.gradient96    static let corner: CGFloat = SPDTheme.Radius.xl9798    static func color(for kind: FileKind) -> Color {99        switch kind {100        case .folder: Color("AccentColor"); case .image: .pink; case .pdf: .red; case .document: .blue; case .sheet: .green; case .slides: .orange101        case .video: .purple; case .audio: .teal; case .archive: .brown; case .text: .gray; case .code: .indigo; case .other: .secondary102        }103    }104}105106extension View {107    /// A card surface of the design system.108    func spdCard(radius: CGFloat = SPDTheme.Radius.xl, elevation: SPDTheme.Elevation = .e0) -> some View { modifier(CardSurface(radius: radius, elevation: elevation)) }109}110111private struct CardSurface: ViewModifier {112    @Environment(\.colorScheme) private var scheme113    let radius: CGFloat114    let elevation: SPDTheme.Elevation115    func body(content: Content) -> some View {116        content.background(SPDTheme.Palette.surfaceRaised, in: RoundedRectangle(cornerRadius: radius, style: .continuous))117            .overlay(RoundedRectangle(cornerRadius: radius, style: .continuous).strokeBorder(SPDTheme.Palette.hairline, lineWidth: elevation == .e0 ? 0 : 0.5))118            .shadow(color: .black.opacity(elevation.opacity(scheme)), radius: elevation.radius, y: elevation.y)119    }120}121122/// Primary action button with the brand gradient.123struct GradientButtonStyle: ButtonStyle {124    @Environment(\.isEnabled) private var enabled125    func makeBody(configuration: Configuration) -> some View {126        configuration.label127            .font(.headline)128            .foregroundStyle(.white)129            .frame(maxWidth: .infinity, minHeight: 52)130            .background(Theme.gradient.opacity(enabled ? (configuration.isPressed ? 0.8 : 1) : 0.4), in: RoundedRectangle(cornerRadius: Theme.corner, style: .continuous))131            .scaleEffect(configuration.isPressed ? 0.98 : 1)132            .animation(.snappy(duration: 0.15), value: configuration.isPressed)133    }134}135136/// Icon tile of a file kind (used when there is no thumbnail).137struct KindIcon: View {138    let kind: FileKind139    var size: CGFloat = 40140    var body: some View {141        RoundedRectangle(cornerRadius: size * 0.26, style: .continuous)142            .fill(kind == .folder ? AnyShapeStyle(Theme.gradient) : AnyShapeStyle(Theme.color(for: kind).opacity(0.16)))143            .frame(width: size, height: size)144            .overlay(Image(systemName: kind.symbol).font(.system(size: size * 0.46, weight: .semibold)).foregroundStyle(kind == .folder ? Color.white : Theme.color(for: kind)))145            .accessibilityHidden(true)146    }147}148149/// Sync state next to an item. Every state has a symbol and a spoken label: colour alone never carries the meaning.150struct SyncBadgeView: View {151    let badge: SyncBadge152    var body: some View {153        switch badge {154        case .none: EmptyView()155        case .available: Image(systemName: "checkmark.circle").foregroundStyle(.secondary).accessibilityLabel(badge.spokenLabel)156        case .pinned: Image(systemName: "arrow.down.circle.fill").foregroundStyle(SPDTheme.Palette.positive).accessibilityLabel(badge.spokenLabel)157        case .downloading(let f): ProgressRing(fraction: f, symbol: "arrow.down").accessibilityLabel(badge.spokenLabel)158        case .waitingDownload: Image(systemName: "arrow.down.circle.dotted").foregroundStyle(.secondary).accessibilityLabel(badge.spokenLabel)159        case .uploading(let f): ProgressRing(fraction: f, symbol: "arrow.up").accessibilityLabel(badge.spokenLabel)160        case .waiting: Image(systemName: "clock.arrow.2.circlepath").foregroundStyle(SPDTheme.Palette.warning).accessibilityLabel(badge.spokenLabel)161        case .conflict: Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(SPDTheme.Palette.warning).accessibilityLabel(badge.spokenLabel)162        case .error: Image(systemName: "exclamationmark.circle.fill").foregroundStyle(SPDTheme.Palette.critical).accessibilityLabel(badge.spokenLabel)163        case .unavailableOffline: Image(systemName: "icloud.slash").foregroundStyle(.tertiary).accessibilityLabel(badge.spokenLabel)164        }165    }166}167168extension SyncBadge {169    /// The state in words (VoiceOver, details sheet).170    var spokenLabel: String {171        switch self {172        case .none: String(localized: "Synchronisé, en ligne seulement")173        case .available: String(localized: "Sur cet appareil")174        case .pinned: String(localized: "Disponible hors ligne")175        case .downloading(let f): String(localized: "Téléchargement \(Int(f * 100)) %")176        case .waitingDownload: String(localized: "Téléchargement en attente")177        case .uploading(let f): String(localized: "Envoi \(Int(f * 100)) %")178        case .waiting: String(localized: "En attente de synchronisation")179        case .conflict: String(localized: "Conflit de versions")180        case .error: String(localized: "Erreur de transfert")181        case .unavailableOffline: String(localized: "Indisponible hors ligne")182        }183    }184    /// Short text for the state chip of the details sheet; nil when there is nothing to say.185    var chipLabel: String? { self == .none ? String(localized: "Synchronisé") : spokenLabel }186}187188struct ProgressRing: View {189    let fraction: Double190    let symbol: String191    var body: some View {192        ZStack {193            Circle().stroke(.tint.opacity(0.2), lineWidth: 2.5)194            Circle().trim(from: 0, to: max(0.03, fraction)).stroke(.tint, style: StrokeStyle(lineWidth: 2.5, lineCap: .round)).rotationEffect(.degrees(-90))195            Image(systemName: symbol).font(.system(size: 8, weight: .bold)).foregroundStyle(.tint)196        }197        .frame(width: 18, height: 18)198        .animation(.linear(duration: 0.3), value: fraction)199    }200}201202/// Full-screen placeholder for an empty list, with real actions (not just an explanation).203struct EmptyState: View {204    struct Action: Identifiable {205        let id: String206        let label: String207        let symbol: String208        let run: () -> Void209    }210    let symbol: String211    let title: String212    let message: String213    var action: (label: String, run: () -> Void)?214    /// Secondary actions, shown as a row of tiles under the main one.215    var more: [Action] = []216    @Environment(\.dynamicTypeSize) private var typeSize217218    var body: some View {219        ContentUnavailableView {220            Label { Text(title) } icon: { Image(systemName: symbol).foregroundStyle(Theme.gradient) }221        } description: {222            Text(message)223        } actions: {224            if let action { Button(action.label, action: action.run).buttonStyle(.borderedProminent).accessibilityIdentifier("empty.primary") }225            if !more.isEmpty {226                let layout = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(spacing: SPDTheme.Space.sm)) : AnyLayout(HStackLayout(spacing: SPDTheme.Space.sm))227                layout {228                    ForEach(more) { a in229                        Button(action: a.run) {230                            Label(a.label, systemImage: a.symbol).font(SPDTheme.Typo.callout.weight(.medium)).frame(maxWidth: typeSize.isAccessibilitySize ? .infinity : nil)231                        }232                        .buttonStyle(.bordered)233                        .accessibilityIdentifier("empty.\(a.id)")234                    }235                }236            }237        }238    }239}240241/// A short message that slides in at the bottom and leaves by itself.242struct ToastOverlay: ViewModifier {243    @Binding var toast: Toast?244    func body(content: Content) -> some View {245        content.overlay(alignment: .bottom) {246            if let t = toast {247                Label(t.text, systemImage: t.style == .error ? "exclamationmark.circle.fill" : t.style == .success ? "checkmark.circle.fill" : "info.circle.fill")248                    .font(.subheadline.weight(.medium))249                    .foregroundStyle(.white)250                    .padding(.horizontal, 16).padding(.vertical, 12)251                    .background(t.style == .error ? AnyShapeStyle(Color("Danger")) : AnyShapeStyle(Theme.gradient), in: Capsule())252                    .shadow(color: .black.opacity(0.2), radius: 12, y: 4)253                    .padding(.horizontal, 20).padding(.bottom, 132) // above the tab bar and the transfer pill254                    .transition(.move(edge: .bottom).combined(with: .opacity))255                    .task(id: t.id) { try? await Task.sleep(for: .seconds(t.style == .error ? 4 : 2.2)); withAnimation { if toast?.id == t.id { toast = nil } } }256                    .accessibilityIdentifier("toast")257            }258        }259        .animation(.snappy, value: toast)260    }261}262263extension View {264    func toast(_ toast: Binding<Toast?>) -> some View { modifier(ToastOverlay(toast: toast)) }265}266267extension Int64 {268    var byteString: String { formatted(.byteCount(style: .file)) }269}270271extension Date {272    /// "aujourd’hui 14:32", "hier", "12 nov." — short, for list rows.273    var shortRelative: String {274        let cal = Calendar.current275        if cal.isDateInToday(self) { return formatted(date: .omitted, time: .shortened) }276        if cal.isDateInYesterday(self) { return "hier" }277        if cal.isDate(self, equalTo: .now, toGranularity: .year) { return formatted(.dateTime.day().month(.abbreviated)) }278        return formatted(.dateTime.day().month(.abbreviated).year())279    }280}281
Files main
Menu

Theme