]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
24b8774a4225036243e3fac4aaf81e9e5c791bc0
[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 // A clock that never goes backwards; monotonic.
17 function Clock() {
18 var previousNow = Date.now();
19 return {
20 now: function (): number {
21 const now = Date.now();
22 if (now > previousNow) {
23 previousNow = now;
24 return now;
25 }
26 return ++previousNow;
27 },
28 };
29 }
30 const clock = Clock();
31
32 // Returns a promise for a hue based on a hash of the string
33 function hashHue(str: string) {
34 // Using crypto for this is overkill
35 return crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)).then((buf) => (new Uint16Array(buf)[0] * 360) / 2 ** 16);
36 }
37
38 const Model = {
39 addTask: function (timestamp: string, description: string): Element {
40 const task = document.createElement("div");
41 const desc = document.createElement("span");
42 desc.textContent = description;
43 desc.classList.add("desc");
44 task.appendChild(desc);
45 task.classList.add("task");
46 task.setAttribute("tabindex", "0");
47 task.setAttribute("data-created", timestamp);
48 task.setAttribute("data-state", "todo");
49 document.getElementById("tasks")!.appendChild(task);
50 return task;
51 },
52
53 addTag: function (createTimestamp: string, tagName: string): Element | null {
54 const task = this.getTask(createTimestamp);
55 if (!task) return null;
56 const existingTag = this.hasTag(task, tagName);
57 if (existingTag) return existingTag;
58 const tag = document.createElement("span");
59 tag.appendChild(document.createTextNode(tagName));
60 tag.classList.add("tag");
61 tag.setAttribute("tabindex", "0");
62 hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`));
63 for (const child of task.getElementsByClassName("tag")) {
64 if (tagName > child.textContent!) {
65 task.insertBefore(tag, child);
66 return tag;
67 }
68 }
69 task.appendChild(tag);
70 return tag;
71 },
72
73 edit: function (createTimestamp: string, newDescription: string): Element | null {
74 const target = this.getTask(createTimestamp);
75 if (!target) return null;
76 if (target.hasAttribute("data-description")) {
77 // Oh no: An edit has arrived from a replica while a local edit is in progress.
78 const input = target.firstChild as HTMLInputElement;
79 if (
80 input.value === target.getAttribute("data-description") &&
81 input.selectionStart === input.value.length &&
82 input.selectionEnd === input.value.length
83 ) {
84 // No local changes have actually been made yet. Change the contents of the edit box!
85 input.value = newDescription;
86 } else {
87 // No great options.
88 // Prefer not to interrupt the local user's edit.
89 // The remote edit is mostly lost; this mostly becomes last-write-wins.
90 target.setAttribute("data-description", newDescription);
91 }
92 } else {
93 target.getElementsByClassName("desc")[0].textContent = newDescription;
94 }
95 return target;
96 },
97
98 hasTag: function (task: Element, tag: string): Element | null {
99 for (const child of task.getElementsByClassName("tag")) {
100 if (child.textContent === tag) {
101 return child;
102 }
103 }
104 return null;
105 },
106
107 getPriority: function (task: Element): number {
108 if (task.hasAttribute("data-priority")) {
109 return parseFloat(task.getAttribute("data-priority")!);
110 }
111 return parseFloat(task.getAttribute("data-created")!);
112 },
113
114 getTask: function (createTimestamp: string) {
115 for (const task of document.getElementsByClassName("task")) {
116 if (task.getAttribute("data-created") === createTimestamp) {
117 return task;
118 }
119 }
120 },
121
122 removeTag: function (createTimestamp: string, tagName: string) {
123 const task = this.getTask(createTimestamp);
124 if (!task) return null;
125 const tag = this.hasTag(task, tagName);
126 if (!tag) return;
127 task.removeChild(tag);
128 if (task instanceof HTMLElement) task.focus();
129 },
130
131 setPriority: function (createTimestamp: string, priority: number): Element | null {
132 const target = this.getTask(createTimestamp);
133 if (!target) return null;
134 target.setAttribute("data-priority", `${priority}`);
135 for (const task of document.getElementsByClassName("task")) {
136 if (task !== target && this.getPriority(task) > priority) {
137 task.parentElement!.insertBefore(target, task);
138 return target;
139 }
140 }
141 document.getElementById("tasks")!.appendChild(target);
142 return target;
143 },
144
145 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
146 const task = this.getTask(createTimestamp);
147 if (!task) return;
148 task.setAttribute("data-state", state);
149 var date = task.getElementsByClassName("statedate")[0];
150 if (state === "todo") {
151 task.removeChild(date);
152 return;
153 }
154 if (!date) {
155 date = document.createElement("span");
156 date.classList.add("statedate");
157 task.insertBefore(date, task.firstChild);
158 }
159 const d = new Date(parseInt(stateTimestamp));
160 date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
161 },
162 };
163
164 function Log(prefix: string = "vp-") {
165 var next_log_index = 0;
166 return {
167 apply: function (entry: string) {
168 const [timestamp, command, data] = splitN(entry, " ", 2);
169 if (command == "Create") {
170 return Model.addTask(timestamp, data);
171 }
172 if (command == "Edit") {
173 const [createTimestamp, description] = splitN(data, " ", 1);
174 return Model.edit(createTimestamp, description);
175 }
176 if (command == "Priority") {
177 const [createTimestamp, newPriority] = splitN(data, " ", 1);
178 return Model.setPriority(createTimestamp, parseFloat(newPriority));
179 }
180 if (command == "State") {
181 const [createTimestamp, state] = splitN(data, " ", 1);
182 return Model.setState(timestamp, createTimestamp, state);
183 }
184 if (command == "Tag") {
185 const [createTimestamp, tag] = splitN(data, " ", 1);
186 return Model.addTag(createTimestamp, tag);
187 }
188 if (command == "Untag") {
189 const [createTimestamp, tag] = splitN(data, " ", 1);
190 return Model.removeTag(createTimestamp, tag);
191 }
192 },
193
194 record: function (entry: string) {
195 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
196 },
197
198 recordAndApply: function (entry: string) {
199 this.record(entry);
200 return this.apply(entry);
201 },
202
203 replay: function () {
204 while (true) {
205 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
206 if (entry === null) {
207 break;
208 }
209 this.apply(entry);
210 next_log_index++;
211 }
212 },
213 };
214 }
215 const log = Log();
216
217 function UI() {
218 const undoLog: string[] = [];
219 return {
220 addTask: function (description: string): Element {
221 const now = clock.now();
222 undoLog.push(`State ${now} deleted`);
223 return <Element>log.recordAndApply(`${now} Create ${description}`);
224 },
225 addTag: function (createTimestamp: string, tag: string) {
226 undoLog.push(`Untag ${createTimestamp} ${tag}`);
227 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
228 },
229 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
230 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
231 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
232 },
233 removeTag: function (createTimestamp: string, tag: string) {
234 undoLog.push(`Tag ${createTimestamp} ${tag}`);
235 return log.recordAndApply(`${clock.now()} Untag ${createTimestamp} ${tag}`);
236 },
237 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
238 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
239 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
240 },
241 setState: function (createTimestamp: string, newState: string, oldState: string) {
242 undoLog.push(`State ${createTimestamp} ${oldState}`);
243 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
244 },
245 undo: function () {
246 if (undoLog.length > 0) {
247 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
248 }
249 },
250 };
251 }
252 const ui = UI();
253
254 enum CommitOrAbort {
255 Commit,
256 Abort,
257 }
258
259 function BrowserUI() {
260 var currentViewState = "todo";
261 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
262 var lastTagNameEntered = "";
263 return {
264 addTask: function (event: KeyboardEvent) {
265 const input = <HTMLInputElement>document.getElementById("taskName");
266 if (input.value.match(/^ *$/)) return;
267 const task = ui.addTask(input.value);
268 if (currentViewState === "todo" || currentViewState === "all") {
269 task instanceof HTMLElement && task.focus();
270 } else if (this.returnFocusAfterInput()) {
271 } else {
272 this.firstVisibleTask()?.focus();
273 }
274 input.value = "";
275 if (event.getModifierState("Control")) {
276 this.makeTopPriority(task);
277 }
278 },
279
280 beginEdit: function (event: Event) {
281 const task = document.activeElement;
282 if (!task) return;
283 const input = document.createElement("input");
284 const desc = task.getElementsByClassName("desc")[0];
285 const oldDescription = desc.textContent!;
286 task.setAttribute("data-description", oldDescription);
287 input.value = oldDescription;
288 input.addEventListener("blur", this.completeEdit, { once: true });
289 desc.textContent = "";
290 task.insertBefore(input, task.firstChild);
291 input.focus();
292 event.preventDefault();
293 },
294
295 beginTagEdit: function (event: Event) {
296 const task = document.activeElement;
297 if (!task) return;
298 const input = document.createElement("input");
299 input.classList.add("tag");
300 input.addEventListener("blur", this.completeTagEdit, { once: true });
301 input.value = lastTagNameEntered;
302 task.appendChild(input);
303 input.focus();
304 input.select();
305 event.preventDefault();
306 },
307
308 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
309 const input = event.target as HTMLInputElement;
310 const task = input.parentElement!;
311 const desc = task.getElementsByClassName("desc")[0];
312 const oldDescription = task.getAttribute("data-description")!;
313 const newDescription = input.value;
314 input.removeEventListener("blur", this.completeEdit);
315 task.removeChild(input);
316 task.removeAttribute("data-description");
317 task.focus();
318 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
319 desc.textContent = oldDescription;
320 } else {
321 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
322 }
323 },
324
325 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
326 const input = event.target as HTMLInputElement;
327 const task = input.parentElement!;
328 const newTagName = input.value;
329 input.removeEventListener("blur", this.completeTagEdit);
330 task.removeChild(input);
331 task.focus();
332 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !Model.hasTag(task, newTagName)) {
333 ui.addTag(task.getAttribute("data-created")!, newTagName);
334 lastTagNameEntered = newTagName;
335 }
336 },
337
338 firstVisibleTask: function () {
339 for (const task of document.getElementsByClassName("task")) {
340 const state = task.getAttribute("data-state");
341 if (task instanceof HTMLElement && (state === currentViewState || (currentViewState === "all" && state !== "deleted"))) {
342 return task;
343 }
344 }
345 },
346
347 focusTaskNameInput: function (event: Event) {
348 if (document.activeElement instanceof HTMLElement) {
349 taskFocusedBeforeJumpingToInput = document.activeElement;
350 }
351 document.getElementById("taskName")!.focus();
352 event.preventDefault();
353 },
354
355 visibleTaskAtOffset(task: Element, offset: number): Element {
356 var cursor: Element | null = task;
357 var valid_cursor = cursor;
358 const increment = offset / Math.abs(offset);
359 while (true) {
360 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
361 if (!cursor || !(cursor instanceof HTMLElement)) break;
362 const state = cursor.getAttribute("data-state")!;
363 if (state === currentViewState || (currentViewState === "all" && state !== "deleted")) {
364 offset -= increment;
365 valid_cursor = cursor;
366 }
367 if (Math.abs(offset) < 0.5) break;
368 }
369 return valid_cursor;
370 },
371
372 makeTopPriority: function (task: Element | null = null) {
373 if (!task) task = document.activeElement;
374 if (!task) return;
375 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
376 },
377
378 moveCursor: function (offset: number): boolean {
379 const active = document.activeElement;
380 if (!active) return false;
381 const dest = this.visibleTaskAtOffset(active, offset);
382 if (dest !== active && dest instanceof HTMLElement) {
383 dest.focus();
384 return true;
385 }
386 return false;
387 },
388
389 moveTask: function (offset: number) {
390 const active = document.activeElement;
391 if (!active) return;
392 const dest = this.visibleTaskAtOffset(active, offset);
393 if (dest === active) return; // Already extremal
394 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
395 if (onePastDest == dest) onePastDest = null; // Will become extremal
396 if (offset > 0) {
397 this.setPriority(active, dest, onePastDest);
398 } else {
399 this.setPriority(active, onePastDest, dest);
400 }
401 },
402
403 removeTag: function () {
404 var target = document.activeElement;
405 if (!target) return;
406 if (target.classList.contains("task")) {
407 const tags = target.getElementsByClassName("tag");
408 target = tags[tags.length - 1];
409 }
410 if (!target || !target.classList.contains("tag")) return;
411 ui.removeTag(target.parentElement!.getAttribute("data-created")!, target.textContent!);
412 },
413
414 returnFocusAfterInput: function (): boolean {
415 if (taskFocusedBeforeJumpingToInput) {
416 taskFocusedBeforeJumpingToInput.focus();
417 return true;
418 }
419 return false;
420 },
421
422 // Change task's priority to be between other tasks a and b.
423 setPriority: function (task: Element, a: Element | null, b: Element | null) {
424 const aPriority = a === null ? 0 : Model.getPriority(a);
425 const bPriority = b === null ? clock.now() : Model.getPriority(b);
426 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
427 const span = bPriority - aPriority;
428 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
429 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
430 const newPriorityRounded = Math.round(newPriority);
431 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
432 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
433 task instanceof HTMLElement && task.focus();
434 },
435
436 setState: function (newState: string) {
437 const task = document.activeElement;
438 if (!task) return;
439 const oldState = task.getAttribute("data-state")!;
440 if (newState === oldState) return;
441 const createTimestamp = task.getAttribute("data-created")!;
442 if (currentViewState !== "all" || newState == "deleted") {
443 this.moveCursor(1) || this.moveCursor(-1);
444 }
445 return ui.setState(createTimestamp, newState, oldState);
446 },
447
448 setView: function (state: string, color: string) {
449 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
450 if (state === "all") {
451 sheet.insertRule(`.task[data-state=deleted] { display: none }`);
452 } else {
453 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
454 }
455 sheet.insertRule(`:root { --view-state-indicator-color: ${color}; }`);
456 sheet.removeRule(2);
457 sheet.removeRule(2);
458 currentViewState = state;
459 if (document.activeElement?.getAttribute("data-state") !== state) {
460 this.firstVisibleTask()?.focus();
461 }
462 },
463
464 undo: function () {
465 const ret = ui.undo();
466 if (ret && ret instanceof HTMLElement) ret.focus();
467 },
468 };
469 }
470 const browserUI = BrowserUI();
471
472 enum InputState {
473 Root,
474 S,
475 V,
476 VS,
477 }
478 var inputState = InputState.Root;
479
480 function handleKey(event: any) {
481 if (event.target.tagName === "INPUT") {
482 if (event.target.id === "taskName") {
483 if (event.key == "Enter") return browserUI.addTask(event);
484 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
485 } else if (event.target.classList.contains("tag")) {
486 if (event.key == "Enter") return browserUI.completeTagEdit(event);
487 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
488 } else {
489 if (event.key == "Enter") return browserUI.completeEdit(event);
490 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
491 }
492 } else {
493 if (inputState === InputState.Root) {
494 if (event.key == "j") return browserUI.moveCursor(1);
495 if (event.key == "k") return browserUI.moveCursor(-1);
496 if (event.key == "J") return browserUI.moveTask(1);
497 if (event.key == "K") return browserUI.moveTask(-1);
498 if (event.key == "T") return browserUI.makeTopPriority();
499 if (event.key == "n") return browserUI.focusTaskNameInput(event);
500 if (event.key == "c") return browserUI.setState("cancelled");
501 if (event.key == "d") return browserUI.setState("done");
502 if (event.key == "q") return browserUI.setState("todo");
503 if (event.key == "s") return (inputState = InputState.S);
504 if (event.key == "w") return browserUI.setState("waiting");
505 if (event.key == "X") return browserUI.setState("deleted");
506 if (event.key == "x") return browserUI.removeTag();
507 if (event.key == "u") return browserUI.undo();
508 if (event.key == "e") return browserUI.beginEdit(event);
509 if (event.key == "t") return browserUI.beginTagEdit(event);
510 if (event.key == "v") return (inputState = InputState.V);
511 } else if (inputState === InputState.S) {
512 inputState = InputState.Root;
513 if (event.key == "m") return browserUI.setState("someday-maybe");
514 } else if (inputState === InputState.V) {
515 inputState = InputState.Root;
516 if (event.key == "a") return browserUI.setView("all", "Gold");
517 if (event.key == "c") return browserUI.setView("cancelled", "Red");
518 if (event.key == "d") return browserUI.setView("done", "LawnGreen");
519 if (event.key == "q") return browserUI.setView("todo", "White");
520 if (event.key == "s") return (inputState = InputState.VS);
521 if (event.key == "v") return browserUI.setView("todo", "White");
522 if (event.key == "w") return browserUI.setView("waiting", "MediumOrchid");
523 if (event.key == "x") return browserUI.setView("deleted", "Black");
524 } else if (inputState === InputState.VS) {
525 inputState = InputState.Root;
526 if (event.key == "m") return browserUI.setView("someday-maybe", "DeepSkyBlue");
527 }
528 }
529 }
530
531 function browserInit() {
532 log.replay();
533 browserUI.firstVisibleTask()?.focus();
534 document.body.addEventListener("keydown", handleKey, { capture: false });
535 }