hex/ios/HEXShared/FullKeyboard/Emoji/EmojiUsageStore.swift
Ryan Vogel 82f5df56c9
iOS: Emoji and Swipe typing are on by default, under Settings › Keyboard (#2129)
Ryan approved graduating both full-keyboard experiments. Swipe typing
(#2106) and the emoji key and panel (#2051) are on for new users and
move out of Experiments.

- Defaults: FullKeyboardSettings.emoji and .swipeTyping read
  experiments.emoji and experiments.swipeTyping as object-or-true (was
  bool(forKey:), unset meaning off), as spatialAutocorrect did in #2097.
  Only their Experiments switches ever wrote those keys, and only on a
  change, so unset means never touched: fresh installs and testers who
  never touched them get them on, a stored false stays off, a stored
  true stays on. The keys keep their names; no migration. Without the
  App Group (no Full Access on an iPhone) both read as on, like the
  keyboard's other on-by-default switches. --experiment-emoji and
  --experiment-swipe still turn them on.
- Settings › Keyboard: a card under the main one with Swipe typing and
  Emoji, plus Clear emoji history while Emoji is on. Both keep "Needs the
  full keyboard" while the Dictation bar is chosen (now from the page's
  own Full/Dictation bar choice). Settings › Experiments keeps Hinglish
  and Clean up with Apple Intelligence. No new strings; every string
  already had zh-Hans.
- Record typing logs' session line adds swipeTyping and emoji, beside
  spatialAutocorrect and cleanupTagger.
- settings-<page> scenes write both switches on, as for
  spatialAutocorrect. Doc comments and README point at Settings ›
  Keyboard.
- Test: KeyboardLayoutTests.testSwipeTypingAndEmojiAreOnByDefaultAnd-
  AStoredOffStaysOff (unset, no App Group, stored off, launch arguments).

Held back: Clean up what I say stays off by default. On the held-out
generated set its false deletes match the reference (0.5% of words; 3.9%
of clean and 2.7% of literal sentences lose a word; 1/43 hand-written
clean sentences), and "late" was never deleted (0/247). But it deletes
every hyphenated name tried: "Tell Hye-jin I said thanks." became "Tell
thanks.", and Jean-Luc, Anne-Marie, Mary-Kate, Ji-woo, Marie-Claire,
Smith-Jones and Zeta-Jones all went (P(DELETE) 0.996-1.0), with
"follow-up" and "re-entry". It also drops a literal "maybe" ("Call me
later, maybe after dinner").

Verified on iPhone 17 simulators (iOS 27.2) on the Mac Studio:
- xcodebuild test: 383 tests, 1 skipped (needs HEX_SPEECH_CLIPS), 0
  failures.
- Swipe on vs off, taps unchanged: the hex-vs-apple held-out sets (2,000
  English and 2,000 Spanish sentences) typed through a real
  KeyboardKeyPlaneView with a temporary, uncommitted harness gave
  identical output in every sentence and 0 swipes from 116,253 letter
  touches, for still taps, motion drawn from Record typing logs, every
  letter dragged 30-95% of a key's pitch, and overlapping (rollover) taps.
  English WER 5.94%, 79/9,203 correct words broken (still) both ways;
  Spanish 8.61%, 23/7,978. A control dragging 1.05-1.5 pitches made
  7,000/7,000 swipes with it on, 0 off. In the typing logs, 1 of about
  1,000 letter touches moved more than a pitch.
- Live keyboard in Messages: with no stored keys the emoji key shows
  and a drag from h to e swipes "He" (strip: Here, Her, He's); with both
  stored false (an upgrade that turned them off) there's no emoji key
  and the same drag slides and types "E".
- Keyboard memory (Release, Full Access, mock mic, probe transcript,
  vmmap physical footprint, resident/peak MB, 2 runs each; a temporary,
  uncommitted probe faked the transcript and headroom):
    typing, emoji and swipe off            34.0 / 46.1
    typing, both on                        35.0-39.9 / 47.0-51.8
    + in-keyboard dictation, Clean up off  35.0 / 46.6
    + dictation, Clean up on               37.6-43.6 / 46.5-51.9
    + emoji panel, a few picks             38.3-38.8 / 51.4-52.2
    + every emoji category browsed         58.8-59.3 / 68.2-68.3
    + all that, then dictation, Clean up   69.2 / 73.7
  Typing sets the peak, not the tagger (loaded after recording stops,
  about 2.6 MB). With a faked 60 MB headroom the 80 MB cleanup guard
  skipped the tagger and the transcript went in as heard (2/2). The
  simulator reports no headroom, so #2045's 32 MB start guard can't fire
  there. On a 4 GB iPhone (reported limits 60-77 MB), browsing every
  emoji category approaches the limit, and a dictation after it would
  open Hex instead. Unverified on a device.
2026-11-21 02:41:15 +00:00

130 lines
5 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 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 }
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)
}
}