diff --git a/README.md b/README.md
index de073c9..ed72f57 100644
--- a/README.md
+++ b/README.md
@@ -109,6 +109,8 @@ export function Composer() {
On iOS, hold space to enter trackpad mode, then slide in any direction. A floating caret follows the finger freely across letters and blank space inside the input. On release, it snaps to the nearest valid insertion position, including wrapped lines. Android's space-slide gesture supports both directions too. The drag target stays independent of the snapped caret, so short lines do not discard its horizontal position. Return follows your input's React Native `submitBehavior`; multiline inputs insert a newline by default.
+For automatic focus, pass `autoFocus: true` to `useKeyflow()` instead of setting it on `TextInput`. Keyflow waits for native attachment before presenting the input.
+
The hook also exposes stable `focus()` and `blur()` methods. They safely do nothing while the input is unmounted. `inputRef` remains available for other native input methods:
```tsx
@@ -157,6 +159,7 @@ export const keyflowTheme = {
const { keyflowInputProps } = useKeyflow({
keyflowTheme,
+ returnKeyContent: { icon: 'send' },
});
;
@@ -175,6 +178,52 @@ const { keyflowInputProps } = useKeyflow({
Sections support colors, pressed colors, borders, corner radius, fonts, and icon sizing where applicable. `color` supplies the icon and pressed foreground unless explicitly overridden. If you set `iconColor`, remember to give selected states a contrasting icon color too.
+Set the custom return key to app-owned text or a portable native icon:
+
+```tsx
+const { keyflowInputProps } = useKeyflow({
+ returnKeyContent: { icon: 'send' },
+});
+
+;
+```
+
+Use `{ text: 'Post' }` for app-owned text. Available icons are `return`, `arrow-right`, `checkmark`, `send`, and `search`. This changes only Keyflow's presentation; use the `TextInput`'s `submitBehavior` and `onSubmitEditing` for behavior. A multiline input with `submitBehavior="newline"` inserts `\n`.
+
+For example, these two multiline inputs display different return keys and keep their normal React Native behavior:
+
+```tsx
+const { keyflowInputProps: sendInputProps } = useKeyflow({
+ returnKeyContent: { icon: 'send' },
+});
+const { keyflowInputProps: newlineInputProps } = useKeyflow({
+ returnKeyContent: { text: 'New line' },
+});
+
+// Displays a send icon and calls sendMessage.
+
+
+// Displays “New line” and inserts a newline.
+
+```
+
+The example app has an interactive **Behavior → Return key actions** screen for testing both cases.
+
+On iOS, the long-press accent popup and its choices omit borders. The selected accent uses the regular keys’ corner radius.
+
The API is shared across phone, tablet, portrait and landscape. Native layout determines the key geometry; customization does not define new rows or touch targets. [Full theme options and limits](docs/api.md#theme-reference).
### Transparent panel, transparent keys—or both
@@ -278,8 +327,8 @@ Watch the MP4s: [iPhone transitions](docs/media/ios-transitions.mp4) · [Android
iPhone · Hold and slide between accents
Android phone · Hold and slide between accents
-
-
+
+
@@ -328,14 +377,14 @@ Need the user’s actual keyboard and its full feature set? Pass `keyboardMode:
## Example app
-| Category | Explore |
-| ----------- | ---------------------------------------------------------------------- |
-| Behavior | Typing, long presses, deletion, cursor movement and native comparisons |
-| Multiline | Notes with paragraphs, wrapped lines, Return and movement on both axes |
-| Transitions | Presentation, dismissal, mode handoffs and keyboard avoidance |
-| Layouts | Number pads, rotation, English/French switching |
-| Appearance | Fonts, borders, sizes, focused accents and customization bounds |
-| Showcases | Platform defaults, Story Studio, Quicksand and transparency |
+| Category | Explore |
+| ----------- | ---------------------------------------------------------------------------- |
+| Behavior | Typing, long presses, return actions, cursor movement and native comparisons |
+| Multiline | Notes with paragraphs, wrapped lines, Return and movement on both axes |
+| Transitions | Presentation, dismissal, mode handoffs and keyboard avoidance |
+| Layouts | Number pads, rotation, English/French switching |
+| Appearance | Fonts, borders, sizes, focused accents and customization bounds |
+| Showcases | Platform defaults, Story Studio, Quicksand and transparency |
The example source lives in [`example/`](example). `corepack yarn example:export` also prepares a standalone example repository under `artifacts/keyflow-example-repo` with a bundled library package.
diff --git a/android/src/androidTest/java/com/keyflow/KeyflowRenderingTest.kt b/android/src/androidTest/java/com/keyflow/KeyflowRenderingTest.kt
index 516258b..cfffbe6 100644
--- a/android/src/androidTest/java/com/keyflow/KeyflowRenderingTest.kt
+++ b/android/src/androidTest/java/com/keyflow/KeyflowRenderingTest.kt
@@ -1,7 +1,10 @@
package com.keyflow
+import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
+import android.view.inputmethod.EditorInfo
+import android.widget.EditText
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -13,6 +16,41 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class KeyflowRenderingTest {
+ @Test
+ fun returnActionLetsReactNativeChooseSubmitOrNewline() {
+ ActivityScenario.launch(KeyflowTestActivity::class.java).use { scenario ->
+ scenario.onActivity { activity ->
+ val singleLine = ReturnTrackingEditText(activity)
+ singleLine.setSingleLine(true)
+ dispatchKeyflowSubmit(singleLine)
+ assertEquals(listOf(EditorInfo.IME_ACTION_DONE), singleLine.editorActions)
+ assertTrue(singleLine.keyEvents.isEmpty())
+
+ val multiline = ReturnTrackingEditText(activity)
+ multiline.setSingleLine(false)
+ dispatchKeyflowSubmit(multiline)
+ assertTrue(multiline.editorActions.isEmpty())
+ assertEquals(
+ listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP),
+ multiline.keyEvents.map { it.action },
+ )
+ assertTrue(multiline.keyEvents.all { it.keyCode == KeyEvent.KEYCODE_ENTER })
+ }
+ }
+ }
+
+ @Test
+ fun returnKeySupportsCustomText() = withKeyboard { activity, keys ->
+ activity.keyboard.theme =
+ KeyflowTheme(
+ JSONObject().apply { put("returnKeyContent", JSONObject().apply { put("text", "Send") }) }
+ )
+ val submit = keys().first { it.action == "submit" }
+ assertEquals("Send", submit.label)
+ assertEquals("Send", submit.text.toString())
+ assertEquals("Send", submit.contentDescription)
+ }
+
@Test
fun reactOwnedSoftInputFlagSurvivesModeChangesAndDetach() {
ActivityScenario.launch(KeyflowTestActivity::class.java).use { scenario ->
@@ -305,3 +343,17 @@ class KeyflowRenderingTest {
keyboard.layout(0, 0, keyboard.measuredWidth, keyboard.measuredHeight)
}
}
+
+private class ReturnTrackingEditText(context: android.content.Context) : EditText(context) {
+ val editorActions = mutableListOf()
+ val keyEvents = mutableListOf()
+
+ override fun onEditorAction(actionCode: Int) {
+ editorActions += actionCode
+ }
+
+ override fun dispatchKeyEvent(event: KeyEvent): Boolean {
+ keyEvents += event
+ return true
+ }
+}
diff --git a/android/src/main/java/com/keyflow/KeyflowIcons.kt b/android/src/main/java/com/keyflow/KeyflowIcons.kt
index 889b625..b7ff334 100644
--- a/android/src/main/java/com/keyflow/KeyflowIcons.kt
+++ b/android/src/main/java/com/keyflow/KeyflowIcons.kt
@@ -79,6 +79,20 @@ internal object KeyflowIcons {
path(18f, 9f, 12f, 15f)
}
"submit" -> path(4f, 12f, 9f, 17f, 20f, 6f)
+ "return" -> path(20f, 5f, 20f, 12f, 7f, 12f, 11f, 8f, 7f, 12f, 11f, 16f)
+ "arrow-right" -> {
+ path(4f, 12f, 20f, 12f)
+ path(14f, 6f, 20f, 12f, 14f, 18f)
+ }
+ "checkmark" -> path(4f, 12f, 9f, 17f, 20f, 6f)
+ "send" -> {
+ path(3f, 4f, 21f, 12f, 3f, 20f, 7f, 12f, close = true)
+ path(7f, 12f, 21f, 12f)
+ }
+ "search" -> {
+ canvas.drawCircle(10f, 10f, 6f, p)
+ path(14.5f, 14.5f, 20f, 20f)
+ }
"paste" -> {
canvas.drawRoundRect(RectF(5f, 4f, 19f, 22f), 1f, 1f, p)
canvas.drawRoundRect(RectF(9f, 2f, 15f, 6f), 1f, 1f, p)
diff --git a/android/src/main/java/com/keyflow/KeyflowInputView.kt b/android/src/main/java/com/keyflow/KeyflowInputView.kt
index 951f74f..b9885e7 100644
--- a/android/src/main/java/com/keyflow/KeyflowInputView.kt
+++ b/android/src/main/java/com/keyflow/KeyflowInputView.kt
@@ -195,13 +195,16 @@ class KeyflowInputView(context: Context, private val expoContext: AppContext) :
}
softInputPolicy.apply(field, mode == "system")
updateInputContext()
- if (changed && field.hasFocus()) requestKeyboard()
+ // Refocusing an already-focused editor does not emit another focus change.
+ // Attachment is also used by the hook's focus(), so restore its panel here.
+ if (field.hasFocus()) requestKeyboard()
}
- private fun detachInput() {
+ private fun detachInput(animated: Boolean = false, resigningFocus: Boolean = false) {
val field = attachedEditor ?: return
removeCallbacks(showRequest)
- hideKeyboard(animated = false)
+ if (resigningFocus) field.clearFocus()
+ hideKeyboard(animated = animated)
field.removeTextChangedListener(providedTextWatcher)
softInputPolicy.restore(field)
attachedEditor = null
@@ -217,6 +220,7 @@ class KeyflowInputView(context: Context, private val expoContext: AppContext) :
private val keyboard = KeyflowKeyboardView(context) { action, text -> activate(action, text) }
private var popup: PopupWindow? = null
private var navigationScrim: ColorDrawable? = null
+ private var navigationScrimHost: View? = null
private var previousLightNavigation: Boolean? = null
private fun updateNavigationScrim() {
@@ -228,6 +232,7 @@ class KeyflowInputView(context: Context, private val expoContext: AppContext) :
navigationScrim
?: ColorDrawable().also {
navigationScrim = it
+ navigationScrimHost = rootView
rootView.overlay.add(it)
previousLightNavigation =
ViewCompat.getWindowInsetsController(rootView)?.isAppearanceLightNavigationBars
@@ -240,12 +245,14 @@ class KeyflowInputView(context: Context, private val expoContext: AppContext) :
}
private fun clearNavigationScrim() {
- navigationScrim?.let { rootView.overlay.remove(it) }
+ val host = navigationScrimHost ?: rootView
+ navigationScrim?.let { host.overlay.remove(it) }
navigationScrim = null
previousLightNavigation?.let {
- ViewCompat.getWindowInsetsController(rootView)?.isAppearanceLightNavigationBars = it
+ ViewCompat.getWindowInsetsController(host)?.isAppearanceLightNavigationBars = it
}
previousLightNavigation = null
+ navigationScrimHost = null
}
private var lastSpace = 0L
@@ -468,15 +475,18 @@ class KeyflowInputView(context: Context, private val expoContext: AppContext) :
handoffHeight = 0f
viewTreeObserver.removeOnGlobalLayoutListener(globalLayout)
viewTreeObserver.removeOnGlobalFocusChangeListener(providedFocusListener)
- detachInput()
+ val animated = navigationScrimHost?.isAttachedToWindow == true
+ detachInput(animated = animated, resigningFocus = true)
ViewCompat.setWindowInsetsAnimationCallback(this, null)
ViewCompat.setOnApplyWindowInsetsListener(this, null)
- hideKeyboard(animated = false)
+ hideKeyboard(animated = animated)
super.onDetachedFromWindow()
}
fun cleanup() {
- detachInput()
+ onKeyflowHeightChange = null
+ onKeyflowFrameChange = null
+ detachInput(animated = navigationScrimHost?.isAttachedToWindow == true, resigningFocus = true)
(parent as? ViewGroup)?.removeView(this)
}
@@ -572,22 +582,7 @@ class KeyflowInputView(context: Context, private val expoContext: AppContext) :
}
private fun submit() {
- // Keep React Native's submitBehavior and onSubmitEditing event pipeline.
- if (editor.inputType and android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE != 0) {
- // Send native Enter events so React Native decides between newline and
- // submit/blur using its existing submitBehavior listener.
- editor.dispatchKeyEvent(
- android.view.KeyEvent(
- android.view.KeyEvent.ACTION_DOWN,
- android.view.KeyEvent.KEYCODE_ENTER,
- )
- )
- editor.dispatchKeyEvent(
- android.view.KeyEvent(android.view.KeyEvent.ACTION_UP, android.view.KeyEvent.KEYCODE_ENTER)
- )
- } else {
- editor.onEditorAction(EditorInfo.IME_ACTION_DONE)
- }
+ dispatchKeyflowSubmit(editor)
}
private fun activate(action: String, text: String) {
@@ -660,3 +655,20 @@ class KeyflowInputView(context: Context, private val expoContext: AppContext) :
}
}
}
+
+/**
+ * Sends Return through Android's editor APIs so React Native remains responsible for
+ * `submitBehavior`, `onSubmitEditing`, newline insertion, and blur behavior.
+ */
+internal fun dispatchKeyflowSubmit(editor: EditText) {
+ if (editor.inputType and android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE != 0) {
+ editor.dispatchKeyEvent(
+ android.view.KeyEvent(android.view.KeyEvent.ACTION_DOWN, android.view.KeyEvent.KEYCODE_ENTER)
+ )
+ editor.dispatchKeyEvent(
+ android.view.KeyEvent(android.view.KeyEvent.ACTION_UP, android.view.KeyEvent.KEYCODE_ENTER)
+ )
+ } else {
+ editor.onEditorAction(EditorInfo.IME_ACTION_DONE)
+ }
+}
diff --git a/android/src/main/java/com/keyflow/KeyflowKeyView.kt b/android/src/main/java/com/keyflow/KeyflowKeyView.kt
index 2f6730d..13fedfd 100644
--- a/android/src/main/java/com/keyflow/KeyflowKeyView.kt
+++ b/android/src/main/java/com/keyflow/KeyflowKeyView.kt
@@ -34,6 +34,8 @@ internal class KeyflowKeyView(
var circular = false
var themeSection: String? = null
var iconSize = if (action in listOf("delete", "submit")) 26f else 24f
+ private var actionIcon: String? = null
+ private var actionUsesText = false
var onSlide: ((Float, Float) -> Unit)? = null
var onSlideStart: (() -> Unit)? = null
var onSlideEnd: (() -> Unit)? = null
@@ -61,8 +63,19 @@ internal class KeyflowKeyView(
private var sliding = false
private val icon
get() =
- action in
- listOf("shift", "capsLock", "tab", "delete", "submit", "paste", "hide", "nextLanguage")
+ actionIcon != null ||
+ (!actionUsesText &&
+ action in
+ listOf("shift", "capsLock", "tab", "delete", "submit", "paste", "hide", "nextLanguage"))
+
+ fun setActionContent(value: String, icon: String?) {
+ label = value
+ contentDescription = value
+ actionIcon = icon
+ actionUsesText = icon == null
+ text = if (icon == null) value else ""
+ invalidate()
+ }
private var repeating = false
private var preferredSize = 22f
@@ -327,7 +340,7 @@ internal class KeyflowKeyView(
if (icon)
KeyflowIcons.draw(
canvas,
- if (action == "shift" && isActivated) "shiftLocked" else action,
+ if (action == "shift" && isActivated) "shiftLocked" else actionIcon ?: action,
bounds.exactCenterX(),
bounds.exactCenterY() - keyDepth * density / 2,
(sourceTheme.json
diff --git a/android/src/main/java/com/keyflow/KeyflowKeyboardView.kt b/android/src/main/java/com/keyflow/KeyflowKeyboardView.kt
index 2d69915..d21c6fa 100644
--- a/android/src/main/java/com/keyflow/KeyflowKeyboardView.kt
+++ b/android/src/main/java/com/keyflow/KeyflowKeyboardView.kt
@@ -559,7 +559,15 @@ internal class KeyflowKeyboardView(
private fun styleKeys() {
background = GradientDrawable().apply { setColor(theme.background) }
- keys.forEach { it.applyTheme(theme) }
+ val content = theme.json.optJSONObject("returnKeyContent")
+ keys.forEach {
+ if (it.action == "submit") {
+ val text = content?.optString("text")?.takeIf(String::isNotEmpty)
+ val icon = content?.optString("icon")?.takeIf(String::isNotEmpty) ?: "checkmark"
+ it.setActionContent(text ?: "Submit", if (text == null) icon else null)
+ }
+ it.applyTheme(theme)
+ }
updateToolbar()
}
diff --git a/docs/api.md b/docs/api.md
index cb2c283..2f502ed 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -75,10 +75,12 @@ export function Input() {
| Option | Behavior |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
+| `autoFocus` | Focuses after native attachment; defaults to `false`. Use instead of TextInput’s `autoFocus` prop. |
| `enabled` | Enables native attachment; defaults to `true` |
| `keyboardMode` | `custom` (default) or `system` |
| `keyboardAppearance` | `light` or `dark`; otherwise follows device appearance |
| `keyboardType` | `default`, `number-pad`, `decimal-pad`, `phone-pad` |
+| `returnKeyContent` | Custom text or a portable native icon for Keyflow's submit key |
| `keyflowTheme` | Partial overrides or a resolved theme |
| `keyboardLanguages` | English/French language and QWERTY/AZERTY template entries |
| `hapticsEnabled` | Optional key feedback, off by default |
@@ -90,6 +92,25 @@ export function Input() {
The app owns its editor and text. Use ordinary React Native `TextInput` props such as `value`, `defaultValue`, `onChangeText`, `onSubmitEditing`, `placeholderTextColor`, `accessibilityLabel`, `editable`, and `submitBehavior` directly on the input. Keyflow adds no input height, padding, border, color, or font. `onSubmitEditing` receives the standard React Native event, not a string.
+Customize Keyflow's return key independently from submission behavior:
+
+```tsx
+const { keyflowInputProps } = useKeyflow({
+ returnKeyContent: { icon: 'send' },
+});
+
+;
+
+// A multiline editor can use the same key to insert a newline.
+;
+```
+
+The portable icon names are `return`, `arrow-right`, `checkmark`, `send`, and `search`. Choose either `text` or `icon`. The option affects only the custom keyboard; the system keyboard continues to follow the platform's `returnKeyType` and `enterKeyHint` behavior.
+
The hook returns:
| Value | Purpose |
@@ -102,7 +123,7 @@ Text state, input appearance, and composer content remain app-controlled. There
Single-line and `multiline` inputs are supported. Set editor height, scrolling, and `numberOfLines` on the input. During trackpad movement, a floating caret follows continuous horizontal and vertical drag coordinates across text and blank space inside the input. The native editor resolves the insertion position through text hit testing, including soft wrapping; release removes the floating caret and restores the native caret at that position. The drag target is anchored at gesture start and remains independent of the snapped caret across short lines. Hold space on iOS, or use the space-slide gesture on Android. Return uses the native React Native editing pipeline and respects `submitBehavior`.
-Call `useKeyflow(options)` and spread `keyflowInputProps` onto your `TextInput`. The hook creates a stable ref and includes it with the `showSoftInputOnFocus`, `onFocus`, and `onSelectionChange` bindings. The ref allows native keyboard attachment; the callbacks keep focus and cursor context synchronized. For custom components, forward the ref and bindings to the underlying `TextInput`, not a surrounding `View`.
+Call `useKeyflow(options)` and spread `keyflowInputProps` onto your `TextInput`. The hook creates a stable ref and includes it with the `showSoftInputOnFocus`, `onFocus`, `onSelectionChange`, and `onLayout` bindings. The ref allows native keyboard attachment; the callbacks keep focus and cursor context synchronized and support automatic focus when an input mounts later. For custom components, forward the ref and bindings to the underlying `TextInput`, not a surrounding `View`. If you override `onLayout`, call `keyflowInputProps.onLayout?.(event)` from your handler too.
Compose your own focus/selection callbacks with the bindings:
diff --git a/docs/media/README.md b/docs/media/README.md
index 270cfc9..4518f74 100644
--- a/docs/media/README.md
+++ b/docs/media/README.md
@@ -1,14 +1,14 @@
# README media
-All six GIFs and MP4s were recorded again on 2026-09-15 using the keyboard implementation merged in `5bc4916`. They show the current example, including multiline trackpad movement. The themed stills and four default-layout previews retain their earlier provenance below. These are simulator/emulator demonstrations, not a comparison against Apple/Gboard or a claim of physical-device frame pacing.
+The transition and trackpad clips were recorded on 2026-09-15 using the keyboard implementation merged in `5bc4916`. Both accent clips were replaced on 2026-09-16 from the current long-press implementation. The themed stills and four default-layout previews retain their earlier provenance below. These are simulator/emulator demonstrations, not a comparison against Apple/Gboard or a claim of physical-device frame pacing.
| Files | Device and action |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ios-transitions.mp4` / `.gif` | Stim-owned iPhone 17, iOS 26.5. Story Studio: two dismissal/refocus cycles |
-| `ios-accents.mp4` / `.gif` | Same iPhone. Story Studio: two holds on E, sliding across accent choices |
+| `ios-accents.mp4` / `.gif` | Same iPhone. Story Studio: hold E, slide the rose focus across several accents, and release to commit the focused choice |
| `ios-trackpad.mp4` / `.gif` | Same iPhone. Native interaction example: reset the multiline fixture, hold space and move diagonally up/left and down/right; labels fade and return |
| `android-transitions.mp4` / `.gif` | Stim-owned Android phone emulator, API 36, 1080 × 2400. Native interaction example: submit dismissal and refocus twice |
-| `android-accents.mp4` / `.gif` | Same Android phone. Hold E and continuously slide left/right across alternatives |
+| `android-accents.mp4` / `.gif` | Same Android phone. Story Studio: hold E, traverse both popup rows with the rose focus, and release to commit `É` |
| `android-trackpad.mp4` / `.gif` | Same Android phone. Reset the multiline fixture, then one continuous space gesture moves horizontally and vertically |
| `studio.jpg` | iPad Story Studio keyboard after accent input, captured on 2026-09-13 from `c4183a6` |
| `transparent.jpg` | Same earlier iPad capture. Transparency example at 35% panel and 70% keys |
@@ -22,7 +22,7 @@ All six GIFs and MP4s were recorded again on 2026-09-15 using the keyboard imple
- The multiline text is seeded through the example’s visible Reset Multiline action. The recordings demonstrate movement through that input, not typing of the fixture text.
- No keys, colors, text, backgrounds or cursor motion were reconstructed. The capture harness is separate from the regression-suite count. Documentation media is outside the npm package’s `files` allowlist.
-To reproduce, launch the current example with Stim. Open Story Studio on iPhone for accents/transitions, or Compare native interactions for multiline trackpad movement. On Android, use Compare native interactions for all three actions. Keep the host display awake for simulator/emulator UI recording.
+To reproduce, launch the current example with Stim. Use Story Studio for accents and transitions on both platforms. Use Compare native interactions for multiline trackpad movement. Keep the host display awake for simulator/emulator UI recording.
## Default-layout previews
diff --git a/docs/media/android-accents.gif b/docs/media/android-accents.gif
index adf24ba..bf33382 100644
Binary files a/docs/media/android-accents.gif and b/docs/media/android-accents.gif differ
diff --git a/docs/media/android-accents.mp4 b/docs/media/android-accents.mp4
index ab2a522..0dd74af 100644
Binary files a/docs/media/android-accents.mp4 and b/docs/media/android-accents.mp4 differ
diff --git a/docs/media/ios-accents.gif b/docs/media/ios-accents.gif
index e5caa57..2c8e54a 100644
Binary files a/docs/media/ios-accents.gif and b/docs/media/ios-accents.gif differ
diff --git a/docs/media/ios-accents.mp4 b/docs/media/ios-accents.mp4
index d925446..853abee 100644
Binary files a/docs/media/ios-accents.mp4 and b/docs/media/ios-accents.mp4 differ
diff --git a/example/src/App.tsx b/example/src/App.tsx
index b0fa390..8e19b26 100644
--- a/example/src/App.tsx
+++ b/example/src/App.tsx
@@ -14,7 +14,11 @@ import { LanguageScreen } from './screens/LanguageScreen';
import { LayoutsScreen } from './screens/LayoutsScreen';
import { InteractionScreen } from './screens/InteractionScreen';
import { LongPressScreen } from './screens/LongPressScreen';
+import { TeardownScreen } from './screens/TeardownScreen';
+import { ReturnActionScreen } from './screens/ReturnActionScreen';
export type Routes = {
+ Teardown: undefined;
+ ReturnActions: undefined;
Showcase: undefined;
Transparency: undefined;
Interactions: undefined;
@@ -82,6 +86,16 @@ export default function App() {
component={InteractionScreen}
options={{ title: 'Native interaction tests' }}
/>
+
+
@@ -188,7 +189,7 @@ export function InteractionScreen({
);
return (
-
+
value={mode}
options={[
@@ -207,7 +208,7 @@ export function InteractionScreen({
if (!running) void switchMode(next);
}}
/>
-
+
Use the same cases with each keyboard. Compare accents, cursor
movement and held delete.
@@ -223,6 +224,7 @@ export function InteractionScreen({
Text: {text || '(empty)'}
diff --git a/example/src/screens/KeyboardScreen.tsx b/example/src/screens/KeyboardScreen.tsx
index 03acb1e..690728f 100644
--- a/example/src/screens/KeyboardScreen.tsx
+++ b/example/src/screens/KeyboardScreen.tsx
@@ -65,6 +65,7 @@ export const KeyboardScreen = observer(function KeyboardScreenContent({
keyboardMode: mode,
keyboardAppearance: dark ? 'dark' : 'light',
keyflowTheme: game ? studioTheme : undefined,
+ returnKeyContent: game ? { icon: 'send' } : undefined,
hapticsEnabled: haptics,
onKeyboardModeChange: setMode,
onKeyboardFrameChange: (next) => {
diff --git a/example/src/screens/LongPressScreen.tsx b/example/src/screens/LongPressScreen.tsx
index 3b49195..e060d6e 100644
--- a/example/src/screens/LongPressScreen.tsx
+++ b/example/src/screens/LongPressScreen.tsx
@@ -23,6 +23,7 @@ export function LongPressScreen() {
const [diagnostic, setDiagnostic] = useState('Ready for comparison.');
const header = useHeaderHeight();
const { inputRef: input, keyflowInputProps: bindings } = useKeyflow({
+ autoFocus: true,
keyboardMode: mode,
keyboardAppearance: 'light',
});
@@ -126,7 +127,6 @@ export function LongPressScreen() {
(null);
+ const [submitCount, setSubmitCount] = useState(0);
+ const [note, setNote] = useState('First line');
+ const [unexpectedNoteSubmits, setUnexpectedNoteSubmits] = useState(0);
+ const { keyflowInputProps: sendInputProps } = useKeyflow({
+ keyflowTheme: studioTheme,
+ returnKeyContent: { icon: 'send' },
+ });
+ const { keyflowInputProps: newlineInputProps } = useKeyflow({
+ keyflowTheme: studioTheme,
+ returnKeyContent: { text: 'New line' },
+ });
+ const lineCount = note.split('\n').length;
+
+ return (
+
+
+
+
+ One key, two actions
+
+
+ The Keyflow option changes what Return displays. The TextInput’s
+ submitBehavior decides what pressing it does.
+
+
+
+
+ {
+ setSubmitted(event.nativeEvent.text);
+ setSubmitCount((count) => count + 1);
+ }}
+ style={{
+ height: 88,
+ paddingVertical: 12,
+ textAlignVertical: 'top',
+ }}
+ />
+
+ {submitted === null
+ ? 'Nothing submitted yet.'
+ : `Submitted ${submitCount}×: ${submitted}`}
+
+
+
+
+
+ setUnexpectedNoteSubmits((count) => count + 1)
+ }
+ style={{
+ height: 116,
+ paddingVertical: 12,
+ textAlignVertical: 'top',
+ }}
+ />
+
+ {lineCount} {lineCount === 1 ? 'line' : 'lines'} · Submit events:{' '}
+ {unexpectedNoteSubmits}
+
+
+
+
+ );
+}
+
+function ExampleCard({
+ title,
+ instruction,
+ children,
+}: {
+ title: string;
+ instruction: string;
+ children: ReactNode;
+}) {
+ return (
+
+
+
+ {title}
+
+
+ {instruction}
+
+
+ {children}
+
+ );
+}
diff --git a/example/src/screens/ShowcaseScreen.tsx b/example/src/screens/ShowcaseScreen.tsx
index f519e9f..216d6c8 100644
--- a/example/src/screens/ShowcaseScreen.tsx
+++ b/example/src/screens/ShowcaseScreen.tsx
@@ -39,6 +39,26 @@ const sections = [
sample: '↑ · ↓',
color: '#E9F6F1',
},
+ {
+ route: 'Teardown',
+ accessibilityLabel: 'Test focused teardown',
+ eyebrow: 'Focus · close · unmount',
+ title: 'Focused teardown',
+ description:
+ 'Close a focused preview and unmount its entire Keyflow hook.',
+ sample: '×',
+ color: '#EAF1FF',
+ },
+ {
+ route: 'ReturnActions',
+ accessibilityLabel: 'Test return key actions',
+ eyebrow: 'Submit · New line',
+ title: 'Return key actions',
+ description:
+ 'Compare a custom send key with a multiline Return that inserts a new line.',
+ sample: '➤ ↵',
+ color: '#FFF2E8',
+ },
],
},
{
diff --git a/example/src/screens/TeardownScreen.tsx b/example/src/screens/TeardownScreen.tsx
new file mode 100644
index 0000000..84dda4c
--- /dev/null
+++ b/example/src/screens/TeardownScreen.tsx
@@ -0,0 +1,89 @@
+import { useEffect, useRef, useState } from 'react';
+import {
+ Button,
+ Keyboard,
+ Platform,
+ Text,
+ TextInput,
+ View,
+} from 'react-native';
+import { KeyflowAvoidingView, useKeyflow } from 'react-native-keyflow';
+import { studioTheme } from '../themes/studio';
+
+function Preview({ onClose }: { onClose: () => void }) {
+ const [text, setText] = useState('Draft message');
+ const { keyflowInputProps } = useKeyflow({
+ autoFocus: true,
+ keyflowTheme: studioTheme,
+ });
+ return (
+
+
+
+ Focused composer
+
+ The whole composer must stay visible while Keyflow is open.
+
+
+
+
+
+ );
+}
+
+export function TeardownScreen() {
+ const [open, setOpen] = useState(false);
+ const [unexpectedShows, setUnexpectedShows] = useState(0);
+ const closed = useRef(false);
+ useEffect(() => {
+ const subscription = Keyboard.addListener(
+ Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
+ () => {
+ if (closed.current) setUnexpectedShows((count) => count + 1);
+ },
+ );
+ return () => subscription.remove();
+ }, []);
+ return (
+
+
+ Close the focused preview to unmount its input and Keyflow hook
+ together.
+
+
+ {open ? 'Preview open' : 'Preview closed'} · Unexpected keyboard shows:{' '}
+ {unexpectedShows}
+
+ {
+ closed.current = false;
+ setUnexpectedShows(0);
+ setOpen(true);
+ }}
+ />
+ {open && (
+ {
+ closed.current = true;
+ setOpen(false);
+ }}
+ />
+ )}
+
+ );
+}
diff --git a/example/src/screens/TransparencyScreen.tsx b/example/src/screens/TransparencyScreen.tsx
index 3c12868..5ad8e91 100644
--- a/example/src/screens/TransparencyScreen.tsx
+++ b/example/src/screens/TransparencyScreen.tsx
@@ -48,6 +48,7 @@ export function TransparencyScreen() {
transparentKeyflowTheme,
);
const { inputRef: input, keyflowInputProps: bindings } = useKeyflow({
+ autoFocus: true,
keyboardAppearance: 'light',
keyflowTheme,
onKeyboardFrameChange: (next) => {
@@ -233,7 +234,6 @@ export function TransparencyScreen() {
UITextPosition? {
+ guard let hit = input.closestPosition(to: target) else { return nil }
+ func distance(to position: UITextPosition) -> CGFloat {
+ let caret = input.caretRect(for: position)
+ return hypot(caret.midX - target.x, caret.midY - target.y)
+ }
+ var best = hit
+ let hitDistance = distance(to: hit)
+ var bestDistance = hitDistance
+ for direction in [-1, 1] {
+ var current = hit
+ var currentDistance = hitDistance
+ while let candidate = input.position(from: current, offset: direction) {
+ let candidateDistance = distance(to: candidate)
+ guard candidateDistance <= currentDistance + 0.01 else { break }
+ if candidateDistance < bestDistance - 0.01
+ || (abs(candidateDistance - bestDistance) <= 0.01
+ && input.compare(candidate, to: best) == .orderedAscending)
+ {
+ best = candidate
+ bestDistance = candidateDistance
+ }
+ current = candidate
+ currentDistance = candidateDistance
+ }
+ }
+ return best
+ }
+
func move(_ input: UIView & UITextInput, translation: CGPoint) {
if origin == nil { begin(input) }
guard let origin else { return }
let target = CGPoint(x: origin.x + translation.x, y: origin.y + translation.y)
- guard let position = input.closestPosition(to: target) else { return }
+ guard let position = nearestCaretPosition(in: input, to: target) else { return }
let before = input.caretRect(for: position)
if editor == nil {
editor = input
@@ -95,6 +133,22 @@ final class KeyflowCursorNavigator {
let y = min(
max(target.y + after.midY - before.midY, input.bounds.minY + height / 2),
input.bounds.maxY - height / 2)
- floatingCaret.frame = CGRect(x: x - width / 2, y: y - height / 2, width: width, height: height)
+ // React Native applies horizontal padding by overriding UITextField's
+ // editing rect, while UIKit's caretRect(for:) omits that inset. Draw the
+ // floating caret in the same visual coordinate space as the text.
+ let textInset =
+ (input as? UITextField).map { $0.editingRect(forBounds: $0.bounds).minX - $0.bounds.minX }
+ ?? 0
+ let visualX = min(
+ max(x + textInset, input.bounds.minX + width / 2), input.bounds.maxX - width / 2)
+ floatingCaret.frame = CGRect(
+ x: visualX - width / 2, y: y - height / 2, width: width, height: height)
+ }
+
+ func end(_: UIView & UITextInput) {
+ // Every move already resolves and applies the closest text position. Do
+ // not hit-test again on release: UITextField can choose the adjacent slot
+ // at a boundary even though the floating caret showed the correct one.
+ reset()
}
}
diff --git a/ios/KeyflowInputView.swift b/ios/KeyflowInputView.swift
index 219d2b9..babaca4 100644
--- a/ios/KeyflowInputView.swift
+++ b/ios/KeyflowInputView.swift
@@ -2,6 +2,8 @@ import ExpoModulesCore
import UIKit
final class KeyflowInputView: ExpoView {
+ // Match the horizontal travel of Apple's space-trackpad gesture.
+ private static let horizontalCursorMovementScale: CGFloat = 1.5
var onKeyflowModeChange: (([String: Any]) -> Void)?
var onKeyflowFrameChange: (([String: Any]) -> Void)?
private var lastKeyboardFrame: CGRect?
@@ -57,7 +59,7 @@ final class KeyflowInputView: ExpoView {
])
}
if attachedEditor !== field {
- detachInput()
+ detachInput(resigningFocus: attachedEditor?.isFirstResponder == true)
attachedEditor = field
savedInputView = field.inputView
savedAccessoryView = field.inputAccessoryView
@@ -90,7 +92,7 @@ final class KeyflowInputView: ExpoView {
updateInputContext()
}
- private func detachInput() {
+ private func detachInput(resigningFocus: Bool = false) {
guard let field = attachedEditor else { return }
keyboard.cancelInteractions()
if let control = field as? UITextField {
@@ -107,7 +109,8 @@ final class KeyflowInputView: ExpoView {
self, name: UITextView.textDidEndEditingNotification, object: field)
}
cursorNavigator.reset()
- field.keyflowSetInputViews(savedInputView, accessory: savedAccessoryView)
+ field.keyflowRestoreInputViews(
+ savedInputView, accessory: savedAccessoryView, resigningFocus: resigningFocus)
field.keyflowSetCorrection(savedAutocorrection, spellChecking: savedSpellChecking)
field.inputAssistantItem.leadingBarButtonGroups = savedLeadingBarButtonGroups
field.inputAssistantItem.trailingBarButtonGroups = savedTrailingBarButtonGroups
@@ -297,7 +300,7 @@ final class KeyflowInputView: ExpoView {
}
func cleanup() {
- detachInput()
+ detachInput(resigningFocus: true)
removeFromSuperview()
}
@@ -447,7 +450,7 @@ final class KeyflowInputView: ExpoView {
case .beginCursorMovement:
cursorNavigator.begin(textField)
case .endCursorMovement:
- cursorNavigator.reset()
+ cursorNavigator.end(textField)
case .text(let value):
cursorNavigator.reset()
let now = CACurrentMediaTime()
@@ -464,19 +467,17 @@ final class KeyflowInputView: ExpoView {
lastSpaceTime = value == " " ? now : 0
}
case .moveCursor(let translation):
- cursorNavigator.move(textField, translation: translation)
+ cursorNavigator.move(
+ textField,
+ translation: CGPoint(
+ x: translation.x * Self.horizontalCursorMovementScale,
+ y: translation.y
+ ))
case .delete:
cursorNavigator.reset()
textField.deleteBackward()
case .submit:
- // Keep React Native's submitBehavior and onSubmitEditing event pipeline.
- if let field = textField as? UITextField {
- if field.delegate?.textFieldShouldReturn?(field) ?? true { field.resignFirstResponder() }
- } else {
- // UIKit invokes React Native's text-view delegate for newline insertion,
- // preserving submitBehavior, filters, and onSubmitEditing.
- textField.insertText("\n")
- }
+ dispatchKeyflowSubmit(textField)
case .dismiss:
textField.resignFirstResponder()
case .nextLanguage:
diff --git a/ios/KeyflowKey.swift b/ios/KeyflowKey.swift
index d36778f..783e717 100644
--- a/ios/KeyflowKey.swift
+++ b/ios/KeyflowKey.swift
@@ -46,6 +46,7 @@ final class KeyflowKey: UIView {
}
}
private let icon = UIImageView()
+ private(set) var displayedSymbol: String?
private let preview = UILabel()
private let previewCallout = KeyflowCallout()
var hidesLegend = false {
@@ -109,6 +110,7 @@ final class KeyflowKey: UIView {
required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
func setSymbol(_ name: String) {
+ displayedSymbol = name
if name == "keyflow.symbols" {
// The native page switch uses an upright number sign, not the slanted
// text glyph. Draw the three marks as one template, just like other icons.
@@ -138,6 +140,15 @@ final class KeyflowKey: UIView {
label.isHidden = true
}
+ func setActionContent(_ value: String, symbol: String?) {
+ caption = value
+ icon.image = nil
+ displayedSymbol = nil
+ label.isHidden = false
+ if let symbol { setSymbol(symbol) }
+ setNeedsLayout()
+ }
+
private var sectionName: String {
if padUnfilled && action != .delete { return "specialKeys" }
if isPadKey && action == .letters { return "keys" }
@@ -359,7 +370,8 @@ final class KeyflowKey: UIView {
face.backgroundColor =
isSelectionChoice
? .clear : UIColor(keyflowHex: isPressed ? theme.pressedKeyBackground : fill)
- face.layer.cornerRadius = CGFloat(theme.keyCornerRadius)
+ face.layer.cornerRadius = min(
+ max(0, CGFloat(theme.keyCornerRadius)), min(face.bounds.width, face.bounds.height) / 2)
face.layer.shadowColor = UIColor.black.cgColor
face.layer.shadowColor = UIColor(keyflowHex: theme.keyShadow).cgColor
face.layer.shadowOpacity = theme.material == "raised" && !isSelectionChoice ? 1 : 0
@@ -382,7 +394,9 @@ final class KeyflowKey: UIView {
face.layer.borderColor = sourceTheme.sections?[sectionName].map {
UIColor(keyflowHex: $0.borderColor).cgColor
}
- face.layer.borderWidth = CGFloat(sourceTheme.sections?[sectionName]?.borderWidth ?? 0)
+ face.layer.borderWidth =
+ isSelectionChoice
+ ? 0 : CGFloat(sourceTheme.sections?[sectionName]?.borderWidth ?? 0)
let size = isText && caption != "space" ? CGFloat(theme.fontSize) : 16
label.font = theme.font(size: size, keyboard: true, character: caption)
let previewTheme = sourceTheme.styled("preview")
diff --git a/ios/KeyflowKeyboardView.swift b/ios/KeyflowKeyboardView.swift
index 4af8ef0..e0f4c3f 100644
--- a/ios/KeyflowKeyboardView.swift
+++ b/ios/KeyflowKeyboardView.swift
@@ -335,7 +335,22 @@ final class KeyflowKeyboardView: UIView {
}
backgroundColor = .clear
panelBottom.backgroundColor = UIColor(keyflowHex: theme.background)
- for key in rows.flatMap({ $0 }) { key.theme = theme }
+ for key in rows.flatMap({ $0 }) {
+ if key.action == .submit {
+ let fallback = language.base == "fr" ? "retour" : "return"
+ if let text = theme.returnKeyContent?.text {
+ key.setActionContent(text, symbol: nil)
+ } else {
+ let name = theme.returnKeyContent?.icon ?? "return"
+ let symbols = [
+ "return": "return", "arrow-right": "arrow.right", "checkmark": "checkmark",
+ "send": "paperplane", "search": "magnifyingglass",
+ ]
+ key.setActionContent(fallback, symbol: symbols[name] ?? "return")
+ }
+ }
+ key.theme = theme
+ }
setNeedsLayout()
}
@@ -584,8 +599,6 @@ final class KeyflowKeyboardView: UIView {
}
holdWork?.cancel()
if cursorMode && id == heldTouch {
- let point = touch.location(in: self)
- onAction?(.moveCursor(CGPoint(x: point.x - cursorOriginX, y: point.y - cursorOriginY)))
cancelTouches()
continue
}
@@ -687,16 +700,21 @@ final class KeyflowKeyboardView: UIView {
accentCallout.cornerRadius = tablet ? 8 : 10
accentCallout.bubble = accentCallout.bounds
accentCallout.stem = .zero
- accentCallout.configure(theme.styled("preview"))
+ var previewTheme = theme.styled("preview")
+ previewTheme.strokeWidth = 0
+ accentCallout.configure(previewTheme)
accentCallout.isHidden = false
bringSubviewToFront(accentCallout)
- let indicatorSize = CGSize(width: tablet ? 30 : 38, height: tablet ? 52 : 40)
+ let indicatorSize = CGSize(
+ width: min(tablet ? 30 : 38, itemWidth), height: tablet ? 52 : itemHeight)
accentSelectionIndicator.bounds = CGRect(origin: .zero, size: indicatorSize)
accentSelectionIndicator.center = CGPoint(
x: start + selectedOffset,
y: top + verticalPadding + (CGFloat(selectedRow) + 0.5) * itemHeight)
- accentSelectionIndicator.layer.cornerRadius = tablet ? 8 : 10
+ let selectionRadius = max(0, CGFloat(theme.styled("keys").keyCornerRadius))
+ accentSelectionIndicator.layer.cornerRadius = min(
+ selectionRadius, min(indicatorSize.width, indicatorSize.height) / 2)
accentSelectionIndicator.backgroundColor = UIColor(
keyflowHex: theme.sections?["selection"]?.background ?? theme.selectedKeyBackground)
accentSelectionIndicator.isHidden = choices.count == 1
diff --git a/ios/KeyflowSubmit.swift b/ios/KeyflowSubmit.swift
new file mode 100644
index 0000000..ac2f52f
--- /dev/null
+++ b/ios/KeyflowSubmit.swift
@@ -0,0 +1,20 @@
+import UIKit
+
+/// Sends Return through UIKit so React Native remains responsible for
+/// `submitBehavior`, `onSubmitEditing`, newline insertion, and blur behavior.
+func dispatchKeyflowSubmit(_ editor: UIView & UITextInput) {
+ if let field = editor as? UITextField {
+ if field.delegate?.textFieldShouldReturn?(field) ?? true { field.resignFirstResponder() }
+ } else if let view = editor as? UITextView {
+ let selected = view.selectedRange
+ let acceptsReturn =
+ view.delegate?.textView?(
+ view,
+ shouldChangeTextIn: selected,
+ replacementText: "\n"
+ ) ?? true
+ if acceptsReturn { view.insertText("\n") }
+ } else {
+ editor.insertText("\n")
+ }
+}
diff --git a/ios/KeyflowTheme.swift b/ios/KeyflowTheme.swift
index 4aeed64..6f7568f 100644
--- a/ios/KeyflowTheme.swift
+++ b/ios/KeyflowTheme.swift
@@ -1,6 +1,7 @@
import UIKit
struct KeyflowTheme: Decodable, Equatable {
+ var returnKeyContent: KeyflowReturnKeyContent?
var sections: [String: KeyflowSectionStyle]?
var sectionOverrides: [String: KeyflowSectionOverrides]?
var strokeColor: String?
@@ -57,6 +58,11 @@ struct KeyflowTheme: Decodable, Equatable {
}
}
+struct KeyflowReturnKeyContent: Decodable, Equatable {
+ var text: String?
+ var icon: String?
+}
+
extension UIColor {
convenience init(keyflowHex: String) {
let hex = String(keyflowHex.dropFirst())
diff --git a/scripts/android-tests/app.py b/scripts/android-tests/app.py
index 524b119..dae476b 100644
--- a/scripts/android-tests/app.py
+++ b/scripts/android-tests/app.py
@@ -16,8 +16,8 @@
class ExampleSuite:
PRIORITY_CASES = ('transitions', 'transparency', 'layouts')
- CASES = PRIORITY_CASES + ('editing', 'multiline', 'pages_and_accents', 'handoff', 'system_editor', 'submit', 'customization')
- SMOKE_CASES = ('core',)
+ CASES = PRIORITY_CASES + ('editing', 'multiline', 'pages_and_accents', 'handoff', 'system_editor', 'submit', 'customization', 'teardown')
+ SMOKE_CASES = ('core', 'teardown')
def __init__(self, serial, output):
self.serial = serial
self.output = Path(output)
@@ -288,6 +288,25 @@ def editing(self):
self.key(metrics, 'a')
self.wait(self.text, lambda text: text is not None and text.lower() == (remaining+'a').lower())
+ def teardown(self):
+ self.open('Test focused teardown')
+ self.tap('OPEN PREVIEW')
+ self.wait(lambda: self.find('Teardown preview input'), lambda node: node is not None and node.get('focused') == 'true')
+ def keyboard_visible():
+ # UIAutomator dumps only the active app window, not this non-focusable popup.
+ windows = self.adb('shell', 'dumpsys', 'window', 'windows').decode()
+ return any('PopupWindow:' in window.splitlines()[0]
+ and 'package=com.keyflow.example ' in window
+ and 'isVisible=true' in window
+ for window in re.split(r'\n Window #', windows)[1:])
+ self.wait(keyboard_visible)
+ self.output.joinpath('teardown-before.png').write_bytes(self.adb('exec-out', 'screencap', '-p'))
+ self.tap('CLOSE PREVIEW')
+ self.wait(lambda: self.find('Teardown preview input'), lambda node: node is None)
+ self.wait(keyboard_visible, lambda visible: not visible)
+ status = self.wait(lambda: self.find('Preview closed', prefix=True))
+ assert 'Unexpected keyboard shows: 0' in status.get('text', ''), status
+
def core(self):
self.open('Compare native interactions')
metrics = self.reset('Empty', '')
diff --git a/scripts/android-tests/test_app.py b/scripts/android-tests/test_app.py
index 754e2b5..99859d6 100644
--- a/scripts/android-tests/test_app.py
+++ b/scripts/android-tests/test_app.py
@@ -50,8 +50,8 @@ def test_ci_android_runner_does_not_spawn_macos_power_tool(self):
process.assert_not_called()
def test_ci_core_profile_runs_real_required_case_and_local_default_retains_full_inventory(self):
- self.assertEqual(ExampleSuite.SMOKE_CASES, ('core',))
- self.assertEqual(set(ExampleSuite.CASES), {'editing','multiline','pages_and_accents','handoff','system_editor','submit','transitions','customization','transparency','layouts'})
+ self.assertEqual(ExampleSuite.SMOKE_CASES, ('core', 'teardown'))
+ self.assertEqual(set(ExampleSuite.CASES), {'editing','multiline','pages_and_accents','handoff','system_editor','submit','transitions','customization','transparency','layouts','teardown'})
with tempfile.TemporaryDirectory() as output:
suite = ExampleSuite.__new__(ExampleSuite)
suite.output = Path(output)
@@ -61,10 +61,11 @@ def test_ci_core_profile_runs_real_required_case_and_local_default_retains_full_
suite.save_log = lambda: None
visited = []
suite.core = lambda: visited.append('core')
+ suite.teardown = lambda: visited.append('teardown')
with patch.dict('os.environ', {'KEYFLOW_CI_PROFILE':'smoke'}):
suite.run()
- self.assertEqual(visited, ['core'])
- self.assertEqual(suite.results, [{'test':'core','result':'PASS'}])
+ self.assertEqual(visited, ['core', 'teardown'])
+ self.assertEqual(suite.results, [{'test':'core','result':'PASS'}, {'test':'teardown','result':'PASS'}])
with patch.dict('os.environ', {'KEYFLOW_CI_PROFILE':'typo'}):
with self.assertRaisesRegex(AssertionError, 'Invalid CI profile'):
suite.run()
@@ -82,8 +83,8 @@ def test_lab_card_cannot_be_tapped_through_tablet_taskbar(self):
self.assertFalse(ExampleSuite.card_visible(visible, viewport))
def test_priority_failures_stop_before_remaining_cases_and_keep_report(self):
- self.assertEqual(len(ExampleSuite.CASES), 10)
- self.assertEqual(len(set(ExampleSuite.CASES)), 10)
+ self.assertEqual(len(ExampleSuite.CASES), 11)
+ self.assertEqual(len(set(ExampleSuite.CASES)), 11)
self.assertEqual(ExampleSuite.CASES[:3], ExampleSuite.PRIORITY_CASES)
with tempfile.TemporaryDirectory() as output:
suite = ExampleSuite.__new__(ExampleSuite)
diff --git a/scripts/ci/run-ios.sh b/scripts/ci/run-ios.sh
index ec70cf5..86cc229 100644
--- a/scripts/ci/run-ios.sh
+++ b/scripts/ci/run-ios.sh
@@ -6,7 +6,7 @@ shift
keyflow_profile="${KEYFLOW_CI_PROFILE:-full}"
[[ "$keyflow_profile" == full || "$keyflow_profile" == smoke ]]
if [[ "$keyflow_profile" == smoke ]]; then
- set -- testKeyflowCoreInteractions
+ set -- testKeyflowCoreInteractions testFocusedHookUnmountDoesNotShowSystemKeyboard
elif [[ "${1:-}" == "--shard" ]]; then
[[ "$#" == 2 ]]
keyflow_test_names=$(node scripts/ci/ios-interaction-shards.mjs "$2")
diff --git a/scripts/ci/workflow.test.mjs b/scripts/ci/workflow.test.mjs
index c556ade..d4698c5 100644
--- a/scripts/ci/workflow.test.mjs
+++ b/scripts/ci/workflow.test.mjs
@@ -177,7 +177,10 @@ test('PRs require core device coverage while scheduled and manual runs retain fu
);
const ios = readFileSync('scripts/ci/run-ios.sh', 'utf8');
assert.match(ios, /KEYFLOW_CI_PROFILE:-full/);
- assert.match(ios, /set -- testKeyflowCoreInteractions/);
+ assert.match(
+ ios,
+ /set -- testKeyflowCoreInteractions testFocusedHookUnmountDoesNotShowSystemKeyboard/,
+ );
assert.ok(
ios.indexOf('node scripts/run-ios-qwerty-tests.mjs') <
ios.indexOf('xcodebuild test-without-building'),
@@ -240,10 +243,19 @@ test('device sources contain the proven inventory plus glyph and Shift regressio
'testPanelCoversBottomCornersWithoutExtraOpacity',
'testPanelMaskLayoutDoesNotStartImplicitAnimations',
'testTrackpadCaretFloatsBetweenCharactersAndRestoresOnRelease',
+ 'testTrackpadSnapsToTheVisuallyNearestCaretInsteadOfTheTrailingHit',
+ 'testTrackpadReleaseCommitsTheVisibleCaretBoundary',
+ 'testTrackpadReleaseDoesNotOverrideTheLastResolvedPosition',
+ 'testTrackpadSelectsTheExactVisibleBoundaryWhenDraggingBackward',
'testMultilineCursorMovesAcrossVisualLinesAndEmoji',
'testTrackpadEmitsBothCursorAxes',
+ 'testTrackpadReleaseKeepsTheLastVisibleCaretPosition',
'testAccentPresentationRespectsHapticsSetting',
'testWideAccentUsesOnlyPopupSelectionHighlight',
+ 'testTeardownResignsBeforeRestoringInputViews',
+ 'testReturnActionLetsReactNativeChooseSubmitOrNewline',
+ 'testReturnKeySupportsCustomTextAndPortableIcons',
+ 'testAccentPopupOmitsBordersAndUsesKeyRadius',
'testPhoneDoubleShiftLocksCaseAndShowsLockGlyph',
'testSpacePressChangesDefaultFillAndRestoresOnRelease',
'testSpacePressRestoresCustomFillOnCancellation',
@@ -261,9 +273,13 @@ test('device sources contain the proven inventory plus glyph and Shift regressio
'testTabletShiftTurnsCapsLockOff',
]
: [
+ 'testFocusedHookUnmountDoesNotShowSystemKeyboard',
'testMultilineEditorSupportsReturnAndVerticalTrackpad',
'testRemountedInputUsesTheSelectedKeyboardBeforeTyping',
'testKeyflowCoreInteractions',
+ 'testKeyflowCoreInteractionsSpaceTrackpadCaretLandsBetweenAAndL',
+ 'testKeyflowCoreInteractionsSingleLineReleaseDoesNotSnapRight',
+ 'testTabletKeyflowCoreInteractionsSpaceTrackpadCaretLandingMatchesApple',
'testMultilineRemountPreservesFocus',
];
assert.deepEqual(
@@ -305,6 +321,8 @@ test('device sources contain the proven inventory plus glyph and Shift regressio
...regressions,
'com.keyflow.KeyflowRenderingTest#reactOwnedSoftInputFlagSurvivesModeChangesAndDetach',
'com.keyflow.KeyflowRenderingTest#nativeEditorSoftInputFlagRestoresItsOriginalValue',
+ 'com.keyflow.KeyflowRenderingTest#returnActionLetsReactNativeChooseSubmitOrNewline',
+ 'com.keyflow.KeyflowRenderingTest#returnKeySupportsCustomText',
].sort(),
);
});
diff --git a/scripts/ios-tests/KeyflowQwertyTests.swift b/scripts/ios-tests/KeyflowQwertyTests.swift
index 93742ea..8f79969 100644
--- a/scripts/ios-tests/KeyflowQwertyTests.swift
+++ b/scripts/ios-tests/KeyflowQwertyTests.swift
@@ -18,6 +18,11 @@ final class KeyflowQwertyTests: XCTestCase {
// Set the sensor before launch so a previous landscape test cannot leave a
// portrait scene racing with a late orientation notification after launch.
XCUIDevice.shared.orientation = .portrait
+ if name.contains("testFocusedHookUnmountDoesNotShowSystemKeyboard") {
+ app.launch()
+ XCTAssertTrue(app.scrollViews.firstMatch.waitForExistence(timeout: 30))
+ return
+ }
launchInteractionScreen()
if UIDevice.current.userInterfaceIdiom == .pad {
setOrientation(.portrait)
@@ -94,14 +99,22 @@ final class KeyflowQwertyTests: XCTestCase {
}
// The JS tab can select before UIKit finishes presenting the requested
// keyboard. Do not cancel that presentation with an immediate reset.
- if Self.preparedSystemKeyboard { _ = key(["space", " "]) }
+ if Self.preparedSystemKeyboard {
+ if native {
+ let editor = app.textFields.firstMatch.exists
+ ? app.textFields.firstMatch : app.textViews.firstMatch
+ center(editor).tap()
+ }
+ _ = key(["space", " "])
+ }
}
func reset(_ name: String) {
settledKeyboardGeometry = nil
let previousEditor = app.textViews.firstMatch.exists ? app.textViews.firstMatch : app.textFields.firstMatch
let previousInputIdentifier = previousEditor.identifier
app.buttons["Reset \(name)"].tap()
- let expected = name == "Empty" ? "" : "alpha beta"
+ let expected =
+ name == "Empty" ? "" : name == "Backward Cursor" ? "beta alpha" : "alpha beta"
let resetFinished = NSPredicate { [self] _, _ in
app.textFields.firstMatch.exists && app.textFields.firstMatch.identifier != previousInputIdentifier && text == expected
}
@@ -571,6 +584,71 @@ final class KeyflowQwertyTests: XCTestCase {
capture(native ? "apple-trackpad" : "keyflow-trackpad")
}
}
+
+ private func dragBackwardAndReadSelection(distance: CGFloat = -24) throws -> Int {
+ let previousState = try readInteractionState()
+ let previousRequest = previousState["diagnosticRequest"] as? Int ?? 0
+ let space = center(key(["space", " "]))
+ space.press(
+ forDuration: 0.7,
+ thenDragTo: space.withOffset(CGVector(dx: distance, dy: 0)),
+ withVelocity: .slow,
+ thenHoldForDuration: 0.1
+ )
+ center(app.buttons["Inspect keyboard state"]).tap()
+ var selection: Int?
+ let freshSelection = NSPredicate { [self] _, _ in
+ guard
+ let raw = app.staticTexts["interaction-state"].label
+ .replacingOccurrences(of: "Diagnostic state: ", with: "")
+ .data(using: .utf8),
+ let state = (try? JSONSerialization.jsonObject(with: raw)) as? [String: Any],
+ (state["diagnosticRequest"] as? Int ?? 0) > previousRequest
+ else { return false }
+ selection = state["selectionStart"] as? Int
+ return selection != nil && selection == state["selectionEnd"] as? Int
+ }
+ XCTAssertEqual(
+ XCTWaiter.wait(
+ for: [XCTNSPredicateExpectation(predicate: freshSelection, object: nil)], timeout: 5),
+ .completed,
+ "The released caret selection must be observable"
+ )
+ return try XCTUnwrap(selection)
+ }
+
+ func testKeyflowCoreInteractionsSpaceTrackpadCaretLandsBetweenAAndL() throws {
+ mode(false)
+ reset("Backward Cursor")
+ let selection = try dragBackwardAndReadSelection()
+ capture("keyflow-caret-between-a-and-l")
+ XCTAssertEqual(selection, 6, "The caret must land at beta a|lpha, not beta al|pha")
+ }
+
+ func testKeyflowCoreInteractionsSingleLineReleaseDoesNotSnapRight() throws {
+ mode(false)
+ reset("Backward Cursor")
+ let selection = try dragBackwardAndReadSelection(distance: -50)
+ capture("keyflow-single-line-release-between-b-and-e")
+ XCTAssertEqual(selection, 1, "The caret must land at b|eta alpha, not be|ta alpha")
+ }
+
+ func testTabletKeyflowCoreInteractionsSpaceTrackpadCaretLandingMatchesApple() throws {
+ var selections: [Int] = []
+ for native in [true, false] {
+ mode(native)
+ reset("Backward Cursor")
+ let offset = try dragBackwardAndReadSelection()
+ capture(native ? "apple-caret-inside-alpha" : "keyflow-caret-inside-alpha")
+ print("KEYFLOW_TRACKPAD_SELECTION mode=\(native ? "apple" : "keyflow") offset=\(offset)")
+ selections.append(offset)
+ }
+ XCTAssertEqual(
+ selections[1], selections[0],
+ "Keyflow must land at the same beta alpha caret boundary as Apple for the same drag"
+ )
+ }
+
func testShiftDragMatchesApple() {
var expected = ""
for native in [true, false] {
@@ -672,6 +750,10 @@ final class KeyflowQwertyTests: XCTestCase {
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: switched, object: nil)], timeout: 15), .completed)
waitForText("alpha beta", context: "Switching must preserve the app's text")
+ // The diagnostic checks configuration, not the completed UIKit handoff.
+ // Wait for the custom keyboard's final geometry before asking it to rotate.
+ settledKeyboardGeometry = nil
+ _ = key(["H", "h"])
setOrientation(.landscapeRight)
// The developer-menu launcher can cover an edge key in phone landscape.
// Check a center key, then inspect through the visible portrait controls.
@@ -856,10 +938,12 @@ final class KeyflowQwertyTests: XCTestCase {
capture("ipad-\(orientation == .portrait ? "portrait" : "landscape")-\(type.lowercased())-\(custom ? "keyflow" : "apple")")
}
}
- func openLab(_ label: String) {
+ func openLab(_ label: String, fromHome: Bool = false) {
let back = app.navigationBars.buttons["Keyflow"]
- XCTAssertTrue(back.waitForExistence(timeout: 5))
- center(back).tap()
+ if !fromHome {
+ XCTAssertTrue(back.waitForExistence(timeout: 5))
+ center(back).tap()
+ }
let hidden = NSPredicate { [self] _, _ in
let firstKey = app.keys.firstMatch
return !firstKey.exists || !firstKey.isHittable
@@ -868,7 +952,9 @@ final class KeyflowQwertyTests: XCTestCase {
XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: hidden, object: nil)], timeout: 10),
.completed, "Keyboard must dismiss before navigating the lab")
let card = app.buttons[label]
- func viewport() -> CGRect { app.scrollViews.firstMatch.frame.intersection(app.frame) }
+ let scroll = app.scrollViews.firstMatch
+ XCTAssertTrue(scroll.waitForExistence(timeout: 10), "Lab navigation must finish before measuring its scroll viewport")
+ func viewport() -> CGRect { scroll.frame.intersection(app.frame) }
func visible() -> Bool {
card.exists && card.isHittable && !card.frame.isEmpty && viewport().contains(card.frame)
}
@@ -904,6 +990,36 @@ final class KeyflowQwertyTests: XCTestCase {
// the scroll viewport. Freeze the fully visible target after deceleration.
center(card).tap()
}
+ func testFocusedHookUnmountDoesNotShowSystemKeyboard() {
+ openLab("Test focused teardown", fromHome: !app.navigationBars.buttons["Keyflow"].exists)
+ app.buttons["Open preview"].tap()
+ let avoidingView = app.otherElements["teardown-avoiding-view"]
+ XCTAssertTrue(avoidingView.waitForExistence(timeout: 10))
+ let input = app.textFields["Teardown preview input"]
+ XCTAssertTrue(input.waitForExistence(timeout: 10))
+ expectsSystemKeyboard = false
+ let customKey = key(["Q", "q"])
+ let close = app.buttons["Close preview"]
+ let panel = app.otherElements["teardown-preview-panel"]
+ XCTAssertTrue(panel.waitForExistence(timeout: 5))
+ XCTAssertLessThanOrEqual(
+ panel.frame.maxY, customKey.frame.minY + 1,
+ "KeyflowAvoidingView must move the complete composer above Keyflow")
+ capture("focused-hook-before-close")
+ close.tap()
+ XCTAssertTrue(avoidingView.waitForNonExistence(timeout: 5))
+ XCTAssertTrue(input.waitForNonExistence(timeout: 5))
+ let dismissed = NSPredicate { [self] _, _ in
+ let customKey = app.descendants(matching: .any).matching(identifier: "keyflow-key-q").firstMatch
+ return !customKey.exists && !app.keyboards.firstMatch.exists
+ }
+ XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: dismissed, object: nil)], timeout: 5), .completed)
+ let status = app.staticTexts["teardown-status"]
+ XCTAssertTrue(status.label.contains("Preview closed"))
+ XCTAssertTrue(status.label.contains("Unexpected keyboard shows: 0"))
+ capture("focused-hook-after-close")
+ }
+
func testTransitionDiagnosticsPass() {
openLab("Test keyboard transitions")
let run = app.buttons["Run transition tests"]
diff --git a/scripts/ios-tests/KeyflowRenderingTests.swift b/scripts/ios-tests/KeyflowRenderingTests.swift
index 8d9547b..44dbce1 100644
--- a/scripts/ios-tests/KeyflowRenderingTests.swift
+++ b/scripts/ios-tests/KeyflowRenderingTests.swift
@@ -2,6 +2,90 @@ import XCTest
import UIKit
final class KeyflowRenderingTests: XCTestCase {
+ func testReturnActionLetsReactNativeChooseSubmitOrNewline() {
+ let field = UITextField()
+ field.text = "message"
+ let fieldDelegate = ReturnFieldDelegate()
+ field.delegate = fieldDelegate
+ dispatchKeyflowSubmit(field)
+ XCTAssertEqual(fieldDelegate.returnCount, 1)
+ XCTAssertEqual(field.text, "message", "A submit-only field must not insert a newline")
+
+ let textView = UITextView()
+ textView.text = "first line"
+ let newlineDelegate = ReturnTextViewDelegate(acceptsNewline: true)
+ textView.delegate = newlineDelegate
+ dispatchKeyflowSubmit(textView)
+ XCTAssertEqual(newlineDelegate.returnCount, 1)
+ XCTAssertEqual(textView.text, "first line\n")
+
+ let submitView = UITextView()
+ submitView.text = "send this"
+ let submitDelegate = ReturnTextViewDelegate(acceptsNewline: false)
+ submitView.delegate = submitDelegate
+ dispatchKeyflowSubmit(submitView)
+ XCTAssertEqual(submitDelegate.returnCount, 1)
+ XCTAssertEqual(
+ submitView.text,
+ "send this",
+ "A multiline submit must be able to reject newline"
+ )
+ }
+
+ func testReturnKeySupportsCustomTextAndPortableIcons() throws {
+ let keyboard = KeyflowKeyboardView()
+ let submit = try XCTUnwrap(
+ keyboard.subviews.compactMap { $0 as? KeyflowKey }.first { $0.action == .submit })
+ var theme = keyboard.theme
+ theme.returnKeyContent = KeyflowReturnKeyContent(text: "Send", icon: nil)
+ keyboard.theme = theme
+ XCTAssertEqual(submit.caption, "Send")
+ XCTAssertNil(submit.displayedSymbol)
+
+ theme.returnKeyContent = KeyflowReturnKeyContent(text: nil, icon: "arrow-right")
+ keyboard.theme = theme
+ XCTAssertEqual(submit.displayedSymbol, "arrow.right")
+ XCTAssertEqual(submit.accessibilityLabel, "return")
+ }
+
+ func testTeardownResignsBeforeRestoringInputViews() {
+ let field = TeardownField()
+ let original = UIView()
+ field.keyflowRestoreInputViews(original, accessory: nil, resigningFocus: true)
+ XCTAssertEqual(field.events, ["resign", "restore"])
+ XCTAssertFalse(field.isFirstResponder)
+ XCTAssertTrue(field.inputView === original)
+ }
+
+ func testAccentPopupOmitsBordersAndUsesKeyRadius() throws {
+ let style = KeyflowSectionStyle(
+ background: "#FFFF00", color: "#FFFFFF", placeholderColor: "#FFFFFF",
+ iconColor: "#FFFFFF", pressedBackground: "#FFFF00", pressedColor: "#FFFFFF",
+ borderColor: "#CC80FF", borderWidth: 4, cornerRadius: 3,
+ fontFamily: nil, fontSize: 22, fontWeight: "regular", iconSize: 22)
+ try withAccentPopup(selectionStyle: style) { keyboard, touch, choices, indicator in
+ let popup = try XCTUnwrap(keyboard.subviews.compactMap { $0 as? KeyflowCallout }.first { !$0.isHidden })
+ let outline = try XCTUnwrap(popup.layer.sublayers?.compactMap { $0 as? CAShapeLayer }.first)
+ XCTAssertEqual(outline.lineWidth, 0)
+ for choice in choices.prefix(3) {
+ touch.point = choice.center
+ keyboard.touchesMoved([touch], with: nil)
+ XCTAssertEqual(indicator.center, choice.center)
+ XCTAssertTrue(choice.frame.contains(indicator.frame))
+ XCTAssertEqual(indicator.bounds.height, UIDevice.current.userInterfaceIdiom == .pad ? 52 : choice.bounds.height)
+ XCTAssertEqual(choice.face.layer.borderWidth, 0)
+ XCTAssertEqual(indicator.layer.cornerRadius, min(indicator.bounds.width, indicator.bounds.height) / 2)
+ }
+ let attachment = XCTAttachment(image: UIGraphicsImageRenderer(bounds: keyboard.bounds.insetBy(dx: 0, dy: -160)).image { context in
+ context.cgContext.translateBy(x: 0, y: 160)
+ keyboard.layer.render(in: context.cgContext)
+ })
+ attachment.name = "borderless-accent-fill"
+ attachment.lifetime = .keepAlways
+ add(attachment)
+ }
+ }
+
func testDefaultFlatSmallSquareFits() { assertFits("default", "flat", 12.0, 0.0) }
func testDefaultFlatSmallRoundedFits() { assertFits("default", "flat", 12.0, 24.0) }
func testDefaultFlatLargeSquareFits() { assertFits("default", "flat", 32.0, 0.0) }
@@ -121,6 +205,136 @@ final class KeyflowRenderingTests: XCTestCase {
XCTAssertEqual(view.selectedRange.location, view.text.count)
}
+ func testTrackpadSnapsToTheVisuallyNearestCaretInsteadOfTheTrailingHit() throws {
+ final class TrailingBiasedTextView: UITextView {
+ override func closestPosition(to point: CGPoint) -> UITextPosition? {
+ super.closestPosition(to: CGPoint(x: point.x + 24, y: point.y))
+ }
+ }
+ let view = TrailingBiasedTextView(frame: CGRect(x: 0, y: 0, width: 240, height: 100))
+ view.font = UIFont.monospacedSystemFont(ofSize: 20, weight: .regular)
+ view.text = "abcdef"
+ view.selectedRange = NSRange(location: 2, length: 0)
+ view.layoutIfNeeded()
+ let start = view.caretRect(for: try XCTUnwrap(view.selectedTextRange).start)
+ let nextPosition = try XCTUnwrap(view.position(from: view.beginningOfDocument, offset: 3))
+ let next = view.caretRect(for: nextPosition)
+ let targetX = start.midX + (next.midX - start.midX) * 0.4
+ let cursor = KeyflowCursorNavigator()
+ cursor.begin(view)
+ cursor.move(view, translation: CGPoint(x: targetX - start.midX, y: 0))
+ XCTAssertEqual(
+ view.selectedRange.location, 2,
+ "A trailing-biased UIKit hit must not move past the visually nearest caret")
+ XCTAssertEqual(cursor.floatingCaret.frame.midX, targetX, accuracy: 0.01)
+ }
+
+ func testTrackpadReleaseCommitsTheVisibleCaretBoundary() throws {
+ final class PaddedTextField: UITextField {
+ override func textRect(forBounds bounds: CGRect) -> CGRect {
+ super.textRect(forBounds: bounds).inset(
+ by: UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12))
+ }
+ override func editingRect(forBounds bounds: CGRect) -> CGRect {
+ textRect(forBounds: bounds)
+ }
+ }
+ let field = PaddedTextField(frame: CGRect(x: 0, y: 0, width: 280, height: 48))
+ field.font = UIFont.systemFont(ofSize: 20)
+ field.text = "beta alpha"
+ field.layoutIfNeeded()
+ let end = field.endOfDocument
+ field.selectedTextRange = field.textRange(from: end, to: end)
+ let cursor = KeyflowCursorNavigator()
+ cursor.begin(field)
+ let afterA = try XCTUnwrap(field.position(from: field.beginningOfDocument, offset: 6))
+ let target = field.caretRect(for: afterA)
+ let initial = field.caretRect(for: end)
+ cursor.move(
+ field,
+ translation: CGPoint(x: target.midX - initial.midX, y: target.midY - initial.midY)
+ )
+ let selectedBeforeRelease = try XCTUnwrap(field.selectedTextRange)
+ XCTAssertEqual(field.offset(from: field.beginningOfDocument, to: selectedBeforeRelease.start), 6)
+ XCTAssertEqual(
+ cursor.floatingCaret.frame.midX, target.midX + 12, accuracy: 0.01,
+ "A single-line floating caret must include React Native's horizontal text inset")
+ cursor.end(field)
+
+ XCTAssertEqual(
+ field.offset(from: field.beginningOfDocument, to: try XCTUnwrap(field.selectedTextRange).start),
+ 6,
+ "Release must keep the caret at beta a|lpha when that is the visible boundary"
+ )
+ }
+
+ func testTrackpadReleaseDoesNotOverrideTheLastResolvedPosition() throws {
+ let field = UITextField(frame: CGRect(x: 0, y: 0, width: 280, height: 48))
+ field.font = UIFont.systemFont(ofSize: 20)
+ field.text = "beta alpha"
+ field.layoutIfNeeded()
+ let leading = try XCTUnwrap(field.position(from: field.beginningOfDocument, offset: 2))
+ let trailing = try XCTUnwrap(field.position(from: field.beginningOfDocument, offset: 3))
+ let leadingX = field.caretRect(for: leading).midX
+ let trailingX = field.caretRect(for: trailing).midX
+ let midpoint = (leadingX + trailingX) / 2
+
+ let backward = KeyflowCursorNavigator()
+ field.selectedTextRange = field.textRange(from: field.endOfDocument, to: field.endOfDocument)
+ backward.begin(field)
+ let endX = field.caretRect(for: field.endOfDocument).midX
+ backward.move(field, translation: CGPoint(x: midpoint - 0.5 - endX, y: 0))
+ backward.end(field)
+ XCTAssertEqual(
+ field.offset(from: field.beginningOfDocument, to: try XCTUnwrap(field.selectedTextRange).start),
+ 2,
+ "Release must preserve the leading position resolved by the final move"
+ )
+
+ let forward = KeyflowCursorNavigator()
+ field.selectedTextRange = field.textRange(
+ from: field.beginningOfDocument, to: field.beginningOfDocument)
+ forward.begin(field)
+ let beginningX = field.caretRect(for: field.beginningOfDocument).midX
+ forward.move(field, translation: CGPoint(x: midpoint + 0.5 - beginningX, y: 0))
+ forward.end(field)
+ XCTAssertEqual(
+ field.offset(from: field.beginningOfDocument, to: try XCTUnwrap(field.selectedTextRange).start),
+ 3,
+ "Release must preserve the trailing position resolved by the final move"
+ )
+ }
+
+ func testTrackpadSelectsTheExactVisibleBoundaryWhenDraggingBackward() throws {
+ let field = UITextField(frame: CGRect(x: 0, y: 0, width: 280, height: 48))
+ field.font = UIFont.systemFont(ofSize: 20)
+ field.text = "beta alpha"
+ let view = UITextView(frame: CGRect(x: 0, y: 0, width: 280, height: 100))
+ view.font = UIFont.systemFont(ofSize: 20)
+ view.text = "beta alpha"
+ let editors: [UIView & UITextInput] = [
+ field,
+ view,
+ ]
+ for editor in editors {
+ editor.layoutIfNeeded()
+ let end = editor.endOfDocument
+ editor.selectedTextRange = editor.textRange(from: end, to: end)
+ let startCaret = editor.caretRect(for: end)
+ let afterB = try XCTUnwrap(editor.position(from: editor.beginningOfDocument, offset: 1))
+ let target = editor.caretRect(for: afterB)
+ let navigator = KeyflowCursorNavigator()
+ navigator.begin(editor)
+ navigator.move(
+ editor,
+ translation: CGPoint(x: target.midX - startCaret.midX, y: target.midY - startCaret.midY)
+ )
+ let selected = try XCTUnwrap(editor.selectedTextRange)
+ XCTAssertEqual(editor.offset(from: editor.beginningOfDocument, to: selected.start), 1)
+ XCTAssertEqual(navigator.floatingCaret.frame.midX, target.midX, accuracy: 0.01)
+ }
+ }
+
func testMultilineCursorMovesAcrossVisualLinesAndEmoji() throws {
let view = UITextView(frame: CGRect(x: 0, y: 0, width: 150, height: 220))
view.font = UIFont.monospacedSystemFont(ofSize: 18, weight: .regular)
@@ -166,6 +380,25 @@ final class KeyflowRenderingTests: XCTestCase {
}
}
+ func testTrackpadReleaseKeepsTheLastVisibleCaretPosition() throws {
+ try withTrackpad { keyboard, touch, _ in
+ var actions: [KeyflowAction] = []
+ keyboard.onAction = { actions.append($0) }
+ touch.point.x += 24
+ keyboard.touchesMoved([touch], with: nil)
+
+ // A finger commonly shifts as it lifts. Releasing must commit the last
+ // visible caret instead of performing a hidden move at this new point.
+ touch.point.x += 12
+ keyboard.touchesEnded([touch], with: nil)
+
+ XCTAssertEqual(
+ actions,
+ [.moveCursor(CGPoint(x: 24, y: 0)), .endCursorMovement]
+ )
+ }
+ }
+
func testAccentPresentationRespectsHapticsSetting() throws {
for enabled in [false, true] {
var pulses = 0
@@ -545,8 +778,16 @@ final class KeyflowRenderingTests: XCTestCase {
}
}
- private func withAccentPopup(value: String = "e", hapticsEnabled: Bool = false, feedback: (() -> Void)? = nil, _ check: (KeyflowKeyboardView, AccentTouch, [KeyflowKey], UIView) throws -> Void) throws {
+ private func withAccentPopup(value: String = "e", hapticsEnabled: Bool = false, feedback: (() -> Void)? = nil, selectionStyle: KeyflowSectionStyle? = nil, _ check: (KeyflowKeyboardView, AccentTouch, [KeyflowKey], UIView) throws -> Void) throws {
let keyboard = KeyflowKeyboardView()
+ if let selectionStyle {
+ var theme = keyboard.theme
+ var keys = selectionStyle
+ keys.cornerRadius = 100
+ keys.background = "#163B50"
+ theme.sections = ["selection": selectionStyle, "keys": keys, "preview": keys]
+ keyboard.theme = theme
+ }
keyboard.hapticsEnabled = hapticsEnabled
if let feedback { keyboard.hapticFeedback = feedback }
let screen = UIScreen.main.bounds.size
@@ -592,3 +833,43 @@ final class KeyflowRenderingTests: XCTestCase {
XCTAssertGreaterThan(metrics["keyCount"] as? Int ?? 0, 10)
}
}
+
+private final class ReturnFieldDelegate: NSObject, UITextFieldDelegate {
+ var returnCount = 0
+
+ func textFieldShouldReturn(_ textField: UITextField) -> Bool {
+ returnCount += 1
+ return false
+ }
+}
+
+private final class ReturnTextViewDelegate: NSObject, UITextViewDelegate {
+ let acceptsNewline: Bool
+ var returnCount = 0
+
+ init(acceptsNewline: Bool) { self.acceptsNewline = acceptsNewline }
+
+ func textView(
+ _ textView: UITextView,
+ shouldChangeTextIn range: NSRange,
+ replacementText text: String
+ ) -> Bool {
+ if text == "\n" { returnCount += 1 }
+ return acceptsNewline
+ }
+}
+
+private final class TeardownField: UITextField {
+ var events: [String] = []
+ private var simulatedFocus = true
+ override var isFirstResponder: Bool { simulatedFocus }
+ override func resignFirstResponder() -> Bool {
+ events.append("resign")
+ simulatedFocus = false
+ return true
+ }
+ override var inputView: UIView? {
+ didSet { events.append("restore") }
+ }
+ override func reloadInputViews() { events.append("reload") }
+}
diff --git a/scripts/ios-tests/create-rendering-project.rb b/scripts/ios-tests/create-rendering-project.rb
index 7b4e68a..c382b2f 100644
--- a/scripts/ios-tests/create-rendering-project.rb
+++ b/scripts/ios-tests/create-rendering-project.rb
@@ -6,7 +6,7 @@
FileUtils.mkdir_p(output)
project = Xcodeproj::Project.new(File.join(output, 'RenderingTests.xcodeproj'))
target = project.new_target(:unit_test_bundle, 'RenderingTests', :ios, '16.0')
-files = %w[KeyflowCursorNavigator.swift KeyflowCallout.swift KeyflowKey.swift KeyflowKeyboardView.swift KeyflowKeyboardLayout.swift KeyflowKeyRows.swift KeyflowLanguage.swift KeyflowTheme.swift KeyflowTabletAccents.swift]
+files = %w[KeyflowCursorNavigator.swift KeyflowCallout.swift KeyflowKey.swift KeyflowKeyboardView.swift KeyflowKeyboardLayout.swift KeyflowKeyRows.swift KeyflowLanguage.swift KeyflowSubmit.swift KeyflowTheme.swift KeyflowTabletAccents.swift]
refs = files.map { |name| project.main_group.new_file(File.join(root, 'ios', name)) }
refs << project.main_group.new_file(File.join(__dir__, 'KeyflowRenderingTests.swift'))
target.add_file_references(refs)
diff --git a/src/KeyflowAvoidingView.tsx b/src/KeyflowAvoidingView.tsx
index 6f22ec3..a4336fc 100644
--- a/src/KeyflowAvoidingView.tsx
+++ b/src/KeyflowAvoidingView.tsx
@@ -77,12 +77,13 @@ export function KeyflowAvoidingView({
return (
{
- // Match RN's keyboardVerticalOffset convention: parent-relative layout
- // plus the caller's offset is compared with the screen keyboard frame.
- const { y, height } = event.nativeEvent.layout;
- setBottom(y + height);
+ // Keyboard frames use screen coordinates. A nested avoiding view's
+ // onLayout position is parent-relative, so measure its window bottom.
+ measure();
onLayout?.(event);
}}
>
diff --git a/src/__tests__/theme.test.ts b/src/__tests__/theme.test.ts
index b76c416..149ecae 100644
--- a/src/__tests__/theme.test.ts
+++ b/src/__tests__/theme.test.ts
@@ -6,6 +6,21 @@ import {
transparentKeyflowTheme,
} from '../theme';
+test('serializes custom return key text or a portable icon', () => {
+ const theme = createKeyflowTheme();
+ expect(
+ JSON.parse(serializeKeyflowTheme(theme, { text: 'Send' })).returnKeyContent,
+ ).toEqual({ text: 'Send' });
+ expect(
+ JSON.parse(serializeKeyflowTheme(theme, { icon: 'arrow-right' }))
+ .returnKeyContent,
+ ).toEqual({ icon: 'arrow-right' });
+ expect(() => serializeKeyflowTheme(theme, { text: ' ' })).toThrow(TypeError);
+ expect(() =>
+ serializeKeyflowTheme(theme, { icon: 'upload' } as never),
+ ).toThrow(TypeError);
+});
+
test('translucent keys stay defined when customizing fonts', () => {
const theme = createKeyflowTheme(
{ fontFamily: 'system-rounded', fontSize: 32 },
diff --git a/src/__tests__/useKeyflow.test.ts b/src/__tests__/useKeyflow.test.ts
index 6c2266f..985dca6 100644
--- a/src/__tests__/useKeyflow.test.ts
+++ b/src/__tests__/useKeyflow.test.ts
@@ -1,5 +1,6 @@
import { createElement, StrictMode, useState } from 'react';
import type { ReactElement } from 'react';
+import type { MeasureInWindowOnSuccessCallback } from 'react-native';
import { act, create } from 'react-test-renderer';
import type { ReactTestRenderer } from 'react-test-renderer';
import { useKeyflow } from '../useKeyflow';
@@ -48,6 +49,7 @@ beforeEach(() => {
function HookInput({
mounted = true,
enabled = true,
+ autoFocus = false,
replacement = false,
keyboardMode = 'custom',
onFrame,
@@ -55,6 +57,7 @@ function HookInput({
}: {
mounted?: boolean;
enabled?: boolean;
+ autoFocus?: boolean;
replacement?: boolean;
keyboardMode?: 'custom' | 'system';
onFrame?: jest.Mock;
@@ -63,6 +66,7 @@ function HookInput({
const [value, setValue] = useState('App owns this');
const { keyflowInputProps, inputRef, focus, blur } = useKeyflow({
enabled,
+ autoFocus,
keyboardMode,
keyflowTheme: { keyboard: { background: '#123456' } },
hapticsEnabled: true,
@@ -88,12 +92,16 @@ function HookInput({
);
}
-const createNodeMock = (element: ReactElement) => ({
- focus: jest.fn(),
- blur: jest.fn(),
- tag:
- (element.props as { testID?: string }).testID === 'replacement' ? 22 : 11,
-});
+const createNodeMock = (element: ReactElement) => {
+ const testID = (element.props as { testID?: string }).testID;
+ return {
+ focus: jest.fn(),
+ blur: jest.fn(),
+ tag: testID === 'replacement' ? 22 : 11,
+ measureInWindow: (callback: MeasureInWindowOnSuccessCallback) =>
+ callback(0, 100, 400, 700),
+ };
+};
test('owns the ref and automatically avoids the active keyboard without consumer frame props', async () => {
const onFrame = jest.fn();
@@ -126,7 +134,9 @@ test('owns the ref and automatically avoids the active keyboard without consumer
);
await act(async () =>
surface().props.onLayout({
- nativeEvent: { layout: { y: 0, height: 800 } },
+ // The surface is nested 100 points below its parent. Avoidance must use
+ // the measured window bottom (800), not this local bottom (700).
+ nativeEvent: { layout: { y: 0, height: 700 } },
}),
);
await act(async () => controls.focus());
@@ -432,3 +442,39 @@ test('keeps the native controller configured and focusable after a StrictMode ef
expect(mockNative.attachInput).toHaveBeenCalledTimes(before + 1);
await act(async () => renderer.unmount());
});
+
+test.each([false, true])(
+ 'automatic focus waits for native readiness and supports cancellation=%s',
+ async (cancel) => {
+ let configureReady!: () => void;
+ let attachReady!: () => void;
+ const attachment = new Promise((resolve) => {
+ attachReady = resolve;
+ });
+ mockNative.configure.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ configureReady = resolve;
+ }),
+ );
+ mockNative.attachInput
+ .mockImplementationOnce(() => attachment)
+ .mockImplementationOnce(() => attachment);
+ let renderer!: ReactTestRenderer;
+ await act(async () => {
+ renderer = create(createElement(HookInput, { autoFocus: true }), {
+ createNodeMock,
+ });
+ });
+ const controls = renderer.root.findByProps({ testID: 'controls' }).props;
+ const input = controls.inputRef.current;
+ expect(input.focus).not.toHaveBeenCalled();
+ expect(mockNative.attachInput).not.toHaveBeenCalled();
+ await act(async () => configureReady());
+ expect(input.focus).not.toHaveBeenCalled();
+ if (cancel) controls.blur();
+ await act(async () => attachReady());
+ expect(input.focus).toHaveBeenCalledTimes(cancel ? 0 : 1);
+ await act(async () => renderer.unmount());
+ },
+);
diff --git a/src/index.ts b/src/index.ts
index 8f3705f..6133dd0 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -20,6 +20,8 @@ export type { KeyflowLanguage } from './languages';
export { useKeyflow } from './useKeyflow';
export type {
KeyflowKeyboardType,
+ KeyflowReturnKeyContent,
+ KeyflowReturnKeyIcon,
KeyflowOptions,
KeyflowInputProps,
KeyflowResult,
diff --git a/src/serializeTheme.ts b/src/serializeTheme.ts
index fbe7a89..6061759 100644
--- a/src/serializeTheme.ts
+++ b/src/serializeTheme.ts
@@ -1,4 +1,5 @@
import type { KeyflowTheme } from './types';
+import type { KeyflowReturnKeyContent } from './useKeyflow';
const surfaceColors = new Set([
'background',
@@ -12,12 +13,38 @@ const surfaceColors = new Set([
'borderColor',
'keyShadow',
]);
+const returnKeyIcons = new Set([
+ 'return',
+ 'arrow-right',
+ 'checkmark',
+ 'send',
+ 'search',
+]);
/** Apply surface alpha once at the native boundary. The reusable theme keeps
* its original colors, so repeated renders and partial updates cannot compound it. */
-export function serializeKeyflowTheme(theme: KeyflowTheme): string {
+export function serializeKeyflowTheme(
+ theme: KeyflowTheme,
+ returnKeyContent?: KeyflowReturnKeyContent,
+): string {
+ if (
+ returnKeyContent &&
+ 'text' in returnKeyContent &&
+ (typeof returnKeyContent.text !== 'string' ||
+ !returnKeyContent.text.trim() ||
+ returnKeyContent.text.length > 32)
+ )
+ throw new TypeError('returnKeyContent.text must contain 1–32 characters');
+ if (
+ returnKeyContent &&
+ 'icon' in returnKeyContent &&
+ (typeof returnKeyContent.icon !== 'string' ||
+ !returnKeyIcons.has(returnKeyContent.icon))
+ )
+ throw new TypeError('returnKeyContent.icon is invalid');
const nativeTheme = {
...theme,
+ ...(returnKeyContent ? { returnKeyContent } : {}),
material: theme.material.type,
keyDepth: theme.material.type === 'raised' ? theme.material.depth : 0,
keyShadow:
diff --git a/src/useKeyflow.ts b/src/useKeyflow.ts
index d7ec9f8..5fbab58 100644
--- a/src/useKeyflow.ts
+++ b/src/useKeyflow.ts
@@ -36,15 +36,30 @@ export type KeyflowKeyboardType =
| 'decimal-pad'
| 'phone-pad';
+export type KeyflowReturnKeyIcon =
+ | 'return'
+ | 'arrow-right'
+ | 'checkmark'
+ | 'send'
+ | 'search';
+
+export type KeyflowReturnKeyContent =
+ | Readonly<{ text: string; icon?: never }>
+ | Readonly<{ icon: KeyflowReturnKeyIcon; text?: never }>;
+
export type KeyflowOptions = {
/** Disable native attachment while retaining stable hook order. Default true. */
enabled?: boolean;
+ /** Focus after native attachment. Use instead of TextInput's autoFocus prop. */
+ autoFocus?: boolean;
hapticsEnabled?: boolean;
/** Show Android's 1–0 secondary legends above the top letter row. Default true. */
showSecondaryKeyLabels?: boolean;
keyboardMode?: 'custom' | 'system';
keyboardType?: KeyflowKeyboardType;
keyboardAppearance?: 'light' | 'dark';
+ /** Content displayed by Keyflow's submit key. This does not change submit behavior. */
+ returnKeyContent?: KeyflowReturnKeyContent;
keyflowTheme?: KeyflowThemeOverrides | KeyflowTheme;
/** Omit to discover supported device languages. Explicit entries also choose layout. */
keyboardLanguages?: readonly KeyflowLanguage[];
@@ -61,7 +76,7 @@ export type KeyflowOptions = {
export type KeyflowInputProps = Pick<
TextInputProps,
- 'showSoftInputOnFocus' | 'onFocus' | 'onSelectionChange'
+ 'showSoftInputOnFocus' | 'onFocus' | 'onSelectionChange' | 'onLayout'
> & { ref: RefObject };
export type KeyflowResult = {
@@ -117,6 +132,7 @@ export function useKeyflow(options: KeyflowOptions = {}): KeyflowResult {
const [id] = useState(() => `keyflow-${++nextKeyflowId}`);
const inputRef = useRef(null);
const focusRequest = useRef(0);
+ const autoFocusedInput = useRef(null);
const configurationReady = useRef>(Promise.resolve());
const blur = useCallback(() => {
focusRequest.current += 1;
@@ -129,9 +145,11 @@ export function useKeyflow(options: KeyflowOptions = {}): KeyflowResult {
const [panelHeight, setPanelHeight] = useState(0);
const {
enabled = true,
+ autoFocus = false,
keyboardMode = 'custom',
keyboardType = 'default',
keyboardAppearance,
+ returnKeyContent,
keyflowTheme,
keyboardLanguages,
hapticsEnabled = false,
@@ -151,6 +169,7 @@ export function useKeyflow(options: KeyflowOptions = {}): KeyflowResult {
keyflowTheme,
Platform.OS === 'ios' && Platform.constants.interfaceIdiom === 'pad',
),
+ returnKeyContent,
);
const languagesJSON = serializeKeyboardLanguages(keyboardLanguages);
@@ -222,6 +241,7 @@ export function useKeyflow(options: KeyflowOptions = {}): KeyflowResult {
mounted.current = true;
return () => {
mounted.current = false;
+ autoFocusedInput.current = null;
focusRequest.current += 1;
attachmentAllowed.current = false;
clearKeyflowFrame(id);
@@ -305,6 +325,17 @@ export function useKeyflow(options: KeyflowOptions = {}): KeyflowResult {
onKeyboardModeChange,
]);
+ const requestAutoFocus = useCallback(() => {
+ const target = inputRef.current;
+ if (!autoFocus || !target || autoFocusedInput.current === target) return;
+ autoFocusedInput.current = target;
+ focus();
+ }, [autoFocus, focus]);
+ useEffect(() => {
+ if (!autoFocus) autoFocusedInput.current = null;
+ requestAutoFocus();
+ }, [autoFocus, requestAutoFocus]);
+
useEffect(() => {
if (Platform.OS !== 'android' || panelHeight === 0) return;
const subscription = BackHandler.addEventListener(
@@ -320,6 +351,7 @@ export function useKeyflow(options: KeyflowOptions = {}): KeyflowResult {
const keyflowInputProps = useMemo(
() => ({
ref: inputRef,
+ onLayout: requestAutoFocus,
// UIKit presents Keyflow as the inputView. Suppressing it here would
// make React Native install a competing empty inputView on iOS.
showSoftInputOnFocus:
@@ -337,7 +369,7 @@ export function useKeyflow(options: KeyflowOptions = {}): KeyflowResult {
});
},
}),
- [attachInput, enabled, id, keyboardMode],
+ [attachInput, enabled, id, keyboardMode, requestAutoFocus],
);
if (error) throw error;
return { keyflowInputProps, inputRef, focus, blur };