SPB Git

Repository Public

DictionaryView.swift 14.5 KB 326 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : App/Screens/DictionaryView.swift10// Description      : Personal dictionary (words, opt-in learned words) and11//                    snippets / message templates with optional triggers, plus12//                    validated import and export of the configuration (never13//                    the key, never the learned words).14// Module           : App15// Repository       : https://git.spboucher.ai/sp-keyboard16// Created          : 2026-12-0117// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI92import KeyboardCore9394struct DictionaryView: View {95    @Environment(AppModel.self) private var model96    @State private var newWord = ""97    @State private var wordMessage: String?98    @State private var editedSnippet: Snippet?99    @State private var isImporting = false100    @State private var isExporting = false101    @State private var exportData = Data()102    @State private var transferMessage: String?103    @State private var confirmEraseLearned = false104105    var body: some View {106        Form {107            Section {108                HStack {109                    TextField("Nouveau mot", text: $newWord)110                        .textInputAutocapitalization(.never)111                        .autocorrectionDisabled()112                        .onSubmit(addWord)113                        .accessibilityIdentifier("dictionary.newWord")114                    Button("Ajouter", action: addWord)115                        .disabled(newWord.trimmingCharacters(in: .whitespaces).isEmpty)116                        .accessibilityIdentifier("dictionary.addWord")117                }118                if let wordMessage {119                    Text(wordMessage).font(.footnote).foregroundStyle(.secondary)120                }121                ForEach(model.dictionary.words, id: \.self) { Text($0) }122                    .onDelete { offsets in123                        offsets.map { model.dictionary.words[$0] }.forEach(model.removeWord)124                    }125            } header: {126                Text("Mes mots (\(model.dictionary.words.count))")127            } footer: {128                Text("Ces mots sont toujours acceptés, proposés en priorité et jamais corrigés. Un mot ne contient pas d'espace.")129            }130131            Section {132                if model.dictionary.learned.isEmpty {133                    Text(model.settings.learnWords ? "Aucun mot appris pour l'instant." : "L'apprentissage est désactivé (Typing Lab).")134                        .foregroundStyle(.secondary)135                } else {136                    ForEach(model.dictionary.learned.sorted { $0.value == $1.value ? $0.key < $1.key : $0.value > $1.value }, id: \.key) { entry in137                        LabeledContent(entry.key, value: "\(entry.value) fois")138                    }139                    .onDelete { offsets in140                        let sorted = model.dictionary.learned.sorted { $0.value == $1.value ? $0.key < $1.key : $0.value > $1.value }141                        offsets.map { sorted[$0].key }.forEach(model.removeLearnedWord)142                    }143                    Button("Effacer tous les mots appris", role: .destructive) { confirmEraseLearned = true }144                        .accessibilityIdentifier("dictionary.eraseLearned")145                }146            } header: {147                Text("Mots appris (\(model.dictionary.learned.count))")148            } footer: {149                Text("Proposés à partir de deux utilisations. Jamais exportés.")150            }151152            ForEach(Snippet.Category.allCases, id: \.self) { category in153                Section {154                    ForEach(model.dictionary.snippets.filter { $0.category == category }) { snippet in155                        Button {156                            editedSnippet = snippet157                        } label: {158                            VStack(alignment: .leading, spacing: 2) {159                                HStack {160                                    Text(snippet.title.isEmpty ? "Sans titre" : snippet.title).foregroundStyle(.primary)161                                    if !snippet.trigger.isEmpty {162                                        Text(snippet.trigger)163                                            .font(.caption.monospaced())164                                            .padding(.horizontal, 6)165                                            .padding(.vertical, 2)166                                            .background(Capsule().fill(Color.secondary.opacity(0.18)))167                                            .accessibilityLabel("déclencheur \(snippet.trigger)")168                                    }169                                }170                                Text(snippet.text).font(.footnote).foregroundStyle(.secondary).lineLimit(2)171                            }172                            .frame(maxWidth: .infinity, alignment: .leading)173                            .contentShape(Rectangle())174                        }175                        .buttonStyle(.plain)176                        .accessibilityHint("Modifier ce snippet")177                    }178                    .onDelete { offsets in179                        let list = model.dictionary.snippets.filter { $0.category == category }180                        offsets.map { list[$0].id }.forEach(model.deleteSnippet)181                    }182                    Button {183                        editedSnippet = Snippet(title: "", text: "", category: category)184                    } label: {185                        Label("Ajouter", systemImage: "plus")186                    }187                    .accessibilityIdentifier("dictionary.addSnippet.\(category.rawValue)")188                } header: {189                    Text(Self.name(category))190                }191            }192193            Section {194                Button {195                    if let data = try? model.exportConfiguration() {196                        exportData = data197                        isExporting = true198                    }199                } label: {200                    Label("Exporter la configuration", systemImage: "square.and.arrow.up")201                }202                .accessibilityIdentifier("dictionary.export")203                Button {204                    isImporting = true205                } label: {206                    Label("Importer une configuration", systemImage: "square.and.arrow.down")207                }208                .accessibilityIdentifier("dictionary.import")209                if let transferMessage {210                    Text(transferMessage).font(.footnote).foregroundStyle(.secondary).accessibilityIdentifier("dictionary.transferMessage")211                }212            } header: {213                Text("Import et export")214            } footer: {215                Text("Le fichier JSON contient les réglages de frappe, vos mots et vos snippets. Il ne contient ni la clé Anthropic, ni les mots appris, ni les thèmes (exportés depuis Theme Studio). L'import remplace les réglages, les mots et les snippets actuels.")216            }217        }218        .navigationTitle("Dictionnaire et snippets")219        .navigationBarTitleDisplayMode(.inline)220        .sheet(item: $editedSnippet) { snippet in221            SnippetEditor(snippet: snippet) { model.upsertSnippet($0) }222        }223        .fileExporter(isPresented: $isExporting, document: JSONFile(data: exportData), contentType: .json, defaultFilename: "sp-keyboard-configuration") { result in224            if case .success = result { transferMessage = "Configuration exportée." }225        }226        .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json]) { result in227            guard case .success(let url) = result, let data = FileReading.data(at: url, limit: SettingsExport.maxImportBytes) else {228                transferMessage = "Fichier illisible ou trop volumineux."229                return230            }231            do {232                try model.importConfiguration(data)233                transferMessage = "Configuration importée."234            } catch {235                transferMessage = Self.describe(error)236            }237        }238        .confirmationDialog("Effacer les mots appris?", isPresented: $confirmEraseLearned, titleVisibility: .visible) {239            Button("Effacer", role: .destructive) { model.eraseLearnedWords() }240        }241    }242243    private func addWord() {244        let word = newWord.trimmingCharacters(in: .whitespacesAndNewlines)245        guard !word.isEmpty else { return }246        if model.addWord(word) {247            newWord = ""248            wordMessage = nil249        } else {250            wordMessage = "Mot refusé : déjà présent, trop long ou contenant un espace."251        }252    }253254    static func name(_ category: Snippet.Category) -> String {255        switch category {256        case .personal: "Raccourcis personnels"257        case .message: "Modèles de messages"258        case .developer: "Snippets de code"259        }260    }261262    static func describe(_ error: Error) -> String {263        switch error as? SettingsExport.ImportError {264        case .tooLarge: "Fichier trop volumineux (512 Ko au plus)."265        case .notRecognized: "Ce fichier n'est pas une configuration SP Keyboard."266        case .unsupportedVersion: "Version de configuration non prise en charge par cette app."267        case nil: "Import impossible."268        }269    }270}271272private struct SnippetEditor: View {273    @State var snippet: Snippet274    var onSave: (Snippet) -> Void275    @Environment(\.dismiss) private var dismiss276277    var body: some View {278        NavigationStack {279            Form {280                Section("Titre") {281                    TextField("Ex. : En route", text: $snippet.title)282                        .accessibilityIdentifier("snippet.title")283                }284                Section {285                    TextField("Texte inséré", text: $snippet.text, axis: .vertical)286                        .lineLimit(3...10)287                        .accessibilityIdentifier("snippet.text")288                } header: {289                    Text("Texte")290                } footer: {291                    Text("\(UserDictionary.maxSnippetLength) caractères au plus.")292                }293                Section {294                    TextField("Facultatif, ex. : omw", text: $snippet.trigger)295                        .textInputAutocapitalization(.never)296                        .autocorrectionDisabled()297                        .accessibilityIdentifier("snippet.trigger")298                } header: {299                    Text("Déclencheur")300                } footer: {301                    Text("Tapez le déclencheur : le texte apparaît dans les suggestions. Il n'est inséré que si vous le touchez.")302                }303                Section("Catégorie") {304                    Picker("Catégorie", selection: $snippet.category) {305                        ForEach(Snippet.Category.allCases, id: \.self) { Text(DictionaryView.name($0)).tag($0) }306                    }307                    .pickerStyle(.inline)308                    .labelsHidden()309                }310            }311            .navigationTitle("Snippet")312            .navigationBarTitleDisplayMode(.inline)313            .toolbar {314                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }315                ToolbarItem(placement: .confirmationAction) {316                    Button("Enregistrer") {317                        onSave(snippet)318                        dismiss()319                    }320                    .disabled(snippet.text.isEmpty)321                }322            }323        }324    }325}326
Files main
Menu

Theme