hex/ios/HEXShared/FullKeyboard/FullKeyboardEngine+SwipeTyping.swift
Ryan Vogel f11913272e
iOS: text replacements fire like the system's and stay put, and no stray capitals from suggestions (#2173)
* iOS: text replacements go in as on Apple's keyboard, and backspace no longer undoes them

TestFlight (Jason, build 56, iPhone 18 Pro Max, iOS 27.3, with a screen
recording): "Text replacement doesn't seem to work accurately. At the times
where it does, tapping the backspace immediately undoes whatever replacement
was done." In the video his shortcut "myem" (his email address) stays as
typed on space and on return with Hex, while Apple's keyboard replaces it.

Apple's keyboard, black box on the iOS 27.2 simulator (Settings > Text
Replacement: myem, tyvm, home, ad2, s.o):
- Delete right after a replacement takes only the space; no revert bubble,
  and the strip shows completions of the last fragment ("com"). After an
  autocorrection it also takes only the space and shows a "teh" revert
  bubble above the word. (Hex keeps its deliberate one-backspace undo for
  autocorrections; only replacements change.)
- A replacement goes in on space, "." and return; after "(" or a comma
  ("hi,myem"); for a shortcut with a digit ("ad2") or a dot ("s.o"); for a
  shortcut that is a word ("home"). Settings refuses shortcuts with spaces.
- Tapping the quoted shortcut keeps it once; typed again it is replaced
  again, however often it was kept.
- After a swipe, space leaves the swiped word, and the strip offers the
  replacement of a reading that is a shortcut.

Changes:
- AutocorrectEngine.textReplacement(before:) finds the longest shortcut
  ending the text at a word boundary, digits and punctuation included.
  Space, a closing mark and return (FullKeyboardEngine.applyTextReplacement)
  put it in before any autocorrection; the new line on return still goes in
  on its own, so Send/Search fields see just "\n".
- Removed: the one-backspace undo of a replacement, which also suppressed the
  shortcut for the session and, after two undos, taught it as a kept word
  that turned the replacement off for good (the likely reason his "myem"
  stopped working). Replacements now ignore kept/learned/rejected words.
- The strip shows a shortcut with digits or punctuation, also without a
  dictionary for the language; picking it replaces the whole shortcut.
- After a swipe, a reading that is a shortcut shows as its replacement.
- Moved the built-in word lists to AutocorrectEngine+Dictionaries.swift
  (no change) so AutocorrectEngine.swift stays under the 1,500-line cap.

Verified on the Mac Studio, iPhone 18 Pro (iOS 27.2 simulator):
- xcodebuild test -only-testing AutocorrectEngineTests,
  FullKeyboardEngineTests: 149 tests, 0 failures (new:
  testTextReplacementsGoInAsOnApplesKeyboard,
  testASwipedShortcutOffersItsReplacementAndATappedOneGoesIn; two tests
  updated from "one backspace puts back the shortcut").
- Live Release build in a hosted field on an iPhone 18 Pro Max simulator:
  "hello there myem" + space -> "hello there jason@example.com ", delete
  takes the space then "m"; "ad2" shows "second address" in the strip and
  goes in on space; "s.o " and "myem" + return go in.

* iOS: a fix or a swiped word brings no capital of its own mid-sentence

TestFlight (Jason, build 56): "Swipe typing keeps auto capitalising in most
cases, even when it shouldn't. It doesn't work how Apple's keyboard does,
where it capitalises only after a full stop." His screen recording also
shows "helli" typed mid-sentence ("myem helli") going in as "Hello", with
"Hello" highlighted in the strip.

Reproduced on dev with the swipe HID tool (iPhone 18 Pro Max simulator, iOS
27.2): shift and auto-capitalisation around swipes are already right after
a comma, a swipe, a strip pick, a delete, a tapped word, a sentence-start
capital turned off, "?" and "!" (#2144, #2159). What still capitalised
mid-sentence was the casing of the candidates:
- Your own words: a Contacts name that is also a common word ("Bell",
  "Will", "Young") is a UILexicon term, and the swipe decoder reads the
  model's "bell" only as that own word, so it went in as "Bell" wherever
  it was swiped. The strip's completions offered it capitalised too.
- Fixes learned at the start of a sentence ("Helli" picked as "Hello"
  twice is learned as "Hello"), and guesses iOS returns capitalised, kept
  that capital mid-sentence (matchCase keeps a target's own capitals).
Apple's keyboard, black box (iOS 27.2, the simulator's contact Kate Bell):
swiping "the bell rang" gives lowercase "bell"; "taylor" and "kate" come out
"Taylor" and "Kate".

AutocorrectEngine.withoutStrayCapital writes such a word in lowercase when
you didn't type a capital and the dictionary knows it in lowercase. Names
the dictionary knows only capitalised ("Taylor", "Monday"), "I" and its
contractions, words with more capitals ("iPhone"), a capital you typed or
the sentence start gives, and German (nouns) keep theirs. Used for space's
fix (learned typos, Spatial readings, spelling guesses), the strip's
candidates and completions, and swipeCased.

Verified on the Mac Studio, iPhone 18 Pro (iOS 27.2 simulator):
- New tests testAFixBringsNoCapitalOfItsOwnMidSentence and
  testSwipedWordsTakeACapitalOnlyWhereApplesKeyboardGivesOne fail on the
  previous commit ("hello there's the Bell Will", "Hello" for "helli") and
  pass now.
- xcodebuild test -only-testing AutocorrectEngineTests,
  FullKeyboardEngineTests, SwipeDecoderTests: 158 tests, 0 failures.
2026-11-21 06:10:45 -05:00

122 lines
6.5 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import QuartzCore
import UIKit
/// Settings › Keyboard › Swipe typing's read side: the word a swipe types and the readings the
/// strip offers for it, and how a reading is cased. The touch and decoding side is
/// `SwipeTyping`; the swipe state (`swipedWord`, `isSwiping`, `swipePreview`) and the methods
/// that change it stay in `FullKeyboardEngine`, since extensions hold no stored properties and
/// that state's setter is file-scoped.
@MainActor
extension FullKeyboardEngine {
/// The word a swipe just typed, until anything else changes the text: delete takes it
/// back whole, space never autocorrects it, and the strip offers the swipe's other
/// readings, any of which takes its place.
struct SwipedWord: Equatable {
/// What the swipe put in: a space when one was needed, then the word.
var inserted: String
var word: String
/// Its other readings, cased as the word is, best first.
var alternatives: [String]
}
/// Whether a letter touch may become a swipe now: on the letters page of a text field
/// (not an address or a URL), with no accent menu open.
var allowsSwipes: Bool {
layerState.layer == .letters && field == .text && activeAccentMenu == nil
}
/// The letter keys a swipe is read against, where they're drawn.
var swipeKeys: TypingDecoder.Keys {
TypingDecoder.Keys(layout: layout) ?? TypingDecoder.Keys(centres: [:], pitch: .zero, bottomRowY: 0)
}
/// The word before a swipe's, lowercased, when only spaces (or the one the swipe will
/// add) come between them.
var swipePreviousWord: String? {
let before = target.documentContextBeforeInput ?? ""
return AutocorrectEngine.previousWord(SwipeTyping.needsSpace(before: before) ? before + " " : before, token: "")
}
/// The strip while swiping (the word so far) and right after (the other readings, the
/// likeliest in the centre slot); nil otherwise.
var swipeSuggestions: [KeyboardSuggestion]? {
if isSwiping {
return swipePreview.map { [KeyboardSuggestion(displayText: $0, replacement: $0, kind: .primary(autoReplace: true))] } ?? []
}
guard let swipedWord else { return nil }
let items = swipedWord.alternatives.prefix(3).map { KeyboardSuggestion(displayText: $0, replacement: $0, kind: .swiped) }
return items.count >= 2 ? [items[1], items[0]] + items.dropFirst(2) : items
}
/// `words` that may be offered after the word before (`AutocorrectEngine.mayOffer`), once each.
func swipeReadings(_ words: [String]) -> [String] {
let previous = swipePreviousWord
var seen = Set<String>()
return words.filter { autocorrect.mayOffer($0, after: previous) && seen.insert($0.lowercased()).inserted }
}
/// Whether a swiped word starts with a capital: shift (one-shot, held, caps lock, or
/// automatic), or the automatic capital the space the swipe adds brings ("Hi." then a
/// swipe types " There").
var swipeCapital: Bool {
if shift.isUppercase { return true }
guard shift.state == .off, !shift.isHeld else { return false }
let before = target.documentContextBeforeInput
guard SwipeTyping.needsSpace(before: before) else { return false }
return AutoCapitalization.shouldCapitalize(
mode: autoCapitalizationMode,
before: (before ?? "") + " ",
hasText: true
)
}
/// A reading as it's typed: all capitals with caps lock, a capital first letter with
/// `capital`, else a name the dictionary only knows capitalised ("monday" -> "Monday").
/// One of your own words with a capital that is also a common word (a Contacts name such
/// as "Bell" or "Will") is written as the sentence needs it, as Apple's keyboard swipes
/// "the bell rang" beside a contact Kate Bell (`AutocorrectEngine.withoutStrayCapital`).
/// With Auto-capitalization off, no capital you didn't ask for ("i'm", "monday"), but
/// your own spellings keep theirs.
func swipeCased(_ word: String, capital: Bool) -> String {
if shift.state == .locked { return word.uppercased() }
guard let first = word.first else { return word }
if capital { return first.uppercased() + word.dropFirst() }
if !autoCapitalizes {
return autocorrect.isOwnSpelling(word) ? word : word.lowercased()
}
if swipeReadsAsName(word) { return first.uppercased() + word.dropFirst() }
return autocorrect.withoutStrayCapital(word, typed: "")
}
/// The strip's other readings after a swipe, cased as its word is (`readings` best first,
/// the first the one typed). A reading that is a text replacement's shortcut shows as its
/// replacement ("home" as "at my house"), the swiped word's first, as Apple's keyboard
/// offers one after a swipe (black box, iOS 27.2); space never puts it in.
func swipeAlternatives(_ readings: [String], capital: Bool) -> [String] {
func replacement(_ reading: String) -> String? {
guard target.autocorrectionType != .no else { return nil }
let typed = capital ? reading.prefix(1).uppercased() + reading.dropFirst() : reading
guard let replaced = autocorrect.textReplacement(before: typed), replaced.typed.count == typed.count else { return nil }
return replaced.replacement
}
var out: [String] = []
if let first = readings.first, let phrase = replacement(first) { out.append(phrase) }
for reading in readings.dropFirst() {
let item = replacement(reading) ?? swipeCased(reading, capital: capital)
if !out.contains(item) { out.append(item) }
}
return Array(out.prefix(3))
}
/// Whether a swipe's reading, as the model spells it (lowercase), is a word the dictionary
/// knows only with a capital: a name, day or place ("monday"), or an abbreviation.
func swipeReadsAsName(_ word: String) -> Bool {
guard autocorrect.hasDictionary, word == word.lowercased(), word.count >= 2, let first = word.first else { return false }
return autocorrect.checker.isWordValid(first.uppercased() + word.dropFirst()) && !autocorrect.checker.isWordValid(word)
}
/// What goes against a swiped word, as on Apple's keyboard: closing punctuation and
/// brackets, an apostrophe, a hyphen and a slash. Anything else tapped right after a swipe
/// (a straight quote and opening brackets included) starts the next word.
static let swipeJoiners: Set<Character> = [",", ".", "!", "?", ";", ":", ")", "]", "}", "'", "’", "-", "/"]
}