]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
17d81b65150ced2b9bcdbf38d47af914a93d5656
[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) {
148 task.setAttribute("data-state", state);
149 }
150 },
151 };
152
153 function Log(prefix: string = "vp-") {
154 var next_log_index = 0;
155 return {
156 apply: function (entry: string) {
157 const [timestamp, command, data] = splitN(entry, " ", 2);
158 if (command == "Create") {
159 return Model.addTask(timestamp, data);
160 }
161 if (command == "Edit") {
162 const [createTimestamp, description] = splitN(data, " ", 1);
163 return Model.edit(createTimestamp, description);
164 }
165 if (command == "Priority") {
166 const [createTimestamp, newPriority] = splitN(data, " ", 1);
167 return Model.setPriority(createTimestamp, parseFloat(newPriority));
168 }
169 if (command == "State") {
170 const [createTimestamp, state] = splitN(data, " ", 1);
171 return Model.setState(timestamp, createTimestamp, state);
172 }
173 if (command == "Tag") {
174 const [createTimestamp, tag] = splitN(data, " ", 1);
175 return Model.addTag(createTimestamp, tag);
176 }
177 if (command == "Untag") {
178 const [createTimestamp, tag] = splitN(data, " ", 1);
179 return Model.removeTag(createTimestamp, tag);
180 }
181 },
182
183 record: function (entry: string) {
184 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
185 },
186
187 recordAndApply: function (entry: string) {
188 this.record(entry);
189 return this.apply(entry);
190 },
191
192 replay: function () {
193 while (true) {
194 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
195 if (entry === null) {
196 break;
197 }
198 this.apply(entry);
199 next_log_index++;
200 }
201 },
202 };
203 }
204 const log = Log();
205
206 function UI() {
207 const undoLog: string[] = [];
208 return {
209 addTask: function (description: string): Element {
210 const now = clock.now();
211 undoLog.push(`State ${now} deleted`);
212 return <Element>log.recordAndApply(`${now} Create ${description}`);
213 },
214 addTag: function (createTimestamp: string, tag: string) {
215 undoLog.push(`Untag ${createTimestamp} ${tag}`);
216 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
217 },
218 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
219 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
220 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
221 },
222 removeTag: function (createTimestamp: string, tag: string) {
223 undoLog.push(`Tag ${createTimestamp} ${tag}`);
224 return log.recordAndApply(`${clock.now()} Untag ${createTimestamp} ${tag}`);
225 },
226 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
227 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
228 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
229 },
230 setState: function (createTimestamp: string, newState: string, oldState: string) {
231 undoLog.push(`State ${createTimestamp} ${oldState}`);
232 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
233 },
234 undo: function () {
235 if (undoLog.length > 0) {
236 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
237 }
238 },
239 };
240 }
241 const ui = UI();
242
243 enum CommitOrAbort {
244 Commit,
245 Abort,
246 }
247
248 function BrowserUI() {
249 var currentViewState = "todo";
250 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
251 var lastTagNameEntered = "";
252 return {
253 addTask: function (event: KeyboardEvent) {
254 const input = <HTMLInputElement>document.getElementById("taskName");
255 if (input.value.match(/^ *$/)) return;
256 const task = ui.addTask(input.value);
257 if (currentViewState === "todo") {
258 task instanceof HTMLElement && task.focus();
259 } else if (this.returnFocusAfterInput()) {
260 } else {
261 this.firstVisibleTask()?.focus();
262 }
263 input.value = "";
264 if (event.getModifierState("Control")) {
265 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
266 }
267 },
268
269 beginEdit: function (event: Event) {
270 const task = document.activeElement;
271 if (!task) return;
272 const input = document.createElement("input");
273 const desc = task.getElementsByClassName("desc")[0];
274 const oldDescription = desc.textContent!;
275 task.setAttribute("data-description", oldDescription);
276 input.value = oldDescription;
277 input.addEventListener("blur", this.completeEdit, { once: true });
278 desc.textContent = "";
279 task.insertBefore(input, task.firstChild);
280 input.focus();
281 event.preventDefault();
282 },
283
284 beginTagEdit: function (event: Event) {
285 const task = document.activeElement;
286 if (!task) return;
287 const input = document.createElement("input");
288 input.classList.add("tag");
289 input.addEventListener("blur", this.completeTagEdit, { once: true });
290 input.value = lastTagNameEntered;
291 task.appendChild(input);
292 input.focus();
293 input.select();
294 event.preventDefault();
295 },
296
297 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
298 const input = event.target as HTMLInputElement;
299 const task = input.parentElement!;
300 const desc = task.getElementsByClassName("desc")[0];
301 const oldDescription = task.getAttribute("data-description")!;
302 const newDescription = input.value;
303 input.removeEventListener("blur", this.completeEdit);
304 task.removeChild(input);
305 task.removeAttribute("data-description");
306 task.focus();
307 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
308 desc.textContent = oldDescription;
309 } else {
310 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
311 }
312 },
313
314 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
315 const input = event.target as HTMLInputElement;
316 const task = input.parentElement!;
317 const newTagName = input.value;
318 input.removeEventListener("blur", this.completeTagEdit);
319 task.removeChild(input);
320 task.focus();
321 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !Model.hasTag(task, newTagName)) {
322 ui.addTag(task.getAttribute("data-created")!, newTagName);
323 lastTagNameEntered = newTagName;
324 }
325 },
326
327 firstVisibleTask: function () {
328 for (const task of document.getElementsByClassName("task")) {
329 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
330 return task;
331 }
332 }
333 },
334
335 focusTaskNameInput: function (event: Event) {
336 if (document.activeElement instanceof HTMLElement) {
337 taskFocusedBeforeJumpingToInput = document.activeElement;
338 }
339 document.getElementById("taskName")!.focus();
340 event.preventDefault();
341 },
342
343 visibleTaskAtOffset(task: Element, offset: number): Element {
344 var cursor: Element | null = task;
345 var valid_cursor = cursor;
346 const increment = offset / Math.abs(offset);
347 while (true) {
348 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
349 if (!cursor || !(cursor instanceof HTMLElement)) break;
350 if (cursor.getAttribute("data-state")! === currentViewState) {
351 offset -= increment;
352 valid_cursor = cursor;
353 }
354 if (Math.abs(offset) < 0.5) break;
355 }
356 return valid_cursor;
357 },
358
359 moveCursor: function (offset: number): boolean {
360 const active = document.activeElement;
361 if (!active) return false;
362 const dest = this.visibleTaskAtOffset(active, offset);
363 if (dest !== active && dest instanceof HTMLElement) {
364 dest.focus();
365 return true;
366 }
367 return false;
368 },
369
370 moveTask: function (offset: number) {
371 const active = document.activeElement;
372 if (!active) return;
373 const dest = this.visibleTaskAtOffset(active, offset);
374 if (dest === active) return; // Already extremal
375 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
376 if (onePastDest == dest) onePastDest = null; // Will become extremal
377 if (offset > 0) {
378 this.setPriority(active, dest, onePastDest);
379 } else {
380 this.setPriority(active, onePastDest, dest);
381 }
382 },
383
384 removeTag: function () {
385 const tag = document.activeElement;
386 if (!tag || !tag.classList.contains("tag")) return;
387 ui.removeTag(tag.parentElement!.getAttribute("data-created")!, tag.textContent!);
388 },
389
390 returnFocusAfterInput: function (): boolean {
391 if (taskFocusedBeforeJumpingToInput) {
392 taskFocusedBeforeJumpingToInput.focus();
393 return true;
394 }
395 return false;
396 },
397
398 // Change task's priority to be between other tasks a and b.
399 setPriority: function (task: Element, a: Element | null, b: Element | null) {
400 const aPriority = a === null ? 0 : Model.getPriority(a);
401 const bPriority = b === null ? clock.now() : Model.getPriority(b);
402 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
403 const span = bPriority - aPriority;
404 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
405 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
406 const newPriorityRounded = Math.round(newPriority);
407 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
408 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
409 task instanceof HTMLElement && task.focus();
410 },
411
412 setState: function (newState: string) {
413 const task = document.activeElement;
414 if (!task) return;
415 const oldState = task.getAttribute("data-state")!;
416 if (newState === oldState) return;
417 const createTimestamp = task.getAttribute("data-created")!;
418 this.moveCursor(1) || this.moveCursor(-1);
419 return ui.setState(createTimestamp, newState, oldState);
420 },
421
422 setView: function (state: string, color: string) {
423 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
424 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
425 sheet.insertRule(`:root { --view-state-indicator-color: ${color}; }`);
426 sheet.removeRule(2);
427 sheet.removeRule(2);
428 currentViewState = state;
429 if (document.activeElement?.getAttribute("data-state") !== state) {
430 this.firstVisibleTask()?.focus();
431 }
432 },
433
434 undo: function () {
435 const ret = ui.undo();
436 if (ret && ret instanceof HTMLElement) ret.focus();
437 },
438 };
439 }
440 const browserUI = BrowserUI();
441
442 enum InputState {
443 Command,
444 View,
445 }
446 var inputState = InputState.Command;
447
448 function handleKey(event: any) {
449 if (event.target.tagName === "INPUT") {
450 if (event.target.id === "taskName") {
451 if (event.key == "Enter") return browserUI.addTask(event);
452 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
453 } else if (event.target.classList.contains("tag")) {
454 if (event.key == "Enter") return browserUI.completeTagEdit(event);
455 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
456 } else {
457 if (event.key == "Enter") return browserUI.completeEdit(event);
458 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
459 }
460 } else {
461 if (inputState === InputState.Command) {
462 if (event.key == "j") return browserUI.moveCursor(1);
463 if (event.key == "k") return browserUI.moveCursor(-1);
464 if (event.key == "J") return browserUI.moveTask(1);
465 if (event.key == "K") return browserUI.moveTask(-1);
466 if (event.key == "n") return browserUI.focusTaskNameInput(event);
467 if (event.key == "c") return browserUI.setState("cancelled");
468 if (event.key == "d") return browserUI.setState("done");
469 if (event.key == "q") return browserUI.setState("todo");
470 if (event.key == "s") return browserUI.setState("someday-maybe");
471 if (event.key == "w") return browserUI.setState("waiting");
472 if (event.key == "X") return browserUI.setState("deleted");
473 if (event.key == "x") return browserUI.removeTag();
474 if (event.key == "u") return browserUI.undo();
475 if (event.key == "e") return browserUI.beginEdit(event);
476 if (event.key == "t") return browserUI.beginTagEdit(event);
477 if (event.key == "v") return (inputState = InputState.View);
478 } else if (inputState === InputState.View) {
479 inputState = InputState.Command;
480 if (event.key == "c") return browserUI.setView("cancelled", "Red");
481 if (event.key == "d") return browserUI.setView("done", "LawnGreen");
482 if (event.key == "q") return browserUI.setView("todo", "White");
483 if (event.key == "s") return browserUI.setView("someday-maybe", "DeepSkyBlue");
484 if (event.key == "v") return browserUI.setView("todo", "White");
485 if (event.key == "w") return browserUI.setView("waiting", "MediumOrchid");
486 if (event.key == "x") return browserUI.setView("deleted", "Black");
487 }
488 }
489 }
490
491 function browserInit() {
492 log.replay();
493 browserUI.firstVisibleTask()?.focus();
494 document.body.addEventListener("keydown", handleKey, { capture: false });
495 }