]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
e997d1c38c8572ed5f60dfe7c5828c4bf5979958
[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 addTask: function (timestamp: string, description: string): Element {
18 const task = document.createElement("div");
19 task.appendChild(document.createTextNode(description));
20 task.setAttribute("class", "task");
21 task.setAttribute("tabindex", "0");
22 task.setAttribute("data-created", timestamp);
23 document.getElementById("tasks")!.appendChild(task);
24 return task;
25 },
26
27 getPriority: function (task: Element): number {
28 if (task.hasAttribute("data-priority")) {
29 return parseFloat(task.getAttribute("data-priority")!);
30 }
31 return parseFloat(task.getAttribute("data-created")!);
32 },
33
34 getState: function (task: Element): string {
35 return task.getAttribute("data-state") ?? "todo";
36 },
37
38 getTask: function (createTimestamp: string) {
39 for (const task of document.getElementsByClassName("task")) {
40 if (task.getAttribute("data-created") === createTimestamp) {
41 return task;
42 }
43 }
44 },
45
46 setPriority: function (createTimestamp: string, priority: number): Element | null {
47 const target = this.getTask(createTimestamp);
48 if (!target) return null;
49 target.setAttribute("data-priority", `${priority}`);
50 for (const task of document.getElementsByClassName("task")) {
51 if (task !== target && this.getPriority(task) > priority) {
52 task.parentElement!.insertBefore(target, task);
53 return target;
54 }
55 }
56 document.getElementById("tasks")!.appendChild(target);
57 return target;
58 },
59
60 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
61 const task = this.getTask(createTimestamp);
62 if (task) {
63 task.setAttribute("data-state", state);
64 if (task instanceof HTMLElement) {
65 task.style.display = state == "todo" ? "block" : "none"; // Until view filtering
66 }
67 }
68 },
69 };
70
71 function Log(prefix: string = "vp-") {
72 var next_log_index = 0;
73 return {
74 apply: function (entry: string) {
75 const [timestamp, command, data] = splitN(entry, " ", 2);
76 if (command == "Create") {
77 return Model.addTask(timestamp, data);
78 }
79 if (command == "State") {
80 const [createTimestamp, state] = splitN(data, " ", 1);
81 return Model.setState(timestamp, createTimestamp, state);
82 }
83 if (command == "Priority") {
84 const [createTimestamp, newPriority] = splitN(data, " ", 1);
85 return Model.setPriority(createTimestamp, parseFloat(newPriority));
86 }
87 },
88
89 record: function (entry: string) {
90 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
91 },
92
93 recordAndApply: function (entry: string) {
94 this.record(entry);
95 return this.apply(entry);
96 },
97
98 replay: function () {
99 while (true) {
100 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
101 if (entry === null) {
102 break;
103 }
104 this.apply(entry);
105 next_log_index++;
106 }
107 },
108 };
109 }
110 const log = Log();
111
112 const undoLog: string[] = [];
113
114 const UI = {
115 addTask: function (description: string): Element {
116 const now = Date.now();
117 undoLog.push(`State ${now} deleted`);
118 return <Element>log.recordAndApply(`${now} Create ${description}`);
119 },
120 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
121 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
122 return log.recordAndApply(`${Date.now()} Priority ${createTimestamp} ${newPriority}`);
123 },
124 setState: function (createTimestamp: string, newState: string, oldState: string) {
125 undoLog.push(`State ${createTimestamp} ${oldState}`);
126 return log.recordAndApply(`${Date.now()} State ${createTimestamp} ${newState}`);
127 },
128 undo: function () {
129 if (undoLog.length > 0) {
130 return log.recordAndApply(`${Date.now()} ${undoLog.pop()}`);
131 }
132 },
133 };
134
135 const BrowserUI = {
136 addTask: function (event: KeyboardEvent) {
137 const input = <HTMLInputElement>document.getElementById("taskName");
138 if (input.value) {
139 const task = UI.addTask(input.value);
140 if (task && task instanceof HTMLElement) task.focus();
141 input.value = "";
142 if (event.getModifierState("Control")) {
143 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
144 }
145 }
146 },
147
148 firstVisibleTask: function () {
149 for (const task of document.getElementsByClassName("task")) {
150 if (task instanceof HTMLElement && task.style.display !== "none") {
151 return task;
152 }
153 }
154 },
155
156 focusTaskNameInput: function (event: Event) {
157 document.getElementById("taskName")!.focus();
158 event.preventDefault();
159 },
160
161 visibleTaskAtOffset(task: Element, offset: number): Element {
162 var cursor: Element | null = task;
163 var valid_cursor = cursor;
164 const increment = offset / Math.abs(offset);
165 while (true) {
166 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
167 if (!cursor || !(cursor instanceof HTMLElement)) break;
168 if (cursor.style.display !== "none") {
169 offset -= increment;
170 valid_cursor = cursor;
171 }
172 if (Math.abs(offset) < 0.5) break;
173 }
174 return valid_cursor;
175 },
176
177 moveCursor: function (offset: number): boolean {
178 const active = document.activeElement;
179 if (!active) return false;
180 const dest = this.visibleTaskAtOffset(active, offset);
181 if (dest !== active && dest instanceof HTMLElement) {
182 dest.focus();
183 return true;
184 }
185 return false;
186 },
187
188 moveTask: function (offset: number) {
189 const active = document.activeElement;
190 if (!active) return;
191 const dest = this.visibleTaskAtOffset(active, offset);
192 if (dest === active) return; // Already extremal
193 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
194 if (onePastDest == dest) onePastDest = null; // Will become extremal
195 if (offset > 0) {
196 this.setPriority(active, dest, onePastDest);
197 } else {
198 this.setPriority(active, onePastDest, dest);
199 }
200 },
201
202 // Change task's priority to be between other tasks a and b.
203 setPriority: function (task: Element, a: Element | null, b: Element | null) {
204 const aPriority = a === null ? 0 : Model.getPriority(a);
205 const bPriority = b === null ? Date.now() : Model.getPriority(b);
206 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
207 const span = bPriority - aPriority;
208 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
209 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
210 const newPriorityRounded = Math.round(newPriority);
211 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
212 UI.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
213 task instanceof HTMLElement && task.focus();
214 },
215
216 setState: function (newState: string) {
217 const task = document.activeElement;
218 if (!task) return;
219 const oldState = Model.getState(task);
220 if (newState === oldState) return;
221 const createTimestamp = task.getAttribute("data-created")!;
222 this.moveCursor(1) || this.moveCursor(-1);
223 return UI.setState(createTimestamp, newState, oldState);
224 },
225
226 undo: function () {
227 const ret = UI.undo();
228 if (ret && ret instanceof HTMLElement) ret.focus();
229 },
230 };
231
232 function handleKey(event: any) {
233 if (event.target.tagName === "INPUT") {
234 if (event.key == "Enter") return BrowserUI.addTask(event);
235 } else {
236 if (event.key == "j") return BrowserUI.moveCursor(1);
237 if (event.key == "k") return BrowserUI.moveCursor(-1);
238 if (event.key == "J") return BrowserUI.moveTask(1);
239 if (event.key == "K") return BrowserUI.moveTask(-1);
240 if (event.key == "n") return BrowserUI.focusTaskNameInput(event);
241 if (event.key == "s") return BrowserUI.setState("someday-maybe");
242 if (event.key == "w") return BrowserUI.setState("waiting");
243 if (event.key == "d") return BrowserUI.setState("done");
244 if (event.key == "c") return BrowserUI.setState("cancelled");
245 if (event.key == "t") return BrowserUI.setState("todo");
246 if (event.key == "X") return BrowserUI.setState("deleted");
247 if (event.key == "u") return BrowserUI.undo();
248 }
249 }
250
251 function browserInit() {
252 document.body.addEventListener("keydown", handleKey, { capture: false });
253 log.replay();
254 BrowserUI.firstVisibleTask()?.focus();
255 }