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;
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[] {
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));
16 // A clock that never goes backwards; monotonic.
18 var previousNow = Date.now();
20 now: function (): number {
21 const now = Date.now();
22 if (now > previousNow) {
30 const clock = Clock();
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);
40 addTask: function (timestamp: string, description: string): Element {
41 const task = document.createElement("div");
42 const desc = document.createElement("span");
43 desc.textContent = description;
44 desc.classList.add("desc");
45 task.appendChild(desc);
46 task.classList.add("task");
47 task.setAttribute("tabindex", "0");
48 task.setAttribute("data-created", timestamp);
49 task.setAttribute("data-state", "todo");
50 const tasks = document.getElementById("tasks")!;
51 tasks.insertBefore(task, tasks.firstElementChild);
55 addTag: function (createTimestamp: string, tagName: string): Element | null {
56 const task = this.getTask(createTimestamp);
57 if (!task) return null;
58 const existingTag = this.hasTag(task, tagName);
59 if (existingTag) return existingTag;
60 const tag = document.createElement("span");
61 tag.appendChild(document.createTextNode(tagName));
62 tag.classList.add("tag");
63 tag.setAttribute("tabindex", "0");
64 hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`));
65 for (const child of task.getElementsByClassName("tag")) {
66 if (tagName > child.textContent!) {
67 task.insertBefore(tag, child);
71 task.insertBefore(tag, task.getElementsByClassName("desc")[0]!);
75 edit: function (createTimestamp: string, newDescription: string): Element | null {
76 const target = this.getTask(createTimestamp);
77 if (!target) return null;
78 if (target.hasAttribute("data-description")) {
79 // Oh no: An edit has arrived from a replica while a local edit is in progress.
80 const input = target.getElementsByTagName("input")[0]!;
82 input.value === target.getAttribute("data-description") &&
83 input.selectionStart === input.value.length &&
84 input.selectionEnd === input.value.length
86 // No local changes have actually been made yet. Change the contents of the edit box!
87 input.value = newDescription;
90 // Prefer not to interrupt the local user's edit.
91 // The remote edit is mostly lost; this mostly becomes last-write-wins.
92 target.setAttribute("data-description", newDescription);
95 target.getElementsByClassName("desc")[0].textContent = newDescription;
100 hasTag: function (task: Element, tag: string): Element | null {
101 for (const child of task.getElementsByClassName("tag")) {
102 if (child.textContent === tag) {
109 getPriority: function (task: Element): number {
110 if (task.hasAttribute("data-priority")) {
111 return parseFloat(task.getAttribute("data-priority")!);
113 return parseFloat(task.getAttribute("data-created")!);
116 getTask: function (createTimestamp: string) {
117 for (const task of document.getElementsByClassName("task")) {
118 if (task.getAttribute("data-created") === createTimestamp) {
124 insertInPriorityOrder: function (task: Element, dest: Element) {
125 const priority = this.getPriority(task);
126 for (const t of dest.children) {
127 if (t !== task && this.getPriority(t) < priority) {
128 dest.insertBefore(task, t);
132 dest.appendChild(task);
135 removeTag: function (createTimestamp: string, tagName: string) {
136 const task = this.getTask(createTimestamp);
137 if (!task) return null;
138 const tag = this.hasTag(task, tagName);
140 task.removeChild(tag);
141 if (task instanceof HTMLElement) task.focus();
144 setPriority: function (createTimestamp: string, priority: number): Element | null {
145 const target = this.getTask(createTimestamp);
146 if (!target) return null;
147 target.setAttribute("data-priority", `${priority}`);
148 this.insertInPriorityOrder(target, target.parentElement!);
152 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
153 const task = this.getTask(createTimestamp);
155 task.setAttribute("data-state", state);
156 var date = task.getElementsByClassName("statedate")[0];
157 if (state === "todo") {
158 task.removeChild(date);
162 date = document.createElement("span");
163 date.classList.add("statedate");
164 task.insertBefore(date, task.firstChild);
166 const d = new Date(parseInt(stateTimestamp));
167 date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
171 const model = Model();
173 function Log(prefix: string = "vp-") {
174 var next_log_index = 0;
176 apply: function (entry: string) {
177 const [timestamp, command, data] = splitN(entry, " ", 2);
178 if (command == "Create") {
179 return model.addTask(timestamp, data);
181 if (command == "Edit") {
182 const [createTimestamp, description] = splitN(data, " ", 1);
183 return model.edit(createTimestamp, description);
185 if (command == "Priority") {
186 const [createTimestamp, newPriority] = splitN(data, " ", 1);
187 return model.setPriority(createTimestamp, parseFloat(newPriority));
189 if (command == "State") {
190 const [createTimestamp, state] = splitN(data, " ", 1);
191 return model.setState(timestamp, createTimestamp, state);
193 if (command == "Tag") {
194 const [createTimestamp, tag] = splitN(data, " ", 1);
195 return model.addTag(createTimestamp, tag);
197 if (command == "Untag") {
198 const [createTimestamp, tag] = splitN(data, " ", 1);
199 return model.removeTag(createTimestamp, tag);
203 record: function (entry: string) {
204 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
207 recordAndApply: function (entry: string) {
209 return this.apply(entry);
212 replay: function () {
213 document.getElementById("tasks")!.style.display = "none";
215 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
216 if (entry === null) {
222 document.getElementById("tasks")!.style.display = "";
229 const undoLog: string[][] = [];
230 const redoLog: string[][] = [];
231 function perform(forward: string, reverse: string) {
232 undoLog.push([reverse, forward]);
233 return log.recordAndApply(`${clock.now()} ${forward}`);
236 addTask: function (description: string): Element {
237 const now = clock.now();
238 undoLog.push([`State ${now} deleted`, `State ${now} todo`]);
239 return <Element>log.recordAndApply(`${now} Create ${description}`);
241 addTag: function (createTimestamp: string, tag: string) {
242 return perform(`Tag ${createTimestamp} ${tag}`, `Untag ${createTimestamp} ${tag}`);
244 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
245 return perform(`Edit ${createTimestamp} ${newDescription}`, `Edit ${createTimestamp} ${oldDescription}`);
247 removeTag: function (createTimestamp: string, tag: string) {
248 return perform(`Untag ${createTimestamp} ${tag}`, `Tag ${createTimestamp} ${tag}`);
250 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
251 return perform(`Priority ${createTimestamp} ${newPriority}`, `Priority ${createTimestamp} ${oldPriority}`);
253 setState: function (createTimestamp: string, newState: string, oldState: string) {
254 return perform(`State ${createTimestamp} ${newState}`, `State ${createTimestamp} ${oldState}`);
257 const entry = undoLog.pop();
260 return log.recordAndApply(`${clock.now()} ${entry[0]}`);
264 const entry = redoLog.pop();
267 return log.recordAndApply(`${clock.now()} ${entry[1]}`);
279 function BrowserUI() {
280 const viewColors: { [key: string]: string } = {
285 "someday-maybe": "DeepSkyBlue",
287 waiting: "MediumOrchid",
289 var currentTagView: string | null = null;
290 var currentViewState = "todo";
291 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
292 var lastTagNameEntered = "";
294 addTask: function (event: KeyboardEvent) {
295 const input = <HTMLInputElement>document.getElementById("taskName");
296 if (input.value.match(/^ *$/)) return;
297 const task = ui.addTask(input.value);
298 if (currentViewState === "todo" || currentViewState === "all") {
299 task instanceof HTMLElement && task.focus();
300 } else if (this.returnFocusAfterInput()) {
302 this.firstVisibleTask()?.focus();
305 if (event.getModifierState("Control")) {
306 this.makeBottomPriority(task);
310 beginEdit: function (event: Event) {
311 const task = this.currentTask();
313 const input = document.createElement("input");
314 const desc = task.getElementsByClassName("desc")[0];
315 const oldDescription = desc.textContent!;
316 task.setAttribute("data-description", oldDescription);
317 input.value = oldDescription;
318 input.addEventListener("blur", this.completeEdit, { once: true });
319 desc.textContent = "";
320 task.insertBefore(input, task.firstChild);
322 event.preventDefault();
325 beginTagEdit: function (event: Event) {
326 const task = this.currentTask();
328 const input = document.createElement("input");
329 input.classList.add("tag");
330 input.addEventListener("blur", this.completeTagEdit, { once: true });
331 input.value = lastTagNameEntered;
332 task.appendChild(input);
335 event.preventDefault();
338 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
339 const input = event.target as HTMLInputElement;
340 const task = input.parentElement!;
341 const desc = task.getElementsByClassName("desc")[0];
342 const oldDescription = task.getAttribute("data-description")!;
343 const newDescription = input.value;
344 input.removeEventListener("blur", this.completeEdit);
345 task.removeChild(input);
346 task.removeAttribute("data-description");
348 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
349 desc.textContent = oldDescription;
351 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
355 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
356 const input = event.target as HTMLInputElement;
357 const task = input.parentElement!;
358 const newTagName = input.value;
359 input.removeEventListener("blur", this.completeTagEdit);
360 task.removeChild(input);
362 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !model.hasTag(task, newTagName)) {
363 ui.addTag(task.getAttribute("data-created")!, newTagName);
364 lastTagNameEntered = newTagName;
368 currentTag: function (): Element | null {
369 var target = document.activeElement;
370 if (!target) return null;
371 if (target.classList.contains("task")) {
372 const tags = target.getElementsByClassName("tag");
373 target = tags[tags.length - 1];
375 if (!target || !target.classList.contains("tag")) return null;
379 currentTask: function (): HTMLElement | null {
380 var target = document.activeElement;
381 if (!target) return null;
382 if (target.classList.contains("tag")) target = target.parentElement!;
383 return target as HTMLElement;
386 firstVisibleTask: function (root: Element | null = null) {
387 if (root === null) root = document.body;
388 for (const task of root.getElementsByClassName("task")) {
389 const state = task.getAttribute("data-state");
391 task instanceof HTMLElement &&
392 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
393 !task.classList.contains("hide")
400 focusTaskNameInput: function (event: Event) {
401 taskFocusedBeforeJumpingToInput = this.currentTask();
402 document.getElementById("taskName")!.focus();
404 event.preventDefault();
407 visibleTaskAtOffset(task: Element, offset: number): Element {
408 var cursor: Element | null = task;
409 var valid_cursor = cursor;
410 const increment = offset / Math.abs(offset);
412 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
413 if (!cursor || !(cursor instanceof HTMLElement)) break;
414 const state = cursor.getAttribute("data-state")!;
416 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
417 !cursor.classList.contains("hide")
420 valid_cursor = cursor;
422 if (Math.abs(offset) < 0.5) break;
427 jumpCursor: function (position: number) {
428 const first = this.firstVisibleTask();
430 const dest = this.visibleTaskAtOffset(first, position - 1);
431 if (dest instanceof HTMLElement) dest.focus();
434 makeBottomPriority: function (task: Element | null = null) {
435 if (!task) task = this.currentTask();
437 this.setPriority(task, document.getElementById("tasks")!.lastElementChild, null);
440 makeTopPriority: function (task: Element | null = null) {
441 if (!task) task = this.currentTask();
443 ui.setPriority(task.getAttribute("data-created")!, clock.now(), model.getPriority(task));
444 task instanceof HTMLElement && task.focus();
447 moveCursorLeft: function () {
448 const active = this.currentTask();
449 if (!active) return false;
450 if (active.parentElement!.classList.contains("task")) {
451 active.parentElement!.focus();
455 moveCursorRight: function () {
456 const active = this.currentTask();
457 if (!active) return false;
458 (this.firstVisibleTask(active) as HTMLElement | null)?.focus();
461 moveCursorVertically: function (offset: number): boolean {
462 const active = this.currentTask();
463 if (!active) return false;
464 const dest = this.visibleTaskAtOffset(active, offset);
465 if (dest !== active && dest instanceof HTMLElement) {
472 moveTask: function (offset: number) {
473 const active = this.currentTask();
475 const dest = this.visibleTaskAtOffset(active, offset);
476 if (dest === active) return; // Already extremal
477 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
478 if (onePastDest == dest) onePastDest = null; // Will become extremal
480 this.setPriority(active, dest, onePastDest);
482 this.setPriority(active, onePastDest, dest);
486 removeTag: function () {
487 const target = this.currentTag();
489 ui.removeTag(target.parentElement!.getAttribute("data-created")!, target.textContent!);
492 resetTagView: function () {
493 currentTagView = null;
494 const taskList = document.getElementById("tasks")!;
495 for (const task of Array.from(document.getElementsByClassName("task"))) {
496 task.classList.remove("hide");
497 if (task.parentElement !== taskList) {
498 model.insertInPriorityOrder(task, taskList);
503 resetView: function () {
504 this.setView("todo");
508 returnFocusAfterInput: function (): boolean {
509 if (taskFocusedBeforeJumpingToInput) {
510 taskFocusedBeforeJumpingToInput.focus();
516 // Change task's priority to be between other tasks a and b.
517 setPriority: function (task: Element, a: Element | null, b: Element | null) {
518 const aPriority = a === null ? clock.now() : model.getPriority(a);
519 const bPriority = b === null ? 0 : model.getPriority(b);
520 console.assert(aPriority > bPriority, aPriority, ">", bPriority);
521 const span = aPriority - bPriority;
522 const newPriority = bPriority + 0.1 * span + 0.8 * span * Math.random();
523 console.assert(aPriority > newPriority && newPriority > bPriority, aPriority, ">", newPriority, ">", bPriority);
524 const newPriorityRounded = Math.round(newPriority);
525 const okToRound = aPriority > newPriorityRounded && newPriorityRounded > bPriority;
526 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, model.getPriority(task));
527 task instanceof HTMLElement && task.focus();
530 setState: function (newState: string) {
531 const task = this.currentTask();
533 const oldState = task.getAttribute("data-state")!;
534 if (newState === oldState) return;
535 const createTimestamp = task.getAttribute("data-created")!;
536 if (currentViewState !== "all" || newState == "deleted") {
537 this.moveCursorVertically(1) || this.moveCursorVertically(-1);
539 return ui.setState(createTimestamp, newState, oldState);
542 setTagView: function (tag: string | null = null) {
544 const target = this.currentTag();
546 tag = target.textContent!;
549 if (currentTagView !== null) {
553 const tasksWithTag = new Map();
554 for (const task of document.getElementsByClassName("task")) {
555 if (model.hasTag(task, tag)) {
556 tasksWithTag.set(task.getElementsByClassName("desc")[0].textContent, [model.getPriority(task), task]);
560 function highestPrioritySuperTask(t: Element) {
561 var maxPriority = -1;
562 var superTask = null;
563 for (const child of t.getElementsByClassName("tag")) {
564 const e = tasksWithTag.get(child.textContent);
565 if (e !== undefined && e[0] > maxPriority) {
573 for (const task of Array.from(document.getElementsByClassName("task"))) {
574 if (model.hasTag(task, tag)) {
575 task.classList.remove("hide");
577 const superTask = highestPrioritySuperTask(task);
578 if (superTask !== null) {
579 model.insertInPriorityOrder(task, superTask);
581 task.classList.add("hide");
586 currentTagView = tag;
589 setView: function (state: string) {
590 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
591 if (state === "all") {
592 sheet.insertRule(`.task[data-state=deleted] { display: none }`);
594 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
596 sheet.insertRule(`:root { --view-state-indicator-color: ${viewColors[state]}; }`);
599 currentViewState = state;
600 if (this.currentTask()?.getAttribute("data-state") !== state) {
601 this.firstVisibleTask()?.focus();
605 setUntaggedView: function () {
606 if (currentTagView !== null) {
609 for (const task of document.getElementsByClassName("task")) {
610 if (task.getElementsByClassName("tag").length === 0) {
611 task.classList.remove("hide");
613 task.classList.add("hide");
619 const ret = ui.undo();
620 if (ret && ret instanceof HTMLElement) ret.focus();
623 const ret = ui.redo();
624 if (ret && ret instanceof HTMLElement) ret.focus();
628 const browserUI = BrowserUI();
630 const scrollIncrement = 60;
637 var inputState = InputState.Root;
638 var inputCount: number | null = null;
640 function handleKey(event: any) {
641 if (["Alt", "Control", "Meta", "Shift"].includes(event.key)) return;
642 if (event.target.tagName === "INPUT") {
643 if (event.target.id === "taskName") {
644 if (event.key == "Enter") return browserUI.addTask(event);
645 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
646 } else if (event.target.classList.contains("tag")) {
647 if (event.key == "Enter") return browserUI.completeTagEdit(event);
648 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
650 if (event.key == "Enter") return browserUI.completeEdit(event);
651 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
654 if (inputState === InputState.Root) {
655 if ("0" <= event.key && event.key <= "9") {
656 return (inputCount = (inputCount ?? 0) * 10 + parseInt(event.key));
660 if (event.key == "e") return window.scrollBy(0, (inputCount ?? 1) * scrollIncrement);
661 if (event.key == "y") return window.scrollBy(0, (inputCount ?? 1) * -scrollIncrement);
663 if (event.key == "h") return browserUI.moveCursorLeft();
664 if (event.key == "l") return browserUI.moveCursorRight();
665 if (event.key == "j") return browserUI.moveCursorVertically(inputCount ?? 1);
666 if (event.key == "k") return browserUI.moveCursorVertically(-(inputCount ?? 1));
667 if (event.key == "J") return browserUI.moveTask(inputCount ?? 1);
668 if (event.key == "K") return browserUI.moveTask(-(inputCount ?? 1));
669 if (event.key == "G") return browserUI.jumpCursor(inputCount ?? MAX_SAFE_INTEGER);
670 if (event.key == "T") return browserUI.makeTopPriority();
671 if (event.key == "n") return browserUI.focusTaskNameInput(event);
672 if (event.key == "c") return browserUI.setState("cancelled");
673 if (event.key == "d") return browserUI.setState("done");
674 if (event.key == "q") return browserUI.setState("todo");
675 if (event.key == "s") return (inputState = InputState.S);
676 if (event.key == "w") return browserUI.setState("waiting");
677 if (event.key == "X") return browserUI.setState("deleted");
678 if (event.key == "x") return browserUI.removeTag();
679 if (event.key == "u") return browserUI.undo();
680 if (event.key == "r") return browserUI.redo();
681 if (event.key == "e") return browserUI.beginEdit(event);
682 if (event.key == "t") return browserUI.beginTagEdit(event);
683 if (event.key == "v") return (inputState = InputState.V);
688 } else if (inputState === InputState.S) {
689 inputState = InputState.Root;
690 if (event.key == "m") return browserUI.setState("someday-maybe");
691 } else if (inputState === InputState.V) {
692 inputState = InputState.Root;
693 if (event.key == "a") return browserUI.setView("all");
694 if (event.key == "c") return browserUI.setView("cancelled");
695 if (event.key == "d") return browserUI.setView("done");
696 if (event.key == "i") return browserUI.setUntaggedView();
697 if (event.key == "p") return browserUI.setTagView("Project");
698 if (event.key == "q") return browserUI.setView("todo");
699 if (event.key == "s") return (inputState = InputState.VS);
700 if (event.key == "T") return browserUI.resetTagView();
701 if (event.key == "t") return browserUI.setTagView();
702 if (event.key == "u") return browserUI.setUntaggedView();
703 if (event.key == "v") return browserUI.resetView();
704 if (event.key == "w") return browserUI.setView("waiting");
705 if (event.key == "x") return browserUI.setView("deleted");
706 } else if (inputState === InputState.VS) {
707 inputState = InputState.Root;
708 if (event.key == "m") return browserUI.setView("someday-maybe");
713 function browserInit() {
715 browserUI.firstVisibleTask()?.focus();
716 document.body.addEventListener("keydown", handleKey, { capture: false });