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);
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);
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);
70 task.insertBefore(tag, task.getElementsByClassName("desc")[0]!);
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.getElementsByTagName("input")[0]!;
81 input.value === target.getAttribute("data-description") &&
82 input.selectionStart === input.value.length &&
83 input.selectionEnd === input.value.length
85 // No local changes have actually been made yet. Change the contents of the edit box!
86 input.value = newDescription;
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);
94 target.getElementsByClassName("desc")[0].textContent = newDescription;
99 hasTag: function (task: Element, tag: string): Element | null {
100 for (const child of task.getElementsByClassName("tag")) {
101 if (child.textContent === tag) {
108 getPriority: function (task: Element): number {
109 if (task.hasAttribute("data-priority")) {
110 return parseFloat(task.getAttribute("data-priority")!);
112 return parseFloat(task.getAttribute("data-created")!);
115 getTask: function (createTimestamp: string) {
116 for (const task of document.getElementsByClassName("task")) {
117 if (task.getAttribute("data-created") === createTimestamp) {
123 insertInPriorityOrder: function (task: Element, dest: Element) {
124 const priority = this.getPriority(task);
125 for (const t of dest.children) {
126 if (t !== task && this.getPriority(t) < priority) {
127 dest.insertBefore(task, t);
131 dest.appendChild(task);
134 removeTag: function (createTimestamp: string, tagName: string) {
135 const task = this.getTask(createTimestamp);
136 if (!task) return null;
137 const tag = this.hasTag(task, tagName);
139 task.removeChild(tag);
140 if (task instanceof HTMLElement) task.focus();
143 setPriority: function (createTimestamp: string, priority: number): Element | null {
144 const target = this.getTask(createTimestamp);
145 if (!target) return null;
146 target.setAttribute("data-priority", `${priority}`);
147 this.insertInPriorityOrder(target, target.parentElement!);
151 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
152 const task = this.getTask(createTimestamp);
154 task.setAttribute("data-state", state);
155 var date = task.getElementsByClassName("statedate")[0];
156 if (state === "todo") {
157 task.removeChild(date);
161 date = document.createElement("span");
162 date.classList.add("statedate");
163 task.insertBefore(date, task.firstChild);
165 const d = new Date(parseInt(stateTimestamp));
166 date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
170 function Log(prefix: string = "vp-") {
171 var next_log_index = 0;
173 apply: function (entry: string) {
174 const [timestamp, command, data] = splitN(entry, " ", 2);
175 if (command == "Create") {
176 return Model.addTask(timestamp, data);
178 if (command == "Edit") {
179 const [createTimestamp, description] = splitN(data, " ", 1);
180 return Model.edit(createTimestamp, description);
182 if (command == "Priority") {
183 const [createTimestamp, newPriority] = splitN(data, " ", 1);
184 return Model.setPriority(createTimestamp, parseFloat(newPriority));
186 if (command == "State") {
187 const [createTimestamp, state] = splitN(data, " ", 1);
188 return Model.setState(timestamp, createTimestamp, state);
190 if (command == "Tag") {
191 const [createTimestamp, tag] = splitN(data, " ", 1);
192 return Model.addTag(createTimestamp, tag);
194 if (command == "Untag") {
195 const [createTimestamp, tag] = splitN(data, " ", 1);
196 return Model.removeTag(createTimestamp, tag);
200 record: function (entry: string) {
201 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
204 recordAndApply: function (entry: string) {
206 return this.apply(entry);
209 replay: function () {
211 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
212 if (entry === null) {
224 const undoLog: string[][] = [];
225 const redoLog: string[][] = [];
226 function perform(forward: string, reverse: string) {
227 undoLog.push([reverse, forward]);
228 return log.recordAndApply(`${clock.now()} ${forward}`);
231 addTask: function (description: string): Element {
232 const now = clock.now();
233 undoLog.push([`State ${now} deleted`, `State ${now} todo`]);
234 return <Element>log.recordAndApply(`${now} Create ${description}`);
236 addTag: function (createTimestamp: string, tag: string) {
237 return perform(`Tag ${createTimestamp} ${tag}`, `Untag ${createTimestamp} ${tag}`);
239 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
240 return perform(`Edit ${createTimestamp} ${newDescription}`, `Edit ${createTimestamp} ${oldDescription}`);
242 removeTag: function (createTimestamp: string, tag: string) {
243 return perform(`Untag ${createTimestamp} ${tag}`, `Tag ${createTimestamp} ${tag}`);
245 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
246 return perform(`Priority ${createTimestamp} ${newPriority}`, `Priority ${createTimestamp} ${oldPriority}`);
248 setState: function (createTimestamp: string, newState: string, oldState: string) {
249 return perform(`State ${createTimestamp} ${newState}`, `State ${createTimestamp} ${oldState}`);
252 const entry = undoLog.pop();
255 return log.recordAndApply(`${clock.now()} ${entry[0]}`);
259 const entry = redoLog.pop();
262 return log.recordAndApply(`${clock.now()} ${entry[1]}`);
274 function BrowserUI() {
275 const viewColors: { [key: string]: string } = {
280 "someday-maybe": "DeepSkyBlue",
282 waiting: "MediumOrchid",
284 var currentTagView: string | null = null;
285 var currentViewState = "todo";
286 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
287 var lastTagNameEntered = "";
289 addTask: function (event: KeyboardEvent) {
290 const input = <HTMLInputElement>document.getElementById("taskName");
291 if (input.value.match(/^ *$/)) return;
292 const task = ui.addTask(input.value);
293 if (currentViewState === "todo" || currentViewState === "all") {
294 task instanceof HTMLElement && task.focus();
295 } else if (this.returnFocusAfterInput()) {
297 this.firstVisibleTask()?.focus();
300 if (currentTagView) {
301 ui.addTag(task.getAttribute("data-created")!, currentTagView);
303 if (event.getModifierState("Control")) {
304 this.makeBottomPriority(task);
308 beginEdit: function (event: Event) {
309 const task = this.currentTask();
311 const input = document.createElement("input");
312 const desc = task.getElementsByClassName("desc")[0];
313 const oldDescription = desc.textContent!;
314 task.setAttribute("data-description", oldDescription);
315 input.value = oldDescription;
316 input.addEventListener("blur", this.completeEdit, { once: true });
317 desc.textContent = "";
318 task.insertBefore(input, task.firstChild);
320 event.preventDefault();
323 beginTagEdit: function (event: Event) {
324 const task = this.currentTask();
326 const input = document.createElement("input");
327 input.classList.add("tag");
328 input.addEventListener("blur", this.completeTagEdit, { once: true });
329 input.value = lastTagNameEntered;
330 task.appendChild(input);
333 event.preventDefault();
336 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
337 const input = event.target as HTMLInputElement;
338 const task = input.parentElement!;
339 const desc = task.getElementsByClassName("desc")[0];
340 const oldDescription = task.getAttribute("data-description")!;
341 const newDescription = input.value;
342 input.removeEventListener("blur", this.completeEdit);
343 task.removeChild(input);
344 task.removeAttribute("data-description");
346 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
347 desc.textContent = oldDescription;
349 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
353 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
354 const input = event.target as HTMLInputElement;
355 const task = input.parentElement!;
356 const newTagName = input.value;
357 input.removeEventListener("blur", this.completeTagEdit);
358 task.removeChild(input);
360 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !Model.hasTag(task, newTagName)) {
361 ui.addTag(task.getAttribute("data-created")!, newTagName);
362 lastTagNameEntered = newTagName;
366 currentTag: function (): Element | null {
367 var target = document.activeElement;
368 if (!target) return null;
369 if (target.classList.contains("task")) {
370 const tags = target.getElementsByClassName("tag");
371 target = tags[tags.length - 1];
373 if (!target || !target.classList.contains("tag")) return null;
377 currentTask: function (): HTMLElement | null {
378 var target = document.activeElement;
379 if (!target) return null;
380 if (target.classList.contains("tag")) target = target.parentElement!;
381 return target as HTMLElement;
384 firstVisibleTask: function () {
385 for (const task of document.getElementsByClassName("task")) {
386 const state = task.getAttribute("data-state");
388 task instanceof HTMLElement &&
389 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
390 !task.classList.contains("hide")
397 focusTaskNameInput: function (event: Event) {
398 taskFocusedBeforeJumpingToInput = this.currentTask();
399 document.getElementById("taskName")!.focus();
401 event.preventDefault();
404 visibleTaskAtOffset(task: Element, offset: number): Element {
405 var cursor: Element | null = task;
406 var valid_cursor = cursor;
407 const increment = offset / Math.abs(offset);
409 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
410 if (!cursor || !(cursor instanceof HTMLElement)) break;
411 const state = cursor.getAttribute("data-state")!;
413 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
414 !cursor.classList.contains("hide")
417 valid_cursor = cursor;
419 if (Math.abs(offset) < 0.5) break;
424 jumpCursor: function (position: number) {
425 const first = this.firstVisibleTask();
427 const dest = this.visibleTaskAtOffset(first, position - 1);
428 if (dest instanceof HTMLElement) dest.focus();
431 makeBottomPriority: function (task: Element | null = null) {
432 if (!task) task = this.currentTask();
434 this.setPriority(task, document.getElementById("tasks")!.lastElementChild, null);
437 makeTopPriority: function (task: Element | null = null) {
438 if (!task) task = this.currentTask();
440 ui.setPriority(task.getAttribute("data-created")!, clock.now(), Model.getPriority(task));
441 task instanceof HTMLElement && task.focus();
444 moveCursor: function (offset: number): boolean {
445 const active = this.currentTask();
446 if (!active) return false;
447 const dest = this.visibleTaskAtOffset(active, offset);
448 if (dest !== active && dest instanceof HTMLElement) {
455 moveTask: function (offset: number) {
456 const active = this.currentTask();
458 const dest = this.visibleTaskAtOffset(active, offset);
459 if (dest === active) return; // Already extremal
460 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
461 if (onePastDest == dest) onePastDest = null; // Will become extremal
463 this.setPriority(active, dest, onePastDest);
465 this.setPriority(active, onePastDest, dest);
469 removeTag: function () {
470 const target = this.currentTag();
472 ui.removeTag(target.parentElement!.getAttribute("data-created")!, target.textContent!);
475 resetTagView: function () {
476 currentTagView = null;
477 const taskList = document.getElementById("tasks")!;
478 for (const task of Array.from(document.getElementsByClassName("task"))) {
479 task.classList.remove("hide");
480 if (task.parentElement !== taskList) {
481 Model.insertInPriorityOrder(task, taskList);
486 resetView: function () {
487 this.setView("todo");
491 returnFocusAfterInput: function (): boolean {
492 if (taskFocusedBeforeJumpingToInput) {
493 taskFocusedBeforeJumpingToInput.focus();
499 // Change task's priority to be between other tasks a and b.
500 setPriority: function (task: Element, a: Element | null, b: Element | null) {
501 const aPriority = a === null ? clock.now() : Model.getPriority(a);
502 const bPriority = b === null ? 0 : Model.getPriority(b);
503 console.assert(aPriority > bPriority, aPriority, ">", bPriority);
504 const span = aPriority - bPriority;
505 const newPriority = bPriority + 0.1 * span + 0.8 * span * Math.random();
506 console.assert(aPriority > newPriority && newPriority > bPriority, aPriority, ">", newPriority, ">", bPriority);
507 const newPriorityRounded = Math.round(newPriority);
508 const okToRound = aPriority > newPriorityRounded && newPriorityRounded > bPriority;
509 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
510 task instanceof HTMLElement && task.focus();
513 setState: function (newState: string) {
514 const task = this.currentTask();
516 const oldState = task.getAttribute("data-state")!;
517 if (newState === oldState) return;
518 const createTimestamp = task.getAttribute("data-created")!;
519 if (currentViewState !== "all" || newState == "deleted") {
520 this.moveCursor(1) || this.moveCursor(-1);
522 return ui.setState(createTimestamp, newState, oldState);
525 setTagView: function () {
526 const target = this.currentTag();
528 const tag = target.textContent!;
530 if (currentTagView !== null) {
534 const tasksWithTag = new Map();
535 for (const task of document.getElementsByClassName("task")) {
536 if (Model.hasTag(task, tag)) {
537 tasksWithTag.set(task.getElementsByClassName("desc")[0].textContent, [Model.getPriority(task), task]);
541 function highestPrioritySuperTask(t: Element) {
542 var maxPriority = -1;
543 var superTask = null;
544 for (const child of t.getElementsByClassName("tag")) {
545 const e = tasksWithTag.get(child.textContent);
546 if (e !== undefined && e[0] > maxPriority) {
554 for (const task of Array.from(document.getElementsByClassName("task"))) {
555 if (Model.hasTag(task, tag)) {
556 task.classList.remove("hide");
558 const superTask = highestPrioritySuperTask(task);
559 if (superTask !== null) {
560 Model.insertInPriorityOrder(task, superTask);
562 task.classList.add("hide");
567 currentTagView = tag;
570 setView: function (state: string) {
571 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
572 if (state === "all") {
573 sheet.insertRule(`.task[data-state=deleted] { display: none }`);
575 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
577 sheet.insertRule(`:root { --view-state-indicator-color: ${viewColors[state]}; }`);
580 currentViewState = state;
581 if (this.currentTask()?.getAttribute("data-state") !== state) {
582 this.firstVisibleTask()?.focus();
586 setUntaggedView: function () {
587 if (currentTagView !== null) {
590 for (const task of document.getElementsByClassName("task")) {
591 if (task.getElementsByClassName("tag").length === 0) {
592 task.classList.remove("hide");
594 task.classList.add("hide");
600 const ret = ui.undo();
601 if (ret && ret instanceof HTMLElement) ret.focus();
604 const ret = ui.redo();
605 if (ret && ret instanceof HTMLElement) ret.focus();
609 const browserUI = BrowserUI();
611 const scrollIncrement = 60;
618 var inputState = InputState.Root;
619 var inputCount: number | null = null;
621 function handleKey(event: any) {
622 if (["Alt", "Control", "Meta", "Shift"].includes(event.key)) return;
623 if (event.target.tagName === "INPUT") {
624 if (event.target.id === "taskName") {
625 if (event.key == "Enter") return browserUI.addTask(event);
626 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
627 } else if (event.target.classList.contains("tag")) {
628 if (event.key == "Enter") return browserUI.completeTagEdit(event);
629 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
631 if (event.key == "Enter") return browserUI.completeEdit(event);
632 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
635 if (inputState === InputState.Root) {
636 if ("0" <= event.key && event.key <= "9") {
637 return (inputCount = (inputCount ?? 0) * 10 + parseInt(event.key));
641 if (event.key == "e") return window.scrollBy(0, (inputCount ?? 1) * scrollIncrement);
642 if (event.key == "y") return window.scrollBy(0, (inputCount ?? 1) * -scrollIncrement);
644 if (event.key == "j") return browserUI.moveCursor(inputCount ?? 1);
645 if (event.key == "k") return browserUI.moveCursor(-(inputCount ?? 1));
646 if (event.key == "J") return browserUI.moveTask(inputCount ?? 1);
647 if (event.key == "K") return browserUI.moveTask(-(inputCount ?? 1));
648 if (event.key == "G") return browserUI.jumpCursor(inputCount ?? MAX_SAFE_INTEGER);
649 if (event.key == "T") return browserUI.makeTopPriority();
650 if (event.key == "n") return browserUI.focusTaskNameInput(event);
651 if (event.key == "c") return browserUI.setState("cancelled");
652 if (event.key == "d") return browserUI.setState("done");
653 if (event.key == "q") return browserUI.setState("todo");
654 if (event.key == "s") return (inputState = InputState.S);
655 if (event.key == "w") return browserUI.setState("waiting");
656 if (event.key == "X") return browserUI.setState("deleted");
657 if (event.key == "x") return browserUI.removeTag();
658 if (event.key == "u") return browserUI.undo();
659 if (event.key == "r") return browserUI.redo();
660 if (event.key == "e") return browserUI.beginEdit(event);
661 if (event.key == "t") return browserUI.beginTagEdit(event);
662 if (event.key == "v") return (inputState = InputState.V);
667 } else if (inputState === InputState.S) {
668 inputState = InputState.Root;
669 if (event.key == "m") return browserUI.setState("someday-maybe");
670 } else if (inputState === InputState.V) {
671 inputState = InputState.Root;
672 if (event.key == "a") return browserUI.setView("all");
673 if (event.key == "c") return browserUI.setView("cancelled");
674 if (event.key == "d") return browserUI.setView("done");
675 if (event.key == "i") return browserUI.setUntaggedView();
676 if (event.key == "q") return browserUI.setView("todo");
677 if (event.key == "s") return (inputState = InputState.VS);
678 if (event.key == "T") return browserUI.resetTagView();
679 if (event.key == "t") return browserUI.setTagView();
680 if (event.key == "u") return browserUI.setUntaggedView();
681 if (event.key == "v") return browserUI.resetView();
682 if (event.key == "w") return browserUI.setView("waiting");
683 if (event.key == "x") return browserUI.setView("deleted");
684 } else if (inputState === InputState.VS) {
685 inputState = InputState.Root;
686 if (event.key == "m") return browserUI.setView("someday-maybe");
691 function browserInit() {
693 browserUI.firstVisibleTask()?.focus();
694 document.body.addEventListener("keydown", handleKey, { capture: false });