SPB Git

Repository Public

ThemeStudioView.swift 10.3 KB 244 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : App/Screens/ThemeStudioView.swift10// Description      : Theme Studio gallery: the twelve built-in themes and the11//                    user's own, with live swatches, favourites, activation,12//                    duplication for editing, and validated JSON import.13// Module           : App14// Repository       : https://git.spboucher.ai/sp-keyboard15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import SwiftUI91import ThemeEngine9293struct ThemeStudioView: View {94    @Environment(AppModel.self) private var model95    @Environment(AppRouter.self) private var router96    @State private var favoritesOnly = false97    @State private var isImporting = false98    @State private var message: String?99    @State private var document = PreviewDocument(text: "Bonjour ")100101    private let columns = [GridItem(.adaptive(minimum: 150, maximum: 240), spacing: 14)]102103    var body: some View {104        ScrollView {105            VStack(alignment: .leading, spacing: 18) {106                if let message {107                    Text(message)108                        .font(.footnote)109                        .foregroundStyle(.secondary)110                        .accessibilityIdentifier("themes.message")111                }112                Toggle("Favoris seulement", isOn: $favoritesOnly)113                    .accessibilityIdentifier("themes.favoritesOnly")114                if !visible(model.library.custom).isEmpty {115                    section("Mes thèmes", themes: visible(model.library.custom))116                }117                section("Thèmes SP", themes: visible(BuiltInThemes.all))118                if favoritesOnly, visible(model.library.all).isEmpty {119                    Text("Aucun favori. Touchez l'étoile d'un thème pour l'ajouter.")120                        .font(.subheadline)121                        .foregroundStyle(.secondary)122                }123            }124            .padding(.horizontal, 16)125            .padding(.bottom, 12)126        }127        .safeAreaInset(edge: .bottom, spacing: 0) {128            PreviewDock(theme: model.library.active, settings: model.settings, dictionary: model.dictionary, aiSettings: model.ai, document: document)129        }130        .navigationTitle("Theme Studio")131        .navigationBarTitleDisplayMode(.inline)132        .toolbar {133            ToolbarItem(placement: .topBarTrailing) {134                Button {135                    isImporting = true136                } label: {137                    Label("Importer un thème", systemImage: "square.and.arrow.down")138                }139                .accessibilityIdentifier("themes.import")140            }141        }142        .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json]) { result in143            guard case .success(let url) = result, let data = FileReading.data(at: url, limit: ThemeCodec.maxImportBytes) else {144                message = "Fichier illisible ou trop volumineux (64 Ko au plus)."145                return146            }147            do {148                let theme = try model.importTheme(data)149                message = "Thème « \(theme.name) » importé."150            } catch {151                message = Self.describe(error)152            }153        }154    }155156    private func visible(_ themes: [Theme]) -> [Theme] {157        favoritesOnly ? themes.filter { model.library.favorites.contains($0.id) } : themes158    }159160    private func section(_ title: String, themes: [Theme]) -> some View {161        VStack(alignment: .leading, spacing: 10) {162            Text(title).font(.headline)163            LazyVGrid(columns: columns, spacing: 14) {164                ForEach(themes) { theme in card(theme) }165            }166        }167    }168169    private func card(_ theme: Theme) -> some View {170        let isActive = model.library.active.id == theme.id171        let isFavorite = model.library.favorites.contains(theme.id)172        return VStack(alignment: .leading, spacing: 6) {173            Button {174                model.activateTheme(id: theme.id)175            } label: {176                ThemeSwatch(theme: theme)177                    .frame(height: 92)178                    .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous)179                        .strokeBorder(isActive ? Palette.violet : Color.secondary.opacity(0.25), lineWidth: isActive ? 3 : 1))180            }181            .buttonStyle(.plain)182            .accessibilityLabel("Thème \(theme.name)")183            .accessibilityValue(isActive ? "actif" : "inactif")184            .accessibilityHint("Active ce thème")185            .accessibilityAddTraits(isActive ? .isSelected : [])186            .accessibilityIdentifier("theme.\(theme.id)")187            Text(theme.name)188                .font(.subheadline.weight(.semibold))189                .lineLimit(2)190                .fixedSize(horizontal: false, vertical: true)191            HStack(spacing: 0) {192                Text(isActive ? "Actif" : (theme.isBuiltIn ? "Thème SP" : "Personnel"))193                    .font(.caption)194                    .foregroundStyle(isActive ? Color.accentColor : .secondary)195                Spacer(minLength: 0)196                Button {197                    model.toggleFavoriteTheme(theme.id)198                } label: {199                    Image(systemName: isFavorite ? "star.fill" : "star")200                        .foregroundStyle(isFavorite ? .yellow : .secondary)201                        .frame(width: 44, height: 44)202                        .contentShape(Rectangle())203                }204                .buttonStyle(.plain)205                .accessibilityLabel(isFavorite ? "Retirer \(theme.name) des favoris" : "Ajouter \(theme.name) aux favoris")206                .accessibilityIdentifier("theme.favorite.\(theme.id)")207                Button {208                    edit(theme)209                } label: {210                    Image(systemName: theme.isBuiltIn ? "plus.square.on.square" : "slider.horizontal.3")211                        .frame(width: 44, height: 44)212                        .contentShape(Rectangle())213                }214                .buttonStyle(.plain)215                .accessibilityLabel(theme.isBuiltIn ? "Dupliquer \(theme.name) pour le modifier" : "Modifier \(theme.name)")216                .accessibilityIdentifier("theme.edit.\(theme.id)")217            }218        }219    }220221    private func edit(_ theme: Theme) {222        if theme.isBuiltIn {223            guard let copy = model.duplicateTheme(theme) else {224                message = "Limite de \(ThemeLibrary.maxCustomThemes) thèmes personnels atteinte."225                return226            }227            router.themePath = [copy.id]228        } else {229            router.themePath = [theme.id]230        }231    }232233    static func describe(_ error: Error) -> String {234        switch error as? ThemeCodecError {235        case .tooLarge: "Fichier trop volumineux (64 Ko au plus)."236        case .notJSON: "Ce fichier n'est pas un JSON valide."237        case .wrongFormat: "Ce fichier n'est pas un thème SP Keyboard."238        case .unsupportedVersion(let version): "Version de thème \(version) non prise en charge par cette app."239        case .malformed(let detail): "Thème invalide : \(detail)."240        case nil: "Import impossible."241        }242    }243}244
Files main
Menu

Theme