Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : App/KeyboardPreview.swift10// Description : The real keyboard (same views and controller as the11// extension) embedded in SwiftUI and typing into an12// in-memory document: live theme preview, test area and13// latency bench.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 UIKit93import AIEngine94import KeyboardCore95import ThemeEngine9697/// The text the preview keyboard edits, observable from SwiftUI.98@MainActor99@Observable100final class PreviewDocument {101 @ObservationIgnored let proxy = InMemoryTextProxy()102 private(set) var before = ""103 private(set) var after = ""104 private(set) var selection = ""105 /// Key-handling durations measured by the embedded keyboard, in milliseconds.106 private(set) var latency = LatencyWindow()107108 init(text: String = "") {109 proxy.reset(text)110 before = text111 proxy.onChange = { [weak self] in self?.sync() }112 }113114 var text: String { before + selection + after }115116 private func sync() {117 before = proxy.before118 after = proxy.after119 selection = proxy.selection120 }121122 func reset(_ text: String = "") {123 proxy.reset(text)124 latency.reset()125 }126127 func record(milliseconds: Double) { latency.record(milliseconds: milliseconds) }128 func resetLatency() { latency.reset() }129}130131@MainActor132final class PreviewHost: KeyboardHost {133 let document: PreviewDocument134 var traits = InputTraits()135 var onHeight: ((CGFloat) -> Void)?136137 init(document: PreviewDocument) { self.document = document }138139 var textProxy: TextDocumentProxying { document.proxy }140 var inputTraits: InputTraits { traits }141 var needsGlobeKey: Bool { false }142 var hasFullAccess: Bool { true }143 var documentIdentifier: String { "preview" }144 func advanceToNextInputMode() {}145 func keyboardHeightDidChange(_ height: CGFloat) { onHeight?(height) }146}147148/// Hosts the keyboard's root view and keeps it at the height the controller asks for.149final class KeyboardPreviewContainer: UIView {150 let host: PreviewHost151 let controller: KeyboardController152 private var height: CGFloat = 263153154 init(document: PreviewDocument, environment: KeyboardEnvironment) {155 host = PreviewHost(document: document)156 controller = KeyboardController(host: host, environment: environment)157 super.init(frame: .zero)158 addSubview(controller.rootView)159 layer.cornerRadius = 14160 layer.cornerCurve = .continuous161 clipsToBounds = true162 host.onHeight = { [weak self] value in163 self?.height = value164 self?.invalidateIntrinsicContentSize()165 }166 controller.onKeyHandled = { [weak document] in document?.record(milliseconds: $0) }167 }168169 @available(*, unavailable)170 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }171172 override var intrinsicContentSize: CGSize { CGSize(width: UIView.noIntrinsicMetric, height: height) }173174 override func layoutSubviews() {175 super.layoutSubviews()176 controller.rootView.frame = bounds177 controller.viewDidLayout(size: bounds.size, isLandscape: false)178 }179180 override func didMoveToWindow() {181 super.didMoveToWindow()182 if window != nil { controller.viewWillAppear() } else { controller.viewDidDisappear() }183 }184}185186struct KeyboardPreview: UIViewRepresentable {187 var theme: Theme188 var settings: KeyboardSettings189 var dictionary = UserDictionary()190 var aiSettings = AISettings()191 var traits = InputTraits()192 let document: PreviewDocument193 /// Panel or page to show when the view appears (screenshots, tests, theme studio).194 var initialPanel: KeyboardPanel?195 var initialPage: KeyboardPage?196197 func makeUIView(context: Context) -> KeyboardPreviewContainer {198 let container = KeyboardPreviewContainer(document: document, environment: .live())199 container.host.traits = traits200 container.controller.inject(settings: settings, dictionary: dictionary, theme: theme, aiSettings: aiSettings)201 #if DEBUG202 if let initialPage { container.controller.debugShow(page: initialPage) }203 if let initialPanel { container.controller.debugOpen(initialPanel) }204 #endif205 container.setContentHuggingPriority(.required, for: .vertical)206 return container207 }208209 func updateUIView(_ container: KeyboardPreviewContainer, context: Context) {210 if container.host.traits != traits {211 container.host.traits = traits212 container.controller.textDidChange()213 }214 if container.controller.theme != theme || container.controller.settings != settings215 || container.controller.dictionary != dictionary || container.controller.aiSettings != aiSettings {216 container.controller.inject(settings: settings, dictionary: dictionary, theme: theme, aiSettings: aiSettings)217 }218 }219220 func sizeThatFits(_ proposal: ProposedViewSize, uiView: KeyboardPreviewContainer, context: Context) -> CGSize? {221 CGSize(width: proposal.width ?? 390, height: uiView.intrinsicContentSize.height)222 }223}224225/// Read-only rendering of a preview document with its caret.226struct PreviewDocumentText: View {227 let document: PreviewDocument228 var placeholder = "Tapez avec le clavier ci-dessous…"229230 var body: some View {231 Group {232 if document.text.isEmpty {233 Text(placeholder).foregroundStyle(.secondary)234 } else {235 Text(document.before) + Text(document.selection).underline() + Text("▏").foregroundColor(.accentColor) + Text(document.after)236 }237 }238 .frame(maxWidth: .infinity, alignment: .topLeading)239 .accessibilityElement(children: .ignore)240 .accessibilityLabel("Zone de test")241 .accessibilityValue(document.text)242 .accessibilityIdentifier("preview.text")243 }244}245246/// The preview keyboard docked at the bottom of a screen, with a handle to fold it away when the content247/// above needs the room.248struct PreviewDock: View {249 var theme: Theme250 var settings: KeyboardSettings251 var dictionary: UserDictionary252 var aiSettings: AISettings253 let document: PreviewDocument254 @State private var isExpanded = true255256 var body: some View {257 VStack(spacing: 4) {258 Button {259 withAnimation(.easeInOut(duration: 0.2)) { isExpanded.toggle() }260 } label: {261 HStack(spacing: 6) {262 Image(systemName: isExpanded ? "chevron.down" : "chevron.up")263 Text(isExpanded ? "Masquer l'aperçu" : "Afficher l'aperçu du clavier")264 }265 .font(.footnote.weight(.semibold))266 .frame(maxWidth: .infinity, minHeight: 30)267 .contentShape(Rectangle())268 }269 .buttonStyle(.plain)270 .foregroundStyle(.secondary)271 .accessibilityIdentifier("preview.toggle")272 if isExpanded {273 KeyboardPreview(theme: theme, settings: settings, dictionary: dictionary, aiSettings: aiSettings, document: document)274 .padding(.horizontal, 6)275 .padding(.bottom, 4)276 }277 }278 .background(.bar)279 }280}281