hex/ios/HEXShared/FullKeyboard/KeyboardStripView.swift
Ryan Vogel 52b9e475a6
iOS: the full keyboard's top bar matches the system keyboard (#2135)
* iOS: the full keyboard's top bar matches Apple's predictive bar

Kit's App Store screenshot (dark mode) showed the suggestions sitting low
with a large empty band between the keyboard panel's top edge and the
words. Measured black-box against Apple's English keyboard in the same
Messages field (iOS 27.2 simulator, iPhone 17 Pro, SE 3rd gen, 17 Pro
Max): iOS 26 draws a band of its own above every third-party keyboard
(16.3 pt on the 17 Pro, 12.5 pt on the SE, 13.3 pt on the Pro Max) that
no extension can draw into (checked with a throwaway build drawing at
negative y: the hosted window is exactly the keyboard's height). Hex
then added Apple's whole 44 pt bar and 8 pt gap below it, so its keycaps
started 68 pt below the panel edge where Apple's start 48-52 pt, and its
words sat 38 pt down where Apple's sit 20-24 pt.

What changed:
- The phone strip is the 27 pt of Apple's bar below iOS's band, then the
  same 8 pt gap: row 1 starts 35 pt down (Apple's keycaps are 35.0-35.5 pt
  below the extension's top on all three iPhones), so the panel edge to
  row 1 now measures 51.3 pt against Apple's 51.7 pt on the 17 Pro. The
  keyboard is 253 pt (172 pt landscape) instead of 270 (189); keys do not
  move on screen, only the panel's top edge comes down 17 pt. The Duo
  keeps its 44 pt bar (KeyboardMetrics.insetStripHeight).
- Slots are thirds of the keyboard as Apple's are (dividers end at 134
  and 268 pt on a 402 pt iPhone), with the Hex key's room taken from the
  slot beside it (KeyboardLayout.stripSlotFrames), instead of thirds of
  the strip left of the Hex key. Typing logs record the real slot frames.
- Dividers are Apple's 1 x 24 pt (were 1 px x 22 pt), ending on the
  boundary, in Apple's measured ink.
- Words are Apple's muted ink (dark 0.58 white, light 0.67 black) instead
  of full white/black; the literal word no longer has its own alpha.
- A pending autocorrection is Apple's full-slot capsule with white words
  in regular weight (was a 10 pt-radius pill inset 4 pt, medium weight).
  The capsule is 26 pt tall, not Apple's 38 pt: Apple's top 11 pt falls
  in iOS's band.
- The Hex key, recording bar (Dot Scope well, X and check) and Undo /
  Paste chips use the strip's pill height (26 pt, 4 pt-inset 36 pt on the
  Duo); the Hex mark keeps its 19 pt. The Full Access hint's two lines
  fit 27 pt (13 / 11.5 pt).
- #2100's rule is unchanged: a fast tap on the strip's lower half (below
  its text line, now 13.5 pt down) types the row-1 key below; its tests
  pass as written.

Kept on purpose: words are centred in the 27 pt Hex can draw, about
5.5 pt lower than Apple's relative to the panel edge, so the pill has
room around them; Apple lets long words run past their slot at 17 pt,
Hex still shrinks them to 15 pt and truncates, so nothing runs under
the Hex key. Which suggestions appear (#2125) is untouched.

Verified: xcodebuild test on the iPhone 17 Pro Max simulator, 383 tests,
0 failures, 1 skipped, with updated KeyboardLayoutTests (heights, strip
metrics, row 1 at 35 pt) and a new case for Apple's thirds with the Hex
key on either side. Side-by-side screenshots of Apple's keyboard and
Hex in Messages (empty, typing, literal in quotes, pending correction,
long word, next word) on the 17 Pro and SE in light and dark, and the
recording bar, Full Access hint and Hex key on the left before and after.

* iOS: the top bar's light-mode autocorrection pill matches Apple's

The first pass guessed an opaque white capsule with black words for a
pending autocorrection in light mode. Apple's, measured in Messages on the
iPhone 17 Pro (iOS 27.2 simulator), is a faint white tint, (235,237,240)
on the (226,227,232) platter, under near-black (44,46,49) words; dark mode
was already measured and is unchanged.

Verified: rebuilt and compared the pending-correction state against
Apple's keyboard in the same field in light mode; xcodebuild test.

* iOS: the top bar offers three words in an empty field and between words

Ryan's screenshot of the current build in an empty field (dark mode, shift
on) showed an empty bar with two dividers and nothing in the slots, where
Apple's keyboard shows three sentence starters (I | The | I'm). After a
word, Hex often showed one prediction in the middle with empty slots
beside it, where Apple's fills all three.

- An empty field, and a new sentence (after ". ", "! ", "? " or a new
  line), offers three common first words from a short hand-written list
  per language (the typing model has no start-of-sentence row): English
  I / The / I'm, Spanish Yo / El / La, and so on for every layout,
  Ukrainian included. They take a capital when shift would turn itself on
  (never with Auto-capitalization off; "I" and "I'm" keep theirs), pass
  never-suggest, and are tap-only like #2125's predictions.
- After a word and a space, the model's next words keep #2125's ranking
  for the slots they fill; when it has fewer than three, the language's
  commonest words fill the rest, so no slot stays empty.
- After a comma (or ; : ) ” ’ —) and a space, three words that start a
  clause (English I / but / and). After a handle, a path, a number or a
  second space the bar stays empty, as #2125 had it.
- With Emoji (on by default since #2129) a finished word's emoji no longer
  replaces the predictions: one emoji takes the centre with next words on
  either side ("pizza ": and | 🍕 | hut); two or three fill from the left.
- Picking a starter in an empty field or after a new line inserts it (the
  queued-tap guard now checks that no word was started, not that the text
  ends in a space).

Verified: xcodebuild test on the iPhone 17 Pro simulator (411 tests,
0 failures, 1 skipped), with a new FullKeyboardEngineTests case for the
starters, capitals, the fill and the comma, and #2125's boundary test
updated for ". " and a new line. Held-out tap benchmark (2,000 English
and 2,000 Spanish test sentences, Spatial autocorrect, freshly erased
simulators): finished text is unchanged within the benchmark's own noise
(two runs of the same build differ in 21 English and 32 Spanish sentences,
from the system spell checker); English words broken 528 and 529 before,
528 after, fixed 3,147/3,148 before, 3,147 after; Spanish broken 419/416
before, 417 after, fixed 3,744 before, 3,745 after. Side-by-side shots
against Apple's keyboard in Messages: empty field, after ". ", after
"hi ", after a comma, light and dark, iPhone 17 Pro, SE and 17 Pro Max.

* iOS: the top bar matches Apple's in landscape and on the Duo's cover screen

The 27 pt strip assumed the band iOS draws above a third-party keyboard,
which the iPhone has in portrait. Measured against Apple's keyboard
(iOS 27.2 simulator):

- Landscape (iPhone 17 Pro Max): iOS draws no band, and Apple's keycaps
  start 50 pt below the panel's edge where Hex's started 35 pt down. The
  landscape strip is now 42 pt plus the 8 pt gap (row 1 at 50 pt, keyboard
  187 pt, was 172 pt).
- The Duo folded and upright: the band is 8.7 pt and Apple's keycaps start
  48.7 pt below the edge where Hex's started 52.7 pt down (its 44 pt bar
  sat right on the keys). It is now 32 pt plus the 8 pt gap, so the panel
  edge to row 1 measures 48.7 pt for both. The unfolded postures and the
  cover in landscape keep the 44 pt bar (not measured against the band).
- Pills (an autocorrection, a pressed word, the Hex key, the recording
  bar) are the strip less half a point above and below, at most 36 pt.

Keys do not move on screen; only the panel's top edge does. iPhone
portrait keeps the 27 + 8 pt contract (51.3 pt panel edge to row 1 on
the 17 Pro against Apple's 51.7; 48.67 pt on the 17 Pro Max, the same as
Apple's).

Verified: KeyboardLayoutTests updated for the new heights and metrics;
xcodebuild test (411 tests, 0 failures, 1 skipped); screenshots of the
hosted keyboard next to Apple's in landscape and on the Duo's cover.

* iOS: top-bar dividers, Logging mark and micro-animations follow Apple's

Measured on Apple's keyboard in the iOS 27.2 simulator, recorded at
60 fps with simctl io recordVideo and timed frame by frame:

- A changed word swaps letter by letter: letters the old and new word
  start with stay, the old word's other letters fade from its end and the
  new word's from its start, each in 0.1 s, staggered over 0.2 s (Apple:
  0.14-0.23 s). A word leaving an emptied slot fades the same way. The
  pending-correction capsule and the dividers change at once, as Apple's
  do, and so does a pressed word's capsule on touch down and release.
  Reduce Motion swaps at once. Before, every change was an instant redraw.
- A pressed word gets the same capsule as a pending correction (Apple's
  measured identical: (115,115,115) dark, (235,237,240) light), not a
  lighter one.
- The Undo dictation, Paste and Code from Messages chips and the Full
  Access hint fade in and out over the same 0.2 s instead of popping.
- Dividers are drawn only between two filled slots, so a bar with
  nothing to show (a URL or email field, or a lone "Kq") has none, as
  Apple's has none in secure fields. Apple does draw them beside empty
  slots in URL fields and for a lone literal; Hex doesn't, by request.
- The Logging mark (Record typing logs) sat at the strip's top corner,
  over slot 1's word since the strip became 27 pt ("Logging" overlapped
  "ritsrdo" in the Italian scene). It now sits on the text line at the
  outer end, and that slot centres its word in the room left.

Verified: xcodebuild test (411 tests, 0 failures, 1 skipped); recordings
of Apple's bar and Hex's on the iPhone SE simulator (typing "hello", a
pending correction, a held and released pick, the Paste chip), and
before/after snapshot scenes for the Logging mark on either side.
2026-11-21 03:26:34 +00:00

682 lines
31 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 3-slot top bar above the keys, drawn as Apple's iOS 26 predictive bar is (measured in
/// the iOS 27.2 simulator): SF 17 pt regular in muted ink, slots a third of the keyboard wide,
/// 1 × 24 pt dividers ending on the thirds, and a pending autocorrection as a full-slot
/// capsule with the divider beside it hidden. iOS's band above the keyboard takes the top of
/// Apple's bar, so everything here is centred in the 27 pt below it. The centred
/// `Undo dictation` chip or a status message replaces the slots when needed.
@MainActor
final class KeyboardStripView: UIView {
var palette = FullKeyboardPalette(isDark: false) { didSet { if palette != oldValue { applyPalette() } } }
/// Hosted in iOS's platter (not a snapshot scene's own backdrop).
var inSystemPlatter = true {
didSet {
guard inSystemPlatter != oldValue else { return }
for button in slotButtons { button.inSystemPlatter = inSystemPlatter }
setNeedsLayout()
setNeedsDisplay()
}
}
/// Each slot's frame in this view, from `KeyboardLayout.stripSlotFrames`; thirds of the
/// view until the keyboard lays it out.
var slotFrames: [CGRect]? { didSet { if slotFrames != oldValue { setNeedsLayout(); setNeedsDisplay() } } }
/// How far the pills sit in from the strip's top and bottom (`KeyboardMetrics.stripInset`).
var pillInset: CGFloat = 0.5 {
didSet {
guard pillInset != oldValue else { return }
for button in slotButtons { button.pillInset = pillInset }
setNeedsLayout()
}
}
var onSelectSuggestion: ((KeyboardSuggestion) -> Void)?
var onUndoDictation: (() -> Void)?
var onPaste: (() -> Void)?
var onNextKeyboard: (() -> Void)?
/// The Full Access hint's Open Hex was tapped (it opens Hex's setup).
var onOpenHexFromHint: (() -> Void)?
private let statusLabel = UILabel()
private let undoChip = UIButton(type: .custom)
private let slotButtons: [SlotButton] = [SlotButton(), SlotButton(), SlotButton()]
private var currentSuggestions: [KeyboardSuggestion] = []
private var showsUndo = false
private var statusText: String?
private var clipboard: KeyboardClipboardOffer?
private var showsFullAccessHint = false
/// Built the first time the Hex key is tapped without Full Access.
private var fullAccessHintView: FullAccessHintView?
/// The Hex key sits left of the strip (Settings › Keyboard › Hex key): the Full Access
/// hint's Open Hex leads, beside the key, and the Logging mark moves to the far corner.
var hexOnLeading = false {
didSet {
guard hexOnLeading != oldValue else { return }
fullAccessHintView?.chipLeads = hexOnLeading
setNeedsLayout()
}
}
/// Record typing logs is recording: a small mark in the strip's corner away from the Hex key.
var showsLoggingMark = false {
didSet {
guard showsLoggingMark != oldValue else { return }
if showsLoggingMark, loggingMark == nil {
let mark = TypingLogMarkView()
mark.textColor = palette.textMuted
addSubview(mark)
loggingMark = mark
}
loggingMark?.isHidden = !showsLoggingMark
setNeedsLayout()
}
}
private var loggingMark: TypingLogMarkView?
/// A plain chip: `UIPasteControl` renders as an empty blue box inside a keyboard
/// extension (TestFlight build 4), so this reads the clipboard on tap instead, once, which
/// iOS asks about until Paste from Other Apps is Allow (`KeyboardClipboardTracker`).
private let pasteControl = UIButton(type: .custom)
private let nextKeyboardChip = UIButton(type: .custom)
override init(frame: CGRect) {
super.init(frame: frame)
isOpaque = false
backgroundColor = .clear
contentMode = .redraw
statusLabel.font = .systemFont(ofSize: 13.5)
statusLabel.textAlignment = .center
statusLabel.adjustsFontSizeToFitWidth = true
statusLabel.minimumScaleFactor = 0.8
statusLabel.isHidden = true
addSubview(statusLabel)
var chip = UIButton.Configuration.plain()
chip.image = UIImage(
systemName: "arrow.uturn.backward",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 12.5, weight: .medium)
)
chip.imagePadding = 6
chip.title = "Undo dictation"
chip.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 13, bottom: 0, trailing: 13)
chip.background.cornerRadius = 15
undoChip.configuration = chip
undoChip.isHidden = true
undoChip.addTarget(self, action: #selector(handleUndo), for: .touchUpInside)
var paste = UIButton.Configuration.plain()
paste.image = UIImage(
systemName: "doc.on.clipboard",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 12.5, weight: .medium)
)
paste.imagePadding = 6
paste.title = "Paste"
paste.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 13, bottom: 0, trailing: 13)
paste.background.cornerRadius = 15
pasteControl.configuration = paste
pasteControl.isHidden = true
pasteControl.addTarget(self, action: #selector(handlePaste), for: .touchUpInside)
addSubview(pasteControl)
addSubview(undoChip)
var next = UIButton.Configuration.plain()
next.image = UIImage(
systemName: "keyboard",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 12.5, weight: .medium)
)
next.imagePadding = 6
next.title = "Code from Messages"
next.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 13, bottom: 0, trailing: 13)
next.background.cornerRadius = 15
nextKeyboardChip.configuration = next
nextKeyboardChip.accessibilityHint = "Switches to the next keyboard, where iOS offers codes from Messages and Mail"
nextKeyboardChip.isHidden = true
nextKeyboardChip.addTarget(self, action: #selector(handleNextKeyboard), for: .touchUpInside)
addSubview(nextKeyboardChip)
for (index, button) in slotButtons.enumerated() {
button.tag = index
button.addTarget(self, action: #selector(handleSlotTap(_:)), for: .touchUpInside)
addSubview(button)
}
applyPalette()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError() }
/// `fullAccessHint`, while true, replaces everything else in the strip with what
/// dictation needs (`FullAccessHintView`).
func update(
suggestions: [KeyboardSuggestion],
showsUndo: Bool,
statusText: String?,
clipboard: KeyboardClipboardOffer? = nil,
fullAccessHint: Bool = false
) {
let changed = suggestions != currentSuggestions || showsUndo != self.showsUndo
|| statusText != self.statusText || clipboard != self.clipboard
|| fullAccessHint != showsFullAccessHint
guard changed else { return }
currentSuggestions = suggestions
self.showsUndo = showsUndo
self.statusText = statusText
self.clipboard = clipboard
showsFullAccessHint = fullAccessHint
if fullAccessHint, fullAccessHintView == nil { _ = makeFullAccessHintView() }
if let hint = fullAccessHintView { show(hint, fullAccessHint) }
let showsHint = fullAccessHint
show(undoChip, showsUndo && !showsHint)
let showsClipboard = showsClipboard
show(pasteControl, showsClipboard && clipboard != .code(canPaste: false))
show(nextKeyboardChip, showsClipboard && clipboard != .paste)
// Words swap letter by letter (and leave the same way when a chip or status takes the
// strip); the strip being shown for the first time just draws them.
let animated = window != nil
if showsHint || showsUndo || showsClipboard {
statusLabel.isHidden = true
slotButtons.forEach { $0.configure(with: nil, palette: palette, animated: animated) }
} else if let statusText, suggestions.isEmpty {
statusLabel.text = statusText
statusLabel.isHidden = false
slotButtons.forEach { $0.configure(with: nil, palette: palette, animated: false) }
} else {
statusLabel.isHidden = true
let slots = Self.slots(for: suggestions)
for (idx, button) in slotButtons.enumerated() {
let item = slots.firstIndex(of: idx).map { suggestions[$0] }
button.configure(with: item, palette: palette, animated: animated)
}
}
setNeedsLayout()
setNeedsDisplay()
}
/// Shows or hides a chip, fading it over Apple's 0.2 s word swap (at once with Reduce Motion).
private func show(_ view: UIView, _ shown: Bool) {
let visible = !view.isHidden && view.alpha > 0
guard shown != visible || (shown && view.alpha < 1) else { return }
guard window != nil, !UIAccessibility.isReduceMotionEnabled else {
view.layer.removeAllAnimations()
view.alpha = 1
view.isHidden = !shown
return
}
if shown {
if view.isHidden { view.alpha = 0 }
view.isHidden = false
}
UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction, .curveEaseOut]) {
view.alpha = shown ? 1 : 0
} completion: { _ in
guard view.alpha == 0 else { return }
view.isHidden = true
view.alpha = 1
}
}
/// Which slot shows each suggestion: in order, except a lone emoji, swiped word or reading
/// of one, which takes the centre.
static func slots(for suggestions: [KeyboardSuggestion]) -> [Int] {
if suggestions.count == 1, suggestions[0].kind != .keepLiteral, suggestions[0].kind != .secondary { return [1] }
return Array(suggestions.indices.prefix(3))
}
/// Clipboard chips replace the empty strip; suggestions and status win.
private var showsClipboard: Bool {
guard let clipboard, !showsUndo, statusText == nil, !showsFullAccessHint else { return false }
if case .code = clipboard { return true }
return currentSuggestions.isEmpty
}
@objc private func handlePaste() {
onPaste?()
}
@objc private func handleNextKeyboard() {
onNextKeyboard?()
}
private func makeFullAccessHintView() -> FullAccessHintView {
let hint = FullAccessHintView()
hint.chipLeads = hexOnLeading
hint.onOpenHex = { [weak self] in self?.onOpenHexFromHint?() }
hint.isHidden = true
addSubview(hint)
fullAccessHintView = hint
applyPalette()
setNeedsLayout()
return hint
}
private func applyPalette() {
statusLabel.textColor = palette.textMuted
var paste = pasteControl.configuration
paste?.baseForegroundColor = palette.textBase
paste?.background.backgroundColor = palette.chipFill
pasteControl.configuration = paste
var next = nextKeyboardChip.configuration
next?.baseForegroundColor = palette.textMuted
next?.background.backgroundColor = palette.chipFill
nextKeyboardChip.configuration = next
var chip = undoChip.configuration
chip?.baseForegroundColor = palette.textMuted
chip?.background.backgroundColor = palette.chipFill
undoChip.configuration = chip
fullAccessHintView?.palette = palette
loggingMark?.textColor = palette.textMuted
for (item, slot) in Self.slots(for: currentSuggestions).enumerated() {
slotButtons[slot].configure(with: currentSuggestions[item], palette: palette, animated: false)
}
setNeedsDisplay()
}
private var contentCenterY: CGFloat {
bounds.height * 0.5
}
override func layoutSubviews() {
super.layoutSubviews()
let midY = contentCenterY
statusLabel.frame = CGRect(x: 16, y: max(0, midY - 12), width: max(0, bounds.width - 32), height: 24)
let chipH = min(34, max(24, bounds.height - 2 * pillInset))
let chipSize = undoChip.sizeThatFits(CGSize(width: bounds.width, height: chipH))
undoChip.frame = CGRect(
x: (bounds.width - chipSize.width) / 2,
y: max(0, midY - chipH / 2),
width: chipSize.width,
height: chipH
)
let pasteW = pasteControl.sizeThatFits(CGSize(width: bounds.width, height: chipH)).width
let nextSize = nextKeyboardChip.sizeThatFits(CGSize(width: bounds.width, height: chipH))
// Laid out for what is shown, not what is still fading out.
let pasteShown = showsClipboard && clipboard != .code(canPaste: false)
let nextShown = showsClipboard && clipboard != .paste
let pair = pasteShown && nextShown
let gap: CGFloat = 8
let total = pair ? pasteW + gap + nextSize.width : (pasteShown ? pasteW : nextSize.width)
let startX = (bounds.width - total) / 2
let chipY = max(0, midY - chipH / 2)
pasteControl.frame = CGRect(x: startX, y: chipY, width: pasteW, height: chipH)
nextKeyboardChip.frame = CGRect(
x: pair ? startX + pasteW + gap : startX,
y: chipY,
width: nextSize.width,
height: chipH
)
var hintFrame = bounds.insetBy(dx: 12, dy: 0)
var markRoom: CGFloat = 0
if let loggingMark, showsLoggingMark {
// On the text line at the outer slot's end, in from the keyboard's rounded corner;
// that slot centres its word in the rest, so a long word never runs under it.
let size = loggingMark.sizeThatFits(bounds.size)
let markX = hexOnLeading ? bounds.width - 12 - size.width : 12
loggingMark.frame = CGRect(x: markX, y: (midY - size.height / 2).rounded(), width: size.width, height: size.height)
markRoom = 12 + size.width + 4
bringSubviewToFront(loggingMark)
hintFrame = hexOnLeading
? CGRect(x: 12, y: 0, width: max(0, loggingMark.frame.minX - 8 - 12), height: bounds.height)
: CGRect(x: loggingMark.frame.maxX + 8, y: 0, width: max(0, bounds.width - loggingMark.frame.maxX - 20), height: bounds.height)
}
fullAccessHintView?.frame = hintFrame
fullAccessHintView?.chipHeight = chipH
let slots = currentSlotFrames
for (idx, button) in slotButtons.enumerated() {
button.inSystemPlatter = inSystemPlatter
button.frame = slots[idx]
button.leadingRoom = !hexOnLeading && idx == 0 ? markRoom : 0
button.trailingRoom = hexOnLeading && idx == 2 ? markRoom : 0
}
}
private var currentSlotFrames: [CGRect] {
if let slotFrames, slotFrames.count == 3 { return slotFrames }
let slotW = bounds.width / 3
return (0..<3).map { CGRect(x: CGFloat($0) * slotW, y: 0, width: slotW, height: bounds.height) }
}
override func draw(_ rect: CGRect) {
guard !showsUndo, !showsClipboard, !showsFullAccessHint, statusLabel.isHidden, bounds.width > 60 else { return }
// Hide the divider adjacent to a highlighted primary pill, matching Apple's strip.
let primaryHighlighted = currentSuggestions.count > 1 && currentSuggestions[1].willAutoReplace
guard !primaryHighlighted else { return }
// Apple's dividers: 1 pt wide, ending on the slot boundary, 24 pt tall on the text's centre.
let lineH: CGFloat = min(24, bounds.height - 2)
let y = contentCenterY - lineH / 2
palette.stripDivider.setFill()
// Only between two filled slots: nothing to show, no dividers (as Apple's bar in a
// field it offers nothing for).
let filled = Set(Self.slots(for: currentSuggestions))
for (index, slot) in currentSlotFrames.prefix(2).enumerated()
where slot.maxX < bounds.width - 1 && filled.contains(index) && filled.contains(index + 1) {
UIRectFill(CGRect(x: slot.maxX - 1, y: y, width: 1, height: lineH))
}
}
@objc private func handleUndo() {
onUndoDictation?()
}
@objc private func handleSlotTap(_ sender: SlotButton) {
guard let item = Self.slots(for: currentSuggestions).firstIndex(of: sender.tag) else { return }
onSelectSuggestion?(currentSuggestions[item])
}
/// One suggestion slot. A word that changes swaps letter by letter, as Apple's bar does
/// (iOS 27.2, recorded at 60 fps): the letters both words share stay, the old word's other
/// letters fade from its end and the new word's from its start, each in 0.1 s, staggered
/// over 0.2 s. The capsule and dividers change at once. Reduce Motion swaps at once.
private final class SlotButton: UIControl {
var inSystemPlatter = true { didSet { if inSystemPlatter != oldValue { setNeedsDisplay() } } }
var pillInset: CGFloat = 0.5 { didSet { if pillInset != oldValue { setNeedsDisplay() } } }
/// Room the Logging mark takes at the slot's outer end: the word centres in the rest.
var leadingRoom: CGFloat = 0 { didSet { if leadingRoom != oldValue { setNeedsDisplay() } } }
var trailingRoom: CGFloat = 0 { didSet { if trailingRoom != oldValue { setNeedsDisplay() } } }
private var suggestion: KeyboardSuggestion?
private var palette = FullKeyboardPalette(isDark: false)
/// The word leaving while its letters fade, and when the swap began.
private var outgoing: KeyboardSuggestion?
private var swapStart: CFTimeInterval = 0
private var displayLink: CADisplayLink?
static let letterFade: CFTimeInterval = 0.1
static let swapLength: CFTimeInterval = 0.2
static let maxStagger: CFTimeInterval = 0.025
override init(frame: CGRect) {
super.init(frame: frame)
isOpaque = false
backgroundColor = .clear
contentMode = .redraw
isAccessibilityElement = false
isUserInteractionEnabled = false
accessibilityTraits = .button
addTarget(self, action: #selector(redraw), for: [.touchDown, .touchDragEnter, .touchDragExit, .touchCancel, .touchUpInside, .touchUpOutside])
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError() }
override var isHighlighted: Bool { didSet { if isHighlighted != oldValue { setNeedsDisplay() } } }
/// nil empties the slot (its word fades out when animated).
func configure(with suggestion: KeyboardSuggestion?, palette: FullKeyboardPalette, animated: Bool) {
let old = self.suggestion
self.suggestion = suggestion
self.palette = palette
isAccessibilityElement = suggestion != nil
isUserInteractionEnabled = suggestion != nil
accessibilityLabel = suggestion?.displayText
if old?.displayText != suggestion?.displayText {
if animated, window != nil, !UIAccessibility.isReduceMotionEnabled {
outgoing = old
swapStart = CACurrentMediaTime()
startTicking()
} else {
endSwap()
}
}
setNeedsDisplay()
}
override func didMoveToWindow() {
super.didMoveToWindow()
if window == nil { endSwap() }
}
private func startTicking() {
guard displayLink == nil else { return }
let link = CADisplayLink(target: self, selector: #selector(tick))
link.add(to: .main, forMode: .common)
displayLink = link
}
private func endSwap() {
outgoing = nil
displayLink?.invalidate()
displayLink = nil
}
@objc private func tick() {
if CACurrentMediaTime() - swapStart >= Self.swapLength { endSwap() }
setNeedsDisplay()
}
@objc private func redraw() { setNeedsDisplay() }
private struct Word {
let text: String
let attributes: [NSAttributedString.Key: Any]
let origin: CGPoint
/// Drawn in a box with a truncating tail (too long for the slot): never swapped by letter.
let truncatedRect: CGRect?
}
private func layout(_ suggestion: KeyboardSuggestion, ink: UIColor) -> Word {
let midY = bounds.height * 0.5
// Apple's words are all SF 17 pt regular, the one in the capsule included.
let font = UIFont.systemFont(ofSize: suggestion.kind == .emoji ? 22 : 17, weight: .regular)
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: ink]
// The word centres in the slot, less any room the Logging mark takes.
let textMidX = (leadingRoom + bounds.width - trailingRoom) / 2
let maxTextW = max(20, min(bounds.width - 12, bounds.width - leadingRoom - trailingRoom - 8))
let text = suggestion.displayText
let size = (text as NSString).size(withAttributes: attributes)
guard size.width > maxTextW else {
let origin = CGPoint(x: textMidX - size.width / 2, y: midY - size.height / 2)
return Word(text: text, attributes: attributes, origin: origin, truncatedRect: nil)
}
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byTruncatingTail
style.alignment = .center
let small: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 15, weight: .regular), .foregroundColor: ink, .paragraphStyle: style,
]
let smallSize = (text as NSString).size(withAttributes: small)
let width = min(maxTextW, smallSize.width)
let box = CGRect(x: textMidX - width / 2, y: midY - smallSize.height / 2, width: width, height: smallSize.height)
return Word(text: text, attributes: small, origin: box.origin, truncatedRect: box)
}
/// Draws the word with each letter's opacity from alpha (1 is the ink's own).
private func draw(_ word: Word, alpha: (Int) -> CGFloat) {
let ink = word.attributes[.foregroundColor] as? UIColor ?? .label
if let box = word.truncatedRect {
var attributes = word.attributes
attributes[.foregroundColor] = ink.withAlphaComponent(ink.cgColor.alpha * max(0, alpha(0)))
(word.text as NSString).draw(in: box, withAttributes: attributes)
return
}
let string = NSMutableAttributedString(string: word.text, attributes: word.attributes)
var offset = 0
for (index, character) in word.text.enumerated() {
let length = String(character).utf16.count
let a = alpha(index)
if a < 1 {
let faded = ink.withAlphaComponent(ink.cgColor.alpha * max(0, a))
string.addAttribute(.foregroundColor, value: faded, range: NSRange(location: offset, length: length))
}
offset += length
}
string.draw(at: word.origin)
}
private static func progress(_ t: CFTimeInterval, start: CFTimeInterval) -> CGFloat {
let x = min(1, max(0, (t - start) / letterFade))
return CGFloat(x * x * (3 - 2 * x))
}
override func draw(_ rect: CGRect) {
let midY = bounds.height * 0.5
let pilled = suggestion != nil && (isHighlighted || suggestion?.willAutoReplace == true)
if pilled {
// Like Apple's, the highlight is a capsule as wide as its slot.
let pillH = max(22, bounds.height - 2 * pillInset)
let pill = CGRect(x: 0, y: max(0.5, midY - pillH / 2), width: bounds.width, height: pillH)
(isHighlighted ? palette.stripPillPressedFill : palette.stripPillFill).setFill()
UIBezierPath(roundedRect: pill, cornerRadius: pillH / 2).fill()
}
let ink = pilled ? palette.stripPillText : palette.stripText
let incoming = suggestion.map { layout($0, ink: ink) }
guard var leaving = outgoing.map({ layout($0, ink: ink) }) else {
if let incoming { draw(incoming) { _ in 1 } }
return
}
let t = CACurrentMediaTime() - swapStart
let oldLetters = Array(leaving.text)
let newLetters = Array(incoming?.text ?? "")
let byLetter = leaving.truncatedRect == nil && incoming?.truncatedRect == nil
// Letters both words start with stay put (drawn once, in the new word).
var shared = 0
if byLetter, incoming != nil {
while shared < min(oldLetters.count, newLetters.count), oldLetters[shared] == newLetters[shared] {
shared += 1
}
}
if shared > 0, let incoming {
// The old ending continues from the shared letters, so it never jumps aside.
leaving = Word(text: leaving.text, attributes: leaving.attributes, origin: incoming.origin, truncatedRect: nil)
}
let changing = max(oldLetters.count, newLetters.count) - shared
let stagger = changing > 1 ? min(Self.maxStagger, (Self.swapLength - Self.letterFade) / Double(changing - 1)) : 0
draw(leaving) { index in
guard index >= shared else { return 0 }
guard byLetter else { return 1 - Self.progress(t, start: 0) }
return 1 - Self.progress(t, start: Double(oldLetters.count - 1 - index) * stagger)
}
if let incoming {
draw(incoming) { index in
guard index >= shared else { return 1 }
guard byLetter else { return Self.progress(t, start: 0) }
return Self.progress(t, start: Double(index - shared) * stagger)
}
}
}
}
}
/// What the Hex key shows without Full Access: dictation needs Allow Full Access, where to
/// turn it on, and an Open Hex chip, the only part that opens Hex, on the Hex key's side.
@MainActor
final class FullAccessHintView: UIView {
static let title = "Allow Full Access to dictate"
static let path = "Settings › Apps › Hex › Keyboards"
var palette = FullKeyboardPalette(isDark: false) { didSet { applyPalette() } }
var chipHeight: CGFloat = 30 { didSet { setNeedsLayout() } }
/// The Hex key is on the left: Open Hex sits at the leading end, the text after it.
var chipLeads = false { didSet { if chipLeads != oldValue { setNeedsLayout() } } }
var onOpenHex: (() -> Void)?
private let titleLabel = UILabel()
private let pathLabel = UILabel()
private let openButton = UIButton(type: .custom)
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
titleLabel.text = Self.title
titleLabel.font = .systemFont(ofSize: 13, weight: .medium)
pathLabel.text = Self.path
pathLabel.font = .systemFont(ofSize: 11.5)
pathLabel.accessibilityLabel = "Settings, Apps, Hex, Keyboards"
for label in [titleLabel, pathLabel] {
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.8
label.lineBreakMode = .byTruncatingTail
addSubview(label)
}
var open = UIButton.Configuration.plain()
open.title = "Open Hex"
open.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 13, bottom: 0, trailing: 13)
open.background.cornerRadius = 15
openButton.configuration = open
openButton.accessibilityHint = "Opens Hex's setup"
openButton.addTarget(self, action: #selector(handleOpen), for: .touchUpInside)
addSubview(openButton)
applyPalette()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError() }
@objc private func handleOpen() {
onOpenHex?()
}
private func applyPalette() {
titleLabel.textColor = palette.textBase
pathLabel.textColor = palette.textMuted
var open = openButton.configuration
open?.baseForegroundColor = palette.textBase
open?.background.backgroundColor = palette.chipFill
openButton.configuration = open
}
override func layoutSubviews() {
super.layoutSubviews()
let buttonWidth = openButton.sizeThatFits(CGSize(width: bounds.width, height: chipHeight)).width
openButton.frame = CGRect(
x: chipLeads ? 0 : bounds.width - buttonWidth,
y: (bounds.height - chipHeight) / 2,
width: buttonWidth,
height: chipHeight
)
let textX = chipLeads ? openButton.frame.maxX + 10 : 0
let textWidth = chipLeads ? max(0, bounds.width - textX) : max(0, openButton.frame.minX - 10)
// Two lines in the strip's 27 pt.
let lineHeight: CGFloat = min(16, (bounds.height + 1) / 2)
let top = (bounds.height - 2 * lineHeight) / 2
titleLabel.frame = CGRect(x: textX, y: top, width: textWidth, height: lineHeight)
pathLabel.frame = CGRect(x: textX, y: top + lineHeight, width: textWidth, height: lineHeight)
}
}
/// Record typing logs is recording this field: a dot and "Logging", flat and small, in the
/// strip's corner and in the recording bar, so logging is never hidden.
@MainActor
final class TypingLogMarkView: UIView {
static let text = "Logging"
static let accessibilityText = "Typing logs are recording"
/// The dot and the word share the strip's muted ink: an orange dot would read as iOS's
/// microphone indicator.
var textColor: UIColor = .secondaryLabel {
didSet {
label.textColor = textColor
dot.backgroundColor = textColor
}
}
private let dot = UIView()
private let label = UILabel()
private static let dotSize: CGFloat = 5
private static let gap: CGFloat = 4
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = false
isAccessibilityElement = true
accessibilityLabel = Self.accessibilityText
dot.backgroundColor = textColor
dot.layer.cornerRadius = Self.dotSize / 2
label.text = Self.text
label.font = .systemFont(ofSize: 10, weight: .medium)
label.textColor = textColor
addSubview(dot)
addSubview(label)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError() }
override func sizeThatFits(_ size: CGSize) -> CGSize {
let text = label.sizeThatFits(size)
return CGSize(width: Self.dotSize + Self.gap + ceil(text.width), height: max(Self.dotSize, ceil(text.height)))
}
override func layoutSubviews() {
super.layoutSubviews()
dot.frame = CGRect(x: 0, y: (bounds.height - Self.dotSize) / 2, width: Self.dotSize, height: Self.dotSize)
label.frame = CGRect(x: Self.dotSize + Self.gap, y: 0, width: max(0, bounds.width - Self.dotSize - Self.gap), height: bounds.height)
}
}