├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── test.yml ├── .gitignore ├── .npmrc ├── license ├── media └── demo.gif ├── package.json ├── readme.md ├── source └── index.tsx ├── test ├── test.tsx └── tsconfig.json └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | *.js text eol=lf 3 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | test: 6 | name: Node.js ${{ matrix.node_version }} 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | node_version: [18, 20] 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - name: Use Node.js ${{ matrix.node_version }} 15 | uses: actions/setup-node@v4 16 | with: 17 | node-version: ${{ matrix.node_version }} 18 | - run: npm install 19 | - run: npm test 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | build 3 | /.tsimp 4 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Vadym Demedes (github.com/vadimdemedes) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /media/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vadimdemedes/ink-text-input/4ac429ca11da17c2321f7dec1076e38c06d738d5/media/demo.gif -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ink-text-input", 3 | "version": "6.0.0", 4 | "description": "Text input component for Ink", 5 | "license": "MIT", 6 | "repository": "vadimdemedes/ink-text-input", 7 | "author": { 8 | "name": "Vadim Demedes", 9 | "email": "vadimdemedes@hey.com", 10 | "url": "https://github.com/vadimdemedes" 11 | }, 12 | "type": "module", 13 | "exports": { 14 | "types": "./build/index.d.ts", 15 | "default": "./build/index.js" 16 | }, 17 | "engines": { 18 | "node": ">=18" 19 | }, 20 | "scripts": { 21 | "test": "tsc --noEmit && xo && FORCE_COLOR=1 ava", 22 | "build": "tsc", 23 | "prepare": "tsc", 24 | "pretest": "tsc" 25 | }, 26 | "files": [ 27 | "build" 28 | ], 29 | "keywords": [ 30 | "ink", 31 | "text", 32 | "input", 33 | "component", 34 | "jsx", 35 | "react", 36 | "stdin", 37 | "keypress", 38 | "search", 39 | "query" 40 | ], 41 | "dependencies": { 42 | "chalk": "^5.3.0", 43 | "type-fest": "^4.18.2" 44 | }, 45 | "devDependencies": { 46 | "@sindresorhus/tsconfig": "^5.0.0", 47 | "@types/react": "^18.3.2", 48 | "@types/sinon": "^17.0.3", 49 | "@vdemedes/prettier-config": "^2.0.1", 50 | "ava": "^6.1.3", 51 | "delay": "^6.0.0", 52 | "eslint-config-xo-react": "^0.27.0", 53 | "eslint-plugin-react": "^7.34.1", 54 | "eslint-plugin-react-hooks": "^4.6.2", 55 | "ink": "^5.0.0", 56 | "ink-testing-library": "vadimdemedes/ink-testing-library#f44b077e9a05a1d615bab41c72906726d34ea085", 57 | "prettier": "^3.2.5", 58 | "react": "^18.3.1", 59 | "sinon": "^17.0.1", 60 | "tsimp": "^2.0.11", 61 | "typescript": "^5.4.5", 62 | "xo": "^0.58.0" 63 | }, 64 | "peerDependencies": { 65 | "ink": ">=5", 66 | "react": ">=18" 67 | }, 68 | "ava": { 69 | "extensions": { 70 | "ts": "module", 71 | "tsx": "module" 72 | }, 73 | "nodeArguments": [ 74 | "--import=tsimp/import" 75 | ] 76 | }, 77 | "xo": { 78 | "extends": [ 79 | "xo-react" 80 | ], 81 | "prettier": true, 82 | "rules": { 83 | "unicorn/prevent-abbreviations": "off" 84 | } 85 | }, 86 | "prettier": "@vdemedes/prettier-config" 87 | } 88 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # ink-text-input ![test](https://github.com/vadimdemedes/ink-text-input/workflows/test/badge.svg) 2 | 3 | > Text input component for [Ink](https://github.com/vadimdemedes/ink). 4 | 5 | ## Install 6 | 7 | ```sh 8 | npm install ink-text-input 9 | ``` 10 | 11 | ## Usage 12 | 13 | ```jsx 14 | import React, {useState} from 'react'; 15 | import {render, Box, Text} from 'ink'; 16 | import TextInput from 'ink-text-input'; 17 | 18 | const SearchQuery = () => { 19 | const [query, setQuery] = useState(''); 20 | 21 | return ( 22 | 23 | 24 | Enter your query: 25 | 26 | 27 | 28 | 29 | ); 30 | }; 31 | 32 | render(); 33 | ``` 34 | 35 | 36 | 37 | ## Props 38 | 39 | ### value 40 | 41 | Type: `string` 42 | 43 | Value to display in a text input. 44 | 45 | ### placeholder 46 | 47 | Type: `string` 48 | 49 | Text to display when `value` is empty. 50 | 51 | ### focus 52 | 53 | Type: `boolean` \ 54 | Default: `true` 55 | 56 | Listen to user's input. Useful in case there are multiple input components at the same time and input must be "routed" to a specific component. 57 | 58 | ### showCursor 59 | 60 | Type: `boolean`\ 61 | Default: `true` 62 | 63 | Whether to show cursor and allow navigation inside text input with arrow keys. 64 | 65 | ### highlightPastedText 66 | 67 | Type: `boolean`\ 68 | Default: `false` 69 | 70 | Highlight pasted text. 71 | 72 | ### mask 73 | 74 | Type: `string` 75 | 76 | Replace all chars and mask the value. Useful for password inputs. 77 | 78 | ```jsx 79 | 80 | //=> "*****" 81 | ``` 82 | 83 | ### onChange 84 | 85 | Type: `Function` 86 | 87 | Function to call when value updates. 88 | 89 | ### onSubmit 90 | 91 | Type: `Function` 92 | 93 | Function to call when `Enter` is pressed, where first argument is a value of the input. 94 | 95 | ## Uncontrolled usage 96 | 97 | This component also exposes an [uncontrolled](https://reactjs.org/docs/uncontrolled-components.html) version, which handles `value` changes for you. To receive the final input value, use `onSubmit` prop. 98 | Initial value can be specified via `initialValue` prop, which is supported only in `UncontrolledTextInput` component. 99 | 100 | ```jsx 101 | import React from 'react'; 102 | import {render, Box, Text} from 'ink'; 103 | import {UncontrolledTextInput} from 'ink-text-input'; 104 | 105 | const SearchQuery = () => { 106 | const handleSubmit = query => { 107 | // Do something with query 108 | }; 109 | 110 | return ( 111 | 112 | 113 | Enter your query: 114 | 115 | 116 | 117 | 118 | ); 119 | }; 120 | 121 | render(); 122 | ``` 123 | -------------------------------------------------------------------------------- /source/index.tsx: -------------------------------------------------------------------------------- 1 | import React, {useState, useEffect} from 'react'; 2 | import {Text, useInput} from 'ink'; 3 | import chalk from 'chalk'; 4 | import type {Except} from 'type-fest'; 5 | 6 | export type Props = { 7 | /** 8 | * Text to display when `value` is empty. 9 | */ 10 | readonly placeholder?: string; 11 | 12 | /** 13 | * Listen to user's input. Useful in case there are multiple input components 14 | * at the same time and input must be "routed" to a specific component. 15 | */ 16 | readonly focus?: boolean; // eslint-disable-line react/boolean-prop-naming 17 | 18 | /** 19 | * Replace all chars and mask the value. Useful for password inputs. 20 | */ 21 | readonly mask?: string; 22 | 23 | /** 24 | * Whether to show cursor and allow navigation inside text input with arrow keys. 25 | */ 26 | readonly showCursor?: boolean; // eslint-disable-line react/boolean-prop-naming 27 | 28 | /** 29 | * Highlight pasted text 30 | */ 31 | readonly highlightPastedText?: boolean; // eslint-disable-line react/boolean-prop-naming 32 | 33 | /** 34 | * Value to display in a text input. 35 | */ 36 | readonly value: string; 37 | 38 | /** 39 | * Function to call when value updates. 40 | */ 41 | readonly onChange: (value: string) => void; 42 | 43 | /** 44 | * Function to call when `Enter` is pressed, where first argument is a value of the input. 45 | */ 46 | readonly onSubmit?: (value: string) => void; 47 | }; 48 | 49 | function TextInput({ 50 | value: originalValue, 51 | placeholder = '', 52 | focus = true, 53 | mask, 54 | highlightPastedText = false, 55 | showCursor = true, 56 | onChange, 57 | onSubmit, 58 | }: Props) { 59 | const [state, setState] = useState({ 60 | cursorOffset: (originalValue || '').length, 61 | cursorWidth: 0, 62 | }); 63 | 64 | const {cursorOffset, cursorWidth} = state; 65 | 66 | useEffect(() => { 67 | setState(previousState => { 68 | if (!focus || !showCursor) { 69 | return previousState; 70 | } 71 | 72 | const newValue = originalValue || ''; 73 | 74 | if (previousState.cursorOffset > newValue.length - 1) { 75 | return { 76 | cursorOffset: newValue.length, 77 | cursorWidth: 0, 78 | }; 79 | } 80 | 81 | return previousState; 82 | }); 83 | }, [originalValue, focus, showCursor]); 84 | 85 | const cursorActualWidth = highlightPastedText ? cursorWidth : 0; 86 | 87 | const value = mask ? mask.repeat(originalValue.length) : originalValue; 88 | let renderedValue = value; 89 | let renderedPlaceholder = placeholder ? chalk.grey(placeholder) : undefined; 90 | 91 | // Fake mouse cursor, because it's too inconvenient to deal with actual cursor and ansi escapes 92 | if (showCursor && focus) { 93 | renderedPlaceholder = 94 | placeholder.length > 0 95 | ? chalk.inverse(placeholder[0]) + chalk.grey(placeholder.slice(1)) 96 | : chalk.inverse(' '); 97 | 98 | renderedValue = value.length > 0 ? '' : chalk.inverse(' '); 99 | 100 | let i = 0; 101 | 102 | for (const char of value) { 103 | renderedValue += 104 | i >= cursorOffset - cursorActualWidth && i <= cursorOffset 105 | ? chalk.inverse(char) 106 | : char; 107 | 108 | i++; 109 | } 110 | 111 | if (value.length > 0 && cursorOffset === value.length) { 112 | renderedValue += chalk.inverse(' '); 113 | } 114 | } 115 | 116 | useInput( 117 | (input, key) => { 118 | if ( 119 | key.upArrow || 120 | key.downArrow || 121 | (key.ctrl && input === 'c') || 122 | key.tab || 123 | (key.shift && key.tab) 124 | ) { 125 | return; 126 | } 127 | 128 | if (key.return) { 129 | if (onSubmit) { 130 | onSubmit(originalValue); 131 | } 132 | 133 | return; 134 | } 135 | 136 | let nextCursorOffset = cursorOffset; 137 | let nextValue = originalValue; 138 | let nextCursorWidth = 0; 139 | 140 | if (key.leftArrow) { 141 | if (showCursor) { 142 | nextCursorOffset--; 143 | } 144 | } else if (key.rightArrow) { 145 | if (showCursor) { 146 | nextCursorOffset++; 147 | } 148 | } else if (key.backspace || key.delete) { 149 | if (cursorOffset > 0) { 150 | nextValue = 151 | originalValue.slice(0, cursorOffset - 1) + 152 | originalValue.slice(cursorOffset, originalValue.length); 153 | 154 | nextCursorOffset--; 155 | } 156 | } else { 157 | nextValue = 158 | originalValue.slice(0, cursorOffset) + 159 | input + 160 | originalValue.slice(cursorOffset, originalValue.length); 161 | 162 | nextCursorOffset += input.length; 163 | 164 | if (input.length > 1) { 165 | nextCursorWidth = input.length; 166 | } 167 | } 168 | 169 | if (cursorOffset < 0) { 170 | nextCursorOffset = 0; 171 | } 172 | 173 | if (cursorOffset > originalValue.length) { 174 | nextCursorOffset = originalValue.length; 175 | } 176 | 177 | setState({ 178 | cursorOffset: nextCursorOffset, 179 | cursorWidth: nextCursorWidth, 180 | }); 181 | 182 | if (nextValue !== originalValue) { 183 | onChange(nextValue); 184 | } 185 | }, 186 | {isActive: focus}, 187 | ); 188 | 189 | return ( 190 | 191 | {placeholder 192 | ? value.length > 0 193 | ? renderedValue 194 | : renderedPlaceholder 195 | : renderedValue} 196 | 197 | ); 198 | } 199 | 200 | export default TextInput; 201 | 202 | type UncontrolledProps = { 203 | /** 204 | * Initial value. 205 | */ 206 | readonly initialValue?: string; 207 | } & Except; 208 | 209 | export function UncontrolledTextInput({ 210 | initialValue = '', 211 | ...props 212 | }: UncontrolledProps) { 213 | const [value, setValue] = useState(initialValue); 214 | 215 | return ; 216 | } 217 | -------------------------------------------------------------------------------- /test/test.tsx: -------------------------------------------------------------------------------- 1 | import React, {useState} from 'react'; 2 | import test from 'ava'; 3 | import chalk from 'chalk'; 4 | import {render} from 'ink-testing-library'; 5 | import {spy} from 'sinon'; 6 | import delay from 'delay'; 7 | import TextInput, {UncontrolledTextInput} from '../source/index.js'; 8 | 9 | const noop = () => { 10 | /* */ 11 | }; 12 | 13 | const cursor = chalk.inverse(' '); 14 | const enter = '\r'; 15 | const arrowLeft = '\u001B[D'; 16 | const arrowRight = '\u001B[C'; 17 | const del = '\u007F'; 18 | 19 | test('default state', t => { 20 | const {lastFrame} = render(); 21 | 22 | t.is(lastFrame(), cursor); 23 | }); 24 | 25 | test('display value', t => { 26 | const {lastFrame} = render( 27 | , 28 | ); 29 | 30 | t.is(lastFrame(), 'Hello'); 31 | }); 32 | 33 | test('display value with cursor', t => { 34 | const {lastFrame} = render(); 35 | 36 | t.is(lastFrame(), `Hello${cursor}`); 37 | }); 38 | 39 | test('display placeholder', t => { 40 | const {lastFrame} = render( 41 | , 42 | ); 43 | 44 | t.is(lastFrame(), chalk.inverse('P') + chalk.grey('laceholder')); 45 | }); 46 | 47 | test('display placeholder when cursor is hidden', t => { 48 | const {lastFrame} = render( 49 | , 55 | ); 56 | 57 | t.is(lastFrame(), chalk.grey('Placeholder')); 58 | }); 59 | 60 | test('display value with mask', t => { 61 | const {lastFrame} = render( 62 | , 63 | ); 64 | 65 | t.is(lastFrame(), `*****${chalk.inverse(' ')}`); 66 | }); 67 | 68 | test('accept input (controlled)', async t => { 69 | function StatefulTextInput() { 70 | const [value, setValue] = useState(''); 71 | 72 | return ; 73 | } 74 | 75 | const {stdin, lastFrame} = render(); 76 | 77 | t.is(lastFrame(), cursor); 78 | await delay(100); 79 | stdin.write('X'); 80 | await delay(100); 81 | t.is(lastFrame(), `X${cursor}`); 82 | }); 83 | 84 | test('accept input (uncontrolled)', async t => { 85 | const {stdin, lastFrame} = render(); 86 | 87 | t.is(lastFrame(), cursor); 88 | await delay(100); 89 | stdin.write('X'); 90 | await delay(100); 91 | t.is(lastFrame(), `X${cursor}`); 92 | }); 93 | 94 | test('initial value (uncontrolled)', async t => { 95 | const {stdin, lastFrame} = render(); 96 | 97 | t.is(lastFrame(), `Y${cursor}`); 98 | await delay(100); 99 | stdin.write('X'); 100 | await delay(100); 101 | t.is(lastFrame(), `YX${cursor}`); 102 | }); 103 | 104 | test('ignore input when not in focus', async t => { 105 | function StatefulTextInput() { 106 | const [value, setValue] = useState(''); 107 | 108 | return ; 109 | } 110 | 111 | const {stdin, frames, lastFrame} = render(); 112 | 113 | t.is(lastFrame(), ''); 114 | await delay(100); 115 | stdin.write('X'); 116 | await delay(100); 117 | t.is(frames.length, 1); 118 | }); 119 | 120 | test('ignore input for Tab and Shift+Tab keys', async t => { 121 | function Test() { 122 | const [value, setValue] = useState(''); 123 | 124 | return ; 125 | } 126 | 127 | const {stdin, lastFrame} = render(); 128 | 129 | await delay(100); 130 | stdin.write('\t'); 131 | await delay(100); 132 | t.is(lastFrame(), cursor); 133 | stdin.write('\u001B[Z'); 134 | await delay(100); 135 | t.is(lastFrame(), cursor); 136 | }); 137 | 138 | test('onSubmit', async t => { 139 | const onSubmit = spy(); 140 | 141 | function StatefulTextInput() { 142 | const [value, setValue] = useState(''); 143 | 144 | return ; 145 | } 146 | 147 | const {stdin, lastFrame} = render(); 148 | 149 | t.is(lastFrame(), cursor); 150 | 151 | await delay(100); 152 | stdin.write('X'); 153 | await delay(100); 154 | stdin.write(enter); 155 | await delay(100); 156 | 157 | t.is(lastFrame(), `X${cursor}`); 158 | t.true(onSubmit.calledWith('X')); 159 | t.true(onSubmit.calledOnce); 160 | }); 161 | 162 | test('paste and move cursor', async t => { 163 | function StatefulTextInput() { 164 | const [value, setValue] = useState(''); 165 | 166 | return ; 167 | } 168 | 169 | const {stdin, lastFrame} = render(); 170 | 171 | await delay(100); 172 | stdin.write('A'); 173 | await delay(100); 174 | stdin.write('B'); 175 | await delay(100); 176 | t.is(lastFrame(), `AB${cursor}`); 177 | 178 | stdin.write(arrowLeft); 179 | await delay(100); 180 | t.is(lastFrame(), `A${chalk.inverse('B')}`); 181 | 182 | stdin.write('Hello World'); 183 | await delay(100); 184 | t.is(lastFrame(), `A${chalk.inverse('Hello WorldB')}`); 185 | 186 | stdin.write(arrowRight); 187 | await delay(100); 188 | t.is(lastFrame(), `AHello WorldB${cursor}`); 189 | }); 190 | 191 | test('delete at the beginning of text', async t => { 192 | function Test() { 193 | const [value, setValue] = useState(''); 194 | 195 | return ; 196 | } 197 | 198 | const {stdin, lastFrame} = render(); 199 | 200 | await delay(100); 201 | stdin.write('T'); 202 | await delay(100); 203 | stdin.write('e'); 204 | await delay(100); 205 | stdin.write('s'); 206 | await delay(100); 207 | stdin.write('t'); 208 | stdin.write(arrowLeft); 209 | await delay(100); 210 | stdin.write(arrowLeft); 211 | await delay(100); 212 | stdin.write(arrowLeft); 213 | await delay(100); 214 | stdin.write(arrowLeft); 215 | await delay(100); 216 | stdin.write(del); 217 | await delay(100); 218 | 219 | t.is(lastFrame(), `${chalk.inverse('T')}est`); 220 | }); 221 | 222 | test('adjust cursor when text is shorter than last value', async t => { 223 | function Test() { 224 | const [value, setValue] = useState(''); 225 | const submit = () => { 226 | setValue(''); 227 | }; 228 | 229 | return ; 230 | } 231 | 232 | const {stdin, lastFrame} = render(); 233 | 234 | await delay(100); 235 | stdin.write('A'); 236 | await delay(100); 237 | stdin.write('B'); 238 | await delay(100); 239 | t.is(lastFrame(), `AB${chalk.inverse(' ')}`); 240 | stdin.write('\r'); 241 | await delay(100); 242 | t.is(lastFrame(), chalk.inverse(' ')); 243 | stdin.write('A'); 244 | await delay(100); 245 | t.is(lastFrame(), `A${chalk.inverse(' ')}`); 246 | stdin.write('B'); 247 | await delay(100); 248 | t.is(lastFrame(), `AB${chalk.inverse(' ')}`); 249 | }); 250 | -------------------------------------------------------------------------------- /test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "include": ["**/*.*"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@sindresorhus/tsconfig", 3 | "compilerOptions": { 4 | "outDir": "build", 5 | "sourceMap": true, 6 | "jsx": "react" 7 | }, 8 | "include": ["source"] 9 | } 10 | --------------------------------------------------------------------------------