-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTenjiInput.tsx
More file actions
87 lines (85 loc) · 2.85 KB
/
TenjiInput.tsx
File metadata and controls
87 lines (85 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { useRef, type KeyboardEvent } from "react";
import {
AvailableKey,
convertKeyboardStateToBraille,
defaultKeyboardValues,
} from "@/hooks/useTypedBrailleString";
export default function TenjiInput(props: {
brailleDotCount: 6 | 8;
inputRef: React.MutableRefObject<HTMLInputElement>;
setValue: React.Dispatch<React.SetStateAction<string>>;
}): JSX.Element {
const { brailleDotCount, inputRef, setValue } = props;
const keys = ["a", "s", "d", "f", "j", "k", "l", ";", " "];
const shouldHandleKeyboardEvent = (e: KeyboardEvent) =>
!e.ctrlKey && !e.altKey && !e.metaKey && keys.includes(e.key.toLowerCase());
const pressedKeysRef = useRef(new Set<string>());
const oncePressedKeysRef = useRef(new Set<string>());
return (
<input
className="border-2 border-solid"
ref={inputRef}
onChange={(e) =>
setValue((e.target.value.match(/[⠀-⣿]/g) ?? [""]).join(""))
}
onKeyDown={(e) => {
if (!shouldHandleKeyboardEvent(e)) return;
const pressedKey = e.code;
pressedKeysRef.current.add(pressedKey);
oncePressedKeysRef.current.add(pressedKey);
e.preventDefault();
}}
onKeyUp={(e) => {
if (!shouldHandleKeyboardEvent(e)) return;
const pressedKey = e.code;
pressedKeysRef.current.delete(pressedKey);
if (pressedKeysRef.current.size === 0) {
const tmpTypedKeys = { ...defaultKeyboardValues };
// eslint-disable-next-line no-restricted-syntax
for (const key of Object.keys(tmpTypedKeys)) {
const KEY = key as AvailableKey;
if (Object.hasOwn(tmpTypedKeys, KEY)) {
if (Array.from(oncePressedKeysRef.current).includes(KEY)) {
tmpTypedKeys[KEY] = true;
}
}
}
const typedBraille = convertKeyboardStateToBraille(
tmpTypedKeys,
brailleDotCount,
);
const { selectionStart, selectionEnd } = e.currentTarget;
if (
typedBraille &&
selectionStart !== null &&
selectionEnd !== null
) {
e.currentTarget.value = (
[
e.currentTarget.value.slice(0, selectionStart),
typedBraille,
e.currentTarget.value.slice(selectionEnd),
]
.join("")
.match(/[⠀-⣿]/g) ?? [""]
).join("");
e.currentTarget.setSelectionRange(
selectionStart + 1,
selectionStart + 1,
);
}
oncePressedKeysRef.current.clear();
}
setValue(e.currentTarget.value);
e.preventDefault();
}}
style={{
width: "100%",
fontSize: "150%",
lineHeight: "2em",
borderRadius: "5px",
borderColor: "whitesmoke",
}}
/>
);
}