Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : KeyboardUI/PanelViews.swift10// Description : Panels that take the place of the keys: emoji (categories,11// explicit favourites, local search), snippets and message12// templates, and the inline field strip used whenever the13// keyboard types into its own buffer (emoji search, SP AI14// prompt and result editing).15// Module : KeyboardUI16// Repository : https://git.spboucher.ai/sp-keyboard17// Created : 2026-12-0118// 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: support@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 UIKit93import KeyboardCore94import ThemeEngine9596extension UIButton {97 /// Pill button in the theme's function-key style.98 static func pill(title: String? = nil, symbol: String? = nil, theme: Theme, accent: Bool = false) -> UIButton {99 let button = UIButton(type: .system)100 button.restyle(theme: theme, accent: accent)101 if let title { button.setTitle(title, for: .normal) }102 if let symbol {103 button.setImage(UIImage(systemName: symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)), for: .normal)104 }105 button.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)106 button.titleLabel?.adjustsFontSizeToFitWidth = true107 button.titleLabel?.minimumScaleFactor = 0.7108 button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)109 return button110 }111112 func restyle(theme: Theme, accent: Bool = false) {113 let style = accent ? theme.accentKey : theme.functionKey114 var fill = style.fill.average115 if !accent { fill = fill.composited(over: theme.background.average) }116 backgroundColor = fill.opacity(1).uiColor117 setTitleColor(style.text.uiColor, for: .normal)118 setTitleColor(style.text.opacity(0.35).uiColor, for: .disabled)119 tintColor = style.text.uiColor120 layer.cornerRadius = min(CGFloat(theme.metrics.cornerRadius), 12)121 layer.cornerCurve = .continuous122 layer.borderWidth = CGFloat(theme.metrics.borderWidth)123 layer.borderColor = style.border.cgColor124 }125}126127// MARK: - Emoji128129@MainActor130protocol EmojiPanelDelegate: AnyObject {131 func emojiPanel(_ panel: EmojiPanelView, didPick emoji: String)132 func emojiPanel(_ panel: EmojiPanelView, didToggleFavorite emoji: String)133 func emojiPanelDidTapBackspace(_ panel: EmojiPanelView)134 func emojiPanelDidTapSearch(_ panel: EmojiPanelView)135 func emojiPanelDidClose(_ panel: EmojiPanelView)136}137138final class EmojiPanelView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {139 weak var delegate: EmojiPanelDelegate?140 private let tabs = UIStackView()141 private let collection: UICollectionView142 private let closeButton = UIButton(type: .system)143 private let searchButton = UIButton(type: .system)144 private let deleteButton = UIButton(type: .system)145 private let hint = UILabel()146 private var theme: Theme = BuiltInThemes.default147 private var favorites: [String] = []148 private var selectedTab = 0149 private var items: [String] = []150151 override init(frame: CGRect) {152 let flow = UICollectionViewFlowLayout()153 flow.minimumInteritemSpacing = 0154 flow.minimumLineSpacing = 2155 collection = UICollectionView(frame: .zero, collectionViewLayout: flow)156 super.init(frame: frame)157 collection.backgroundColor = .clear158 collection.dataSource = self159 collection.delegate = self160 collection.register(EmojiCell.self, forCellWithReuseIdentifier: "emoji")161 collection.delaysContentTouches = false162 addSubview(collection)163 let press = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))164 press.minimumPressDuration = 0.45165 collection.addGestureRecognizer(press)166 tabs.axis = .horizontal167 tabs.distribution = .fillEqually168 addSubview(tabs)169 for (button, action) in [(closeButton, #selector(tapClose)), (searchButton, #selector(tapSearch)), (deleteButton, #selector(tapDelete))] {170 button.addTarget(self, action: action, for: .touchUpInside)171 addSubview(button)172 }173 closeButton.setTitle("ABC", for: .normal)174 closeButton.accessibilityLabel = "Retour aux lettres"175 searchButton.setTitle(" Rechercher", for: .normal)176 searchButton.setImage(UIImage(systemName: "magnifyingglass"), for: .normal)177 deleteButton.setImage(UIImage(systemName: "delete.left"), for: .normal)178 deleteButton.accessibilityLabel = "Effacer"179 hint.text = "Appui long sur un emoji pour l'ajouter aux favoris ou l'en retirer."180 hint.font = .systemFont(ofSize: 12)181 hint.textAlignment = .center182 hint.numberOfLines = 2183 hint.isHidden = true184 addSubview(hint)185 rebuildTabs()186 select(tab: 0)187 }188189 @available(*, unavailable)190 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }191192 func apply(theme: Theme) {193 self.theme = theme194 [closeButton, searchButton, deleteButton].forEach { $0.restyle(theme: theme) }195 closeButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)196 searchButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)197 hint.textColor = theme.suggestionText.opacity(0.7).uiColor198 refreshTabs()199 }200201 func setFavorites(_ favorites: [String]) {202 self.favorites = favorites203 if selectedTab == 0 { select(tab: 0) }204 }205206 private func rebuildTabs() {207 tabs.arrangedSubviews.forEach { $0.removeFromSuperview() }208 let icons = ["★"] + EmojiCatalog.categories.map(\.icon)209 let names = ["Favoris"] + EmojiCatalog.categories.map(\.title)210 for (index, icon) in icons.enumerated() {211 let button = UIButton(type: .system)212 button.setTitle(icon, for: .normal)213 button.titleLabel?.font = .systemFont(ofSize: 17)214 button.tag = index215 button.accessibilityLabel = names[index]216 button.layer.cornerRadius = 8217 button.addTarget(self, action: #selector(tapTab(_:)), for: .touchUpInside)218 tabs.addArrangedSubview(button)219 }220 }221222 private func refreshTabs() {223 for case let button as UIButton in tabs.arrangedSubviews {224 button.backgroundColor = button.tag == selectedTab ? theme.suggestionText.opacity(0.18).uiColor : .clear225 button.setTitleColor(theme.suggestionText.uiColor, for: .normal)226 }227 }228229 private func select(tab: Int) {230 selectedTab = tab231 items = tab == 0 ? favorites : EmojiCatalog.categories[tab - 1].emoji232 hint.isHidden = !(tab == 0 && items.isEmpty)233 collection.reloadData()234 collection.setContentOffset(.zero, animated: false)235 refreshTabs()236 }237238 @objc private func tapTab(_ sender: UIButton) { select(tab: sender.tag) }239 @objc private func tapClose() { delegate?.emojiPanelDidClose(self) }240 @objc private func tapSearch() { delegate?.emojiPanelDidTapSearch(self) }241 @objc private func tapDelete() { delegate?.emojiPanelDidTapBackspace(self) }242243 @objc private func longPress(_ gesture: UILongPressGestureRecognizer) {244 guard gesture.state == .began, let path = collection.indexPathForItem(at: gesture.location(in: collection)), items.indices.contains(path.item) else { return }245 delegate?.emojiPanel(self, didToggleFavorite: items[path.item])246 }247248 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { items.count }249250 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {251 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "emoji", for: indexPath)252 (cell as? EmojiCell)?.label.text = items[indexPath.item]253 cell.accessibilityLabel = items[indexPath.item]254 return cell255 }256257 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {258 let columns = max(6, floor(collectionView.bounds.width / 42))259 let side = floor(collectionView.bounds.width / columns)260 return CGSize(width: side, height: min(side, 40))261 }262263 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {264 guard items.indices.contains(indexPath.item) else { return }265 delegate?.emojiPanel(self, didPick: items[indexPath.item])266 }267268 override func layoutSubviews() {269 super.layoutSubviews()270 let bottom: CGFloat = min(46, bounds.height * 0.22)271 let tabHeight: CGFloat = 32272 tabs.frame = CGRect(x: 4, y: 2, width: bounds.width - 8, height: tabHeight)273 collection.frame = CGRect(x: 4, y: tabHeight + 4, width: bounds.width - 8, height: bounds.height - tabHeight - bottom - 8)274 hint.frame = collection.frame.insetBy(dx: 16, dy: 8)275 let y = bounds.height - bottom + 2, height = bottom - 6276 closeButton.frame = CGRect(x: 4, y: y, width: 64, height: height)277 deleteButton.frame = CGRect(x: bounds.width - 68, y: y, width: 64, height: height)278 searchButton.frame = CGRect(x: closeButton.frame.maxX + 6, y: y, width: deleteButton.frame.minX - closeButton.frame.maxX - 12, height: height)279 collection.collectionViewLayout.invalidateLayout()280 }281}282283final class EmojiCell: UICollectionViewCell {284 let label = UILabel()285286 override init(frame: CGRect) {287 super.init(frame: frame)288 label.font = .systemFont(ofSize: 28)289 label.textAlignment = .center290 contentView.addSubview(label)291 isAccessibilityElement = true292 accessibilityTraits = .keyboardKey293 }294295 @available(*, unavailable)296 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }297298 override func layoutSubviews() {299 super.layoutSubviews()300 label.frame = contentView.bounds301 }302303 override var isHighlighted: Bool {304 didSet { contentView.alpha = isHighlighted ? 0.4 : 1 }305 }306}307308// MARK: - Snippets309310@MainActor311protocol SnippetPanelDelegate: AnyObject {312 func snippetPanel(_ panel: SnippetPanelView, didPick snippet: Snippet)313 func snippetPanelDidClose(_ panel: SnippetPanelView)314}315316final class SnippetPanelView: UIView, UITableViewDataSource, UITableViewDelegate {317 weak var delegate: SnippetPanelDelegate?318 private let segments = UISegmentedControl(items: ["Messages", "Personnels", "Code"])319 private let table = UITableView(frame: .zero, style: .plain)320 private let closeButton = UIButton(type: .system)321 private let empty = UILabel()322 private var theme: Theme = BuiltInThemes.default323 private var snippets: [Snippet] = []324 private var visible: [Snippet] = []325 private let order: [Snippet.Category] = [.message, .personal, .developer]326327 override init(frame: CGRect) {328 super.init(frame: frame)329 segments.selectedSegmentIndex = 0330 segments.addTarget(self, action: #selector(changed), for: .valueChanged)331 addSubview(segments)332 table.backgroundColor = .clear333 table.dataSource = self334 table.delegate = self335 table.rowHeight = 46336 table.separatorInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)337 table.register(UITableViewCell.self, forCellReuseIdentifier: "snippet")338 addSubview(table)339 closeButton.setTitle("ABC", for: .normal)340 closeButton.accessibilityLabel = "Retour aux lettres"341 closeButton.addTarget(self, action: #selector(tapClose), for: .touchUpInside)342 addSubview(closeButton)343 empty.text = "Aucun élément ici. Ajoutez-en dans l'app SP Keyboard."344 empty.font = .systemFont(ofSize: 13)345 empty.textAlignment = .center346 empty.numberOfLines = 2347 addSubview(empty)348 }349350 @available(*, unavailable)351 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }352353 func apply(theme: Theme) {354 self.theme = theme355 closeButton.restyle(theme: theme)356 empty.textColor = theme.suggestionText.opacity(0.7).uiColor357 segments.overrideUserInterfaceStyle = theme.isDark ? .dark : .light358 table.separatorColor = theme.suggestionText.opacity(0.18).uiColor359 table.reloadData()360 }361362 func setSnippets(_ snippets: [Snippet]) {363 self.snippets = snippets364 changed()365 }366367 @objc private func changed() {368 let category = order[max(0, segments.selectedSegmentIndex)]369 visible = snippets.filter { $0.category == category }370 empty.isHidden = !visible.isEmpty371 table.reloadData()372 }373374 @objc private func tapClose() { delegate?.snippetPanelDidClose(self) }375376 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { visible.count }377378 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {379 let cell = tableView.dequeueReusableCell(withIdentifier: "snippet", for: indexPath)380 let snippet = visible[indexPath.row]381 var content = UIListContentConfiguration.subtitleCell()382 content.text = snippet.title.isEmpty ? snippet.text : snippet.title383 content.secondaryText = snippet.text.replacingOccurrences(of: "\n", with: " ⏎ ")384 content.textProperties.color = theme.suggestionText.uiColor385 content.textProperties.font = .systemFont(ofSize: 15, weight: .semibold)386 content.secondaryTextProperties.color = theme.suggestionText.opacity(0.7).uiColor387 content.secondaryTextProperties.numberOfLines = 1388 content.secondaryTextProperties.font = .systemFont(ofSize: 12)389 cell.contentConfiguration = content390 cell.backgroundColor = .clear391 let selected = UIView()392 selected.backgroundColor = theme.pressedTint.uiColor393 cell.selectedBackgroundView = selected394 return cell395 }396397 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {398 tableView.deselectRow(at: indexPath, animated: false)399 delegate?.snippetPanel(self, didPick: visible[indexPath.row])400 }401402 override func layoutSubviews() {403 super.layoutSubviews()404 closeButton.frame = CGRect(x: 6, y: 5, width: 60, height: 32)405 segments.frame = CGRect(x: closeButton.frame.maxX + 8, y: 5, width: bounds.width - closeButton.frame.maxX - 14, height: 32)406 table.frame = CGRect(x: 0, y: 42, width: bounds.width, height: bounds.height - 42)407 empty.frame = table.frame.insetBy(dx: 20, dy: 10)408 }409}410411// MARK: - Inline field strip412413@MainActor414protocol FieldStripDelegate: AnyObject {415 func fieldStripDidTapDone(_ strip: FieldStripView)416 func fieldStripDidTapCancel(_ strip: FieldStripView)417 func fieldStrip(_ strip: FieldStripView, didPickResult text: String)418}419420/// A read-only rendering of the keyboard's own edit buffer, with a caret, a title, Done / Cancel, and an421/// optional row of tappable results (emoji search).422final class FieldStripView: UIView {423 weak var delegate: FieldStripDelegate?424 private let titleLabel = UILabel()425 private let textView = UITextView()426 private let doneButton = UIButton(type: .system)427 private let cancelButton = UIButton(type: .system)428 private let resultsScroll = UIScrollView()429 private let resultsStack = UIStackView()430 private var theme: Theme = BuiltInThemes.default431 private var showsResults = false432 private var placeholder = ""433434 static func height(showsResults: Bool, multiline: Bool) -> CGFloat {435 showsResults ? 92 : (multiline ? 104 : 60)436 }437438 override init(frame: CGRect) {439 super.init(frame: frame)440 titleLabel.font = .systemFont(ofSize: 11, weight: .semibold)441 addSubview(titleLabel)442 textView.isEditable = false443 textView.isSelectable = false444 textView.backgroundColor = .clear445 textView.font = .systemFont(ofSize: 15)446 textView.textContainerInset = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6)447 textView.layer.cornerRadius = 9448 textView.layer.borderWidth = 1449 addSubview(textView)450 doneButton.setTitle("OK", for: .normal)451 doneButton.accessibilityIdentifier = "strip.done"452 doneButton.addTarget(self, action: #selector(tapDone), for: .touchUpInside)453 addSubview(doneButton)454 cancelButton.setImage(UIImage(systemName: "xmark"), for: .normal)455 cancelButton.accessibilityLabel = "Annuler"456 cancelButton.addTarget(self, action: #selector(tapCancel), for: .touchUpInside)457 addSubview(cancelButton)458 resultsStack.axis = .horizontal459 resultsStack.spacing = 2460 resultsScroll.showsHorizontalScrollIndicator = false461 resultsScroll.addSubview(resultsStack)462 addSubview(resultsScroll)463 }464465 @available(*, unavailable)466 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }467468 func apply(theme: Theme) {469 self.theme = theme470 titleLabel.textColor = theme.suggestionText.opacity(0.75).uiColor471 textView.layer.borderColor = theme.suggestionText.opacity(0.35).cgColor472 doneButton.restyle(theme: theme, accent: true)473 cancelButton.restyle(theme: theme)474 }475476 func configure(title: String, placeholder: String, showsResults: Bool) {477 titleLabel.text = title.uppercased()478 self.placeholder = placeholder479 self.showsResults = showsResults480 resultsScroll.isHidden = !showsResults481 setNeedsLayout()482 }483484 /// Renders the buffer with a caret between `before` and `after`.485 func setText(before: String, after: String) {486 let color = theme.suggestionText.uiColor487 let font = UIFont.systemFont(ofSize: 15)488 if before.isEmpty, after.isEmpty {489 let text = NSMutableAttributedString(string: "▏", attributes: [.foregroundColor: theme.accentKey.fill.average.opacity(1).uiColor, .font: font])490 text.append(NSAttributedString(string: placeholder, attributes: [.foregroundColor: theme.suggestionText.opacity(0.45).uiColor, .font: font]))491 textView.attributedText = text492 return493 }494 let text = NSMutableAttributedString(string: before, attributes: [.foregroundColor: color, .font: font])495 text.append(NSAttributedString(string: "▏", attributes: [.foregroundColor: theme.accentKey.fill.average.opacity(1).uiColor, .font: font]))496 text.append(NSAttributedString(string: after, attributes: [.foregroundColor: color, .font: font]))497 textView.attributedText = text498 textView.accessibilityValue = before + after499 let caret = NSRange(location: (before as NSString).length, length: 1)500 textView.scrollRangeToVisible(caret)501 }502503 func setResults(_ results: [String]) {504 resultsStack.arrangedSubviews.forEach { $0.removeFromSuperview() }505 for result in results {506 let button = UIButton(type: .system)507 button.setTitle(result, for: .normal)508 button.titleLabel?.font = .systemFont(ofSize: 26)509 button.widthAnchor.constraint(equalToConstant: 40).isActive = true510 button.addAction(UIAction { [weak self] _ in511 guard let self else { return }512 self.delegate?.fieldStrip(self, didPickResult: result)513 }, for: .touchUpInside)514 resultsStack.addArrangedSubview(button)515 }516 setNeedsLayout()517 }518519 @objc private func tapDone() { delegate?.fieldStripDidTapDone(self) }520 @objc private func tapCancel() { delegate?.fieldStripDidTapCancel(self) }521522 override func layoutSubviews() {523 super.layoutSubviews()524 let resultsHeight: CGFloat = showsResults ? 38 : 0525 titleLabel.frame = CGRect(x: 10, y: 3, width: bounds.width - 20, height: 13)526 let fieldTop: CGFloat = 18527 let fieldHeight = bounds.height - fieldTop - resultsHeight - 5528 cancelButton.frame = CGRect(x: 6, y: fieldTop, width: 36, height: min(fieldHeight, 36))529 doneButton.frame = CGRect(x: bounds.width - 58, y: fieldTop, width: 52, height: min(fieldHeight, 36))530 textView.frame = CGRect(x: cancelButton.frame.maxX + 6, y: fieldTop, width: doneButton.frame.minX - cancelButton.frame.maxX - 12, height: fieldHeight)531 resultsScroll.frame = CGRect(x: 6, y: bounds.height - resultsHeight - 2, width: bounds.width - 12, height: resultsHeight)532 let width = CGFloat(resultsStack.arrangedSubviews.count) * 42533 resultsStack.frame = CGRect(x: 0, y: 0, width: width, height: resultsHeight)534 resultsScroll.contentSize = resultsStack.frame.size535 }536}537