SPB Git

Repository Public

SuggestionBarView.swift 15.6 KB 377 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : KeyboardUI/SuggestionBarView.swift10// Description      : The strip above the keys: the multicolour ✦ SP AI button,11//                    up to three suggestions (the pending autocorrection is12//                    marked), and a tools tray (emoji, snippets, developer,13//                    finance, one hand, language). Also the haptic and click14//                    feedback helper.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 AudioToolbox94import KeyboardCore95import PredictionCore96import ThemeEngine9798enum BarTool: String, CaseIterable {99    case emoji, snippets, developer, finance, oneHanded, language, clipboard100101    var symbol: String {102        switch self {103        case .emoji: "face.smiling"104        case .snippets: "text.badge.plus"105        case .developer: "curlybraces"106        case .finance: "dollarsign.circle"107        case .oneHanded: "hand.point.up.left"108        case .language: "globe.americas"109        case .clipboard: "doc.on.clipboard"110        }111    }112113    var label: String {114        switch self {115        case .emoji: "Emoji"116        case .snippets: "Raccourcis et modèles"117        case .developer: "Clavier développeur"118        case .finance: "Clavier finance"119        case .oneHanded: "Mode une main"120        case .language: "Langue"121        case .clipboard: "Coller le presse-papiers"122        }123    }124}125126@MainActor127protocol SuggestionBarDelegate: AnyObject {128    func suggestionBar(_ bar: SuggestionBarView, didPick suggestion: Suggestion)129    func suggestionBarDidTapAI(_ bar: SuggestionBarView)130    func suggestionBar(_ bar: SuggestionBarView, didPick tool: BarTool)131}132133final class SuggestionBarView: UIView {134    weak var delegate: SuggestionBarDelegate?135    static let height: CGFloat = 44136137    private let aiButton = AIGlyphButton()138    private let toolsButton = UIButton(type: .system)139    private let suggestionStack = UIStackView()140    private let toolStack = UIStackView()141    private var suggestionButtons: [UIButton] = []142    private var separators: [UIView] = []143    private var suggestions: [Suggestion] = []144    private var autocorrection: Suggestion?145    private var theme: Theme = BuiltInThemes.default146    private(set) var showsTools = false147    var availableTools: [BarTool] = BarTool.allCases { didSet { rebuildTools() } }148149    override init(frame: CGRect) {150        super.init(frame: frame)151        aiButton.addTarget(self, action: #selector(tapAI), for: .touchUpInside)152        aiButton.accessibilityLabel = "SP AI"153        aiButton.accessibilityHint = "Ouvre le panneau de transformation de texte"154        addSubview(aiButton)155        toolsButton.setImage(UIImage(systemName: "ellipsis.circle", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .medium)), for: .normal)156        toolsButton.addTarget(self, action: #selector(toggleTools), for: .touchUpInside)157        toolsButton.accessibilityLabel = "Outils"158        addSubview(toolsButton)159        suggestionStack.axis = .horizontal160        suggestionStack.distribution = .fillEqually161        addSubview(suggestionStack)162        toolStack.axis = .horizontal163        toolStack.distribution = .fillEqually164        toolStack.isHidden = true165        addSubview(toolStack)166        for index in 0..<3 {167            let button = UIButton(type: .system)168            button.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)169            button.titleLabel?.lineBreakMode = .byTruncatingMiddle170            button.titleLabel?.adjustsFontSizeToFitWidth = true171            button.titleLabel?.minimumScaleFactor = 0.75172            button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 6, bottom: 0, right: 6)173            button.tag = index174            button.addTarget(self, action: #selector(tapSuggestion(_:)), for: .touchUpInside)175            suggestionStack.addArrangedSubview(button)176            suggestionButtons.append(button)177            if index > 0 {178                let separator = UIView()179                separator.isUserInteractionEnabled = false180                addSubview(separator)181                separators.append(separator)182            }183        }184        rebuildTools()185    }186187    @available(*, unavailable)188    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }189190    private func rebuildTools() {191        toolStack.arrangedSubviews.forEach { $0.removeFromSuperview() }192        for tool in availableTools {193            let button = UIButton(type: .system)194            button.setImage(UIImage(systemName: tool.symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .medium)), for: .normal)195            button.accessibilityLabel = tool.label196            button.accessibilityIdentifier = "tool.\(tool.rawValue)"197            button.addAction(UIAction { [weak self] _ in198                guard let self else { return }199                self.delegate?.suggestionBar(self, didPick: tool)200            }, for: .touchUpInside)201            button.tintColor = theme.suggestionText.uiColor202            toolStack.addArrangedSubview(button)203        }204    }205206    func apply(theme: Theme) {207        self.theme = theme208        let text = theme.suggestionText.uiColor209        toolsButton.tintColor = text210        toolStack.arrangedSubviews.forEach { $0.tintColor = text }211        separators.forEach { $0.backgroundColor = theme.suggestionText.opacity(0.22).uiColor }212        aiButton.apply(theme: theme)213        refreshButtons()214    }215216    func setSuggestions(_ suggestions: [Suggestion], autocorrection: Suggestion?) {217        self.suggestions = Array(suggestions.prefix(3))218        self.autocorrection = autocorrection219        refreshButtons()220    }221222    private func refreshButtons() {223        for (index, button) in suggestionButtons.enumerated() {224            guard suggestions.indices.contains(index) else {225                button.setAttributedTitle(nil, for: .normal)226                button.setTitle(nil, for: .normal)227                button.isEnabled = false228                button.backgroundColor = .clear229                button.accessibilityLabel = nil230                continue231            }232            let suggestion = suggestions[index]233            let isCorrection = autocorrection.map { $0.text == suggestion.text && suggestion.kind != .verbatim } ?? false234            var title = suggestion.text.replacingOccurrences(of: "\n", with: " ⏎ ")235            if suggestion.kind == .verbatim { title = "« \(title) »" }236            if title.count > 28 { title = String(title.prefix(27)) + "…" }237            button.isEnabled = true238            button.setTitle(title, for: .normal)239            button.setTitleColor(theme.suggestionText.uiColor, for: .normal)240            button.titleLabel?.font = .systemFont(ofSize: 16, weight: isCorrection ? .semibold : .regular)241            // The word a separator would apply is boxed, so correction and suggestion never look alike.242            button.backgroundColor = isCorrection ? theme.suggestionText.opacity(0.16).uiColor : .clear243            button.layer.cornerRadius = 8244            button.accessibilityLabel = isCorrection ? "Correction automatique : \(suggestion.text)" : suggestion.text245        }246    }247248    func setToolsVisible(_ visible: Bool) {249        showsTools = visible250        toolStack.isHidden = !visible251        suggestionStack.isHidden = visible252        separators.forEach { $0.isHidden = visible }253        toolsButton.setImage(UIImage(systemName: visible ? "xmark.circle" : "ellipsis.circle",254                                     withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .medium)), for: .normal)255        toolsButton.accessibilityLabel = visible ? "Fermer les outils" : "Outils"256    }257258    @objc private func toggleTools() { setToolsVisible(!showsTools) }259    @objc private func tapAI() { delegate?.suggestionBarDidTapAI(self) }260261    @objc private func tapSuggestion(_ sender: UIButton) {262        guard suggestions.indices.contains(sender.tag) else { return }263        delegate?.suggestionBar(self, didPick: suggestions[sender.tag])264    }265266    override func layoutSubviews() {267        super.layoutSubviews()268        let side: CGFloat = 44269        aiButton.frame = CGRect(x: 4, y: 0, width: side, height: bounds.height)270        toolsButton.frame = CGRect(x: bounds.width - side - 2, y: 0, width: side, height: bounds.height)271        let middle = CGRect(x: aiButton.frame.maxX + 2, y: 5, width: toolsButton.frame.minX - aiButton.frame.maxX - 4, height: bounds.height - 10)272        suggestionStack.frame = middle273        toolStack.frame = middle274        for (index, separator) in separators.enumerated() {275            let x = middle.minX + middle.width * CGFloat(index + 1) / 3276            separator.frame = CGRect(x: x, y: 12, width: 1 / max(traitCollection.displayScale, 1), height: bounds.height - 24)277        }278    }279}280281/// The ✦ button: a four-point star filled with the theme's effect colours.282final class AIGlyphButton: UIControl {283    private let gradient = CAGradientLayer()284    private let starMask = CAShapeLayer()285286    override init(frame: CGRect) {287        super.init(frame: frame)288        layer.addSublayer(gradient)289        gradient.mask = starMask290        gradient.startPoint = CGPoint(x: 0, y: 0)291        gradient.endPoint = CGPoint(x: 1, y: 1)292        isAccessibilityElement = true293        accessibilityTraits = .button294        accessibilityIdentifier = "ai.button"295    }296297    @available(*, unavailable)298    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }299300    func apply(theme: Theme) {301        var colors = theme.effectColors302        if colors.count < 2 { colors = [theme.accentKey.fill.average.opacity(1), theme.suggestionText] }303        // Keep the glyph readable on its backdrop: mix weak colours towards the text colour.304        let backdrop = theme.background.average305        gradient.colors = colors.map { color -> CGColor in306            let solid = color.opacity(1)307            return (solid.contrast(with: backdrop) < 2.2 ? solid.mixed(with: theme.suggestionText, 0.55) : solid).cgColor308        }309    }310311    static func starPath(in rect: CGRect) -> CGPath {312        let center = CGPoint(x: rect.midX, y: rect.midY)313        let outer = min(rect.width, rect.height) / 2314        let inner = outer * 0.28315        let path = UIBezierPath()316        for index in 0..<8 {317            let radius = index % 2 == 0 ? outer : inner318            let angle = CGFloat(index) * .pi / 4 - .pi / 2319            let point = CGPoint(x: center.x + cos(angle) * radius, y: center.y + sin(angle) * radius)320            if index == 0 { path.move(to: point) } else { path.addLine(to: point) }321        }322        path.close()323        return path.cgPath324    }325326    override func layoutSubviews() {327        super.layoutSubviews()328        let side: CGFloat = 26329        let box = CGRect(x: (bounds.width - side) / 2, y: (bounds.height - side) / 2, width: side, height: side)330        gradient.frame = box331        starMask.frame = gradient.bounds332        starMask.path = Self.starPath(in: gradient.bounds)333    }334335    override var isHighlighted: Bool {336        didSet { alpha = isHighlighted ? 0.5 : 1 }337    }338}339340/// Haptic and click feedback within what an extension may do: haptics need Full Access, the click needs the341/// system "keyboard clicks" setting and Full Access. Both silently do nothing otherwise.342@MainActor343final class KeyFeedback {344    private var light: UIImpactFeedbackGenerator?345    private var medium: UIImpactFeedbackGenerator?346    private let selection = UISelectionFeedbackGenerator()347    var haptic: HapticLevel = .off {348        didSet {349            guard oldValue != haptic else { return }350            light = haptic == .light ? UIImpactFeedbackGenerator(style: .light) : nil351            medium = haptic == .medium ? UIImpactFeedbackGenerator(style: .rigid) : nil352            light?.prepare()353            medium?.prepare()354        }355    }356    var sound = false357    var hasFullAccess = false358359    func keyDown(_ key: Key) {360        if haptic != .off, hasFullAccess {361            light?.impactOccurred(intensity: 0.7)362            medium?.impactOccurred(intensity: 0.9)363        }364        guard sound, hasFullAccess else { return }365        switch key.action {366        case .backspace: AudioServicesPlaySystemSound(1155)367        case .character, .space: AudioServicesPlaySystemSound(1104)368        default: AudioServicesPlaySystemSound(1156)369        }370    }371372    func tick() {373        guard haptic != .off, hasFullAccess else { return }374        selection.selectionChanged()375    }376}377
Files main
Menu

Theme