From 1e6f4354dd8a4d9e7c338ed1a03091d44285eaa1 Mon Sep 17 00:00:00 2001 From: Rainkolwa Date: Thu, 17 Dec 2020 20:33:42 +0800 Subject: [PATCH] fix: caret position --- src/InputNumber.tsx | 2 +- tests/index.test.js | 57 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/InputNumber.tsx b/src/InputNumber.tsx index a71139eb..390ec4c0 100644 --- a/src/InputNumber.tsx +++ b/src/InputNumber.tsx @@ -170,7 +170,7 @@ class InputNumber extends React.Component, InputNumber ) { // If not match any of then, let's just keep the position // TODO: Logic should not reach here, need check if happens - let pos = this.cursorStart + 1; + let pos = this.getInputDisplayValue(this.state).length; // If not have last string, just position to the end if (!this.cursorAfter) { diff --git a/tests/index.test.js b/tests/index.test.js index d73d625c..dd5fa33b 100644 --- a/tests/index.test.js +++ b/tests/index.test.js @@ -1563,6 +1563,63 @@ describe('InputNumber', () => { }); }); + // https://github.com/ant-design/ant-design/issues/28366 + describe('cursor position when last string exists', () => { + const setUpCursorTest = (initValue, prependValue) => { + class Demo extends React.Component { + state = { + value: initValue, + }; + + onChange = value => { + this.setState({ value }); + }; + + render() { + return ( + `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} + parser={value => value.replace(/\$\s?|(,*)/g, '')} + /> + ); + } + } + example = ReactDOM.render(, container); + inputNumber = example.refs.inputNum; + inputNumber.input.selectionStart = 0; + inputNumber.input.selectionEnd = 0; + inputElement = ReactDOM.findDOMNode(inputNumber.input); + Simulate.focus(inputElement); + for (let i = 0; i < prependValue.length; i += 1) { + Simulate.keyDown(inputElement, { keyCode: keyCode.ONE }); + } + Simulate.change(inputElement, { target: { value: prependValue + initValue } }); + }; + it('shold fix caret position on case 1', () => { + // '$ 1' + setUpCursorTest('', '1'); + expect(inputNumber.input.selectionStart).to.be(3); + }); + it('shold fix caret position on case 2', () => { + // '$ 111' + setUpCursorTest('', '111'); + expect(inputNumber.input.selectionStart).to.be(5); + }); + it('shold fix caret position on case 3', () => { + // '$ 111' + setUpCursorTest('1', '11'); + expect(inputNumber.input.selectionStart).to.be(4); + }); + it('shold fix caret position on case 4', () => { + // '$ 123,456' + setUpCursorTest('456', '123'); + expect(inputNumber.input.selectionStart).to.be(6); + }); + }); + describe(`required prop`, () => { it(`should add required attr to the input tag when get passed as true`, () => { ReactDOM.render(, container);