Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/Kit/Views/ThemeEditorView.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 SwiftUI42import SPGlassKit4344extension GlassColorToken {45 var title: String {46 switch self {47 case .primary: L("Primary")48 case .secondary: L("Secondary")49 case .accent: L("Accent")50 case .destructive: L("Destructive")51 case .success: L("Success")52 case .warning: L("Warning")53 case .background: L("Background")54 case .surface: L("Surface")55 case .textPrimary: L("Primary text")56 case .textSecondary: L("Secondary text")57 case .separator: L("Separator")58 case .focusRing: L("Focus ring")59 }60 }61}6263/// Edits a custom theme with a live preview, undo and redo, contrast checks and export.64struct ThemeEditorView: View {65 @Bindable var model: StudioModel66 let onClose: () -> Void67 @State private var history: ThemeEditHistory68 @State private var editsDark = false69 @State private var compares = false70 @State private var exportsJSON = false71 @State private var showsSwift = false72 @Environment(\.self) private var environment73 @Environment(\.colorScheme) private var colorScheme7475 init(model: StudioModel, theme: GlassTheme, onClose: @escaping () -> Void) {76 self.model = model77 self.onClose = onClose78 _history = State(initialValue: ThemeEditHistory(theme))79 _editsDark = State(initialValue: false)80 }8182 private var theme: GlassTheme { history.current }8384 private func binding<Value>(_ keyPath: WritableKeyPath<GlassTheme, Value>) -> Binding<Value> {85 Binding(get: { history.current[keyPath: keyPath] }, set: { value in history.apply { $0[keyPath: keyPath] = value } })86 }8788 var body: some View {89 Form {90 Section {91 PreviewCanvas(configuration: previewConfiguration, theme: theme, minHeight: 200) { ThemeSampleView() }92 .listRowInsets(EdgeInsets())93 if compares {94 PreviewCanvas(configuration: previewConfiguration, theme: history.original, minHeight: 200) { ThemeSampleView() }95 .listRowInsets(EdgeInsets())96 .overlay(alignment: .topTrailing) { Text(L("Before")).font(.caption2.weight(.medium)).padding(6).background(.background.opacity(0.9), in: Capsule()).padding(8) }97 }98 Toggle(L("Compare with the version before editing"), isOn: $compares)99 }100101 Section(L("Identity")) {102 TextField(L("Name"), text: binding(\.name))103 TextField(L("Summary"), text: binding(\.summary), axis: .vertical).lineLimit(1...3)104 LabeledContent(L("Identifier")) { Text(verbatim: theme.id.rawValue).font(.callout.monospaced()).textSelection(.enabled) }105 Picker(L("Appearance"), selection: binding(\.appearance)) {106 Text(L("Follows the system")).tag(GlassAppearance.system)107 Text(L("Always light")).tag(GlassAppearance.light)108 Text(L("Always dark")).tag(GlassAppearance.dark)109 }110 }111112 Section {113 Picker(L("Palette"), selection: $editsDark) {114 Text(L("Light")).tag(false)115 Text(L("Dark")).tag(true)116 }117 .pickerStyle(.segmented)118 ForEach(GlassColorToken.allCases, id: \.self) { token in colorRow(token) }119 } header: {120 Text(L("Colours"))121 } footer: {122 Text(L("A role set to System follows the system colour for that role, including the user's accent colour."))123 }124125 let issues = GlassThemeValidator.validate(theme)126 Section {127 if issues.isEmpty {128 Label(L("No contrast issue found between text and the opaque backgrounds of this theme."), systemImage: "checkmark.circle")129 }130 ForEach(issues, id: \.self) { issue in131 Label { Text(verbatim: issue.message) } icon: {132 Image(systemName: issue.severity == .error ? "xmark.octagon" : "exclamationmark.triangle")133 }134 .foregroundStyle(issue.severity == .error ? .red : .primary)135 }136 } header: {137 Text(L("Contrast"))138 } footer: {139 Text(L("Ratios are measured on opaque colours (WCAG 2). Over Liquid Glass the backdrop changes with the content behind it, so these ratios do not guarantee the contrast of text on glass. Check your screens over real content."))140 }141142 Section(L("Typography")) {143 Picker(L("Typeface design"), selection: binding(\.typography.design)) {144 Text(L("Default")).tag(GlassFontDesign.default)145 Text(L("Rounded")).tag(GlassFontDesign.rounded)146 Text(L("Serif")).tag(GlassFontDesign.serif)147 Text(L("Monospaced")).tag(GlassFontDesign.monospaced)148 }149 weightPicker(L("Heading weight"), binding(\.typography.headingWeight))150 weightPicker(L("Body weight"), binding(\.typography.bodyWeight))151 Text(L("Text sizes follow Dynamic Type and are not part of a theme.")).font(.footnote).foregroundStyle(.secondary)152 }153154 Section(L("Spacing and shape")) {155 Picker(L("Density"), selection: binding(\.density)) {156 Text(L("Compact")).tag(GlassDensity.compact)157 Text(L("Regular density")).tag(GlassDensity.regular)158 Text(L("Comfortable")).tag(GlassDensity.comfortable)159 }160 slider(L("Base spacing"), binding(\.spacing.md), 8...32, step: 1)161 slider(L("Small radius"), binding(\.radii.small), 0...24, step: 1)162 slider(L("Medium radius"), binding(\.radii.medium), 0...32, step: 1)163 slider(L("Large radius"), binding(\.radii.large), 0...48, step: 1)164 Text(L("Radii apply to surfaces GlassKit draws. System controls keep the shape chosen by the system.")).font(.footnote).foregroundStyle(.secondary)165 }166167 Section(L("Motion")) {168 Picker(L("Animation style"), selection: binding(\.motion.style)) {169 Text(L("Smooth")).tag(GlassMotionStyle.smooth)170 Text(L("Snappy")).tag(GlassMotionStyle.snappy)171 Text(L("Bouncy")).tag(GlassMotionStyle.bouncy)172 }173 slider(L("Standard duration (s)"), binding(\.motion.standard), 0.1...0.8, step: 0.05, fraction: 2)174 Toggle(L("Haptic feedback"), isOn: binding(\.hapticsEnabled))175 }176177 Section {178 Picker(L("Glass variant"), selection: binding(\.glass.variant)) {179 Text(L("Regular")).tag(GlassVariant.regular)180 Text(L("Clear")).tag(GlassVariant.clear)181 }182 Picker(L("Glass tint"), selection: binding(\.glass.tint)) {183 Text(L("None")).tag(GlassColorToken?.none)184 ForEach([GlassColorToken.primary, .secondary, .accent], id: \.self) { Text($0.title).tag(GlassColorToken?.some($0)) }185 }186 } header: {187 Text(L("Liquid Glass"))188 } footer: {189 Text(L("These are the parameters the system exposes. Blur, refraction and the opacity of the glass are decided by the system and cannot be set by a theme."))190 }191192 if showsSwift {193 Section { CodeView(GlassThemeSwiftExporter.source(for: theme), title: L("Swift")) }194 }195 }196 .formStyle(.grouped)197 .navigationTitle(Text(verbatim: theme.name))198 #if os(iOS)199 .navigationBarTitleDisplayMode(.inline)200 #endif201 .toolbar {202 ToolbarItem(placement: .cancellationAction) { Button(L("Close")) { onClose() } }203 ToolbarItemGroup(placement: .primaryAction) {204 Button(L("Undo"), systemImage: "arrow.uturn.backward") { history.undo() }205 .disabled(!history.canUndo).keyboardShortcut("z", modifiers: .command).accessibilityIdentifier("theme-undo")206 Button(L("Redo"), systemImage: "arrow.uturn.forward") { history.redo() }207 .disabled(!history.canRedo).keyboardShortcut("z", modifiers: [.command, .shift]).accessibilityIdentifier("theme-redo")208 Menu {209 Button(L("Reset to the version before editing"), systemImage: "arrow.counterclockwise") { history.reset() }.disabled(!history.isModified)210 Button(L("Export JSON…"), systemImage: "square.and.arrow.down") { exportsJSON = true }211 ShareLink(item: ThemeFile(theme: theme), preview: SharePreview(theme.name)) { Label(L("Share JSON"), systemImage: "square.and.arrow.up") }212 Button(L("Copy as Swift"), systemImage: "swift") { StudioPasteboard.copy(GlassThemeSwiftExporter.source(for: theme)) }213 Toggle(L("Show Swift code"), isOn: $showsSwift)214 } label: {215 Label(L("More"), systemImage: "ellipsis.circle")216 }217 Button(L("Save")) {218 if model.themes.save(theme) { model.preview.themeID = theme.id; onClose() }219 }220 .disabled(!GlassThemeValidator.isUsable(theme))221 .keyboardShortcut("s", modifiers: .command)222 .accessibilityIdentifier("theme-save")223 }224 }225 .fileExporter(isPresented: $exportsJSON, document: ThemeFile(theme: theme), contentType: .json, defaultFilename: theme.id.rawValue) { _ in }226 .onAppear { editsDark = colorScheme == .dark }227 }228229 private var previewConfiguration: PreviewConfiguration {230 var configuration = model.preview231 configuration.themeID = theme.id232 configuration.density = nil233 // The preview follows the palette being edited.234 configuration.appearance = editsDark ? .dark : .light235 return configuration236 }237238 private func colorRow(_ token: GlassColorToken) -> some View {239 let keyPath: WritableKeyPath<GlassTheme, GlassPalette> = editsDark ? \.dark : \.light240 let value = theme[keyPath: keyPath][token]241 return HStack {242 if let value {243 ColorPicker(token.title, selection: Binding(244 get: { Color(glass: value) },245 set: { color in history.apply { $0[keyPath: keyPath][token] = GlassRGBA(color, in: environment).opacity(1) } }246 ), supportsOpacity: false)247 Text(verbatim: value.hexString).font(.caption.monospaced()).foregroundStyle(.secondary)248 } else {249 Text(token.title)250 Spacer()251 Text(L("System")).foregroundStyle(.secondary)252 }253 Toggle(L("Follow the system"), isOn: Binding(254 get: { value == nil },255 set: { followsSystem in256 history.apply { $0[keyPath: keyPath][token] = followsSystem ? nil : GlassRGBA(GlassSystemColors.color(for: token), in: environment).opacity(1) }257 }258 ))259 .labelsHidden()260 .toggleStyle(.button)261 .controlSize(.small)262 .help(L("Follow the system"))263 .accessibilityLabel(Text(L("Follow the system") + ": " + token.title))264 }265 .accessibilityIdentifier("color-\(token.rawValue)")266 }267268 private func weightPicker(_ title: String, _ binding: Binding<GlassFontWeight>) -> some View {269 Picker(title, selection: binding) {270 Text(L("Regular weight")).tag(GlassFontWeight.regular)271 Text(L("Medium")).tag(GlassFontWeight.medium)272 Text(L("Semibold")).tag(GlassFontWeight.semibold)273 Text(L("Bold")).tag(GlassFontWeight.bold)274 }275 }276277 private func slider(_ title: String, _ binding: Binding<Double>, _ range: ClosedRange<Double>, step: Double, fraction: Int = 0) -> some View {278 LabeledContent(title) {279 HStack {280 Slider(value: binding, in: range, step: step) { Text(title) }.frame(minWidth: 120)281 Text(binding.wrappedValue, format: .number.precision(.fractionLength(fraction))).monospacedDigit().foregroundStyle(.secondary).frame(minWidth: 36, alignment: .trailing)282 }283 }284 }285}286