hex/ios/HEXShared/FullKeyboard/Emoji/EmojiUsageStore.swift
Ryan Vogel c2d78847d4 iOS: rank emoji for the text before the cursor, on device
What changed
- EmojiLibrary maps an emoji-index file (Data .alwaysMapped) and keeps only the emoji,
  their skin tones and byte offsets: word and phrase lookups binary-search the file's
  sorted keys and parse postings in place; search scans each emoji's folded name and
  keyword words for prefixes (name words first, a short name the query fills before a
  long one it touches, then your use and everyday emoji). Emoji newer than 15.1 are
  listed only if the emoji font itself draws them as one glyph.
- EmojiSuggester reads the last eight content words (the newest counts 1, then 0.85
  each word back), their forms (plurals, -ing, -ed, held-down letters: "lmaooo"),
  two- to four-word phrases ("new year", "good luck") and the word still being typed;
  an emoji several words point at gains a third of the rest. One emoji per family
  ("man running", "woman running"); your use breaks ties and fills the row, then
  everyday defaults. forFinishedWord gives the strip at most three strong matches for
  the word just finished ("pizza " -> 🍕).
- EmojiUsageStore keeps, in the App Group, a use count per emoji that halves every 10
  days (frequency and recency in one score, at most 120 emoji) and the skin tone last
  picked for each; no words. clear() empties both.
- EmojiRoutedTarget lets the keys type into the emoji search's query instead of the
  field while you search.
- EmojiSemanticIndex (app target only, for the comparison test): Apple's on-device
  NLEmbedding word vectors over the index's 3,257 words, standing in for a context word
  with no emoji of its own. Not used by the keyboard (see Measured).
- EmojiSuggesterTests: index, folding, context, families, endings, other layouts,
  strip, search, history decay and tones, the search's routing, and quality on 60
  hand-written sentences (Fixtures/emoji-context-sentences.json, 30 to tune, 30 held
  out) with and without the embedding.

Measured (sensible emoji in the top 5, context only; top-1 in brackets)
- Simulator, iPhone 17, iOS 27.2: keywords dev 30/30 (27), held-out 30/30 (27), 0.04 ms
  a sentence; with the embedding the same counts at 0.14 ms, its index built in 120 ms.
- Mac harness, same code: CLDR keywords alone dev 26/30 (13), held-out 22/30 (14);
  with Hex's chat words 30/30 (27) and 30/30 (27). A blind set of 40 messages and
  sensible emoji written by a separate agent that saw no code or word lists: CLDR
  alone 30/40 (13), with chat words 37/40 (28), adding the embedding 37/40 (28); 38/40
  after the held-down-letter rule, which those failures suggested. Apple's sentence
  embedding scored 18/40 (7) and took 7.5 s to embed the 1,923 descriptions.
- Memory on the Mac: the mapped index adds 0.72 MB; the embedding adds 5.3 MB (1 MB
  NLEmbedding, 3.9 MB vectors) and none of it came back after release. No measurable
  gain for that, so the keyboard uses keywords and your history only.

Verified: xcodebuild test on an iPhone 17 simulator (iOS 27.2): 245 tests, 1 skipped,
0 failures.
2026-11-20 10:49:41 -05:00

130 lines
4.9 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. Experiments › 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)
}
}