summaryrefslogtreecommitdiff
path: root/src/ui/inputHandler.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/ui/inputHandler.ts')
-rw-r--r--src/ui/inputHandler.ts53
1 files changed, 53 insertions, 0 deletions
diff --git a/src/ui/inputHandler.ts b/src/ui/inputHandler.ts
new file mode 100644
index 0000000..74bfdd8
--- /dev/null
+++ b/src/ui/inputHandler.ts
@@ -0,0 +1,53 @@
+export enum Key {
+ CTRL_C = "ctrl_c",
+ LEFT_ARROW = "left_arrow",
+ RIGHT_ARROW = "right_arrow",
+}
+
+const keyToBuffer: Record<Key, Buffer> = {
+ [Key.CTRL_C]: Buffer.from("\u0003"),
+ [Key.LEFT_ARROW]: Buffer.from("\u001b[D"),
+ [Key.RIGHT_ARROW]: Buffer.from("\u001b[C"),
+};
+
+export const createAndBindHandler = (
+ onInput: (key: Key) => any,
+ onExit: () => any
+) => {
+ process.stdin.setRawMode(true);
+
+ let seq = Buffer.alloc(0);
+
+ process.stdin.on("data", (inputBuffer) => {
+ seq = Buffer.concat([seq, inputBuffer]);
+
+ for (const [key, buffer] of Object.entries(keyToBuffer) as [
+ Key,
+ Buffer
+ ][]) {
+ if (
+ !(
+ seq.length >= buffer.length &&
+ seq.slice(-buffer.length).equals(buffer)
+ )
+ ) {
+ continue;
+ }
+ {
+ if (key === Key.CTRL_C) {
+ onExit();
+ } else {
+ onInput(key);
+ }
+ seq = Buffer.alloc(0);
+ return;
+ }
+ }
+
+ if (seq.length > 6) {
+ seq = Buffer.alloc(0);
+ }
+ });
+
+ process.stdin.resume();
+};