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