SPB Git

Repository Public

TextProxy.swift 8.8 KB 236 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/KeyboardCore/TextProxy.swift10// Description      : The text-document contract the typing engine talks to11//                    (mirrors UITextDocumentProxy), the host input traits, and12//                    an in-memory document used by tests, the in-app preview13//                    and the latency bench.14// Module           : KeyboardCore15// 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 Foundation9293/// What the engine needs from the host field. The extension adapts `UITextDocumentProxy` to it.94@MainActor95public protocol TextDocumentProxying: AnyObject {96    var contextBefore: String? { get }97    var contextAfter: String? { get }98    var selectedText: String? { get }99    /// Whether the field contains any text at all (`UIKeyInput.hasText`).100    var hasText: Bool { get }101    func insertText(_ text: String)102    func deleteBackward()103    /// Offset in UTF-16 code units, as `UITextDocumentProxy.adjustTextPosition(byCharacterOffset:)` counts.104    func adjustTextPosition(byCharacterOffset offset: Int)105}106107/// Layout family requested by the host field (`UIKeyboardType`).108public enum LayoutVariant: String, Sendable, Codable {109    case standard, url, email, webSearch, numberPad, decimalPad, phonePad, numbersAndPunctuation110111    public var isPad: Bool { self == .numberPad || self == .decimalPad || self == .phonePad }112}113114public enum ReturnKeyKind: String, Sendable, Codable {115    case `default`, go, search, send, done, next, join, route, `continue`, emergencyCall116}117118public enum AutocapitalizationMode: String, Sendable, Codable {119    case none, words, sentences, allCharacters120}121122/// Traits of the focused field, refreshed on every `textDidChange`.123public struct InputTraits: Hashable, Sendable {124    public var variant: LayoutVariant = .standard125    public var returnKey: ReturnKeyKind = .default126    public var autocapitalization: AutocapitalizationMode = .sentences127    public var allowsAutocorrection = true128    public var allowsSmartPunctuation = true129    public var enablesReturnKeyAutomatically = false130131    public init() {}132133    /// Fields where prose helpers (autocorrection, autocapitalisation, smart punctuation) must stay out of the way.134    public var isProse: Bool {135        switch variant {136        case .standard, .webSearch: true137        default: false138        }139    }140}141142/// A tiny editable document with a cursor and an optional selection.143@MainActor144public final class InMemoryTextProxy: TextDocumentProxying {145    public private(set) var before: String146    public private(set) var after: String147    public private(set) var selection: String148    /// Simulates hosts that delete one Unicode scalar per `deleteBackward` instead of one grapheme.149    public var deletesByScalar = false150    /// Simulates hosts that expose only a window of the text before the cursor.151    public var contextWindow: Int?152    /// Simulates hosts that stop reporting the text before the cursor once it contains an emoji153    /// (seen in a system search field).154    public var hidesContextWithEmoji = false155    public private(set) var insertions = 0156    public private(set) var deletions = 0157    public var onChange: (() -> Void)?158159    public init(before: String = "", after: String = "", selection: String = "") {160        self.before = before161        self.after = after162        self.selection = selection163    }164165    public var text: String { before + selection + after }166    public var hasText: Bool { !text.isEmpty }167    public var contextBefore: String? {168        if hidesContextWithEmoji, before.unicodeScalars.contains(where: { $0.properties.isEmojiPresentation || $0.value == 0xFE0F }) { return nil }169        guard let contextWindow else { return before.isEmpty ? nil : before }170        let window = String(before.suffix(contextWindow))171        return window.isEmpty ? nil : window172    }173    public var contextAfter: String? { after.isEmpty ? nil : after }174    public var selectedText: String? { selection.isEmpty ? nil : selection }175176    public func insertText(_ text: String) {177        selection = ""178        before += text179        insertions += 1180        onChange?()181    }182183    public func deleteBackward() {184        deletions += 1185        defer { onChange?() }186        if !selection.isEmpty {187            selection = ""188            return189        }190        guard !before.isEmpty else { return }191        if deletesByScalar {192            before.unicodeScalars.removeLast()193        } else {194            before.removeLast()195        }196    }197198    public func adjustTextPosition(byCharacterOffset offset: Int) {199        guard offset != 0 else { return }200        if !selection.isEmpty {201            before += selection202            selection = ""203        }204        if offset < 0 {205            var remaining = -offset206            while remaining > 0, let last = before.last {207                remaining -= last.utf16.count208                before.removeLast()209                after.insert(last, at: after.startIndex)210            }211        } else {212            var remaining = offset213            while remaining > 0, let first = after.first {214                remaining -= first.utf16.count215                after.removeFirst()216                before.append(first)217            }218        }219        onChange?()220    }221222    public func select(lastCharacters count: Int) {223        let picked = String(before.suffix(count))224        before.removeLast(picked.count)225        selection = picked226        onChange?()227    }228229    public func reset(_ text: String = "") {230        before = text231        after = ""232        selection = ""233        onChange?()234    }235}236
Files main
Menu

Theme