SPB Git

Repository Public

SettingsLogic.swift 7.3 KB 175 lines swift

1import AppKit2import CoreImage3import CoreImage.CIFilterBuiltins4import MCCCore5import SwiftUI67/// Identifiable wrapper for rows of the generated contract types (which carry an `id` but do not declare the protocol).8struct AdminKeyed<T>: Identifiable {9    let id: String10    let value: T11}1213extension Array {14    func keyed(_ id: (Element) -> String) -> [AdminKeyed<Element>] { map { AdminKeyed(id: id($0), value: $0) } }15}1617/// Panes of the Settings section. Administration panes appear only with their permission (the server enforces).18enum SettingsPane: String, CaseIterable, Identifiable, Sendable {19    case profile, passkeys, sessions, security, shortcuts, about20    case users, invitations, grants, agents, system, serverSettings, freeze2122    var id: String { rawValue }23    var title: String { Localization.shared.string("settings.pane." + rawValue) }2425    var symbol: String {26        switch self {27        case .profile: "person.crop.circle"28        case .passkeys: "person.badge.key"29        case .sessions: "laptopcomputer.and.iphone"30        case .security: "lock"31        case .shortcuts: "keyboard"32        case .about: "info.circle"33        case .users: "person.2"34        case .invitations: "envelope"35        case .grants: "checklist"36        case .agents: "antenna.radiowaves.left.and.right"37        case .system: "waveform.path.ecg"38        case .serverSettings: "slider.horizontal.3"39        case .freeze: "snowflake"40        }41    }4243    var permission: String? {44        switch self {45        case .profile, .passkeys, .sessions, .security, .shortcuts, .about: nil46        case .users, .grants: "users.manage"47        case .invitations: "invitations.manage"48        case .agents: "agents.manage"49        case .system, .serverSettings, .freeze: "settings.manage"50        }51    }5253    var isAdministration: Bool { permission != nil }5455    static func visible(permissions: Set<String>) -> [SettingsPane] {56        allCases.filter { $0.permission.map(permissions.contains) ?? true }57    }58}5960enum SettingsLogic {61    /// Numeric components of a version string: "1.2.0 (7)" → [1, 2, 0].62    static func versionComponents(_ s: String) -> [Int] {63        let head = s.split(whereSeparator: { $0 == " " || $0 == "(" || $0 == "-" || $0 == "+" }).first.map(String.init) ?? ""64        let trimmed = head.hasPrefix("v") ? String(head.dropFirst()) : head65        return trimmed.split(separator: ".").map { Int($0.prefix { $0.isNumber }) ?? 0 }66    }6768    /// True when `app` is strictly older than `minimum`. Unparseable versions are never reported as too old.69    static func isOlder(app: String, than minimum: String) -> Bool {70        let a = versionComponents(app), m = versionComponents(minimum)71        guard !a.isEmpty, !m.isEmpty else { return false }72        for i in 0..<max(a.count, m.count) {73            let x = i < a.count ? a[i] : 0, y = i < m.count ? m[i] : 074            if x != y { return x < y }75        }76        return false77    }7879    /// Parses the text of a setting value; nil when it is not valid JSON (a bare scalar is valid).80    static func parseSettingValue(_ text: String) -> JSONValue? {81        let t = text.trimmingCharacters(in: .whitespacesAndNewlines)82        guard !t.isEmpty else { return nil }83        // JSONSerialization rejects top-level scalars without `.fragmentsAllowed`; wrap to accept them uniformly.84        guard let v = try? JSONValue.parse(Data("[\(t)]".utf8)), case .array(let a) = v, a.count == 1 else { return nil }85        return a[0]86    }8788    /// The typed confirmation of the emergency freeze: exact word, case-insensitive, surrounding spaces ignored.89    static func confirmationMatches(_ input: String, word: String) -> Bool {90        !word.isEmpty && input.trimmingCharacters(in: .whitespacesAndNewlines).caseInsensitiveCompare(word) == .orderedSame91    }9293    /// TTL of an invitation in minutes, clamped to what the server accepts (1 … 1440).94    static func clampTTL(_ minutes: Int) -> Int { min(1440, max(1, minutes)) }9596    /// Handle rule mirrored for input help only (the server validates): lowercase, digits, `._-`, 2–32 chars.97    static func looksLikeHandle(_ s: String) -> Bool {98        guard (2...32).contains(s.count), let first = s.first, first.isLowercase || first.isNumber else { return false }99        return s.allSatisfy { $0.isASCII && ($0.isLowercase || $0.isNumber || $0 == "." || $0 == "_" || $0 == "-") }100    }101102    /// QR code of `text`, generated locally with CoreImage (nothing leaves the Mac).103    static func qrCode(_ text: String, scale: CGFloat = 8) -> NSImage? {104        let filter = CIFilter.qrCodeGenerator()105        filter.message = Data(text.utf8)106        filter.correctionLevel = "M"107        guard let output = filter.outputImage?.transformed(by: CGAffineTransform(scaleX: scale, y: scale)),108              let cg = CIContext().createCGImage(output, from: output.extent) else { return nil }109        return NSImage(cgImage: cg, size: NSSize(width: output.extent.width, height: output.extent.height))110    }111112    static func tone(_ s: API.ComponentStatus.StatusPayload) -> StatusTone {113        switch s {114        case .ok: .ok115        case .degraded: .warning116        case .down: .critical117        case .unknown: .neutral118        }119    }120121    static func tone(_ s: API.BackupStatus.StatusPayload) -> StatusTone {122        switch s {123        case .ok: .ok124        case .failed: .critical125        case .unknown: .neutral126        }127    }128}129130/// A secret shown exactly once (invitation link, enrollment token): selectable, copyable, never persisted.131struct OneTimeSecretField: View {132    let title: String133    let value: String134    @Environment(\.mccTheme) private var theme135    var body: some View {136        VStack(alignment: .leading, spacing: Tokens.Space.s1) {137            Text(title).font(.caption).foregroundStyle(theme.textSecondary)138            HStack(alignment: .top, spacing: Tokens.Space.s2) {139                Text(value).font(.callout.monospaced()).foregroundStyle(theme.textPrimary).textSelection(.enabled)140                    .frame(maxWidth: .infinity, alignment: .leading)141                    .padding(Tokens.Space.s3)142                    .background(theme.inset, in: RoundedRectangle(cornerRadius: Tokens.Radius.md))143                CopyButton(value: value)144            }145        }146        .accessibilityElement(children: .contain)147        .accessibilityLabel(title)148    }149}150151/// Optional date as text, or an explicit dash.152func settingsDate(_ d: Date?) -> String { d.map { Format.dateTime($0) } ?? "—" }153154/// Standard container of a settings pane.155struct SettingsPaneContainer<Content: View>: View {156    let pane: SettingsPane157    var subtitle: String?158    @ViewBuilder var content: Content159    @Environment(\.mccTheme) private var theme160    var body: some View {161        ScrollView {162            VStack(alignment: .leading, spacing: Tokens.Space.s5) {163                VStack(alignment: .leading, spacing: 2) {164                    Text(pane.title).font(.title3.weight(.semibold)).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)165                    if let subtitle { Text(subtitle).font(.callout).foregroundStyle(theme.textSecondary) }166                }167                content168            }169            .padding(Tokens.Space.s6)170            .frame(maxWidth: .infinity, alignment: .topLeading)171        }172        .accessibilityIdentifier("settings-pane-\(pane.rawValue)")173    }174}175
Files main
Menu

Theme