]> git.scottworley.com Git - vopamoi/blame - vopamoi.ts
Factor out makeTopPriority
[vopamoi] / vopamoi.ts
CommitLineData
121d9948
SW
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;
5const MAX_SAFE_INTEGER = 9007199254740991;
6
7// A sane split that splits N *times*, leaving the last chunk unsplit.
8function 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
27c67784
SW
16// A clock that never goes backwards; monotonic.
17function 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}
30const clock = Clock();
31
c70b3eed
SW
32// Returns a promise for a hue based on a hash of the string
33function 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
13c97b99 38const Model = {
6d01c406 39 addTask: function (timestamp: string, description: string): Element {
13c97b99 40 const task = document.createElement("div");
26737687
SW
41 const desc = document.createElement("span");
42 desc.textContent = description;
43 desc.classList.add("desc");
44 task.appendChild(desc);
7ccc80f6 45 task.classList.add("task");
13c97b99 46 task.setAttribute("tabindex", "0");
4101e1b1 47 task.setAttribute("data-created", timestamp);
682139fc 48 task.setAttribute("data-state", "todo");
ef7ebad4 49 document.getElementById("tasks")!.appendChild(task);
6d01c406 50 return task;
13c97b99 51 },
974848d3 52
7b5b90b9
SW
53 addTag: function (createTimestamp: string, tagName: string): Element | null {
54 const task = this.getTask(createTimestamp);
55 if (!task) return null;
3916a89c
SW
56 const existingTag = this.hasTag(task, tagName);
57 if (existingTag) return existingTag;
7b5b90b9
SW
58 const tag = document.createElement("span");
59 tag.appendChild(document.createTextNode(tagName));
60 tag.classList.add("tag");
61 tag.setAttribute("tabindex", "0");
c70b3eed 62 hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`));
360beccb
SW
63 for (const child of task.getElementsByClassName("tag")) {
64 if (tagName > child.textContent!) {
65 task.insertBefore(tag, child);
66 return tag;
67 }
68 }
7b5b90b9
SW
69 task.appendChild(tag);
70 return tag;
71 },
72
7b574407
SW
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.
132921e6 78 const input = target.firstChild as HTMLInputElement;
7b574407
SW
79 if (
80 input.value === target.getAttribute("data-description") &&
3a731557 81 input.selectionStart === input.value.length &&
7b574407
SW
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;
7b574407
SW
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 {
26737687 93 target.getElementsByClassName("desc")[0].textContent = newDescription;
7b574407
SW
94 }
95 return target;
96 },
97
3916a89c 98 hasTag: function (task: Element, tag: string): Element | null {
54c19180
SW
99 for (const child of task.getElementsByClassName("tag")) {
100 if (child.textContent === tag) {
3916a89c 101 return child;
e1eb33ad
SW
102 }
103 }
3916a89c 104 return null;
e1eb33ad
SW
105 },
106
68a72fde
SW
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
799f4e89
SW
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
0726872b
SW
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);
b5f15e0e 128 if (task instanceof HTMLElement) task.focus();
0726872b
SW
129 },
130
43f3cc0c 131 setPriority: function (createTimestamp: string, priority: number): Element | null {
68a72fde 132 const target = this.getTask(createTimestamp);
43f3cc0c 133 if (!target) return null;
68a72fde
SW
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);
43f3cc0c 138 return target;
68a72fde
SW
139 }
140 }
141 document.getElementById("tasks")!.appendChild(target);
43f3cc0c 142 return target;
68a72fde
SW
143 },
144
01f41859
SW
145 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
146 const task = this.getTask(createTimestamp);
147 if (task) {
5350da9f 148 task.setAttribute("data-state", state);
01f41859 149 }
799f4e89 150 },
13c97b99 151};
f1afad9b 152
d03daa19 153function Log(prefix: string = "vp-") {
60a63831
SW
154 var next_log_index = 0;
155 return {
e88c099c 156 apply: function (entry: string) {
60a63831
SW
157 const [timestamp, command, data] = splitN(entry, " ", 2);
158 if (command == "Create") {
6d01c406 159 return Model.addTask(timestamp, data);
60a63831 160 }
7b574407
SW
161 if (command == "Edit") {
162 const [createTimestamp, description] = splitN(data, " ", 1);
163 return Model.edit(createTimestamp, description);
164 }
68a72fde
SW
165 if (command == "Priority") {
166 const [createTimestamp, newPriority] = splitN(data, " ", 1);
6d01c406 167 return Model.setPriority(createTimestamp, parseFloat(newPriority));
68a72fde 168 }
6a5644f3
SW
169 if (command == "State") {
170 const [createTimestamp, state] = splitN(data, " ", 1);
171 return Model.setState(timestamp, createTimestamp, state);
172 }
7b5b90b9
SW
173 if (command == "Tag") {
174 const [createTimestamp, tag] = splitN(data, " ", 1);
175 return Model.addTag(createTimestamp, tag);
176 }
0726872b
SW
177 if (command == "Untag") {
178 const [createTimestamp, tag] = splitN(data, " ", 1);
179 return Model.removeTag(createTimestamp, tag);
180 }
60a63831
SW
181 },
182
e88c099c 183 record: function (entry: string) {
d03daa19 184 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
60a63831
SW
185 },
186
e88c099c
SW
187 recordAndApply: function (entry: string) {
188 this.record(entry);
6d01c406 189 return this.apply(entry);
60a63831
SW
190 },
191
192 replay: function () {
193 while (true) {
d03daa19 194 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
60a63831
SW
195 if (entry === null) {
196 break;
197 }
e88c099c 198 this.apply(entry);
60a63831
SW
199 next_log_index++;
200 }
201 },
202 };
d03daa19
SW
203}
204const log = Log();
262705dd 205
b56a37d3
SW
206function 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 },
7b5b90b9 214 addTag: function (createTimestamp: string, tag: string) {
0726872b 215 undoLog.push(`Untag ${createTimestamp} ${tag}`);
7b5b90b9
SW
216 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
217 },
b56a37d3
SW
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 },
b5f15e0e
SW
222 removeTag: function (createTimestamp: string, tag: string) {
223 undoLog.push(`Tag ${createTimestamp} ${tag}`);
224 return log.recordAndApply(`${clock.now()} Untag ${createTimestamp} ${tag}`);
225 },
b56a37d3
SW
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}
241const ui = UI();
e88c099c 242
ad72cd51
SW
243enum CommitOrAbort {
244 Commit,
245 Abort,
246}
247
ada060d7 248function BrowserUI() {
868667c1 249 var currentViewState = "todo";
a59fbe41 250 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
09cd65ad 251 var lastTagNameEntered = "";
ada060d7
SW
252 return {
253 addTask: function (event: KeyboardEvent) {
254 const input = <HTMLInputElement>document.getElementById("taskName");
fb19ac80
SW
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")) {
792b8a18 265 this.makeTopPriority(task);
bc7996fe 266 }
ada060d7 267 },
09657615 268
ada060d7
SW
269 beginEdit: function (event: Event) {
270 const task = document.activeElement;
271 if (!task) return;
272 const input = document.createElement("input");
26737687
SW
273 const desc = task.getElementsByClassName("desc")[0];
274 const oldDescription = desc.textContent!;
ada060d7
SW
275 task.setAttribute("data-description", oldDescription);
276 input.value = oldDescription;
277 input.addEventListener("blur", this.completeEdit, { once: true });
26737687 278 desc.textContent = "";
7b5b90b9
SW
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 });
09cd65ad 290 input.value = lastTagNameEntered;
ada060d7
SW
291 task.appendChild(input);
292 input.focus();
09cd65ad 293 input.select();
ada060d7
SW
294 event.preventDefault();
295 },
7b574407 296
ad72cd51 297 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
ada060d7
SW
298 const input = event.target as HTMLInputElement;
299 const task = input.parentElement!;
26737687 300 const desc = task.getElementsByClassName("desc")[0];
ada060d7
SW
301 const oldDescription = task.getAttribute("data-description")!;
302 const newDescription = input.value;
303 input.removeEventListener("blur", this.completeEdit);
132921e6 304 task.removeChild(input);
ada060d7
SW
305 task.removeAttribute("data-description");
306 task.focus();
fb19ac80 307 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
26737687 308 desc.textContent = oldDescription;
ada060d7 309 } else {
b56a37d3 310 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
ada060d7
SW
311 }
312 },
7b574407 313
7b5b90b9
SW
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();
fb19ac80 321 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !Model.hasTag(task, newTagName)) {
e1eb33ad 322 ui.addTag(task.getAttribute("data-created")!, newTagName);
09cd65ad 323 lastTagNameEntered = newTagName;
e1eb33ad 324 }
7b5b90b9
SW
325 },
326
ada060d7
SW
327 firstVisibleTask: function () {
328 for (const task of document.getElementsByClassName("task")) {
868667c1 329 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
ada060d7
SW
330 return task;
331 }
65a7510d 332 }
ada060d7 333 },
caa93fd1 334
ada060d7 335 focusTaskNameInput: function (event: Event) {
a59fbe41
SW
336 if (document.activeElement instanceof HTMLElement) {
337 taskFocusedBeforeJumpingToInput = document.activeElement;
338 }
ada060d7
SW
339 document.getElementById("taskName")!.focus();
340 event.preventDefault();
341 },
09657615 342
ada060d7
SW
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;
868667c1 350 if (cursor.getAttribute("data-state")! === currentViewState) {
ada060d7
SW
351 offset -= increment;
352 valid_cursor = cursor;
353 }
354 if (Math.abs(offset) < 0.5) break;
5fa4704c 355 }
ada060d7
SW
356 return valid_cursor;
357 },
23be73e3 358
792b8a18
SW
359 makeTopPriority: function (task: Element) {
360 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
361 },
362
ada060d7
SW
363 moveCursor: function (offset: number): boolean {
364 const active = document.activeElement;
365 if (!active) return false;
366 const dest = this.visibleTaskAtOffset(active, offset);
367 if (dest !== active && dest instanceof HTMLElement) {
368 dest.focus();
369 return true;
370 }
371 return false;
372 },
01f41859 373
ada060d7
SW
374 moveTask: function (offset: number) {
375 const active = document.activeElement;
376 if (!active) return;
377 const dest = this.visibleTaskAtOffset(active, offset);
378 if (dest === active) return; // Already extremal
379 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
380 if (onePastDest == dest) onePastDest = null; // Will become extremal
381 if (offset > 0) {
382 this.setPriority(active, dest, onePastDest);
383 } else {
384 this.setPriority(active, onePastDest, dest);
385 }
386 },
68a72fde 387
b5f15e0e 388 removeTag: function () {
4ccaa1d6
SW
389 var target = document.activeElement;
390 if (!target) return;
391 if (target.classList.contains("task")) {
392 const tags = target.getElementsByClassName("tag");
393 target = tags[tags.length - 1];
394 }
395 if (!target || !target.classList.contains("tag")) return;
396 ui.removeTag(target.parentElement!.getAttribute("data-created")!, target.textContent!);
b5f15e0e
SW
397 },
398
a59fbe41
SW
399 returnFocusAfterInput: function (): boolean {
400 if (taskFocusedBeforeJumpingToInput) {
401 taskFocusedBeforeJumpingToInput.focus();
402 return true;
403 }
404 return false;
405 },
406
ada060d7
SW
407 // Change task's priority to be between other tasks a and b.
408 setPriority: function (task: Element, a: Element | null, b: Element | null) {
409 const aPriority = a === null ? 0 : Model.getPriority(a);
410 const bPriority = b === null ? clock.now() : Model.getPriority(b);
411 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
412 const span = bPriority - aPriority;
413 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
414 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
415 const newPriorityRounded = Math.round(newPriority);
416 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
b56a37d3 417 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
ada060d7
SW
418 task instanceof HTMLElement && task.focus();
419 },
68a72fde 420
ada060d7
SW
421 setState: function (newState: string) {
422 const task = document.activeElement;
423 if (!task) return;
424 const oldState = task.getAttribute("data-state")!;
425 if (newState === oldState) return;
426 const createTimestamp = task.getAttribute("data-created")!;
427 this.moveCursor(1) || this.moveCursor(-1);
b56a37d3 428 return ui.setState(createTimestamp, newState, oldState);
ada060d7 429 },
43f3cc0c 430
4c532769 431 setView: function (state: string, color: string) {
868667c1
SW
432 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
433 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
4c532769
SW
434 sheet.insertRule(`:root { --view-state-indicator-color: ${color}; }`);
435 sheet.removeRule(2);
436 sheet.removeRule(2);
868667c1
SW
437 currentViewState = state;
438 if (document.activeElement?.getAttribute("data-state") !== state) {
439 this.firstVisibleTask()?.focus();
440 }
441 },
442
ada060d7 443 undo: function () {
b56a37d3 444 const ret = ui.undo();
ada060d7
SW
445 if (ret && ret instanceof HTMLElement) ret.focus();
446 },
447 };
448}
449const browserUI = BrowserUI();
06ee32a1 450
e94e9f27
SW
451enum InputState {
452 Command,
854992ec 453 View,
e94e9f27
SW
454}
455var inputState = InputState.Command;
456
f1afad9b 457function handleKey(event: any) {
a26b1f4b 458 if (event.target.tagName === "INPUT") {
7b574407 459 if (event.target.id === "taskName") {
ada060d7 460 if (event.key == "Enter") return browserUI.addTask(event);
a59fbe41 461 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
7b5b90b9
SW
462 } else if (event.target.classList.contains("tag")) {
463 if (event.key == "Enter") return browserUI.completeTagEdit(event);
464 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
7b574407 465 } else {
ada060d7 466 if (event.key == "Enter") return browserUI.completeEdit(event);
ad72cd51 467 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
7b574407 468 }
a26b1f4b 469 } else {
e94e9f27 470 if (inputState === InputState.Command) {
ada060d7
SW
471 if (event.key == "j") return browserUI.moveCursor(1);
472 if (event.key == "k") return browserUI.moveCursor(-1);
473 if (event.key == "J") return browserUI.moveTask(1);
474 if (event.key == "K") return browserUI.moveTask(-1);
475 if (event.key == "n") return browserUI.focusTaskNameInput(event);
ada060d7 476 if (event.key == "c") return browserUI.setState("cancelled");
868667c1 477 if (event.key == "d") return browserUI.setState("done");
1f300e10 478 if (event.key == "q") return browserUI.setState("todo");
868667c1 479 if (event.key == "s") return browserUI.setState("someday-maybe");
868667c1 480 if (event.key == "w") return browserUI.setState("waiting");
ada060d7 481 if (event.key == "X") return browserUI.setState("deleted");
b5f15e0e 482 if (event.key == "x") return browserUI.removeTag();
ada060d7
SW
483 if (event.key == "u") return browserUI.undo();
484 if (event.key == "e") return browserUI.beginEdit(event);
7b5b90b9 485 if (event.key == "t") return browserUI.beginTagEdit(event);
854992ec
SW
486 if (event.key == "v") return (inputState = InputState.View);
487 } else if (inputState === InputState.View) {
868667c1 488 inputState = InputState.Command;
4c532769
SW
489 if (event.key == "c") return browserUI.setView("cancelled", "Red");
490 if (event.key == "d") return browserUI.setView("done", "LawnGreen");
491 if (event.key == "q") return browserUI.setView("todo", "White");
492 if (event.key == "s") return browserUI.setView("someday-maybe", "DeepSkyBlue");
4c9b0554 493 if (event.key == "v") return browserUI.setView("todo", "White");
4c532769
SW
494 if (event.key == "w") return browserUI.setView("waiting", "MediumOrchid");
495 if (event.key == "x") return browserUI.setView("deleted", "Black");
e94e9f27 496 }
f1afad9b
SW
497 }
498}
499
f1afad9b 500function browserInit() {
d03daa19 501 log.replay();
ada060d7 502 browserUI.firstVisibleTask()?.focus();
bd267c29 503 document.body.addEventListener("keydown", handleKey, { capture: false });
f1afad9b 504}