Skip to content

Commit eb20b34

Browse files
committed
feat: Automatic indent on new lines.
1 parent 0928344 commit eb20b34

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

src/SelectionText.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ export class SelectionText {
4444
}
4545
return start;
4646
}
47+
/** Indent on new lines */
48+
getIndentText() {
49+
const start = this.getLineStartNumber();
50+
const str = this.getSelectedValue(start);
51+
let indent = '';
52+
str.replace(/(^(\s)+)/, (str, old) => (indent = old));
53+
return indent;
54+
}
4755
lineStarInstert(text: string = '') {
4856
if (text) {
4957
const oldStart = this.start;

src/__test__/index.test.tsx

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,3 +256,32 @@ it('TextareaCodeEditor onKeyDown Tab Multi-Line 2 Input', async () => {
256256
});
257257
}
258258
});
259+
260+
it('TextareaCodeEditor onKeyDown Enter Input', async () => {
261+
const example = `\nfunction stopPropagation(e) {\n e.stopPropagation();\n e.preventDefault();\n}`;
262+
const expected = `\nfunction stopPropagation(e) {\n \n e.stopPropagation();\n e.preventDefault();\n}`;
263+
const {
264+
container: { firstChild },
265+
} = render(
266+
<TextareaCodeEditor
267+
language="js"
268+
data-testid="textarea"
269+
autoFocus
270+
value={example}
271+
onKeyDown={(evn) => {
272+
expect(evn.code.toLowerCase()).toEqual('enter');
273+
console.log(JSON.stringify((evn.target as any).value));
274+
expect((evn.target as any).value).toEqual(expected);
275+
}}
276+
/>,
277+
);
278+
279+
if (firstChild && firstChild.firstChild) {
280+
(firstChild.firstChild as any).setSelectionRange(32, 32);
281+
fireEvent.keyDown(firstChild.firstChild, {
282+
key: 'Enter',
283+
code: 'Enter',
284+
charCode: 13,
285+
});
286+
}
287+
});

src/shortcuts.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,10 @@ export default function shortcuts(e: React.KeyboardEvent<HTMLTextAreaElement>) {
1515
api.insertText(' ').position(api.start + 2, api.end);
1616
}
1717
api.notifyChange();
18+
} else if (e.code && e.code.toLowerCase() === 'enter') {
19+
stopPropagation(e);
20+
const indent = `\n${api.getIndentText()}`;
21+
api.insertText(indent).position(api.start + indent.length, api.start + indent.length);
22+
api.notifyChange();
1823
}
1924
}

0 commit comments

Comments
 (0)