mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS: emoji index built from Unicode's emoji list and CLDR
What changed
- scripts/build-emoji-data.py builds HEXShared/FullKeyboard/Emoji/emoji-index-<lang>.txt
for the four keyboard layouts (en, nb, es, de) from Unicode emoji-test.txt 18.0
(pinned by SHA-256) and CLDR 49 annotations and annotationsDerived (release-49 tag),
plus Hex's own chat words in scripts/emoji-aliases-en.txt ("congrats", "bday",
"lol", "new year"; 336 words, written for Hex).
- Each file holds the catalog in panel order (8 categories, 1,923 emoji, 332 with five
uniform skin tones), each emoji's English name, its folded search words, and the
word and phrase postings already weighted (one-word name 1.0, name word 0.75,
keyword 0.6, keyword-phrase word 0.3, chat word 1.2 down to 0.9, an IDF factor for
words many emoji share), sorted by key so the keyboard can binary-search the file
in place. Non-English layouts carry English's words at 0.85.
- LICENSE-Unicode.txt (Unicode License v3) ships beside the data, as the licence
asks: both emoji-test.txt and CLDR's data are under it, which allows commercial
use with the notice.
Why
- The emoji panel (next commits) suggests emoji for what you type and searches them
on the iPhone. Precomputing the index keeps the keyboard extension's heap small:
the first version built Swift dictionaries at runtime and held 5.7 MB, which
malloc kept after release; the mapped file plus offsets measures 0.7 MB.
Verified
- The generator runs from a sources folder or downloads the pinned files; output is
deterministic. Files: en 351 KB, nb 560 KB, es 549 KB, de 610 KB.
* 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.
* iOS: emoji panel for the full keyboard (Experiments › Emoji)
What changed
- Experiments › Full keyboard › Emoji (experiments.emoji, off by default; shown with the
full keyboard): an emoji key (face.smiling) right of 123, after the globe, in plain
text fields (not URL, email or ASCII-only ones). The bottom row takes the compact
sizes it uses beside the globe. "Clear emoji history" empties EmojiUsageStore.
- EmojiPanelView replaces the strip and the keys: a row of up to ten suggestions for
the text before the cursor and your history (one emoji per family, your skin tone),
a search button; a grid that scrolls sideways through Frequently used (your history,
then everyday emoji, 16 at least) and the eight categories in four rows of 42 pt
(three of 38 in landscape), each section's name kept at the left edge while it
scrolls; a bar with ABC, the categories and a repeating delete, drawn like the
letter keys' 123 and delete. Holding an emoji with skin tones opens the accent
picker with its five tones; the pick is typed and remembered for that emoji. Key
pop-ups and haptics follow their switches.
- Search: the letter keys type into a search field in the strip (EmojiRoutedTarget),
results above it in a row the keyboard grows 44 pt for, your suggestions while it's
empty; return, the field's close button or the emoji key go back to the panel.
Typing logs and Learn how I type see the emoji typed into the field, never the query.
- The strip, when it would be empty after a space, offers the finished word's strong
emoji ("pizza " -> 🍕, "birthday " -> 🎂 🎉 🥳), a lone one in the centre slot; never
over word suggestions, Undo dictation, a status or the clipboard chips.
- Grid cells drop their text (and bitmap) when they scroll off and prefetching is off:
scrolling every section had kept 353 cell bitmaps, 35 MB.
- FullKeyboardView+Emoji.swift holds the wiring; the engine's target is now the routed
target, which forwards everything to the field unless a search is open.
- Scenes: full-keyboard-emoji, -emoji-search (--emoji-query), -emoji-tones,
-emoji-food, -emoji-strip (each -dark and -dark-field), and -emoji-probe, which prints
the panel's footprint and open latency.
Measured in the keyboard extension (Release, iPhone 17 simulator, iOS 27.2, a field
focused with the real HEXKeyboard.appex and a temporary, uncommitted probe; the
simulator counts no GPU memory and reports no headroom), footprint:
keyboard with the emoji key, nothing loaded 19.0 MB
after "pizza " (the strip loads the index) 19.0 MB
panel open 28.7 MB
picked three suggestions, closed 22.7 MB
every section scrolled 41.6 MB (peak 48.4; 71.1 before the cell fix)
closed after that 36.5 MB
The 17.5 MB left after browsing everything is about 351 emoji glyph images the system's
text rendering caches process-wide (18.7 MB in the heap, 351 CGImages); drawing with a
font instance the panel owns or at 21 pt left it the same, and no public API frees it.
Whether iOS purges it under memory pressure is unverified on an iPhone.
Opening: 22-26 ms from the emoji key to the panel laid out the first time, 12-14 ms
after (median of 10), about 21 ms until committed.
Verified: xcodebuild test (245 tests, 1 skipped, 0 failures); every scene above in
light, dark and dark field looked at on the simulator.
* iOS: document the emoji experiment and keep its blind sentences as a check
What changed
- README: the emoji experiment under Capabilities (what the panel, search, skin tones
and strip do, what the history keeps, where the index comes from and its licence),
how to rebuild the index, and its proof limits with the quality, memory and latency
measurements and what is unverified on an iPhone (whether iOS purges the cached
emoji glyph images that browsing every section leaves, about 18 MB).
- emoji-context-sentences.json gains the 40-message blind set a separate agent wrote
without seeing code or word lists; EmojiSuggesterTests scores it beside the other
60 and fails below 35/40.
Why: the blind set is the least biased quality number; keeping it catches a ranking
change that helps the hand-written sentences at its expense.
Verified: xcodebuild test on an iPhone 17 simulator (iOS 27.2): 245 tests, 1 skipped,
0 failures; EMOJI_QUALITY: dev 30/30 (top-1 27), held-out 30/30 (27), blind 38/40 (29),
the same with the embedding, which built in 101 ms.
530 lines
22 KiB
Swift
530 lines
22 KiB
Swift
import UIKit
|
||
|
||
/// The emoji panel (Experiments › Emoji), in place of the strip and the keys: a row of
|
||
/// emoji for what you just typed, then a grid that scrolls sideways through what you use
|
||
/// most and every category, and a bar with ABC, the categories and delete. Holding an emoji
|
||
/// that has skin tones offers them; the one you pick is remembered for it.
|
||
@MainActor
|
||
final class EmojiPanelView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
|
||
struct Section {
|
||
let title: String
|
||
let symbol: String
|
||
let entries: [Int]
|
||
}
|
||
|
||
var palette = FullKeyboardPalette(isDark: false) {
|
||
didSet {
|
||
guard palette != oldValue else { return }
|
||
applyPalette()
|
||
}
|
||
}
|
||
var showsKeyPopups = true
|
||
var metrics = KeyboardMetrics.portrait { didSet { if metrics != oldValue { setNeedsLayout() } } }
|
||
var horizontalInset: CGFloat = 0 { didSet { if horizontalInset != oldValue { setNeedsLayout() } } }
|
||
/// An emoji went in: the text to insert, its entry, and where it came from
|
||
/// ("suggestion", "grid", "tone").
|
||
var onInsert: ((String, Int, String) -> Void)?
|
||
var onDelete: (() -> Void)?
|
||
/// The delete key is still held: how long, for repeat and word delete.
|
||
var onDeleteRepeat: ((TimeInterval) -> Void)?
|
||
var onLetters: (() -> Void)?
|
||
var onSearch: (() -> Void)?
|
||
/// A key went down (click and haptic), or a tone was stepped over.
|
||
var onKeyDown: (() -> Void)?
|
||
var onSelectionStep: (() -> Void)?
|
||
|
||
let library: EmojiLibrary
|
||
let usage: EmojiUsageStore
|
||
private(set) var sections: [Section] = []
|
||
private(set) var suggestions: [Int] = []
|
||
|
||
let suggestionRow = EmojiRowView()
|
||
private let searchButton = UIButton(type: .custom)
|
||
private let grid: UICollectionView
|
||
private let categoryBar: EmojiCategoryBar
|
||
private let lettersKey = PanelKeyButton()
|
||
private let deleteKey = PanelKeyButton()
|
||
private let callout = KeyCalloutView()
|
||
private let tonePicker = AccentCalloutView()
|
||
private var toneEntry: Int?
|
||
private var layoutKey: GridGeometry?
|
||
private var sectionStarts: [CGFloat] = []
|
||
private var deleteTimer: Timer?
|
||
private var deleteStartedAt: TimeInterval = 0
|
||
|
||
struct GridGeometry: Equatable {
|
||
let rows: Int
|
||
let rowHeight: CGFloat
|
||
let columnWidth: CGFloat
|
||
let headerHeight: CGFloat
|
||
let fontSize: CGFloat
|
||
let counts: [Int]
|
||
}
|
||
|
||
init(library: EmojiLibrary, usage: EmojiUsageStore) {
|
||
self.library = library
|
||
self.usage = usage
|
||
grid = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
|
||
categoryBar = EmojiCategoryBar(items: [("clock", "Frequently used")] + EmojiCategory.allCases.map { ($0.symbol, $0.title) })
|
||
super.init(frame: .zero)
|
||
backgroundColor = .clear
|
||
isOpaque = false
|
||
|
||
searchButton.setImage(
|
||
UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)),
|
||
for: .normal
|
||
)
|
||
searchButton.accessibilityLabel = "Search emoji"
|
||
searchButton.layer.cornerCurve = .continuous
|
||
searchButton.addTarget(self, action: #selector(searchTapped), for: .touchUpInside)
|
||
addSubview(searchButton)
|
||
|
||
suggestionRow.onPick = { [weak self] index in self?.pickSuggestion(index) }
|
||
addSubview(suggestionRow)
|
||
|
||
grid.backgroundColor = .clear
|
||
grid.showsHorizontalScrollIndicator = false
|
||
grid.delaysContentTouches = false
|
||
// Each drawn cell holds a bitmap of its emoji; only the visible ones should.
|
||
grid.isPrefetchingEnabled = false
|
||
grid.dataSource = self
|
||
grid.delegate = self
|
||
grid.register(EmojiCell.self, forCellWithReuseIdentifier: EmojiCell.reuseID)
|
||
grid.register(
|
||
EmojiSectionHeader.self,
|
||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||
withReuseIdentifier: EmojiSectionHeader.reuseID
|
||
)
|
||
let hold = UILongPressGestureRecognizer(target: self, action: #selector(held(_:)))
|
||
hold.minimumPressDuration = FullKeyboardEngine.accentHoldDelay
|
||
grid.addGestureRecognizer(hold)
|
||
addSubview(grid)
|
||
|
||
categoryBar.onSelect = { [weak self] index in self?.jump(toSection: index) }
|
||
addSubview(categoryBar)
|
||
|
||
lettersKey.title = "ABC"
|
||
lettersKey.isPrimary = true
|
||
lettersKey.drawsLikeKeys = true
|
||
lettersKey.accessibilityLabel = "Letters"
|
||
lettersKey.addTarget(self, action: #selector(lettersTapped), for: .touchUpInside)
|
||
addSubview(lettersKey)
|
||
|
||
deleteKey.symbol = "delete.left"
|
||
deleteKey.isPrimary = true
|
||
deleteKey.drawsLikeKeys = true
|
||
deleteKey.accessibilityLabel = "Delete"
|
||
deleteKey.addTarget(self, action: #selector(deleteDown), for: .touchDown)
|
||
deleteKey.addTarget(self, action: #selector(deleteUp), for: [.touchUpInside, .touchUpOutside, .touchCancel])
|
||
addSubview(deleteKey)
|
||
|
||
callout.isUserInteractionEnabled = false
|
||
addSubview(callout)
|
||
tonePicker.isHidden = true
|
||
addSubview(tonePicker)
|
||
applyPalette()
|
||
}
|
||
|
||
@available(*, unavailable)
|
||
required init?(coder: NSCoder) { fatalError() }
|
||
|
||
// MARK: - Content
|
||
|
||
/// Fills the panel: `suggestions` for the row, `frequent` for the grid's first section.
|
||
func show(suggestions: [Int], frequent: [Int]) {
|
||
self.suggestions = suggestions
|
||
suggestionRow.setItems(suggestions.map { (display(for: $0), library.name(of: $0)) })
|
||
var sections = [Section(title: "Frequently used", symbol: "clock", entries: frequent)]
|
||
var byCategory = Array(repeating: [Int](), count: EmojiCategory.allCases.count)
|
||
for (index, entry) in library.entries.enumerated() {
|
||
byCategory[entry.category.rawValue].append(index)
|
||
}
|
||
for category in EmojiCategory.allCases {
|
||
sections.append(Section(title: category.title, symbol: category.symbol, entries: byCategory[category.rawValue]))
|
||
}
|
||
self.sections = sections
|
||
layoutKey = nil
|
||
sectionStarts = []
|
||
grid.reloadData()
|
||
setNeedsLayout()
|
||
}
|
||
|
||
/// The emoji with the skin tone you last picked for it.
|
||
func display(for entry: Int) -> String {
|
||
let item = library.entries[entry]
|
||
let tone = item.hasTones ? usage.tone(for: item.emoji) : 0
|
||
return tone > 0 && tone <= item.tones.count ? item.tones[tone - 1] : item.emoji
|
||
}
|
||
|
||
private func pickSuggestion(_ index: Int) {
|
||
guard index < suggestions.count else { return }
|
||
onKeyDown?()
|
||
let entry = suggestions[index]
|
||
onInsert?(display(for: entry), entry, "suggestion")
|
||
}
|
||
|
||
// MARK: - Layout
|
||
|
||
private var rowFrame: CGRect {
|
||
CGRect(x: horizontalInset, y: metrics.stripTop, width: bounds.width - 2 * horizontalInset, height: metrics.stripHeight)
|
||
}
|
||
|
||
/// The suggestion row's and the search results' emoji size.
|
||
var rowFontSize: CGFloat {
|
||
metrics.keyHeight >= 40 ? 27 : 23
|
||
}
|
||
|
||
private var barKeyHeight: CGFloat {
|
||
metrics.keyHeight >= 40 ? 38 : metrics.keyHeight
|
||
}
|
||
|
||
override func layoutSubviews() {
|
||
super.layoutSubviews()
|
||
let row = rowFrame
|
||
let side = metrics.side
|
||
let buttonSide = min(36, row.height - 8)
|
||
searchButton.frame = CGRect(x: row.minX + side, y: row.midY - buttonSide / 2, width: buttonSide + 4, height: buttonSide)
|
||
searchButton.layer.cornerRadius = 10
|
||
suggestionRow.frame = CGRect(x: searchButton.frame.maxX + 4, y: row.minY, width: row.maxX - side - searchButton.frame.maxX - 4, height: row.height)
|
||
suggestionRow.fontSize = rowFontSize
|
||
|
||
let barY = bounds.height - metrics.keysBottom - barKeyHeight
|
||
let keyWidth = KeyboardLayout.letterWidth(innerWidth: bounds.width - 2 * horizontalInset, metrics: metrics) * KeyboardLayout.bottomSwitchWidthRatio
|
||
lettersKey.frame = CGRect(x: horizontalInset + side, y: barY, width: keyWidth, height: barKeyHeight)
|
||
deleteKey.frame = CGRect(x: bounds.width - horizontalInset - side - keyWidth, y: barY, width: keyWidth, height: barKeyHeight)
|
||
lettersKey.cornerRadius = metrics.cornerRadius
|
||
deleteKey.cornerRadius = metrics.cornerRadius
|
||
categoryBar.frame = CGRect(x: lettersKey.frame.maxX + 4, y: barY, width: deleteKey.frame.minX - lettersKey.frame.maxX - 8, height: barKeyHeight)
|
||
|
||
let gridTop = row.maxY
|
||
let gridFrame = CGRect(x: horizontalInset, y: gridTop, width: bounds.width - 2 * horizontalInset, height: barY - 4 - gridTop)
|
||
grid.frame = gridFrame
|
||
callout.frame = bounds
|
||
tonePicker.frame = bounds
|
||
applyGridLayout(height: gridFrame.height)
|
||
}
|
||
|
||
private func applyGridLayout(height: CGFloat) {
|
||
let isRoomy = metrics.keyHeight >= 40
|
||
let headerHeight: CGFloat = isRoomy ? 20 : 16
|
||
let rows = isRoomy ? 4 : 3
|
||
let rowHeight = max(20, (height - headerHeight) / CGFloat(rows))
|
||
let geometry = GridGeometry(
|
||
rows: rows,
|
||
rowHeight: rowHeight,
|
||
columnWidth: isRoomy ? 42 : 38,
|
||
headerHeight: headerHeight,
|
||
fontSize: isRoomy ? 29 : 23,
|
||
counts: sections.map(\.entries.count)
|
||
)
|
||
guard geometry != layoutKey, height > 0 else { return }
|
||
layoutKey = geometry
|
||
sectionStarts = []
|
||
grid.setCollectionViewLayout(Self.makeLayout(geometry), animated: false)
|
||
}
|
||
|
||
private static func makeLayout(_ g: GridGeometry) -> UICollectionViewCompositionalLayout {
|
||
let config = UICollectionViewCompositionalLayoutConfiguration()
|
||
config.scrollDirection = .horizontal
|
||
config.interSectionSpacing = 8
|
||
let counts = g.counts
|
||
return UICollectionViewCompositionalLayout(sectionProvider: { index, _ in
|
||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
|
||
widthDimension: .fractionalWidth(1),
|
||
heightDimension: .absolute(g.rowHeight)
|
||
))
|
||
let group = NSCollectionLayoutGroup.vertical(
|
||
layoutSize: NSCollectionLayoutSize(
|
||
widthDimension: .absolute(g.columnWidth),
|
||
heightDimension: .absolute(g.rowHeight * CGFloat(g.rows))
|
||
),
|
||
repeatingSubitem: item,
|
||
count: g.rows
|
||
)
|
||
let section = NSCollectionLayoutSection(group: group)
|
||
let count = counts[safe: index] ?? 0
|
||
let columns = max(1, (count + g.rows - 1) / g.rows)
|
||
// Above the section and as wide as it; scrolling keeps its name in view
|
||
// (keepHeadersInView), as a pinned header would.
|
||
let header = NSCollectionLayoutBoundarySupplementaryItem(
|
||
layoutSize: NSCollectionLayoutSize(
|
||
widthDimension: .absolute(CGFloat(columns) * g.columnWidth),
|
||
heightDimension: .absolute(g.headerHeight)
|
||
),
|
||
elementKind: UICollectionView.elementKindSectionHeader,
|
||
alignment: .top
|
||
)
|
||
section.boundarySupplementaryItems = [header]
|
||
// A horizontal layout doesn't move the items below a top header; the inset does,
|
||
// and the header ignores it.
|
||
section.contentInsets = NSDirectionalEdgeInsets(top: g.headerHeight, leading: 2, bottom: 0, trailing: 2)
|
||
section.supplementaryContentInsetsReference = .none
|
||
return section
|
||
}, configuration: config)
|
||
}
|
||
|
||
private func applyPalette() {
|
||
searchButton.backgroundColor = palette.chipFill
|
||
searchButton.tintColor = palette.textMuted
|
||
suggestionRow.palette = palette
|
||
categoryBar.palette = palette
|
||
lettersKey.palette = palette
|
||
deleteKey.palette = palette
|
||
callout.palette = palette
|
||
tonePicker.palette = palette
|
||
grid.reloadData()
|
||
}
|
||
|
||
// MARK: - Grid
|
||
|
||
func numberOfSections(in collectionView: UICollectionView) -> Int {
|
||
sections.count
|
||
}
|
||
|
||
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
|
||
sections[section].entries.count
|
||
}
|
||
|
||
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
|
||
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmojiCell.reuseID, for: indexPath)
|
||
if let cell = cell as? EmojiCell {
|
||
let entry = sections[indexPath.section].entries[indexPath.item]
|
||
cell.configure(
|
||
emoji: display(for: entry),
|
||
name: library.name(of: entry),
|
||
fontSize: layoutKey?.fontSize ?? 29,
|
||
palette: palette
|
||
)
|
||
}
|
||
return cell
|
||
}
|
||
|
||
func collectionView(
|
||
_ collectionView: UICollectionView,
|
||
viewForSupplementaryElementOfKind kind: String,
|
||
at indexPath: IndexPath
|
||
) -> UICollectionReusableView {
|
||
let view = collectionView.dequeueReusableSupplementaryView(
|
||
ofKind: kind,
|
||
withReuseIdentifier: EmojiSectionHeader.reuseID,
|
||
for: indexPath
|
||
)
|
||
if let header = view as? EmojiSectionHeader {
|
||
header.label.text = sections[indexPath.section].title
|
||
header.label.textColor = palette.textMuted
|
||
}
|
||
return view
|
||
}
|
||
|
||
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
|
||
(cell as? EmojiCell)?.clear()
|
||
}
|
||
|
||
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
|
||
onKeyDown?()
|
||
guard showsKeyPopups, let frame = cellFrame(indexPath) else { return }
|
||
let entry = sections[indexPath.section].entries[indexPath.item]
|
||
callout.show(balloon(over: frame), label: display(for: entry))
|
||
}
|
||
|
||
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
|
||
callout.show(nil, label: "")
|
||
}
|
||
|
||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||
collectionView.deselectItem(at: indexPath, animated: false)
|
||
let entry = sections[indexPath.section].entries[indexPath.item]
|
||
onInsert?(display(for: entry), entry, "grid")
|
||
}
|
||
|
||
func scrollViewDidScroll(_ scrollView: UIScrollView) {
|
||
callout.show(nil, label: "")
|
||
if sectionStarts.isEmpty { measureSections() }
|
||
let x = scrollView.contentOffset.x + 24
|
||
let current = sectionStarts.lastIndex { $0 <= x } ?? 0
|
||
categoryBar.selected = current
|
||
keepHeadersInView()
|
||
}
|
||
|
||
func collectionView(
|
||
_ collectionView: UICollectionView,
|
||
willDisplaySupplementaryView view: UICollectionReusableView,
|
||
forElementKind elementKind: String,
|
||
at indexPath: IndexPath
|
||
) {
|
||
keepHeadersInView()
|
||
}
|
||
|
||
/// A section's name stays at the grid's left edge while the section scrolls past, and
|
||
/// the next section's name pushes it out.
|
||
private func keepHeadersInView() {
|
||
let left = grid.contentOffset.x
|
||
for case let header as EmojiSectionHeader in grid.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader) {
|
||
let room = max(0, header.frame.width - header.label.intrinsicContentSize.width - 12)
|
||
header.shift = min(room, max(0, left - header.frame.minX))
|
||
}
|
||
}
|
||
|
||
private func measureSections() {
|
||
sectionStarts = sections.indices.map { section in
|
||
guard !sections[section].entries.isEmpty,
|
||
let attributes = grid.layoutAttributesForItem(at: IndexPath(item: 0, section: section)) else {
|
||
return .greatestFiniteMagnitude
|
||
}
|
||
return attributes.frame.minX
|
||
}
|
||
}
|
||
|
||
private func jump(toSection section: Int) {
|
||
guard section < sections.count else { return }
|
||
onKeyDown?()
|
||
grid.layoutIfNeeded()
|
||
if sectionStarts.isEmpty { measureSections() }
|
||
let start = sectionStarts[section] == .greatestFiniteMagnitude ? 0 : sectionStarts[section]
|
||
let maxX = max(0, grid.contentSize.width - grid.bounds.width)
|
||
grid.setContentOffset(CGPoint(x: min(maxX, max(0, start - 2)), y: 0), animated: false)
|
||
categoryBar.selected = section
|
||
}
|
||
|
||
private func cellFrame(_ indexPath: IndexPath) -> CGRect? {
|
||
guard let attributes = grid.layoutAttributesForItem(at: indexPath) else { return nil }
|
||
return grid.convert(attributes.frame, to: self)
|
||
}
|
||
|
||
private func balloon(over cell: CGRect) -> KeyBalloon {
|
||
let width = cell.width + KeyBalloon.extraWidth
|
||
let x = max(2, min(bounds.width - 2 - width, cell.midX - width / 2))
|
||
let bubble = CGRect(x: x, y: max(0, cell.minY - KeyBalloon.neck - KeyBalloon.bubbleHeight), width: width, height: KeyBalloon.bubbleHeight)
|
||
return KeyBalloon(keyFrame: cell, bubble: bubble)
|
||
}
|
||
|
||
// MARK: - Skin tones
|
||
|
||
@objc private func held(_ gesture: UILongPressGestureRecognizer) {
|
||
let point = gesture.location(in: self)
|
||
switch gesture.state {
|
||
case .began:
|
||
callout.show(nil, label: "")
|
||
guard let indexPath = grid.indexPathForItem(at: gesture.location(in: grid)),
|
||
let frame = cellFrame(indexPath) else { return }
|
||
let entry = sections[indexPath.section].entries[indexPath.item]
|
||
let item = library.entries[entry]
|
||
guard item.hasTones else {
|
||
// Without tones a hold types it, as a tap would.
|
||
onInsert?(display(for: entry), entry, "grid")
|
||
return
|
||
}
|
||
showTones(for: entry, over: frame)
|
||
case .changed:
|
||
guard var menu = tonePicker.menu else { return }
|
||
let index = menu.index(for: point.x)
|
||
if index != menu.selectedIndex {
|
||
menu.selectedIndex = index
|
||
tonePicker.show(menu)
|
||
onSelectionStep?()
|
||
}
|
||
case .ended:
|
||
guard let menu = tonePicker.menu, let entry = toneEntry else { return }
|
||
let chosen = menu.options[menu.index(for: point.x)]
|
||
pickTone(chosen, for: entry)
|
||
default:
|
||
tonePicker.show(nil)
|
||
toneEntry = nil
|
||
}
|
||
}
|
||
|
||
/// Opens the skin tone picker over a cell, the remembered tone selected.
|
||
func showTones(for entry: Int, over frame: CGRect) {
|
||
let item = library.entries[entry]
|
||
var menu = AccentMenu.build(for: frame, rawOptions: [item.emoji] + item.tones, in: bounds.width, horizontalInset: horizontalInset)
|
||
if let index = menu.options.firstIndex(of: display(for: entry)) { menu.selectedIndex = index }
|
||
toneEntry = entry
|
||
tonePicker.show(menu)
|
||
onSelectionStep?()
|
||
}
|
||
|
||
private func pickTone(_ chosen: String, for entry: Int) {
|
||
let item = library.entries[entry]
|
||
let tone = item.tones.firstIndex(of: chosen).map { $0 + 1 } ?? 0
|
||
usage.setTone(tone, for: item.emoji)
|
||
tonePicker.show(nil)
|
||
toneEntry = nil
|
||
onInsert?(chosen, entry, "tone")
|
||
// Every cell showing it takes the new tone.
|
||
grid.reloadData()
|
||
suggestionRow.setItems(suggestions.map { (display(for: $0), library.name(of: $0)) })
|
||
}
|
||
|
||
/// Fixtures: hold an emoji in the grid until its tones open.
|
||
func debugShowTones(for emoji: String, selecting tone: Int) {
|
||
grid.layoutIfNeeded()
|
||
guard let entry = library.entryByEmoji[emoji] else { return }
|
||
for (section, content) in sections.enumerated() {
|
||
guard let item = content.entries.firstIndex(of: entry) else { continue }
|
||
let indexPath = IndexPath(item: item, section: section)
|
||
if cellFrame(indexPath).map({ !grid.frame.contains(CGPoint(x: $0.midX, y: $0.midY)) }) ?? true {
|
||
grid.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
|
||
grid.layoutIfNeeded()
|
||
}
|
||
guard let frame = cellFrame(indexPath) else { return }
|
||
showTones(for: entry, over: frame)
|
||
if var menu = tonePicker.menu, let index = menu.options.firstIndex(of: library.entries[entry].tones[tone - 1]) {
|
||
menu.selectedIndex = index
|
||
tonePicker.show(menu)
|
||
}
|
||
return
|
||
}
|
||
}
|
||
|
||
/// Fixtures and probes: the section the grid shows first.
|
||
func debugJump(toSection section: Int) {
|
||
jump(toSection: section)
|
||
}
|
||
|
||
// MARK: - Keys
|
||
|
||
@objc private func searchTapped() {
|
||
onKeyDown?()
|
||
onSearch?()
|
||
}
|
||
|
||
@objc private func lettersTapped() {
|
||
onKeyDown?()
|
||
onLetters?()
|
||
}
|
||
|
||
@objc private func deleteDown() {
|
||
onKeyDown?()
|
||
onDelete?()
|
||
deleteTimer?.invalidate()
|
||
deleteStartedAt = CACurrentMediaTime()
|
||
let timer = Timer(timeInterval: FullKeyboardEngine.repeatInterval, repeats: true) { [weak self] _ in
|
||
MainActor.assumeIsolated {
|
||
guard let self else { return }
|
||
let held = CACurrentMediaTime() - self.deleteStartedAt
|
||
guard held >= FullKeyboardEngine.repeatDelay else { return }
|
||
self.onDeleteRepeat?(held)
|
||
self.onKeyDown?()
|
||
}
|
||
}
|
||
RunLoop.main.add(timer, forMode: .common)
|
||
deleteTimer = timer
|
||
}
|
||
|
||
@objc private func deleteUp() {
|
||
deleteTimer?.invalidate()
|
||
deleteTimer = nil
|
||
}
|
||
|
||
func tearDown() {
|
||
deleteUp()
|
||
tonePicker.show(nil)
|
||
callout.show(nil, label: "")
|
||
}
|
||
}
|
||
|
||
private extension Array {
|
||
subscript(safe index: Int) -> Element? {
|
||
indices.contains(index) ? self[index] : nil
|
||
}
|
||
}
|