feat: ability to insert tabs on Tab keypress

This commit is contained in:
diced 2023-01-14 11:27:59 -08:00
parent cc0ffc6e60
commit 516e93cee2
No known key found for this signature in database
GPG key ID: 370BD1BA142842D1

View file

@ -1,4 +1,5 @@
import { createStyles, MantineSize, Textarea } from '@mantine/core';
import { useEffect } from 'react';
const useStyles = createStyles((theme, { size }: { size: MantineSize }) => ({
input: {
@ -11,5 +12,26 @@ const useStyles = createStyles((theme, { size }: { size: MantineSize }) => ({
export default function CodeInput({ ...props }) {
const { classes } = useStyles({ size: 'md' }, { name: 'CodeInput' });
return <Textarea classNames={{ input: classes.input }} autoComplete='nope' {...props} />;
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Tab') {
if (document.activeElement?.tagName !== 'TEXTAREA') return;
e.preventDefault();
const target = e.target as HTMLTextAreaElement;
const start = target.selectionStart;
const end = target.selectionEnd;
target.value = `${target.value.substring(0, start)} ${target.value.substring(end)}`;
target.selectionStart = target.selectionEnd = start + 2;
target.focus();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, []);
return <Textarea classNames={{ input: classes.input }} {...props} />;
}