Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/Kit/Views/ThemeViews.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 UniformTypeIdentifiers43import SPGlassKit4445/// A theme as a JSON file, for export, sharing and drag and drop.46struct ThemeFile: Transferable, FileDocument {47 static let readableContentTypes: [UTType] = [.json]48 var theme: GlassTheme4950 init(theme: GlassTheme) { self.theme = theme }5152 init(configuration: ReadConfiguration) throws {53 guard let data = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) }54 theme = try GlassThemeCodec.decode(data)55 }5657 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {58 FileWrapper(regularFileWithContents: try GlassThemeCodec.encode(theme))59 }6061 static var transferRepresentation: some TransferRepresentation {62 DataRepresentation(exportedContentType: .json) { file in63 try GlassThemeCodec.encode(file.theme)64 }65 .suggestedFileName { "\($0.theme.id.rawValue).json" }66 }67}6869struct ThemesView: View {70 @Bindable var model: StudioModel71 @State private var editing: GlassTheme?72 @State private var importing = false73 @State private var message: String?7475 private let columns = [GridItem(.adaptive(minimum: 158, maximum: 280), spacing: 14)]7677 var body: some View {78 ScrollView {79 LazyVStack(alignment: .leading, spacing: 26) {80 if let notice = model.themes.recoveryNotice {81 VStack(alignment: .leading, spacing: 10) {82 Label(notice.hasPrefix("recovered") ? L("Your theme library was damaged. The last backup was restored and the damaged file was kept.") : L("Your theme library was damaged and could not be restored. The damaged file was kept."), systemImage: "exclamationmark.triangle")83 Button(L("OK")) { model.themes.acknowledgeRecovery() }.buttonStyle(.bordered)84 }85 .padding(16)86 .frame(maxWidth: .infinity, alignment: .leading)87 .studioCard()88 }89 themeSection(L("Built-in"), GlassTheme.builtIn)90 if !model.themes.customThemes.isEmpty { themeSection(L("My themes"), model.themes.customThemes) }91 VStack(alignment: .leading, spacing: 8) {92 themeSection(L("Examples"), GlassTheme.examples)93 Text(L("Example themes show how a product theme is declared. Their colours are illustrations, not the palettes of those products."))94 .font(.footnote).foregroundStyle(.secondary)95 }96 }97 .padding(.horizontal, 20)98 .padding(.top, 8)99 .padding(.bottom, 32)100 }101 .background(StudioPalette.page)102 .navigationTitle(Text(L("Themes")))103 .toolbar {104 ToolbarItemGroup(placement: .primaryAction) {105 Button(L("Import theme"), systemImage: "square.and.arrow.down") { importing = true }106 .accessibilityIdentifier("import-theme")107 Button(L("New theme"), systemImage: "plus") {108 if let copy = model.themes.duplicate(model.themes.theme(model.preview.themeID) ?? .system, name: L("My theme")) { editing = copy }109 }110 .accessibilityIdentifier("new-theme")111 }112 }113 .fileImporter(isPresented: $importing, allowedContentTypes: [.json]) { result in114 guard case .success(let url) = result else { return }115 let scoped = url.startAccessingSecurityScopedResource()116 defer { if scoped { url.stopAccessingSecurityScopedResource() } }117 do {118 // The size is checked before the file is read into memory.119 let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0120 guard size <= GlassThemeCodec.maximumBytes else { throw GlassThemeError.tooLarge(bytes: size, limit: GlassThemeCodec.maximumBytes) }121 let theme = try model.themes.importTheme(from: Data(contentsOf: url))122 model.preview.themeID = theme.id123 message = L("Theme imported.")124 } catch let error as GlassThemeError {125 message = error.description126 } catch {127 message = L("The file could not be read.")128 }129 }130 .alert(L("Themes"), isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) {131 Button(L("OK")) { message = nil }132 } message: {133 Text(verbatim: message ?? "")134 }135 .sheet(item: $editing) { theme in136 NavigationStack {137 ThemeEditorView(model: model, theme: theme) { editing = nil }138 }139 #if os(macOS)140 .frame(minWidth: 760, minHeight: 620)141 #endif142 }143 .accessibilityIdentifier("themes")144 }145146 private func themeSection(_ title: String, _ themes: [GlassTheme]) -> some View {147 VStack(alignment: .leading, spacing: 12) {148 Text(title).font(.title3.weight(.semibold)).accessibilityAddTraits(.isHeader)149 LazyVGrid(columns: columns, alignment: .leading, spacing: 14) {150 ForEach(themes) { card($0) }151 }152 }153 }154155 @ViewBuilder156 private func actions(_ theme: GlassTheme) -> some View {157 Button(L("Use in previews"), systemImage: "checkmark.circle") { model.preview.themeID = theme.id }158 if model.themes.isCustom(theme.id) {159 Button(L("Edit"), systemImage: "pencil") { editing = theme }160 }161 Button(L("Duplicate and edit"), systemImage: "plus.square.on.square") {162 if let copy = model.themes.duplicate(theme) { editing = copy }163 }164 ShareLink(item: ThemeFile(theme: theme), preview: SharePreview(theme.name)) { Label(L("Share JSON"), systemImage: "square.and.arrow.up") }165 Button(L("Copy as Swift"), systemImage: "swift") { StudioPasteboard.copy(GlassThemeSwiftExporter.source(for: theme)) }166 if model.themes.isCustom(theme.id) {167 Button(L("Delete"), systemImage: "trash", role: .destructive) {168 if model.preview.themeID == theme.id { model.preview.themeID = "system" }169 model.themes.delete(theme.id)170 }171 }172 }173174 private func card(_ theme: GlassTheme) -> some View {175 let isSelected = model.preview.themeID == theme.id176 return VStack(alignment: .leading, spacing: 0) {177 Button { model.preview.themeID = theme.id } label: {178 ThemeSpecimen(theme: theme)179 .frame(height: 118)180 .clipped()181 .overlay(alignment: .topTrailing) {182 if isSelected {183 Image(systemName: "checkmark.circle.fill")184 .font(.title3)185 .symbolRenderingMode(.palette)186 .foregroundStyle(.white, .black.opacity(0.75))187 .padding(10)188 .accessibilityLabel(Text(L("Selected")))189 }190 }191 }192 .buttonStyle(.plain)193 .accessibilityLabel(Text(verbatim: theme.name))194 Divider()195 HStack(alignment: .top, spacing: 4) {196 VStack(alignment: .leading, spacing: 2) {197 Text(verbatim: theme.name).font(.subheadline.weight(.semibold)).lineLimit(1)198 if !theme.summary.isEmpty {199 Text(verbatim: theme.summary).font(.caption).foregroundStyle(.secondary).lineLimit(2, reservesSpace: true)200 }201 }202 Spacer(minLength: 0)203 Menu { actions(theme) } label: {204 Label(L("Theme actions"), systemImage: "ellipsis")205 .labelStyle(.iconOnly)206 .frame(width: 32, height: 32)207 .contentShape(Rectangle())208 }209 .menuStyle(.borderlessButton)210 .fixedSize()211 }212 .padding(.leading, 12)213 .padding(.trailing, 4)214 .padding(.vertical, 8)215 }216 .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))217 .studioCard(radius: 18)218 .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(.primary, lineWidth: isSelected ? 2 : 0))219 .contextMenu { actions(theme) }220 .accessibilityElement(children: .contain)221 .accessibilityIdentifier("theme-\(theme.id.rawValue)")222 .accessibilityAddTraits(isSelected ? .isSelected : [])223 }224}225226/// A theme shown as itself: its colour stage on the light half and the dark half, with a glass control on227/// top of each so that the tint and the legibility can be judged at a glance.228struct ThemeSpecimen: View {229 let theme: GlassTheme230231 var body: some View {232 HStack(spacing: 0) {233 ForEach([ColorScheme.light, .dark], id: \.self) { scheme in234 ZStack {235 PreviewBackdropView(backdrop: .stage)236 SpecimenControl()237 }238 .glassTheme(theme)239 .environment(\.colorScheme, scheme)240 }241 }242 .allowsHitTesting(false)243 .accessibilityHidden(true)244 }245}246247private struct SpecimenControl: View {248 @GlassThemed private var theme249250 var body: some View {251 Text(verbatim: "Aa")252 .font(theme.font(.headline))253 .foregroundStyle(theme.color(.textPrimary))254 .padding(.horizontal, 14)255 .padding(.vertical, 8)256 .glassSurface(.regular, in: Capsule())257 }258}259260/// Light and dark colours of a theme side by side.261struct ThemeStrip: View {262 let theme: GlassTheme263264 var body: some View {265 VStack(spacing: 0) {266 ForEach([ColorScheme.light, .dark], id: \.self) { scheme in267 let resolved = GlassThemeResolver.resolve(theme, colorScheme: scheme)268 HStack(spacing: 0) {269 ForEach([GlassColorToken.background, .primary, .accent, .textPrimary], id: \.self) { resolved.color($0) }270 }271 .environment(\.colorScheme, scheme)272 }273 }274 .frame(width: 56, height: 36)275 .clipShape(RoundedRectangle(cornerRadius: 7, style: .continuous))276 .overlay(RoundedRectangle(cornerRadius: 7, style: .continuous).strokeBorder(.separator))277 .accessibilityHidden(true)278 }279}280281/// A small composition used to judge a theme: text, buttons, a field, a banner and a floating glass surface.282struct ThemeSampleView: View {283 @GlassThemed private var theme284 @State private var text = ""285 @State private var isOn = true286287 var body: some View {288 VStack(alignment: .leading, spacing: theme.spacing.md) {289 Text(L("Sample heading")).font(theme.font(.title)).foregroundStyle(theme.color(.textPrimary))290 Text(L("Body text shows how readable this theme is on its background and on its surface."))291 .font(theme.font(.body)).foregroundStyle(theme.color(.textSecondary))292 HStack(spacing: theme.spacing.sm) {293 GlassButton(verbatim: L("Primary"), variant: .prominent) {}294 GlassButton(verbatim: L("Secondary")) {}295 GlassIconButton(systemImage: "trash", label: Text(L("Delete")), role: .destructive) {}296 }297 VStack(alignment: .leading, spacing: theme.spacing.xs) {298 Toggle(L("Option"), isOn: $isOn).tint(theme.color(.primary))299 HStack(spacing: theme.spacing.xs) {300 ForEach([(GlassColorToken.success, "checkmark.circle.fill", "Success"), (.warning, "exclamationmark.triangle.fill", "Warning"), (.destructive, "xmark.octagon.fill", "Error")], id: \.2) { token, symbol, name in301 Label(L(name), systemImage: symbol).font(theme.font(.caption)).foregroundStyle(theme.color(token))302 }303 }304 }305 .padding(theme.spacing.md)306 .frame(maxWidth: .infinity, alignment: .leading)307 .glassOpaqueSurface(in: theme.shape(\.medium))308 Label(L("Floating glass surface"), systemImage: "circle.lefthalf.filled")309 .font(theme.font(.callout))310 .padding(.horizontal, theme.spacing.md)311 .padding(.vertical, theme.spacing.sm)312 .glassSurface(.regular, in: Capsule())313 }314 .frame(maxWidth: .infinity, alignment: .leading)315 }316}317