hex/ios/HEXShared/FullKeyboard/Emoji/EmojiUsageStore.swift
Ryan Vogel 64d6eccfa6 iOS: the space-bar trackpad moves up and down lines, as the system keyboard's does
X tester Brandon McConnell: "holding down on the space bar only allows scrubbing
horizontally, whereas Apple's keyboard treats it like a cursor on both x/y axes".

Apple's (black box, iOS 27.2 simulator, iPhone 17, a UITextView with 17 pt text and
20.3 pt lines, the caret read back from the host): after the hold, the caret moved a line
every 15 to 16 pt of finger travel up or down, the first after about 8 (crossings at 9,
24, 39, 54, 72 and 87 pt both ways), kept its x, and stayed on the first or last line
past them; in a wrapped paragraph it moved by a wrapped line (about 43 characters in a
360 pt line). Along a line it moved about a character per 6 pt and stopped at the line's
ends.

A keyboard can only move the cursor by characters (adjustTextPosition), so
TrackpadCursor works out the line before or after from the text the field shares around
the cursor: lines split at new lines and every lineLength characters (the keyboard's
width less 40 pt, at 8.2 pt a character, as the field's width and font can't be read),
at the same column, kept across short lines until a move along the line. Vertical steps
are trackpadPointsPerLine (15.5 pt), the first half as far; past the first or last line
the cursor stays and coming back moves it at once. Horizontal movement is unchanged (7.5 pt
a character, crossing line ends as before).

The host's context lags the moves: in the simulator a second line up read the text from
before the first, and after a move the host shared only the cursor's own line. So each
gesture keeps a copy of the text (TrackpadCursor.State) and adds the host's context once it
has caught up (it reads the same either side of the cursor). Lines the host never shares
stay out of reach. KeyboardTextTarget gains documentContextAfterInput.

Not done: Apple's tap with a second finger while holding space starts a selection. The
iOS 27.2 SDK's UITextDocumentProxy has documentContextBeforeInput/AfterInput, selectedText
(read-only), documentInputMode, documentIdentifier, adjustTextPosition(byCharacterOffset:),
setMarkedText(_:selectedRange:) and unmarkText, and UIInputViewController nothing more: no
public API makes or extends a selection, and marked text would type provisional text into
the field, so Hex doesn't fake it.

TrackpadCursor is surface-independent so the dictation bar's trackpad (#2180) can use it
too; it isn't wired there here.

Verified on the Studio (iPhone 17, iOS 27.2 simulator): FullKeyboardEngineTests (new
testTheSpaceBarTrackpadMovesUpAndDownLines), AutocorrectEngineTests and EmojiSuggesterTests
pass. Live in the simulator's HEXKeyboard (Release) in a UITextView with four lines: from
the end, holding space and sliding up moved the cursor 88 -> 64 -> 41 -> 20 (each line up,
same column), further up kept it on the first line, and sliding back down returned it 41 ->
64 -> 88; nothing was typed.
2026-11-21 09:13:20 -05:00

133 lines
5.2 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import UIKit
/// The emoji you use, kept in the App Group on this iPhone: a count that fades by half every
/// ten days (so both how often and how lately count) and the skin tone you last picked for
/// each emoji. No words, nothing about what you write. Settings › Keyboard › Clear emoji history
/// empties it.
@MainActor
final class EmojiUsageStore {
static let halfLife: TimeInterval = 10 * 86_400
/// The most emoji remembered; the faintest go first.
static let capacity = 120
private enum Key {
static let usage = "emoji.usage"
static let tones = "emoji.tones"
}
private let defaults: UserDefaults?
private let now: () -> Date
/// Base emoji to [score at `last`, last use as seconds since 1970].
private var usage: [String: [Double]]
/// Base emoji to the skin tone picked for it: 1 (light) to 5 (dark).
private var tones: [String: Int]
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup), now: @escaping () -> Date = Date.init) {
self.defaults = defaults
self.now = now
usage = defaults?.dictionary(forKey: Key.usage) as? [String: [Double]] ?? [:]
tones = defaults?.dictionary(forKey: Key.tones) as? [String: Int] ?? [:]
}
/// You picked `base` (the emoji without a skin tone).
func record(_ base: String) {
let time = now().timeIntervalSince1970
usage[base] = [score(of: base, at: time) + 1, time]
if usage.count > Self.capacity {
let faintest = usage.keys.min { score(of: $0, at: time) < score(of: $1, at: time) }
if let faintest { usage[faintest] = nil }
}
defaults?.set(usage, forKey: Key.usage)
}
private func score(of base: String, at time: TimeInterval) -> Double {
guard let stored = usage[base], stored.count == 2 else { return 0 }
return stored[0] * pow(0.5, max(0, time - stored[1]) / Self.halfLife)
}
/// Your emoji, most used first, with scores scaled so the first is 1.
func ranked(limit: Int = 40) -> [(emoji: String, score: Float)] {
let time = now().timeIntervalSince1970
let scored = usage.keys
.map { ($0, score(of: $0, at: time)) }
.sorted { $0.1 != $1.1 ? $0.1 > $1.1 : $0.0 < $1.0 }
.prefix(limit)
guard let top = scored.first?.1, top > 0 else { return [] }
return scored.map { ($0.0, Float($0.1 / top)) }
}
/// 0 for the default yellow, else 1 (light) to 5 (dark).
func tone(for base: String) -> Int {
tones[base] ?? 0
}
func setTone(_ tone: Int, for base: String) {
tones[base] = tone == 0 ? nil : tone
defaults?.set(tones, forKey: Key.tones)
}
var isEmpty: Bool { usage.isEmpty && tones.isEmpty }
func clear() {
usage = [:]
tones = [:]
defaults?.removeObject(forKey: Key.usage)
defaults?.removeObject(forKey: Key.tones)
}
}
/// The keyboard's text target while the emoji panel is up: the field, or the emoji search's
/// query while you search, so the letter keys type into the search instead of the field.
@MainActor
final class EmojiRoutedTarget: KeyboardTextTarget {
let document: KeyboardTextTarget
/// Set while searching; the keys type here.
var query: String?
/// Return while searching.
var onSearchReturn: (() -> Void)?
init(document: KeyboardTextTarget) {
self.document = document
}
var isSearching: Bool { query != nil }
var documentContextBeforeInput: String? { query ?? document.documentContextBeforeInput }
var documentContextAfterInput: String? { isSearching ? nil : document.documentContextAfterInput }
var hasText: Bool { query.map { !$0.isEmpty } ?? document.hasText }
var autocapitalizationType: UITextAutocapitalizationType? { isSearching ? UITextAutocapitalizationType.none : document.autocapitalizationType }
var autocorrectionType: UITextAutocorrectionType? { isSearching ? .no : document.autocorrectionType }
var keyboardType: UIKeyboardType? { isSearching ? .default : document.keyboardType }
var returnKeyType: UIReturnKeyType? { isSearching ? .done : document.returnKeyType }
var enablesReturnKeyAutomatically: Bool? { isSearching ? false : document.enablesReturnKeyAutomatically }
var keyboardAppearance: UIKeyboardAppearance? { document.keyboardAppearance }
var textContentType: UITextContentType? { isSearching ? nil : document.textContentType }
var smartQuotesType: UITextSmartQuotesType? { isSearching ? .no : document.smartQuotesType }
var smartDashesType: UITextSmartDashesType? { isSearching ? .no : document.smartDashesType }
func insertText(_ text: String) {
guard let current = query else {
document.insertText(text)
return
}
if text.contains("\n") {
onSearchReturn?()
} else {
query = current + text
}
}
func deleteBackward() {
guard var current = query else {
document.deleteBackward()
return
}
if !current.isEmpty { current.removeLast() }
query = current
}
func adjustTextPosition(byCharacterOffset offset: Int) {
guard !isSearching else { return }
document.adjustTextPosition(byCharacterOffset: offset)
}
}