-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommandWatcher.ts
59 lines (52 loc) · 1.57 KB
/
commandWatcher.ts
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
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="dom" />
import { promisify } from "./deps/async-lib.ts";
import { toVimKey } from "./toVimKey.ts";
export async function* commandWatcher(
element: HTMLInputElement | HTMLTextAreaElement,
) {
const [watcher, handleEvent] = promisify<CompositionEvent | KeyboardEvent>({
maxQueued: 0,
});
const callback = (e: unknown) => handleEvent(e as CompositionEvent);
element.addEventListener("compositionstart", callback);
element.addEventListener("compositionend", callback);
document.addEventListener("keydown", handleEvent);
try {
while (true) {
const event = await watcher();
if (event instanceof KeyboardEvent) {
if (event.isComposing) continue;
const key = toVimKey(event);
if (key === undefined) continue;
yield key;
continue;
}
if (event.type === "compositionend") {
for (const char of event.data) {
yield char;
}
continue;
}
// compositionendになるまで待つ
while (true) {
const endEvent = await watcher();
if (
!(endEvent instanceof KeyboardEvent &&
endEvent.type === "compositionend")
) {
continue;
}
for (const char of event.data) {
yield char;
}
break;
}
}
} finally {
element.removeEventListener("compositionstart", callback);
element.removeEventListener("compositionend", callback);
document.removeEventListener("keydown", handleEvent);
}
}