Skip to content

Commit 1a7591d

Browse files
fix textarea newline handle (#32966)
- Fix cursor position if input newline on middle of lines - ~Increment number if numbered list~ ![image](https://github.com/user-attachments/assets/bcfe2625-11a8-4ea4-9a71-b7ecfe81b2e0) --------- Co-authored-by: wxiaoguang <[email protected]>
1 parent abaeae0 commit 1a7591d

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

web_src/js/features/comp/EditorMarkdown.test.ts

+19-5
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,36 @@ test('EditorMarkdown', () => {
44
const textarea = document.createElement('textarea');
55
initTextareaMarkdown(textarea);
66

7-
const testInput = (value, expected) => {
8-
textarea.value = value;
9-
textarea.setSelectionRange(value.length, value.length);
7+
type ValueWithCursor = string | {
8+
value: string;
9+
pos: number;
10+
}
11+
const testInput = (input: ValueWithCursor, result: ValueWithCursor) => {
12+
const intputValue = typeof input === 'string' ? input : input.value;
13+
const inputPos = typeof input === 'string' ? intputValue.length : input.pos;
14+
textarea.value = intputValue;
15+
textarea.setSelectionRange(inputPos, inputPos);
16+
1017
const e = new KeyboardEvent('keydown', {key: 'Enter', cancelable: true});
1118
textarea.dispatchEvent(e);
12-
if (!e.defaultPrevented) textarea.value += '\n';
13-
expect(textarea.value).toEqual(expected);
19+
if (!e.defaultPrevented) textarea.value += '\n'; // simulate default behavior
20+
21+
const expectedValue = typeof result === 'string' ? result : result.value;
22+
const expectedPos = typeof result === 'string' ? expectedValue.length : result.pos;
23+
expect(textarea.value).toEqual(expectedValue);
24+
expect(textarea.selectionStart).toEqual(expectedPos);
1425
};
1526

1627
testInput('-', '-\n');
1728
testInput('1.', '1.\n');
1829

1930
testInput('- ', '');
2031
testInput('1. ', '');
32+
testInput({value: '1. \n2. ', pos: 3}, {value: '\n2. ', pos: 0});
2133

2234
testInput('- x', '- x\n- ');
35+
testInput('1. foo', '1. foo\n1. ');
36+
testInput({value: '1. a\n2. b\n3. c', pos: 4}, {value: '1. a\n1. \n2. b\n3. c', pos: 8});
2337
testInput('- [ ]', '- [ ]\n- ');
2438
testInput('- [ ] foo', '- [ ] foo\n- [ ] ');
2539
testInput('* [x] foo', '* [x] foo\n* [ ] ');

web_src/js/features/comp/EditorMarkdown.ts

+1
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ function handleNewline(textarea: HTMLTextAreaElement, e: Event) {
9292
if (!line) {
9393
// clear current line if we only have i.e. '1. ' and the user presses enter again to finish creating a list
9494
textarea.value = value.slice(0, lineStart) + value.slice(lineEnd);
95+
textarea.setSelectionRange(selStart - prefix.length, selStart - prefix.length);
9596
} else {
9697
// start a new line with the same indention and prefix
9798
let newPrefix = prefix;

0 commit comments

Comments
 (0)