hex/ios/HEXShared/FullKeyboard/View/FullKeyboardView+Emoji.swift
Ryan Vogel b8b161d499
iOS keyboard: Emoji key and Emoji suggestions as two switches (#2740)
* iOS keyboard: Emoji key and Emoji suggestions are two switches

Settings › Keyboard › Emoji was one switch for the emoji key and the
strip's emoji, so the only way to lose the key was to lose the
suggestions too. Three testers asked to keep the suggestions without the
key (X, tagged by Ryan, and a second person under it, 2026-11-24;
TestFlight build 148 feedback AOZxo_bQHPVi, 2026-11-23).

- Emoji key keeps the old key (experiments.emoji: unset or true on) and
  covers the key on the full keyboard and the dictation bar, with its
  panel and search. Emoji suggestions (settings.keyboardEmojiSuggestions)
  covers the strip's emoji for the typed and the finished word, and Emoji
  shortcodes' while that experiment is on.
- Migration: unset, Emoji suggestions reads Emoji key's value, so the one
  switch's on or off carries over to both in the app and the keyboard
  whichever reads first, with nothing written; the first change to Emoji
  key writes the suggestions' value it had, so turning the key off later
  leaves them on.
- With the key off there is no way into Hex's emoji panel or search
  (Apple's emoji keyboard stays a globe press away); suggestions don't
  need it.
- Settings: "Emoji key" ("Opens all emoji from the keyboard"; with the
  full keyboard off, "An emoji key on the dictation bar" as before) and,
  with the full keyboard on, "Emoji suggestions" ("Suggests an emoji for
  the word you type, like 😭 for cry"). Clear emoji history shows while
  either is on. "cry" rather than the tester's "sob": the index gives
  sob → 😭 a weight of 0.6, under the strip's 0.85, so "sob" offers
  nothing today. English and Simplified Chinese, the catalog's only
  languages.
- Removed: the "Emoji" switch title and "Emoji key and suggestions"
  detail, and FullKeyboardSettings.emoji (now emojiKey and
  emojiSuggestions). The typing log's settings line keeps "emoji" for the
  key and adds "emojiSuggestions".

Verified: build-for-testing (generic iOS Simulator) on basebook; new
cases in FullKeyboardSettingsTests (KeyboardLayoutTests.swift) for the
split, the migration and the key-off layout with the strip's 😭 for
"cry". Full suite on the Mac Studio not run yet.

* iOS Settings: shorter Emoji suggestions detail

"Suggests an emoji for the word you type, like 😭 for cry" wrapped to
two lines on an iPhone 17 Pro, leaving "😭 for cry" on its own line. It
is now "Suggests 😭 as you type cry" (zh-Hans "输入 cry 时推荐 😭"), one line
in both languages; "cry" still offers 😭 today (index weight 1.2), "sob"
does not (0.6, under the strip's 0.85).

Removed: the longer detail and its zh-Hans translation.

Verified: Debug build on basebook's one iOS 27.2 simulator (iPhone 17
Pro), Settings › Keyboard in English and Chinese, and the four
combinations of the two switches typing "Cry" in Hex's Test keyboard
field: the emoji key shows only with Emoji key on, 😭 only with Emoji
suggestions on.

* iOS emoji: "sob" offers 😭

The tester who asked for Emoji suggestions without the key types "sob"
for 😭, and the strip offered nothing for it: CLDR has "sob" only as one
of 😭's keywords, which the index weighs 0.6 (0.51 on the Norwegian,
Spanish and German layouts), under the 0.85 a typed or finished word's
emoji needs. "sob 😭" is now one of Hex's chat words
(scripts/emoji-aliases-en.txt), so it weighs 1.2 on every layout, as
"cry" and "crying" do.

The four index files were regenerated with scripts/build-emoji-data.py at
its pinned sources (emoji-test.txt 18.0, checked against its SHA-256, and
CLDR release-49). A build without the new line reproduced all four
committed files byte for byte first; with it, each file changes in that
one line ("W sob 95:..." to 1.200) and nothing else. LICENSE-Unicode.txt
and the files' source headers are unchanged.

Verified: build-for-testing on basebook; a case beside the "cry" one in
testEmojiSuggestionsWithoutTheEmojiKey (key off, suggestions on, "we sob"
offers 😭). Full suite on the Mac Studio not run yet.
2026-11-24 17:28:25 -05:00

414 lines
19 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 QuartzCore
import UIKit
/// Settings › Keyboard › Emoji key and Emoji suggestions in the full keyboard: the emoji key,
/// its panel, the emoji search (the letter keys type into it while the results sit above), and,
/// on their own switch, the strip's emoji for the word typed or just finished ("pizza " offers
/// 🍕). With the key off there is no way into the panel; the suggestions don't need it.
///
/// The index (`EmojiLibrary`, a memory-mapped file and about 0.7 MB of offsets) loads on
/// the first emoji key press or finished word and stays while the keyboard runs, apart
/// from memory warnings; the panel, its grid and the search go when the panel closes.
extension FullKeyboardView {
var emojiEnabled: Bool {
emojiOverride ?? FullKeyboardSettings().emojiKey
}
var emojiSuggestionsEnabled: Bool {
emojiSuggestionsOverride ?? emojiOverride ?? FullKeyboardSettings().emojiSuggestions
}
/// Emoji in text fields that take any text: not web addresses, email addresses or
/// ASCII-only fields. The key and the strip's suggestions each follow their own switch.
func refreshEmojiKey() {
let document = routedTarget.document
let takesEmoji: Bool = {
guard case .keys(let kind, _) = KeyboardFieldRouting.route(for: document.keyboardType), kind.takesWords else { return false }
return document.keyboardType != .asciiCapable
}()
showsEmojiSuggestions = emojiSuggestionsEnabled && takesEmoji
let shows = emojiEnabled && takesEmoji
guard engine.showsEmoji != shows else { return }
engine.showsEmoji = shows
plane.setNeedsDisplay()
setNeedsLayout()
}
var isShowingEmoji: Bool { emojiPanel != nil }
func loadEmojiLibrary() -> EmojiLibrary? {
let language = engine.language.rawValue
if let library = emojiLibrary, library.language == language || !EmojiLibrary.languages.contains(language) {
return library
}
emojiLibrary = EmojiLibrary.bundled(language: language, bundle: Bundle(for: FullKeyboardView.self))
return emojiLibrary
}
// MARK: - Panel
func emojiKeyTapped() {
if routedTarget.isSearching {
endEmojiSearch()
} else {
openEmojiPanel()
}
}
func openEmojiPanel() {
guard emojiPanel == nil, !showsRecording else { return }
let started = CACurrentMediaTime()
guard let library = loadEmojiLibrary() else { return }
engine.commitHangulComposition()
typingLog?.ui("emoji_open")
dismissStyleMenu()
plane.cancelAllTouches()
let panel = EmojiPanelView(library: library, usage: makeEmojiUsage())
panel.palette = palette
panel.showsKeyPopups = engine.showsKeyPopups
panel.onKeyDown = { [weak self] in self?.keyFeedback() }
panel.onSelectionStep = { [weak self] in self?.selectionFeedback() }
panel.onInsert = { [weak self] text, entry, source in self?.insertEmoji(text, entry: entry, source: source) }
panel.onDelete = { [weak self] in self?.engine.deleteBackward(source: "emoji") }
panel.onDeleteRepeat = { [weak self] held in self?.engine.repeatDelete(heldFor: held) }
panel.onLetters = { [weak self] in
self?.typingLog?.ui("emoji_close")
self?.closeEmojiPanel()
}
panel.onSearch = { [weak self] in self?.beginEmojiSearch() }
insertSubview(panel, belowSubview: callout)
emojiPanel = panel
for view in [plane, stripView, hexKey, globeButton] as [UIView] { view.isHidden = true }
callout.show(nil, label: "")
accentCallout.isHidden = true
fillEmojiPanel()
setNeedsLayout()
layoutIfNeeded()
lastEmojiPanelLatency = CACurrentMediaTime() - started
}
/// The row's suggestions for the text before the cursor and your use, and the grid's
/// Frequently used.
func fillEmojiPanel() {
emojiPanel?.fill(before: routedTarget.document.documentContextBeforeInput)
}
func closeEmojiPanel() {
guard let panel = emojiPanel else { return }
if routedTarget.isSearching { endEmojiSearch() }
panel.tearDown()
panel.removeFromSuperview()
emojiPanel = nil
for view in [plane, stripView, hexKey] as [UIView] {
view.isHidden = false
view.alpha = 1
}
engine.textDidChange()
refreshReturnKey()
refreshStrip()
setNeedsLayout()
}
func insertEmoji(_ text: String, entry: Int, source: String) {
// An emoji ends a Hangul run, whether the keys search emoji first or not.
engine.commitHangulComposition()
if routedTarget.isSearching {
// The keys type into the search; the emoji goes into the field.
suspendedTypingLog?.edit("insert", [
TypingLogField("inserted", .string(text)),
TypingLogField("src", .string("emoji_\(source)")),
])
routedTarget.document.insertText(text)
onTextEdit?()
} else {
engine.insertEmoji(text, source: "emoji_\(source)")
}
if let library = emojiPanel?.library ?? emojiLibrary, entry < library.entries.count {
emojiPanel?.usage.record(library.entries[entry].emoji)
}
}
/// An emoji picked from the strip: counted like one from the panel.
func recordEmojiUse(_ emoji: String) {
guard let library = emojiLibrary, let entry = library.entryByEmoji[emoji] else { return }
makeEmojiUsage().record(library.entries[entry].emoji)
}
// MARK: - Shortcodes (Settings › Experiments; EmojiShortcode)
/// A shortcode, or a typed word's emoji, works where the finished word's emoji does: a text
/// field that takes emoji (the emoji key shows), with autocorrect on and no secure entry,
/// and not one for a password, a one-time code, a username, an email address or a web
/// address. The emoji search types into its own query, so the keys there are not a field's
/// either.
var allowsEmojiShortcodes: Bool {
let refused: Set<UITextContentType> = [.password, .newPassword, .oneTimeCode, .username, .emailAddress, .URL]
return engine.target.autocorrectionType != .no && engine.target.isSecureTextEntry != true
&& !(engine.target.textContentType.map(refused.contains) ?? false)
}
/// The strip's emoji for the token right before the cursor, or nil (the strip shows what
/// it always does) when the experiment is off, the field keeps emoji or autocorrect away,
/// no token is being typed, or none matches.
func emojiShortcodeSuggestions() -> [KeyboardSuggestion]? {
guard emojiShortcodesEnabled, showsEmojiSuggestions, !routedTarget.isSearching,
emojiPanel == nil, allowsEmojiShortcodes,
let before = engine.typingContext ?? engine.textBefore,
let token = EmojiShortcode.token(before: before) else { return nil }
guard let library = loadEmojiLibrary() else { return nil }
let usage = makeEmojiUsage()
let entries = EmojiShortcode.matches(
token: token,
library: library,
usage: emojiUsageScores(usage, library: library)
)
guard !entries.isEmpty else { return nil }
// The same kind as the finished word's emoji: both are an emoji in a slot, and a tap
// tells them apart by the token still before the cursor (`acceptEmojiShortcode`).
return entries.map { entry in
let emoji = emojiText(entry, library: library, usage: usage)
return KeyboardSuggestion(displayText: emoji, replacement: emoji, kind: .emoji)
}
}
/// A strip emoji was tapped while a shortcode token is before the cursor: the whole
/// ":name" goes, and the emoji is counted like one picked from the panel. False for the
/// finished word's own emoji, or a chip that no longer matches the token.
@discardableResult
func acceptEmojiShortcode(_ suggestion: KeyboardSuggestion) -> Bool {
guard emojiShortcodesEnabled,
let token = EmojiShortcode.token(before: engine.typingContext ?? engine.textBefore),
let library = loadEmojiLibrary(),
let entry = library.entryByEmoji[suggestion.replacement] else { return false }
let usage = makeEmojiUsage()
let matches = EmojiShortcode.matches(
token: token,
library: library,
usage: emojiUsageScores(usage, library: library)
)
guard matches.contains(entry) else { return false }
// A host still reporting the text from before the token caught up: the replacement
// does nothing, and the tap is swallowed here rather than fall through to the ordinary
// emoji pick, which would take back only part of the token. The next edit refreshes
// the strip once the host shows the token again.
if engine.replaceEmojiShortcode(suggestion.replacement, token: token) {
usage.record(library.entries[entry].emoji)
}
return true
}
/// The engine's closing ":" hook: a name typed in full (":pizza") types its emoji instead.
func emojiShortcodeReplacement(before text: String?) -> EmojiShortcode.Replacement? {
guard emojiShortcodesEnabled, showsEmojiSuggestions, !routedTarget.isSearching,
emojiPanel == nil, allowsEmojiShortcodes,
let text, EmojiShortcode.token(before: text) != nil,
let library = loadEmojiLibrary() else { return nil }
let usage = makeEmojiUsage()
guard let completion = EmojiShortcode.completion(
before: text,
library: library,
usage: emojiUsageScores(usage, library: library)
) else { return nil }
return EmojiShortcode.Replacement(
token: completion.token.text,
emoji: emojiText(completion.entry, library: library, usage: usage)
)
}
/// An entry's emoji with your skin tone for it, as the panel and the finished word's chip.
func emojiText(_ entry: Int, library: EmojiLibrary, usage: EmojiUsageStore) -> String {
let item = library.entries[entry]
let tone = item.hasTones ? usage.tone(for: item.emoji) : 0
return tone > 0 ? item.tones[tone - 1] : item.emoji
}
/// Your emoji use as a score per index entry, for ranking shortcode matches.
func emojiUsageScores(_ usage: EmojiUsageStore, library: EmojiLibrary) -> [Int: Float] {
var scores: [Int: Float] = [:]
for (emoji, score) in usage.ranked() {
if let entry = library.entryByEmoji[emoji] { scores[entry] = score }
}
return scores
}
// MARK: - Search
func beginEmojiSearch() {
guard let panel = emojiPanel, !routedTarget.isSearching else { return }
typingLog?.ui("emoji_search")
suspendedTypingLog = engine.typingLog
engine.typingLog = nil
routedTarget.query = ""
panel.isHidden = true
let field = EmojiSearchField()
field.palette = palette
field.onClose = { [weak self] in self?.endEmojiSearch() }
addSubview(field)
emojiSearchField = field
let results = EmojiRowView()
results.renderer = panel.glyphs
results.palette = palette
results.fontSize = panel.rowFontSize
results.emptyText = "No emoji"
results.onPick = { [weak self] index in
guard let self, index < self.emojiResultEntries.count, let panel = self.emojiPanel else { return }
self.keyFeedback()
let entry = self.emojiResultEntries[index]
self.insertEmoji(panel.display(for: entry), entry: entry, source: "search")
}
addSubview(results)
emojiResults = results
plane.isHidden = false
emojiSearchLift = engine.layout.metrics.stripHeight
onPreferredHeightChange?()
engine.configureForField()
refreshReturnKey()
refreshEmojiSearch()
setNeedsLayout()
layoutIfNeeded()
}
/// Typing changed the query: the results follow, your suggestions while it's empty.
func refreshEmojiSearch() {
guard let panel = emojiPanel, let query = routedTarget.query else { return }
emojiSearchField?.query = query
let library = panel.library
let ranked = panel.usage.ranked(limit: 32)
var boost: [Int: Float] = [:]
for (emoji, score) in ranked {
if let entry = library.entryByEmoji[emoji] { boost[entry] = score }
}
emojiResultEntries = query.trimmingCharacters(in: .whitespaces).isEmpty
? panel.suggestions
: EmojiSuggester.search(query, library: library, usage: boost)
emojiResults?.setItems(emojiResultEntries.map { (panel.display(for: $0), library.name(of: $0)) })
}
func endEmojiSearch() {
guard routedTarget.isSearching else { return }
routedTarget.query = nil
plane.cancelAllTouches()
engine.typingLog = suspendedTypingLog
suspendedTypingLog = nil
emojiSearchField?.removeFromSuperview()
emojiSearchField = nil
emojiResults?.removeFromSuperview()
emojiResults = nil
emojiResultEntries = []
emojiSearchLift = 0
onPreferredHeightChange?()
engine.configureForField()
refreshReturnKey()
if let panel = emojiPanel {
plane.isHidden = true
panel.isHidden = false
fillEmojiPanel()
}
setNeedsLayout()
}
func layoutEmoji(content: CGRect, lift: CGFloat) {
let layout = engine.layout
let m = layout.metrics
if let panel = emojiPanel {
panel.frame = routedTarget.isSearching ? content : bounds
panel.metrics = m
panel.horizontalInset = layout.horizontalInset
// The panel covers the keyboard while it shows, so the emoji key's keycap sits in
// it at the plane's frame (the lift is zero then); the ABC experiment puts the
// panel's ABC under it. Searching lifts the panel and hides it, and shows ABC
// nowhere, so there is no key to sit under.
let underEmojiKey = emojiLettersUnderEmojiKeyOverride ?? FullKeyboardSettings().emojiLettersUnderEmojiKey
panel.emojiKeyFrame = underEmojiKey && !routedTarget.isSearching
? layout.key(.emoji)?.frame.offsetBy(dx: 0, dy: lift)
: nil
}
let inset = layout.horizontalInset
// Centred on the strip's words' line, as the emoji panel's top row.
let band = m.stripLineBand
emojiSearchField?.frame = CGRect(x: inset, y: m.stripTop + lift + band.top, width: bounds.width - 2 * inset, height: band.height)
emojiResults?.frame = CGRect(x: inset + m.side, y: 0, width: bounds.width - 2 * (inset + m.side), height: lift)
}
// MARK: - Strip
/// Up to three emoji for the word just finished, when the strip would be empty.
func emojiForFinishedWord() -> [KeyboardSuggestion] {
guard showsEmojiSuggestions, emojiPanel == nil, !routedTarget.isSearching,
engine.target.autocorrectionType != .no else { return [] }
let before = routedTarget.document.documentContextBeforeInput
guard let before, before.hasSuffix(" "), !before.hasSuffix(" ") else { return [] }
guard let library = loadEmojiLibrary() else { return [] }
let usage = makeEmojiUsage()
return EmojiSuggester.forFinishedWord(before, library: library).map { entry in
let item = library.entries[entry]
let tone = item.hasTones ? usage.tone(for: item.emoji) : 0
let emoji = tone > 0 ? item.tones[tone - 1] : item.emoji
return KeyboardSuggestion(displayText: emoji, replacement: emoji, kind: .emoji)
}
}
/// The strip's suggestions with its emoji (`refreshStrip`): a shortcode's in its place; in an
/// empty strip or one of next words, the finished word's, unless `quiet` (Undo, a status or
/// a clipboard chip has the strip, and the next words go too); else the typed word's.
func withStripEmoji(_ suggestions: [KeyboardSuggestion], quiet: Bool) -> [KeyboardSuggestion] {
if let shortcodes = emojiShortcodeSuggestions() { return shortcodes }
guard suggestions.isEmpty || suggestions.first?.kind == .nextWord else {
return withTypedWordEmoji(suggestions) ?? suggestions
}
guard !quiet else { return [] }
let emoji = emojiForFinishedWord()
guard !emoji.isEmpty else { return suggestions }
// The finished word's emoji, with next words beside it so every slot fills: one emoji
// takes the centre.
let words = Array(suggestions.prefix(max(0, 3 - emoji.count)))
return emoji.count == 1 && words.count == 2 ? [words[0], emoji[0], words[1]] : emoji + words
}
/// The strip while a word that names an emoji is typed ("smile" offers 😊, as Apple's
/// keyboard does): its emoji in the next empty slot, else in place of the right slot's
/// runner-up word, else the centre's; never in place of what you typed, a revert, the
/// word space will put in, or your own words, and never while space would put in another
/// word. Whole words only, as the finished word's emoji (`EmojiSuggester.forWord`), in a
/// field that takes them (`allowsEmojiShortcodes`), not for a swiped word (the strip
/// shows its readings). Nil leaves the strip as it is. A tap puts the emoji in the word's
/// place (`FullKeyboardEngine.acceptEmoji`).
func withTypedWordEmoji(_ suggestions: [KeyboardSuggestion]) -> [KeyboardSuggestion]? {
guard showsEmojiSuggestions, emojiPanel == nil, !routedTarget.isSearching, allowsEmojiShortcodes,
!suggestions.contains(where: { $0.kind == .swiped }),
let token = AutocorrectEngine.currentToken(in: engine.typingContext ?? engine.textBefore),
token.count >= 2, token.allSatisfy(\.isLetter),
!(engine.target.documentContextAfterInput?.first.map { $0.isLetter || $0.isNumber } ?? false),
!suggestions.contains(where: { $0.willAutoReplace && $0.replacement.caseInsensitiveCompare(token) != .orderedSame }),
let library = loadEmojiLibrary(),
let entry = EmojiSuggester.forWord(EmojiText.fold(token), library: library, limit: 1).first else { return nil }
let emoji = emojiText(entry, library: library, usage: makeEmojiUsage())
let chip = KeyboardSuggestion(displayText: emoji, replacement: emoji, kind: .emoji)
var strip = suggestions
if strip.count < 3 { return strip + [chip] }
let autocorrect = engine.autocorrect
func keeps(_ item: KeyboardSuggestion) -> Bool {
item.kind == .keepLiteral || item.kind == .revert || item.willAutoReplace
|| autocorrect.isVocabularySpelling(item.replacement) || autocorrect.isOwnSpelling(item.replacement)
|| autocorrect.vocabularyCompletion(for: token) == item.replacement
}
guard let slot = [2, 1].first(where: { !keeps(strip[$0]) }) else { return nil }
strip[slot] = chip
return strip
}
// MARK: - Fixtures
/// Fixtures: open the panel, optionally searching `query`.
func debugOpenEmoji(search query: String? = nil) {
openEmojiPanel()
guard let query else { return }
beginEmojiSearch()
for character in query {
routedTarget.insertText(String(character))
}
refreshEmojiSearch()
}
}