SPB Git

Repository Public MIT

InspectorField.swift 8.0 KB 205 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Model/InspectorField.swift8// Module           : GlassStudio9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SPGlassKit4344/// A value edited in the inspector. Only these types exist: there is no free-form code.45public enum InspectorValue: Hashable, Codable, Sendable {46    case bool(Bool)47    case choice(String)48    case number(Double)49    case text(String)50    case color(GlassRGBA)51    case size(GlassControlSize)52}5354/// One typed, bounded parameter of a component preview.55public struct InspectorField: Identifiable, Hashable, Sendable {56    public struct Option: Hashable, Sendable {57        public let id: String58        public let title: String59        public init(_ id: String, _ title: String) { self.id = id; self.title = title }60    }6162    public enum Kind: Hashable, Sendable {63        case toggle(default: Bool)64        case choice(options: [Option], default: String)65        case number(range: ClosedRange<Double>, step: Double, default: Double)66        case text(default: String, maxLength: Int)67        case color(default: GlassRGBA)68        case size(default: GlassControlSize)69    }7071    public let id: String72    /// Label shown in the inspector, in English; the Studio looks its translation up by `id`.73    public let title: String74    public let kind: Kind7576    public init(_ id: String, _ title: String, _ kind: Kind) {77        self.id = id; self.title = title; self.kind = kind78    }7980    public static func toggle(_ id: String, _ title: String, default value: Bool = false) -> InspectorField {81        InspectorField(id, title, .toggle(default: value))82    }8384    public static func choice(_ id: String, _ title: String, options: [Option], default value: String? = nil) -> InspectorField {85        InspectorField(id, title, .choice(options: options, default: value ?? options.first?.id ?? ""))86    }8788    public static func number(_ id: String, _ title: String, in range: ClosedRange<Double>, step: Double = 1, default value: Double) -> InspectorField {89        InspectorField(id, title, .number(range: range, step: step, default: value))90    }9192    public static func text(_ id: String, _ title: String, default value: String, maxLength: Int = 120) -> InspectorField {93        InspectorField(id, title, .text(default: value, maxLength: maxLength))94    }9596    public static func color(_ id: String, _ title: String, default value: GlassRGBA) -> InspectorField {97        InspectorField(id, title, .color(default: value))98    }99100    public static func size(_ id: String = "size", _ title: String = "Size", default value: GlassControlSize = .regular) -> InspectorField {101        InspectorField(id, title, .size(default: value))102    }103104    public var defaultValue: InspectorValue {105        switch kind {106        case .toggle(let value): .bool(value)107        case .choice(_, let value): .choice(value)108        case .number(_, _, let value): .number(value)109        case .text(let value, _): .text(value)110        case .color(let value): .color(value)111        case .size(let value): .size(value)112        }113    }114115    /// Returns `value` if it is acceptable for this field, a corrected value if it can be repaired116    /// (number out of range, text too long), and the default otherwise (wrong type, unknown choice).117    public func validated(_ value: InspectorValue) -> InspectorValue {118        switch (kind, value) {119        case (.toggle, .bool), (.color, .color), (.size, .size):120            return value121        case (.choice(let options, _), .choice(let id)):122            return options.contains { $0.id == id } ? value : defaultValue123        case (.number(let range, let step, _), .number(let number)):124            guard number.isFinite else { return defaultValue }125            var clamped = min(max(number, range.lowerBound), range.upperBound)126            if step > 0 {127                clamped = range.lowerBound + ((clamped - range.lowerBound) / step).rounded() * step128                // Remove binary noise (0.1 × 3 = 0.30000000000000004) so that values compare and print exactly.129                clamped = (clamped * 1_000_000).rounded() / 1_000_000130                clamped = min(max(clamped, range.lowerBound), range.upperBound)131            }132            return .number(clamped)133        case (.text(_, let maxLength), .text(let text)):134            let cleaned = String(text.unicodeScalars.filter { $0.value >= 0x20 || $0 == "\n" }.map(Character.init))135            return .text(String(cleaned.prefix(maxLength)))136        default:137            return defaultValue138        }139    }140}141142/// The current values of a component's fields. Reads always succeed: a missing or invalid value gives the143/// field's default, so previews and snippets never see out-of-range input.144public struct InspectorValues: Hashable, Sendable {145    public let fields: [InspectorField]146    private var storage: [String: InspectorValue]147148    public init(fields: [InspectorField], values: [String: InspectorValue] = [:]) {149        self.fields = fields150        storage = [:]151        for field in fields {152            storage[field.id] = field.validated(values[field.id] ?? field.defaultValue)153        }154    }155156    public subscript(id: String) -> InspectorValue? {157        get { storage[id] }158        set {159            guard let field = fields.first(where: { $0.id == id }), let newValue else { return }160            storage[id] = field.validated(newValue)161        }162    }163164    /// The raw values, for storage in a playground document.165    public var dictionary: [String: InspectorValue] { storage }166167    public func bool(_ id: String) -> Bool {168        if case .bool(let value) = storage[id] { value } else { false }169    }170171    public func choice(_ id: String) -> String {172        if case .choice(let value) = storage[id] { value } else { "" }173    }174175    public func number(_ id: String) -> Double {176        if case .number(let value) = storage[id] { value } else { 0 }177    }178179    public func text(_ id: String) -> String {180        if case .text(let value) = storage[id] { value } else { "" }181    }182183    public func color(_ id: String) -> GlassRGBA {184        if case .color(let value) = storage[id] { value } else { .black }185    }186187    public func size(_ id: String = "size") -> GlassControlSize {188        if case .size(let value) = storage[id] { value } else { .regular }189    }190191    public mutating func reset() {192        for field in fields { storage[field.id] = field.defaultValue }193    }194195    public func applying(_ overrides: [String: InspectorValue]) -> InspectorValues {196        var copy = self197        for (id, value) in overrides { copy[id] = value }198        return copy199    }200201    public var isDefault: Bool {202        fields.allSatisfy { storage[$0.id] == $0.defaultValue }203    }204}205
Files main
Menu

Theme