-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
62 lines (56 loc) · 1.63 KB
/
main.js
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
import { render, renderIncremental } from "./ui.js";
import {
handleBackspace,
handleBackspaceWord,
handleChar,
makeState,
} from "./state.js";
import { generateNonsense } from "./nonsense.js";
const app = document.querySelector("#app");
const wordCount =
parseInt(new URL(document.location).searchParams.get("wordCount")) || 100;
let wordWeights, state;
function generateState() {
return makeState(generateNonsense(wordWeights, wordCount), wordCount);
}
fetch("word-weights.txt")
.then((res) => res.text())
.then((text) => {
wordWeights = [...text.matchAll(/(\S+)\s+(\d+)/g)].map((m) => ({
word: m[1],
weight: parseInt(m[2]),
}));
state = generateState();
render(state, app);
})
.catch(console.error);
document.addEventListener("keydown", (e) => {
if (!state) {
// do nothing
} else if (!e.ctrlKey && !e.altKey && !e.metaKey && e.key === "Escape") {
e.preventDefault();
state = generateState();
render(state, app);
} else if (state.finish) {
// do nothing
} else if (!e.ctrlKey && !e.altKey && !e.metaKey && e.key.length === 1) {
e.preventDefault();
state = handleChar(state, e.key);
renderIncremental(state);
} else if (
(!e.ctrlKey && !e.altKey && !e.metaKey && e.key === "Backspace") ||
((e.ctrlKey || e.altKey) && !e.metaKey && e.key === "h")
) {
e.preventDefault();
state = handleBackspace(state);
renderIncremental(state);
} else if (
(e.ctrlKey || e.altKey) &&
!e.metaKey &&
(e.key === "Backspace" || e.key === "w")
) {
e.preventDefault();
state = handleBackspaceWord(state);
renderIncremental(state);
}
});