SPB Git

Repository Public

Styling.swift 13.8 KB 351 lines swift

1import AppKit2import DesignSystem3import SettingsModel4import SwiftUI5import TerminalCore6import WorkspaceKit78extension Color {9    init(_ rgb: SPColor) {10        self.init(.sRGB, red: Double(rgb.red) / 255, green: Double(rgb.green) / 255, blue: Double(rgb.blue) / 255, opacity: 1)11    }12}1314/// Colours of the chrome, derived from the active terminal theme and the current accent.15struct Palette {16    let theme: TerminalTheme17    let accentColor: SPColor1819    var background: Color { Color(theme.background) }20    var chrome: Color { Color(theme.chromeBackground) }21    var tintedChrome: Color { Color(theme.tintedChrome(accent: accentColor)) }22    var elevated: Color { Color(theme.elevatedSurface) }23    var text: Color { Color(theme.foreground) }24    var secondary: Color { Color(theme.secondaryText) }25    var separator: Color { Color(theme.separator) }26    var accent: Color { Color(accentColor) }27    var warning: Color { Color(theme.ansi[theme.isDark ? 11 : 3]) }28    var danger: Color { Color(theme.ansi[theme.isDark ? 9 : 1]) }29    var success: Color { Color(theme.ansi[theme.isDark ? 10 : 2]) }30    var hover: Color { Color(theme.foreground).opacity(0.08) }31    var selected: Color { Color(theme.foreground).opacity(theme.isHighContrast ? 0.22 : 0.12) }32    /// Soft halo of the focused pane.33    var glow: Color { accent.opacity(theme.isHighContrast ? 0 : (theme.isDark ? 0.42 : 0.28)) }34    var cardShadow: Color { Color.black.opacity(theme.isDark ? 0.32 : 0.12) }35    /// Hairline around cards and floating surfaces.36    var hairline: Color { Color(theme.foreground).opacity(theme.isHighContrast ? 0.6 : (theme.isDark ? 0.10 : 0.12)) }37}3839/// Animations of the chrome. When motion is reduced every movement becomes a short fade.40struct Motion: Equatable {41    var reduced = false4243    func spring(_ spec: SpringSpec) -> Animation {44        reduced ? .easeOut(duration: MotionSpec.reducedDuration) : .spring(response: spec.response, dampingFraction: spec.damping)45    }46    var snappy: Animation { spring(MotionSpec.snappy) }47    var smooth: Animation { spring(MotionSpec.smooth) }48    var gentle: Animation { spring(MotionSpec.gentle) }49    var fade: Animation { .easeOut(duration: reduced ? MotionSpec.reducedDuration : MotionSpec.fadeDuration) }50    /// The ambient gradient does not move at all when motion is reduced.51    var ambient: Animation? { reduced ? nil : .easeInOut(duration: MotionSpec.ambientDuration) }5253    func transition(_ full: AnyTransition) -> AnyTransition { reduced ? .opacity : full }54    var pop: AnyTransition { transition(.scale(scale: 0.96).combined(with: .opacity)) }55    func slide(_ edge: Edge) -> AnyTransition { transition(.move(edge: edge).combined(with: .opacity)) }56}5758/// What every chrome component needs to know about the current presentation.59struct ChromeContext: Equatable {60    var motion = Motion()61    /// Liquid Glass is wanted (it is used only where the system provides it).62    var glass = true63}6465private struct ChromeContextKey: EnvironmentKey { static let defaultValue = ChromeContext() }66extension EnvironmentValues {67    var chrome: ChromeContext {68        get { self[ChromeContextKey.self] }69        set { self[ChromeContextKey.self] = newValue }70    }71}7273extension AppModel {74    var palette: Palette { Palette(theme: theme, accentColor: accent) }7576    /// Accent for a pane: with "dynamic accent" on, every SSH host has its own stable colour.77    func accent(for pane: PaneID?) -> SPColor {78        guard settings.dynamicAccent, let pane, let host = remoteHost(of: pane), !host.isEmpty else { return accent }79        return AccentEngine.accent(forHost: host, theme: theme)80    }8182    func palette(for pane: PaneID?) -> Palette { Palette(theme: theme, accentColor: accent(for: pane)) }83    /// Palette of a window: its accent follows the focused pane.84    func palette(in window: WindowState) -> Palette { palette(for: window.focusedPane) }8586    var motion: Motion { Motion(reduced: reduceMotion || settings.motion == .reduced) }87    var chromeContext: ChromeContext { ChromeContext(motion: motion, glass: settings.useLiquidGlass && !theme.isHighContrast) }8889    static var systemHasLiquidGlass: Bool { if #available(macOS 26.0, *) { return true } else { return false } }90}9192// MARK: Surfaces9394/// A floating surface: Liquid Glass where the system has it, a material with a hairline elsewhere.95private struct FloatingSurface<S: InsettableShape>: ViewModifier {96    let shape: S97    let stroke: Color98    @Environment(\.chrome) private var chrome99100    func body(content: Content) -> some View {101        if #available(macOS 26.0, *), chrome.glass {102            content.glassEffect(.regular, in: shape)103        } else {104            content.background(shape.fill(.regularMaterial)).overlay(shape.strokeBorder(stroke))105        }106    }107}108109extension View {110    func floatingSurface<S: InsettableShape>(_ shape: S, stroke: Color) -> some View {111        modifier(FloatingSurface(shape: shape, stroke: stroke))112    }113114    /// Geometry below this point snaps instead of animating. Terminal views must never be resized115    /// frame by frame: every intermediate size would reach the shell as a terminal resize.116    func snapGeometry() -> some View { transaction { $0.animation = nil } }117}118119struct VisualEffectBackground: NSViewRepresentable {120    var material: NSVisualEffectView.Material = .underWindowBackground121    func makeNSView(context: Context) -> NSVisualEffectView {122        let view = NSVisualEffectView()123        view.blendingMode = .behindWindow124        view.state = .followsWindowActiveState125        view.material = material126        return view127    }128    func updateNSView(_ nsView: NSVisualEffectView, context: Context) { nsView.material = material }129}130131/// Low-contrast accent light in the chrome. It moves only when `phase` changes (focus, tab,132/// command finished), so it costs nothing while the window is idle.133struct AmbientGradient: View {134    let palette: Palette135    let phase: Int136    @Environment(\.chrome) private var chrome137138    private static let anchors: [UnitPoint] = [.init(x: 0.12, y: 0), .init(x: 0.55, y: 0.05), .init(x: 0.9, y: 0), .init(x: 0.3, y: 0.1)]139140    var body: some View {141        let strength = palette.theme.isDark ? 0.20 : 0.13142        GeometryReader { geometry in143            let anchor = AmbientGradient.anchors[abs(phase) % AmbientGradient.anchors.count]144            RadialGradient(colors: [palette.accent.opacity(strength), palette.accent.opacity(strength * 0.3), .clear],145                           center: anchor, startRadius: 0, endRadius: max(geometry.size.width * 0.55, 320))146                .animation(chrome.motion.ambient, value: phase)147        }148        .allowsHitTesting(false)149        .accessibilityHidden(true)150    }151}152153// MARK: Controls154155/// A keyboard shortcut drawn as key caps.156struct KeyCaps: View {157    let text: String158    let palette: Palette159    var body: some View {160        Text(text)161            .font(.system(size: TypeScale.caption, weight: .medium, design: .rounded))162            .foregroundStyle(palette.secondary)163            .padding(.horizontal, 5).padding(.vertical, 1.5)164            .background(RoundedRectangle(cornerRadius: Radius.xs, style: .continuous).fill(palette.hover))165    }166}167168/// Tooltip of the title bar: the name of the action and its current shortcut.169private struct RichTip: View {170    let title: String171    let shortcut: String172    var body: some View {173        HStack(spacing: 6) {174            Text(title).font(.system(size: TypeScale.footnote, weight: .medium))175            if !shortcut.isEmpty {176                Text(shortcut).font(.system(size: TypeScale.caption, weight: .medium, design: .rounded)).opacity(0.65)177            }178        }179        .padding(.horizontal, 9).padding(.vertical, 5)180        .floatingSurface(Capsule(), stroke: Color.primary.opacity(0.12))181        .shadow(color: .black.opacity(0.18), radius: 8, y: 3)182        .fixedSize()183        .allowsHitTesting(false)184        .accessibilityHidden(true)185    }186}187188/// Small icon button used throughout the chrome.189struct IconButton: View {190    let systemName: String191    let help: String192    var shortcut: String = ""193    var tint: Color?194    var size: CGFloat = 12195    /// Shows the designed tooltip (title bar only: elsewhere it would be clipped by a card).196    var richTip: Bool = false197    var tipAlignment: Alignment = .bottom198    var active: Bool = false199    let action: () -> Void200    @State private var hovering = false201    @State private var tipVisible = false202    @State private var tipTask: Task<Void, Never>?203    @Environment(\.chrome) private var chrome204205    var body: some View {206        Button {207            hideTip()208            action()209        } label: {210            Image(systemName: systemName)211                .font(.system(size: size, weight: .medium))212                .frame(width: size + 14, height: size + 12)213                .background(RoundedRectangle(cornerRadius: Radius.s, style: .continuous)214                    .fill(Color.primary.opacity(hovering ? 0.12 : (active ? 0.08 : 0))))215                .contentShape(Rectangle())216                .scaleEffect(hovering && !chrome.motion.reduced ? 1.06 : 1)217        }218        .buttonStyle(.plain)219        .foregroundStyle(tint ?? Color.primary.opacity(hovering ? 0.95 : 0.72))220        .animation(chrome.motion.snappy, value: hovering)221        .onHover { inside in222            hovering = inside223            if inside { scheduleTip() } else { hideTip() }224        }225        .help(richTip ? "" : (shortcut.isEmpty ? help : "\(help)  \(shortcut)"))226        .accessibilityLabel(help)227        .overlay(alignment: tipAlignment) {228            if richTip && tipVisible {229                RichTip(title: help, shortcut: shortcut)230                    .offset(y: 32)231                    .transition(chrome.motion.transition(.offset(y: -4).combined(with: .opacity)))232            }233        }234        .animation(chrome.motion.fade, value: tipVisible)235        .zIndex(tipVisible ? 10 : 0)236        .onDisappear { tipTask?.cancel() }237    }238239    private func scheduleTip() {240        guard richTip else { return }241        tipTask?.cancel()242        tipTask = Task { @MainActor in243            try? await Task.sleep(for: .seconds(MotionSpec.tooltipDelay))244            if !Task.isCancelled && hovering { tipVisible = true }245        }246    }247248    private func hideTip() {249        tipTask?.cancel()250        tipVisible = false251    }252}253254// MARK: Session state255256/// What a session is doing, as shown by the tab, the sidebar and the pane header.257enum SessionActivity: Equatable {258    case idle, busy, ended259260    @MainActor init(_ session: TerminalSession?) {261        guard let session, session.status.isRunning || session.status == .notStarted else { self = .ended; return }262        self = session.hasForegroundJob ? .busy : .idle263    }264265    var label: String {266        switch self {267        case .idle: return "idle"268        case .busy: return "task running"269        case .ended: return "ended"270        }271    }272}273274/// Status mark of a session. The shape changes with the state, so it never relies on colour alone:275/// filled = idle, filled with a halo = busy, hollow = ended.276struct StatusDot: View {277    let activity: SessionActivity278    let palette: Palette279    /// Changes when a command has just finished: the dot pulses once.280    var pulse: UUID?281    @State private var pulsing = false282    @Environment(\.chrome) private var chrome283284    var body: some View {285        ZStack {286            switch activity {287            case .ended: Circle().strokeBorder(palette.secondary.opacity(0.8), lineWidth: 1.2)288            case .busy:289                Circle().fill(palette.accent.opacity(0.28)).scaleEffect(1.9)290                Circle().fill(palette.accent)291            case .idle: Circle().fill(palette.success.opacity(0.85))292            }293            Circle().strokeBorder(palette.accent, lineWidth: 1.5)294                .scaleEffect(pulsing ? 2.8 : 1).opacity(pulsing ? 0 : (pulse == nil ? 0 : 0.9))295        }296        .frame(width: 6, height: 6)297        .animation(chrome.motion.snappy, value: activity)298        .onChange(of: pulse) { _, token in299            guard token != nil, !chrome.motion.reduced else { return }300            pulsing = false301            withAnimation(.easeOut(duration: 0.9)) { pulsing = true }302        }303        .accessibilityLabel(activity.label)304    }305}306307/// Placeholder for an empty list: an icon, a title and what to do next.308struct EmptyStateView: View {309    let icon: String310    let title: String311    let message: String312    let palette: Palette313314    var body: some View {315        VStack(spacing: 6) {316            Image(systemName: icon)317                .font(.system(size: 20, weight: .light))318                .foregroundStyle(palette.accent.opacity(0.85))319                .frame(width: 40, height: 40)320                .background(Circle().fill(palette.accent.opacity(0.10)))321            Text(title).font(.system(size: TypeScale.body, weight: .semibold))322            Text(message).font(.system(size: TypeScale.footnote)).foregroundStyle(palette.secondary)323                .multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)324        }325        .frame(maxWidth: .infinity)326        .padding(.vertical, Space.m).padding(.horizontal, Space.s)327        .accessibilityElement(children: .combine)328    }329}330331/// Hover highlight for list rows.332struct HoverRow: ViewModifier {333    let palette: Palette334    var selected = false335    @State private var hovering = false336    @Environment(\.chrome) private var chrome337338    func body(content: Content) -> some View {339        content340            .background(RoundedRectangle(cornerRadius: Radius.s, style: .continuous)341                .fill(selected ? palette.selected : (hovering ? palette.hover : .clear)))342            .onHover { hovering = $0 }343            .animation(chrome.motion.snappy, value: hovering)344            .animation(chrome.motion.snappy, value: selected)345    }346}347348extension View {349    func hoverRow(_ palette: Palette, selected: Bool = false) -> some View { modifier(HoverRow(palette: palette, selected: selected)) }350}351
Files main
Menu

Theme