Skip to content

Commit

Permalink
Reset cursor if updated text is shorter than the last one (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vadim Demedes committed Sep 19, 2020
1 parent e83cbf4 commit 35558d4
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -51,7 +51,7 @@
"eslint-plugin-react": "^7.20.0",
"eslint-plugin-react-hooks": "^4.0.4",
"husky": "^4.2.5",
"ink": "^3.0.0-3",
"ink": "^3.0.5",
"ink-testing-library": "^2.0.0",
"prettier": "^2.0.5",
"pretty-quick": "^2.0.1",
Expand Down
21 changes: 20 additions & 1 deletion source/index.tsx
@@ -1,5 +1,5 @@
import * as React from 'react';
import {useState} from 'react';
import {useState, useEffect} from 'react';
import type {FC} from 'react';
import {Text, useInput} from 'ink';
import chalk = require('chalk');
Expand Down Expand Up @@ -63,6 +63,25 @@ const TextInput: FC<Props> = ({
cursorWidth: 0
});

useEffect(() => {
setState(previousState => {
if (!focus || !showCursor) {
return previousState;
}

const newValue = originalValue || '';

if (previousState.cursorOffset > newValue.length - 1) {
return {
cursorOffset: newValue.length,
cursorWidth: 0
};
}

return previousState;
});
}, [originalValue, focus, showCursor]);

const cursorActualWidth = highlightPastedText ? cursorWidth : 0;

const value = mask ? mask.repeat(originalValue.length) : originalValue;
Expand Down
27 changes: 27 additions & 0 deletions test.js
Expand Up @@ -214,3 +214,30 @@ test('delete at the beginning of text', async t => {

t.is(lastFrame(), `${chalk.inverse('T')}est`);
});

test('adjust cursor when text is shorter than last value', async t => {
const Test = () => {
const [value, setValue] = useState('');
const submit = () => setValue('');

return <TextInput value={value} onChange={setValue} onSubmit={submit} />;
};

const {stdin, lastFrame} = render(<Test />);

await delay(100);
stdin.write('A');
await delay(100);
stdin.write('B');
await delay(100);
t.is(lastFrame(), `AB${chalk.inverse(' ')}`);
stdin.write('\r');
await delay(100);
t.is(lastFrame(), chalk.inverse(' '));
stdin.write('A');
await delay(100);
t.is(lastFrame(), `A${chalk.inverse(' ')}`);
stdin.write('B');
await delay(100);
t.is(lastFrame(), `AB${chalk.inverse(' ')}`);
});

0 comments on commit 35558d4

Please sign in to comment.