Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 59 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -157,6 +159,7 @@ export const keyflowTheme = {

const { keyflowInputProps } = useKeyflow({
keyflowTheme,
returnKeyContent: { icon: 'send' },
});

<TextInput {...keyflowInputProps} style={styles.input} />;
Expand All @@ -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' },
});

<TextInput
{...keyflowInputProps}
submitBehavior="submit"
onSubmitEditing={sendMessage}
/>;
```

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.
<TextInput
{...sendInputProps}
multiline
submitBehavior="submit"
onSubmitEditing={sendMessage}
/>

// Displays “New line” and inserts a newline.
<TextInput
{...newlineInputProps}
multiline
submitBehavior="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
Expand Down Expand Up @@ -278,8 +327,8 @@ Watch the MP4s: [iPhone transitions](docs/media/ios-transitions.mp4) · [Android
<table>
<tr><th>iPhone · Hold and slide between accents</th><th>Android phone · Hold and slide between accents</th></tr>
<tr>
<td><a href="docs/media/ios-accents.mp4"><img src="docs/media/ios-accents.gif" width="420" alt="Slide between iPhone accent choices with Story Studio’s rose selection highlight" /></a></td>
<td><a href="docs/media/android-accents.mp4"><img src="docs/media/android-accents.gif" width="420" alt="Android accent highlight following a continuous drag across accent choices" /></a></td>
<td><a href="docs/media/ios-accents.mp4"><img src="docs/media/ios-accents.gif" width="420" alt="Story Studio on iPhone opening the accent row, sliding its rose focus, and committing the focused accent" /></a></td>
<td><a href="docs/media/android-accents.mp4"><img src="docs/media/android-accents.gif" width="420" alt="Story Studio on Android opening the accent grid, sliding its rose focus across both rows, and committing the focused accent" /></a></td>
</tr>
</table>

Expand Down Expand Up @@ -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.

Expand Down
52 changes: 52 additions & 0 deletions android/src/androidTest/java/com/keyflow/KeyflowRenderingTest.kt
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 ->
Expand Down Expand Up @@ -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<Int>()
val keyEvents = mutableListOf<KeyEvent>()

override fun onEditorAction(actionCode: Int) {
editorActions += actionCode
}

override fun dispatchKeyEvent(event: KeyEvent): Boolean {
keyEvents += event
return true
}
}
14 changes: 14 additions & 0 deletions android/src/main/java/com/keyflow/KeyflowIcons.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
60 changes: 36 additions & 24 deletions android/src/main/java/com/keyflow/KeyflowInputView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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() {
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}
}
19 changes: 16 additions & 3 deletions android/src/main/java/com/keyflow/KeyflowKeyView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion android/src/main/java/com/keyflow/KeyflowKeyboardView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down
Loading
Loading