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("id", 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("id")!);
116 getTask: function (createTimestamp: string) {
117 return document.getElementById(createTimestamp);
120 insertInPriorityOrder: function (task: Element, dest: Element) {
121 const priority = this.getPriority(task);
122 for (const t of dest.children) {
123 if (t !== task && this.getPriority(t) < priority) {
124 dest.insertBefore(task, t);
128 dest.appendChild(task);
131 removeTag: function (createTimestamp: string, tagName: string) {
132 const task = this.getTask(createTimestamp);
133 if (!task) return null;
134 const tag = this.hasTag(task, tagName);
136 task.removeChild(tag);
137 if (task instanceof HTMLElement) task.focus();
140 setPriority: function (createTimestamp: string, priority: number): Element | null {
141 const target = this.getTask(createTimestamp);
142 if (!target) return null;
143 target.setAttribute("data-priority", `${priority}`);
144 this.insertInPriorityOrder(target, target.parentElement!);
148 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
149 const task = this.getTask(createTimestamp);
151 task.setAttribute("data-state", state);
152 var date = task.getElementsByClassName("statedate")[0];
153 if (state === "todo") {
154 task.removeChild(date);
158 date = document.createElement("span");
159 date.classList.add("statedate");
160 task.insertBefore(date, task.firstChild);
162 const d = new Date(parseInt(stateTimestamp));
163 date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
167 const model = Model();
169 function Log(prefix: string = "vp-") {
170 var next_log_index = 0;
172 apply: function (entry: string) {
173 const [timestamp, command, data] = splitN(entry, " ", 2);
174 if (command == "Create") {
175 return model.addTask(timestamp, data);
177 if (command == "Edit") {
178 const [createTimestamp, description] = splitN(data, " ", 1);
179 return model.edit(createTimestamp, description);
181 if (command == "Priority") {
182 const [createTimestamp, newPriority] = splitN(data, " ", 1);
183 return model.setPriority(createTimestamp, parseFloat(newPriority));
185 if (command == "State") {
186 const [createTimestamp, state] = splitN(data, " ", 1);
187 return model.setState(timestamp, createTimestamp, state);
189 if (command == "Tag") {
190 const [createTimestamp, tag] = splitN(data, " ", 1);
191 return model.addTag(createTimestamp, tag);
193 if (command == "Untag") {
194 const [createTimestamp, tag] = splitN(data, " ", 1);
195 return model.removeTag(createTimestamp, tag);
199 record: function (entry: string) {
200 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
203 recordAndApply: function (entry: string) {
205 return this.apply(entry);
208 replay: function () {
209 document.getElementById("tasks")!.style.display = "none";
211 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
212 if (entry === null) {
218 document.getElementById("tasks")!.style.display = "";
225 const undoLog: string[][] = [];
226 const redoLog: string[][] = [];
227 function perform(forward: string, reverse: string) {
228 undoLog.push([reverse, forward]);
229 return log.recordAndApply(`${clock.now()} ${forward}`);
232 addTask: function (description: string): Element {
233 const now = clock.now();
234 undoLog.push([`State ${now} deleted`, `State ${now} todo`]);
235 return <Element>log.recordAndApply(`${now} Create ${description}`);
237 addTag: function (createTimestamp: string, tag: string) {
238 return perform(`Tag ${createTimestamp} ${tag}`, `Untag ${createTimestamp} ${tag}`);
240 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
241 return perform(`Edit ${createTimestamp} ${newDescription}`, `Edit ${createTimestamp} ${oldDescription}`);
243 removeTag: function (createTimestamp: string, tag: string) {
244 return perform(`Untag ${createTimestamp} ${tag}`, `Tag ${createTimestamp} ${tag}`);
246 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
247 return perform(`Priority ${createTimestamp} ${newPriority}`, `Priority ${createTimestamp} ${oldPriority}`);
249 setState: function (createTimestamp: string, newState: string, oldState: string) {
250 return perform(`State ${createTimestamp} ${newState}`, `State ${createTimestamp} ${oldState}`);
253 const entry = undoLog.pop();
256 return log.recordAndApply(`${clock.now()} ${entry[0]}`);
260 const entry = redoLog.pop();
263 return log.recordAndApply(`${clock.now()} ${entry[1]}`);
275 function BrowserUI() {
276 const viewColors: { [key: string]: string } = {
281 "someday-maybe": "DeepSkyBlue",
283 waiting: "MediumOrchid",
285 var currentTagView: string | null = null;
286 var currentViewState = "todo";
287 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
288 var lastTagNameEntered = "";
290 addTask: function (event: KeyboardEvent) {
291 const input = <HTMLInputElement>document.getElementById("taskName");
292 if (input.value.match(/^ *$/)) return;
293 const task = ui.addTask(input.value);
294 if (currentViewState === "todo" || currentViewState === "all") {
295 task instanceof HTMLElement && task.focus();
296 } else if (this.returnFocusAfterInput()) {
298 this.firstVisibleTask()?.focus();
301 if (event.getModifierState("Control")) {
302 this.makeBottomPriority(task);
306 beginEdit: function (event: Event) {
307 const task = this.currentTask();
309 const input = document.createElement("input");
310 const desc = task.getElementsByClassName("desc")[0];
311 const oldDescription = desc.textContent!;
312 task.setAttribute("data-description", oldDescription);
313 input.value = oldDescription;
314 input.addEventListener("blur", this.completeEdit, { once: true });
315 desc.textContent = "";
316 task.insertBefore(input, task.firstChild);
318 event.preventDefault();
321 beginTagEdit: function (event: Event) {
322 const task = this.currentTask();
324 const input = document.createElement("input");
325 input.classList.add("tag");
326 input.addEventListener("blur", this.completeTagEdit, { once: true });
327 input.value = lastTagNameEntered;
328 task.appendChild(input);
331 event.preventDefault();
334 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
335 const input = event.target as HTMLInputElement;
336 const task = input.parentElement!;
337 const desc = task.getElementsByClassName("desc")[0];
338 const oldDescription = task.getAttribute("data-description")!;
339 const newDescription = input.value;
340 input.removeEventListener("blur", this.completeEdit);
341 task.removeChild(input);
342 task.removeAttribute("data-description");
344 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
345 desc.textContent = oldDescription;
347 ui.edit(task.getAttribute("id")!, newDescription, oldDescription);
351 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
352 const input = event.target as HTMLInputElement;
353 const task = input.parentElement!;
354 const newTagName = input.value;
355 input.removeEventListener("blur", this.completeTagEdit);
356 task.removeChild(input);
358 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !model.hasTag(task, newTagName)) {
359 ui.addTag(task.getAttribute("id")!, newTagName);
360 lastTagNameEntered = newTagName;
364 currentTag: function (): Element | null {
365 var target = document.activeElement;
366 if (!target) return null;
367 if (target.classList.contains("task")) {
368 const tags = target.getElementsByClassName("tag");
369 target = tags[tags.length - 1];
371 if (!target || !target.classList.contains("tag")) return null;
375 currentTask: function (): HTMLElement | null {
376 var target = document.activeElement;
377 if (!target) return null;
378 if (target.classList.contains("tag")) target = target.parentElement!;
379 return target as HTMLElement;
382 firstVisibleTask: function (root: Element | null = null) {
383 if (root === null) root = document.body;
384 for (const task of root.getElementsByClassName("task")) {
385 const state = task.getAttribute("data-state");
387 task instanceof HTMLElement &&
388 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
389 !task.classList.contains("hide")
396 focusTaskNameInput: function (event: Event) {
397 taskFocusedBeforeJumpingToInput = this.currentTask();
398 document.getElementById("taskName")!.focus();
400 event.preventDefault();
403 visibleTaskAtOffset(task: Element, offset: number): Element {
404 var cursor: Element | null = task;
405 var valid_cursor = cursor;
406 const increment = offset / Math.abs(offset);
408 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
409 if (!cursor || !(cursor instanceof HTMLElement)) break;
410 const state = cursor.getAttribute("data-state")!;
412 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
413 !cursor.classList.contains("hide")
416 valid_cursor = cursor;
418 if (Math.abs(offset) < 0.5) break;
423 jumpCursor: function (position: number) {
424 const first = this.firstVisibleTask();
426 const dest = this.visibleTaskAtOffset(first, position - 1);
427 if (dest instanceof HTMLElement) dest.focus();
430 makeBottomPriority: function (task: Element | null = null) {
431 if (!task) task = this.currentTask();
433 this.setPriority(task, document.getElementById("tasks")!.lastElementChild, null);
436 makeTopPriority: function (task: Element | null = null) {
437 if (!task) task = this.currentTask();
439 ui.setPriority(task.getAttribute("id")!, clock.now(), model.getPriority(task));
440 task instanceof HTMLElement && task.focus();
443 moveCursorLeft: function () {
444 const active = this.currentTask();
445 if (!active) return false;
446 if (active.parentElement!.classList.contains("task")) {
447 active.parentElement!.focus();
451 moveCursorRight: function () {
452 const active = this.currentTask();
453 if (!active) return false;
454 (this.firstVisibleTask(active) as HTMLElement | null)?.focus();
457 moveCursorVertically: function (offset: number): boolean {
458 const active = this.currentTask();
459 if (!active) return false;
460 const dest = this.visibleTaskAtOffset(active, offset);
461 if (dest !== active && dest instanceof HTMLElement) {
468 moveTask: function (offset: number) {
469 const active = this.currentTask();
471 const dest = this.visibleTaskAtOffset(active, offset);
472 if (dest === active) return; // Already extremal
473 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
474 if (onePastDest == dest) onePastDest = null; // Will become extremal
476 this.setPriority(active, dest, onePastDest);
478 this.setPriority(active, onePastDest, dest);
482 removeTag: function () {
483 const target = this.currentTag();
485 ui.removeTag(target.parentElement!.getAttribute("id")!, target.textContent!);
488 resetTagView: function () {
489 currentTagView = null;
490 const taskList = document.getElementById("tasks")!;
491 for (const task of Array.from(document.getElementsByClassName("task"))) {
492 task.classList.remove("hide");
493 if (task.parentElement !== taskList) {
494 model.insertInPriorityOrder(task, taskList);
499 resetView: function () {
500 this.setView("todo");
504 returnFocusAfterInput: function (): boolean {
505 if (taskFocusedBeforeJumpingToInput) {
506 taskFocusedBeforeJumpingToInput.focus();
512 // Change task's priority to be between other tasks a and b.
513 setPriority: function (task: Element, a: Element | null, b: Element | null) {
514 const aPriority = a === null ? clock.now() : model.getPriority(a);
515 const bPriority = b === null ? 0 : model.getPriority(b);
516 console.assert(aPriority > bPriority, aPriority, ">", bPriority);
517 const span = aPriority - bPriority;
518 const newPriority = bPriority + 0.1 * span + 0.8 * span * Math.random();
519 console.assert(aPriority > newPriority && newPriority > bPriority, aPriority, ">", newPriority, ">", bPriority);
520 const newPriorityRounded = Math.round(newPriority);
521 const okToRound = aPriority > newPriorityRounded && newPriorityRounded > bPriority;
522 ui.setPriority(task.getAttribute("id")!, okToRound ? newPriorityRounded : newPriority, model.getPriority(task));
523 task instanceof HTMLElement && task.focus();
526 setState: function (newState: string) {
527 const task = this.currentTask();
529 const oldState = task.getAttribute("data-state")!;
530 if (newState === oldState) return;
531 const createTimestamp = task.getAttribute("id")!;
532 if (currentViewState !== "all" || newState == "deleted") {
533 this.moveCursorVertically(1) || this.moveCursorVertically(-1);
535 return ui.setState(createTimestamp, newState, oldState);
538 setTagView: function (tag: string | null = null) {
540 const target = this.currentTag();
542 tag = target.textContent!;
545 if (currentTagView !== null) {
549 const tasksWithTag = new Map();
550 for (const task of document.getElementsByClassName("task")) {
551 if (model.hasTag(task, tag)) {
552 tasksWithTag.set(task.getElementsByClassName("desc")[0].textContent, [model.getPriority(task), task]);
556 function highestPrioritySuperTask(t: Element) {
557 var maxPriority = -1;
558 var superTask = null;
559 for (const child of t.getElementsByClassName("tag")) {
560 const e = tasksWithTag.get(child.textContent);
561 if (e !== undefined && e[0] > maxPriority) {
569 for (const task of Array.from(document.getElementsByClassName("task"))) {
570 if (model.hasTag(task, tag)) {
571 task.classList.remove("hide");
573 const superTask = highestPrioritySuperTask(task);
574 if (superTask !== null) {
575 model.insertInPriorityOrder(task, superTask);
577 task.classList.add("hide");
582 currentTagView = tag;
585 setView: function (state: string) {
586 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
587 if (state === "all") {
588 sheet.insertRule(`.task[data-state=deleted] { display: none }`);
590 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
592 sheet.insertRule(`:root { --view-state-indicator-color: ${viewColors[state]}; }`);
595 currentViewState = state;
596 if (this.currentTask()?.getAttribute("data-state") !== state) {
597 this.firstVisibleTask()?.focus();
601 setUntaggedView: function () {
602 if (currentTagView !== null) {
605 for (const task of document.getElementsByClassName("task")) {
606 if (task.getElementsByClassName("tag").length === 0) {
607 task.classList.remove("hide");
609 task.classList.add("hide");
615 const ret = ui.undo();
616 if (ret && ret instanceof HTMLElement) ret.focus();
619 const ret = ui.redo();
620 if (ret && ret instanceof HTMLElement) ret.focus();
624 const browserUI = BrowserUI();
626 const scrollIncrement = 60;
633 var inputState = InputState.Root;
634 var inputCount: number | null = null;
636 function handleKey(event: any) {
637 if (["Alt", "Control", "Meta", "Shift"].includes(event.key)) return;
638 if (event.target.tagName === "INPUT") {
639 if (event.target.id === "taskName") {
640 if (event.key == "Enter") return browserUI.addTask(event);
641 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
642 } else if (event.target.classList.contains("tag")) {
643 if (event.key == "Enter") return browserUI.completeTagEdit(event);
644 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
646 if (event.key == "Enter") return browserUI.completeEdit(event);
647 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
650 if (inputState === InputState.Root) {
651 if ("0" <= event.key && event.key <= "9") {
652 return (inputCount = (inputCount ?? 0) * 10 + parseInt(event.key));
656 if (event.key == "e") return window.scrollBy(0, (inputCount ?? 1) * scrollIncrement);
657 if (event.key == "y") return window.scrollBy(0, (inputCount ?? 1) * -scrollIncrement);
659 if (event.key == "h") return browserUI.moveCursorLeft();
660 if (event.key == "l") return browserUI.moveCursorRight();
661 if (event.key == "j") return browserUI.moveCursorVertically(inputCount ?? 1);
662 if (event.key == "k") return browserUI.moveCursorVertically(-(inputCount ?? 1));
663 if (event.key == "J") return browserUI.moveTask(inputCount ?? 1);
664 if (event.key == "K") return browserUI.moveTask(-(inputCount ?? 1));
665 if (event.key == "G") return browserUI.jumpCursor(inputCount ?? MAX_SAFE_INTEGER);
666 if (event.key == "T") return browserUI.makeTopPriority();
667 if (event.key == "n") return browserUI.focusTaskNameInput(event);
668 if (event.key == "c") return browserUI.setState("cancelled");
669 if (event.key == "d") return browserUI.setState("done");
670 if (event.key == "q") return browserUI.setState("todo");
671 if (event.key == "s") return (inputState = InputState.S);
672 if (event.key == "w") return browserUI.setState("waiting");
673 if (event.key == "X") return browserUI.setState("deleted");
674 if (event.key == "x") return browserUI.removeTag();
675 if (event.key == "u") return browserUI.undo();
676 if (event.key == "r") return browserUI.redo();
677 if (event.key == "e") return browserUI.beginEdit(event);
678 if (event.key == "t") return browserUI.beginTagEdit(event);
679 if (event.key == "v") return (inputState = InputState.V);
684 } else if (inputState === InputState.S) {
685 inputState = InputState.Root;
686 if (event.key == "m") return browserUI.setState("someday-maybe");
687 } else if (inputState === InputState.V) {
688 inputState = InputState.Root;
689 if (event.key == "a") return browserUI.setView("all");
690 if (event.key == "c") return browserUI.setView("cancelled");
691 if (event.key == "d") return browserUI.setView("done");
692 if (event.key == "i") return browserUI.setUntaggedView();
693 if (event.key == "p") return browserUI.setTagView("Project");
694 if (event.key == "q") return browserUI.setView("todo");
695 if (event.key == "s") return (inputState = InputState.VS);
696 if (event.key == "T") return browserUI.resetTagView();
697 if (event.key == "t") return browserUI.setTagView();
698 if (event.key == "u") return browserUI.setUntaggedView();
699 if (event.key == "v") return browserUI.resetView();
700 if (event.key == "w") return browserUI.setView("waiting");
701 if (event.key == "x") return browserUI.setView("deleted");
702 } else if (inputState === InputState.VS) {
703 inputState = InputState.Root;
704 if (event.key == "m") return browserUI.setView("someday-maybe");
709 function browserInit() {
711 browserUI.firstVisibleTask()?.focus();
712 document.body.addEventListener("keydown", handleKey, { capture: false });