]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
Keep handleKey lean
[vopamoi] / vopamoi.ts
1 // Typescript doesn't know about MAX_SAFE_INTEGER?? This was supposed to be
2 // fixed in typescript 2.0.1 in 2016, but is not working for me in typescript
3 // 4.2.4 in 2022. :( https://github.com/microsoft/TypeScript/issues/9937
4 //const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
5 const MAX_SAFE_INTEGER = 9007199254740991;
6
7 // A sane split that splits N *times*, leaving the last chunk unsplit.
8 function splitN(str: string, delimiter: string, limit: number = MAX_SAFE_INTEGER): string[] {
9 if (limit < 1) {
10 return [str];
11 }
12 const at = str.indexOf(delimiter);
13 return at === -1 ? [str] : [str.substring(0, at)].concat(splitN(str.substring(at + delimiter.length), delimiter, limit - 1));
14 }
15
16 const Model = {
17 createTask: function (description: string) {
18 const task = document.createElement("div");
19 task.appendChild(document.createTextNode(description));
20 task.setAttribute("tabindex", "0");
21 return task;
22 },
23
24 addTask: function (description: string) {
25 document.body.appendChild(this.createTask(description)).focus();
26 },
27
28 moveCursor: function (offset: number) {
29 var active = document.activeElement;
30 if (offset === 1 && active) {
31 active = active.nextElementSibling;
32 }
33 if (offset === -1 && active) {
34 active = active.previousElementSibling;
35 }
36 if (active && active instanceof HTMLElement) active.focus();
37 },
38 };
39
40 const Log = (function () {
41 var next_log_index = 0;
42 return {
43 apply: function (entry: string) {
44 const [timestamp, command, data] = splitN(entry, " ", 2);
45 if (command == "Create") {
46 Model.addTask(data);
47 }
48 },
49
50 record: function (entry: string) {
51 window.localStorage.setItem(`${next_log_index++}`, entry);
52 },
53
54 recordAndApply: function (entry: string) {
55 this.record(entry);
56 this.apply(entry);
57 },
58
59 replay: function () {
60 while (true) {
61 const entry = window.localStorage.getItem(`${next_log_index}`);
62 if (entry === null) {
63 break;
64 }
65 this.apply(entry);
66 next_log_index++;
67 }
68 },
69 };
70 })();
71
72 const UI = {
73 addTask: function (description: string) {
74 Log.recordAndApply(`${Date.now()} Create ${description}`);
75 },
76 };
77
78 function focusTaskNameInput(event: any) {
79 document.getElementById("taskName")!.focus();
80 event.preventDefault();
81 }
82
83 function handleKey(event: any) {
84 if (event.target.tagName !== "INPUT") {
85 if (event.key == "j") return Model.moveCursor(1);
86 if (event.key == "k") return Model.moveCursor(-1);
87 if (event.key == "c") return focusTaskNameInput(event);
88 }
89 }
90
91 function browserCreateTask(form: any) {
92 if (form.taskName.value) {
93 UI.addTask(form.taskName.value);
94 }
95 form.taskName.value = "";
96 return false;
97 }
98
99 function browserInit() {
100 document.body.addEventListener("keydown", handleKey, { capture: false });
101 Log.replay();
102 }