Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr SMS Gateway9// File : ios/MacLustrSMS/UI/TemplateLibrary.swift10// Description : Galerie de modèles : catégories, recherche, favoris,11// récents, aperçu en bulle avec segments, bascule FR / EN,12// dupliquer, modifier, créer, réordonner, importer et13// exporter (JSON).14// Module : ios15// Repository : https://git.spboucher.ai/maclustr-sms16// Project Website : https://sms.spboucher.ai17// Created : 2026-11-3018// Last Modified : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: admin@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftData93import SwiftUI94import UniformTypeIdentifiers9596/// Ce que la galerie rend au composeur : le modèle choisi et la langue voulue.97struct TemplateChoice { let template: MessageTemplate; let english: Bool }9899struct TemplateLibrary: View {100 var onPick: ((TemplateChoice) -> Void)? = nil101 @Environment(\.modelContext) private var store102 @Environment(\.dismiss) private var dismiss103 @Query(sort: \MessageTemplate.order) private var templates: [MessageTemplate]104 @State private var search = ""105 @State private var category: String? = nil106 @State private var editing: MessageTemplate?107 @State private var creating = false108 @State private var importing = false109 @State private var exportURL: URL?110 @State private var notice: String?111 @State private var englishFor: Set<UUID> = []112113 private var filtered: [MessageTemplate] {114 let q = search.trimmingCharacters(in: .whitespaces).folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil)115 return templates.filter { t in116 (category == nil || t.category == category) &&117 (q.isEmpty || (t.name + " " + t.body + " " + t.category).folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil).contains(q))118 }119 }120 private var categories: [String] {121 let present = Set(templates.map(\.category))122 return TemplateCategory.order.filter(present.contains) + present.subtracting(TemplateCategory.order).sorted()123 }124 private var browsing: Bool { search.isEmpty && category == nil }125126 var body: some View {127 NavigationStack {128 ScrollView {129 LazyVStack(alignment: .leading, spacing: 14, pinnedViews: []) {130 categoryBar131 if let notice { Banner(text: notice, tone: .info, symbol: "checkmark.circle") }132 if filtered.isEmpty {133 ContentUnavailableView(search.isEmpty ? "Aucun modèle" : "Aucun résultat", systemImage: "rectangle.stack", description: Text(search.isEmpty ? "Créez votre premier modèle avec le bouton +." : "Essayez un autre mot ou une autre catégorie.")).padding(.top, 30)134 }135 if browsing {136 let favs = filtered.filter(\.favorite)137 if !favs.isEmpty { section("Favoris", "star.fill", favs, tag: "fav") }138 let recent = filtered.filter { $0.lastUsed != nil }.sorted { $0.lastUsed! > $1.lastUsed! }.prefix(4)139 if !recent.isEmpty { section("Récemment utilisés", "clock.arrow.circlepath", Array(recent), tag: "recent") }140 }141 ForEach(categories.filter { category == nil || $0 == category }, id: \.self) { c in142 let items = filtered.filter { $0.category == c }143 if !items.isEmpty { section(c, TemplateCategory.symbol(c), items, tag: c) }144 }145 }146 .padding(16).padding(.bottom, 20)147 }148 .background(Theme.bg)149 .navigationTitle("Modèles").navigationBarTitleDisplayMode(.inline)150 .searchable(text: $search, placement: .navigationBarDrawer(displayMode: .always), prompt: "Rechercher un modèle")151 .toolbar {152 ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } }153 ToolbarItemGroup(placement: .primaryAction) {154 Menu {155 Button { exportAll() } label: { Label("Exporter tous les modèles", systemImage: "square.and.arrow.up") }156 Button { importing = true } label: { Label("Importer un fichier", systemImage: "square.and.arrow.down") }157 } label: { Image(systemName: "ellipsis.circle") }.accessibilityLabel("Importer ou exporter")158 Button { creating = true } label: { Image(systemName: "plus") }.accessibilityLabel("Nouveau modèle").accessibilityIdentifier("newTemplateButton")159 }160 }161 .sheet(item: $editing) { t in TemplateEditor(template: t) }162 .sheet(isPresented: $creating) { TemplateEditor(template: nil) }163 .sheet(item: $exportURL) { url in ShareSheet(items: [url]) }164 .fileImporter(isPresented: $importing, allowedContentTypes: [.json]) { result in importFile(result) }165 }166 }167168 private var categoryBar: some View {169 ScrollView(.horizontal, showsIndicators: false) {170 HStack(spacing: 8) {171 chip("Tous", "square.grid.2x2", selected: category == nil) { category = nil }172 ForEach(categories, id: \.self) { c in chip(c, TemplateCategory.symbol(c), selected: category == c) { category = category == c ? nil : c } }173 }174 }175 }176 private func chip(_ title: String, _ symbol: String, selected: Bool, action: @escaping () -> Void) -> some View {177 Button(action: action) {178 Label(title, systemImage: symbol).font(.subheadline.weight(.medium)).foregroundStyle(selected ? Theme.onAccent : Theme.text)179 .padding(.horizontal, 12).padding(.vertical, 7)180 .background(selected ? Theme.accent : Theme.panel, in: Capsule())181 .overlay(Capsule().strokeBorder(selected ? Color.clear : Theme.line, lineWidth: 1))182 }.accessibilityIdentifier("category-\(title)").accessibilityAddTraits(selected ? .isSelected : [])183 }184 private func section(_ title: String, _ symbol: String, _ items: [MessageTemplate], tag: String) -> some View {185 VStack(alignment: .leading, spacing: 10) {186 HStack(spacing: 6) { Image(systemName: symbol).font(.caption).foregroundStyle(Theme.muted); SectionLabel(title); Text("\(items.count)").font(.caption.monospacedDigit()).foregroundStyle(Theme.faint) }.padding(.top, 4)187 ForEach(items) { t in card(t, tag: tag) }188 }189 }190191 private func card(_ t: MessageTemplate, tag: String) -> some View {192 let english = englishFor.contains(t.id) && t.hasEnglish193 let body = t.text(english: english)194 let preview = StarterTemplates.preview(body)195 let info = Segments.info(preview)196 return VStack(alignment: .leading, spacing: 10) {197 HStack(alignment: .firstTextBaseline, spacing: 8) {198 Image(systemName: t.symbol).foregroundStyle(Theme.accent).frame(width: 22)199 Text(t.name).font(.headline).foregroundStyle(Theme.text).lineLimit(1)200 Spacer(minLength: 4)201 if t.hasEnglish {202 Button { if english { englishFor.remove(t.id) } else { englishFor.insert(t.id) } } label: {203 Text(english ? "EN" : "FR").font(.caption.weight(.bold).monospaced()).foregroundStyle(Theme.text).padding(.horizontal, 7).padding(.vertical, 3)204 .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Theme.line, lineWidth: 1))205 }.buttonStyle(.plain).accessibilityLabel(english ? "Version anglaise, passer au français" : "Version française, passer à l'anglais").accessibilityIdentifier("lang-\(t.starterKey ?? t.name)")206 }207 Button { t.favorite.toggle() } label: { Image(systemName: t.favorite ? "star.fill" : "star").foregroundStyle(t.favorite ? Theme.warn : Theme.faint) }208 .buttonStyle(.plain).accessibilityLabel(t.favorite ? "Retirer des favoris" : "Ajouter aux favoris").accessibilityIdentifier("fav-\(t.starterKey ?? t.name)")209 }210 Bubble(text: preview, outgoing: false).padding(.trailing, -44)211 HStack(spacing: 8) {212 SegmentPill(info: info)213 let vars = TemplateEngine.variables(in: body)214 if !vars.isEmpty { Text("\(vars.count) variable\(vars.count > 1 ? "s" : "")").font(.caption).foregroundStyle(Theme.faint) }215 Spacer()216 if onPick != nil { Text("Utiliser").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.accent) }217 }218 }219 .padding(14)220 .background(Theme.panel, in: RoundedRectangle(cornerRadius: 14, style: .continuous))221 .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))222 .contentShape(RoundedRectangle(cornerRadius: 14))223 .onTapGesture { if let onPick { onPick(TemplateChoice(template: t, english: english)) } else { editing = t } }224 .accessibilityElement(children: .contain)225 .accessibilityIdentifier("template-\(tag)-\(t.starterKey ?? t.name)")226 .contextMenu {227 Button { editing = t } label: { Label("Modifier", systemImage: "pencil") }228 Button { duplicate(t) } label: { Label("Dupliquer", systemImage: "plus.square.on.square") }229 Button { move(t, by: -1) } label: { Label("Monter", systemImage: "arrow.up") }230 Button { move(t, by: 1) } label: { Label("Descendre", systemImage: "arrow.down") }231 Button(role: .destructive) { store.delete(t) } label: { Label("Supprimer", systemImage: "trash") }232 }233 }234235 // MARK: Actions236 private func duplicate(_ t: MessageTemplate) {237 let c = MessageTemplate(name: t.name + " (copie)", body: t.body, symbol: t.symbol, order: (templates.map(\.order).max() ?? 0) + 1, category: TemplateCategory.mine, bodyEN: t.bodyEN)238 store.insert(c); editing = c239 }240 /// Réordonne à l'intérieur de la catégorie du modèle.241 private func move(_ t: MessageTemplate, by delta: Int) {242 var peers = templates.filter { $0.category == t.category }243 guard let i = peers.firstIndex(where: { $0.id == t.id }), peers.indices.contains(i + delta) else { return }244 peers.swapAt(i, i + delta)245 let base = peers.map(\.order).min() ?? 0246 for (n, p) in peers.enumerated() { p.order = base + n }247 }248 private func exportAll() {249 do {250 let url = FileManager.default.temporaryDirectory.appendingPathComponent("MacLustr-SMS-modeles.json")251 try TemplateArchive.export(templates).write(to: url, options: .atomic)252 exportURL = url253 } catch { notice = "L'export a échoué." }254 }255 private func importFile(_ result: Result<URL, Error>) {256 guard case .success(let url) = result else { return }257 let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }258 do {259 let r = try TemplateArchive.importInto(store, data: Data(contentsOf: url))260 notice = "\(r.added) modèle\(r.added > 1 ? "s" : "") importé\(r.added > 1 ? "s" : "")\(r.skipped > 0 ? ", \(r.skipped) déjà présent\(r.skipped > 1 ? "s" : "")" : "")."261 } catch { notice = "Ce fichier n'est pas une sauvegarde de modèles MacLustr SMS." }262 }263}264extension URL: @retroactive Identifiable { public var id: String { absoluteString } }265266struct ShareSheet: UIViewControllerRepresentable {267 let items: [Any]268 func makeUIViewController(context: Context) -> UIActivityViewController { UIActivityViewController(activityItems: items, applicationActivities: nil) }269 func updateUIViewController(_ vc: UIActivityViewController, context: Context) {}270}271272/// « 1 segment · GSM » : la taille réelle du modèle une fois rempli avec des valeurs typiques.273struct SegmentPill: View {274 let info: SegmentInfo275 var body: some View {276 let tone: Color = info.segments > 1 ? Theme.warn : info.encoding == .ucs2 ? Theme.info : Theme.ok277 HStack(spacing: 5) {278 Circle().fill(tone).frame(width: 6, height: 6)279 Text("\(info.segments) segment\(info.segments > 1 ? "s" : "") · \(info.encoding == .gsm7 ? "GSM" : "Unicode") · \(info.units)/\(info.segments * info.perSegment)").font(.caption.monospacedDigit()).foregroundStyle(Theme.muted)280 }281 .padding(.horizontal, 8).padding(.vertical, 4).background(Theme.panel2, in: Capsule())282 .accessibilityElement(children: .combine)283 }284}285286struct TemplateEditor: View {287 let template: MessageTemplate?288 @Environment(\.modelContext) private var store289 @Environment(\.dismiss) private var dismiss290 @Query private var all: [MessageTemplate]291 @State private var name = ""292 @State private var text = ""293 @State private var textEN = ""294 @State private var category = TemplateCategory.mine295 @State private var english = false296 @State private var suggestion: WritingSuggestion?297298 private var current: Binding<String> { english ? $textEN : $text }299 private static let commonVariables = ["prénom", "date", "heure", "adresse", "montant", "lien", "marque", "signature", "code", "aujourd'hui", "demain"]300301 var body: some View {302 NavigationStack {303 Screen {304 Card { TextField("Nom du modèle", text: $name).font(.headline).foregroundStyle(Theme.text).accessibilityIdentifier("templateNameField") }305 Card {306 VStack(alignment: .leading, spacing: 10) {307 HStack {308 SectionLabel(english ? "Texte anglais" : "Texte")309 Spacer()310 Picker("Langue", selection: $english) { Text("FR").tag(false); Text("EN").tag(true) }.pickerStyle(.segmented).frame(width: 110)311 }312 TextField(english ? "Hi {{prénom}}, …" : "Bonjour {{prénom}}, …", text: current, axis: .vertical).lineLimit(5...12).foregroundStyle(Theme.text).accessibilityIdentifier("templateBodyField")313 // Puces : toucher une variable l'ajoute à la fin du texte.314 ScrollView(.horizontal, showsIndicators: false) {315 HStack(spacing: 6) {316 ForEach(Self.commonVariables, id: \.self) { v in317 Button { current.wrappedValue += (current.wrappedValue.isEmpty || current.wrappedValue.hasSuffix(" ") ? "" : " ") + "{{\(v)}}" } label: {318 Label(v, systemImage: VariableKind.of(v).symbol).font(.caption.weight(.medium)).foregroundStyle(Theme.text).padding(.horizontal, 9).padding(.vertical, 5).background(Theme.panel2, in: Capsule())319 }.buttonStyle(.plain).accessibilityIdentifier("chip-\(v)")320 }321 }322 }323 let preview = StarterTemplates.preview(current.wrappedValue), info = Segments.info(preview)324 SegmentGauge(info: info)325 Text("Avec des valeurs typiques : \(info.segments) segment\(info.segments > 1 ? "s" : "") · \(info.encoding == .gsm7 ? "GSM 7 bits" : "Unicode") · \(info.units) sur \(info.segments * info.perSegment)").font(.caption.monospacedDigit()).foregroundStyle(info.segments > 1 || info.encoding == .ucs2 ? Theme.warn : Theme.muted)326 }327 }328 if !current.wrappedValue.isEmpty {329 SectionLabel("Aperçu")330 Bubble(text: StarterTemplates.preview(current.wrappedValue), outgoing: false)331 WritingToolsBar(text: current.wrappedValue) { suggestion = $0 }332 }333 Card {334 Picker("Catégorie", selection: $category) { ForEach(TemplateCategory.order, id: \.self) { Text($0).tag($0) } }.tint(Theme.text)335 }336 Text("Une variable s'écrit entre doubles accolades. Son type se déduit de son nom : « heure » ouvre un sélecteur d'heure, « date » un calendrier, « montant » un clavier numérique. « marque » et « signature » se règlent une fois dans Réglages. « aujourd'hui » et « demain » se remplissent seuls.").font(.footnote).foregroundStyle(Theme.faint)337 }338 .navigationTitle(template == nil ? "Nouveau modèle" : "Modifier").navigationBarTitleDisplayMode(.inline)339 .toolbar {340 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }341 ToolbarItem(placement: .confirmationAction) {342 Button("Enregistrer") {343 if let template { template.name = name; template.body = text; template.bodyEN = textEN; template.category = category }344 else { store.insert(MessageTemplate(name: name, body: text, order: (all.map(\.order).max() ?? -1) + 1, category: category, bodyEN: textEN)) }345 dismiss()346 }.disabled(name.trimmingCharacters(in: .whitespaces).isEmpty || text.trimmingCharacters(in: .whitespaces).isEmpty).accessibilityIdentifier("saveTemplateButton")347 }348 }349 .sheet(item: $suggestion) { s in SuggestionSheet(suggestion: s) { current.wrappedValue = $0 } }350 .onAppear { name = template?.name ?? ""; text = template?.body ?? ""; textEN = template?.bodyEN ?? ""; category = template?.category ?? TemplateCategory.mine }351 }352 }353}354355/// Deux outils locaux, sans IA ni réseau : compatibilité GSM et raccourcissement en un segment.356struct WritingToolsBar: View {357 let text: String358 let onSuggestion: (WritingSuggestion) -> Void359 var body: some View {360 let info = Segments.info(StarterTemplates.preview(text))361 if info.encoding == .ucs2 || info.segments > 1 {362 HStack(spacing: 8) {363 if info.encoding == .ucs2 { Button { onSuggestion(WritingTools.gsmCompatible(text)) } label: { Label("Rendre compatible GSM", systemImage: "character.cursor.ibeam") }.buttonStyle(QuietButtonStyle(tone: Theme.accent)).accessibilityIdentifier("toolGSM") }364 if info.segments > 1 { Button { onSuggestion(WritingTools.shortenToOneSegment(text)) } label: { Label("Raccourcir", systemImage: "arrow.down.right.and.arrow.up.left") }.buttonStyle(QuietButtonStyle(tone: Theme.accent)).accessibilityIdentifier("toolShorten") }365 }366 }367 }368}369extension WritingSuggestion: Identifiable { var id: String { text } }370371struct SuggestionSheet: View {372 let suggestion: WritingSuggestion373 let apply: (String) -> Void374 @Environment(\.dismiss) private var dismiss375 var body: some View {376 NavigationStack {377 Screen {378 HStack(spacing: 10) {379 VStack(alignment: .leading, spacing: 4) { SectionLabel("Avant"); SegmentPill(info: suggestion.before) }380 Image(systemName: "arrow.right").foregroundStyle(Theme.faint)381 VStack(alignment: .leading, spacing: 4) { SectionLabel("Après"); SegmentPill(info: suggestion.after) }382 }383 Bubble(text: suggestion.text, outgoing: false)384 if suggestion.steps.isEmpty { Text("Rien à changer : aucune modification sûre ne raccourcit ce texte.").font(.footnote).foregroundStyle(Theme.muted) }385 else { Card { VStack(alignment: .leading, spacing: 6) { ForEach(suggestion.steps, id: \.self) { s in Label(s, systemImage: "checkmark").font(.footnote).foregroundStyle(Theme.muted) } } } }386 if suggestion.after.segments > 1 { Text("Le texte tient encore sur \(suggestion.after.segments) segments : pour aller plus loin, il faut le réécrire.").font(.footnote).foregroundStyle(Theme.warn) }387 Text("Ces changements sont calculés sur l'appareil par des règles fixes. Aucun texte n'est envoyé où que ce soit.").font(.caption).foregroundStyle(Theme.faint)388 Button("Appliquer") { apply(suggestion.text); dismiss() }.buttonStyle(PrimaryButtonStyle()).disabled(suggestion.steps.isEmpty).accessibilityIdentifier("applySuggestion")389 }390 .navigationTitle("Suggestion").navigationBarTitleDisplayMode(.inline)391 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Garder mon texte") { dismiss() } } }392 }393 .presentationDetents([.medium, .large])394 }395}396