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 removeTag: function (createTimestamp: string, tagName: string) {
124 const task = this.getTask(createTimestamp);
125 if (!task) return null;
126 const tag = this.hasTag(task, tagName);
128 task.removeChild(tag);
129 if (task instanceof HTMLElement) task.focus();
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);
142 document.getElementById("tasks")!.appendChild(target);
146 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
147 const task = this.getTask(createTimestamp);
149 task.setAttribute("data-state", state);
150 var date = task.getElementsByClassName("statedate")[0];
151 if (state === "todo") {
152 task.removeChild(date);
156 date = document.createElement("span");
157 date.classList.add("statedate");
158 task.insertBefore(date, task.firstChild);
160 const d = new Date(parseInt(stateTimestamp));
161 date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
165 function Log(prefix: string = "vp-") {
166 var next_log_index = 0;
168 apply: function (entry: string) {
169 const [timestamp, command, data] = splitN(entry, " ", 2);
170 if (command == "Create") {
171 return Model.addTask(timestamp, data);
173 if (command == "Edit") {
174 const [createTimestamp, description] = splitN(data, " ", 1);
175 return Model.edit(createTimestamp, description);
177 if (command == "Priority") {
178 const [createTimestamp, newPriority] = splitN(data, " ", 1);
179 return Model.setPriority(createTimestamp, parseFloat(newPriority));
181 if (command == "State") {
182 const [createTimestamp, state] = splitN(data, " ", 1);
183 return Model.setState(timestamp, createTimestamp, state);
185 if (command == "Tag") {
186 const [createTimestamp, tag] = splitN(data, " ", 1);
187 return Model.addTag(createTimestamp, tag);
189 if (command == "Untag") {
190 const [createTimestamp, tag] = splitN(data, " ", 1);
191 return Model.removeTag(createTimestamp, tag);
195 record: function (entry: string) {
196 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
199 recordAndApply: function (entry: string) {
201 return this.apply(entry);
204 replay: function () {
206 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
207 if (entry === null) {
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}`);
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}`);
231 addTag: function (createTimestamp: string, tag: string) {
232 return perform(`Tag ${createTimestamp} ${tag}`, `Untag ${createTimestamp} ${tag}`);
234 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
235 return perform(`Edit ${createTimestamp} ${newDescription}`, `Edit ${createTimestamp} ${oldDescription}`);
237 removeTag: function (createTimestamp: string, tag: string) {
238 return perform(`Untag ${createTimestamp} ${tag}`, `Tag ${createTimestamp} ${tag}`);
240 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
241 return perform(`Priority ${createTimestamp} ${newPriority}`, `Priority ${createTimestamp} ${oldPriority}`);
243 setState: function (createTimestamp: string, newState: string, oldState: string) {
244 return perform(`State ${createTimestamp} ${newState}`, `State ${createTimestamp} ${oldState}`);
247 const entry = undoLog.pop();
250 return log.recordAndApply(`${clock.now()} ${entry[0]}`);
254 const entry = redoLog.pop();
257 return log.recordAndApply(`${clock.now()} ${entry[1]}`);
269 function BrowserUI() {
270 const viewColors: { [key: string]: string } = {
275 "someday-maybe": "DeepSkyBlue",
277 waiting: "MediumOrchid",
279 var currentTagView: string | null = null;
280 var currentViewState = "todo";
281 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
282 var lastTagNameEntered = "";
284 addTask: function (event: KeyboardEvent) {
285 const input = <HTMLInputElement>document.getElementById("taskName");
286 if (input.value.match(/^ *$/)) return;
287 const task = ui.addTask(input.value);
288 if (currentViewState === "todo" || currentViewState === "all") {
289 task instanceof HTMLElement && task.focus();
290 } else if (this.returnFocusAfterInput()) {
292 this.firstVisibleTask()?.focus();
295 if (currentTagView) {
296 ui.addTag(task.getAttribute("data-created")!, currentTagView);
298 if (event.getModifierState("Control")) {
299 this.makeBottomPriority(task);
303 beginEdit: function (event: Event) {
304 const task = this.currentTask();
306 const input = document.createElement("input");
307 const desc = task.getElementsByClassName("desc")[0];
308 const oldDescription = desc.textContent!;
309 task.setAttribute("data-description", oldDescription);
310 input.value = oldDescription;
311 input.addEventListener("blur", this.completeEdit, { once: true });
312 desc.textContent = "";
313 task.insertBefore(input, task.firstChild);
315 event.preventDefault();
318 beginTagEdit: function (event: Event) {
319 const task = this.currentTask();
321 const input = document.createElement("input");
322 input.classList.add("tag");
323 input.addEventListener("blur", this.completeTagEdit, { once: true });
324 input.value = lastTagNameEntered;
325 task.appendChild(input);
328 event.preventDefault();
331 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
332 const input = event.target as HTMLInputElement;
333 const task = input.parentElement!;
334 const desc = task.getElementsByClassName("desc")[0];
335 const oldDescription = task.getAttribute("data-description")!;
336 const newDescription = input.value;
337 input.removeEventListener("blur", this.completeEdit);
338 task.removeChild(input);
339 task.removeAttribute("data-description");
341 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
342 desc.textContent = oldDescription;
344 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
348 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
349 const input = event.target as HTMLInputElement;
350 const task = input.parentElement!;
351 const newTagName = input.value;
352 input.removeEventListener("blur", this.completeTagEdit);
353 task.removeChild(input);
355 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !Model.hasTag(task, newTagName)) {
356 ui.addTag(task.getAttribute("data-created")!, newTagName);
357 lastTagNameEntered = newTagName;
361 currentTag: function (): Element | null {
362 var target = document.activeElement;
363 if (!target) return null;
364 if (target.classList.contains("task")) {
365 const tags = target.getElementsByClassName("tag");
366 target = tags[tags.length - 1];
368 if (!target || !target.classList.contains("tag")) return null;
372 currentTask: function (): HTMLElement | null {
373 var target = document.activeElement;
374 if (!target) return null;
375 if (target.classList.contains("tag")) target = target.parentElement!;
376 return target as HTMLElement;
379 firstVisibleTask: function () {
380 for (const task of document.getElementsByClassName("task")) {
381 const state = task.getAttribute("data-state");
383 task instanceof HTMLElement &&
384 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
385 !task.classList.contains("hide")
392 focusTaskNameInput: function (event: Event) {
393 taskFocusedBeforeJumpingToInput = this.currentTask();
394 document.getElementById("taskName")!.focus();
396 event.preventDefault();
399 visibleTaskAtOffset(task: Element, offset: number): Element {
400 var cursor: Element | null = task;
401 var valid_cursor = cursor;
402 const increment = offset / Math.abs(offset);
404 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
405 if (!cursor || !(cursor instanceof HTMLElement)) break;
406 const state = cursor.getAttribute("data-state")!;
408 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
409 !cursor.classList.contains("hide")
412 valid_cursor = cursor;
414 if (Math.abs(offset) < 0.5) break;
419 jumpCursor: function (position: number) {
420 const first = this.firstVisibleTask();
422 const dest = this.visibleTaskAtOffset(first, position - 1);
423 if (dest instanceof HTMLElement) dest.focus();
426 makeBottomPriority: function (task: Element | null = null) {
427 if (!task) task = this.currentTask();
429 this.setPriority(task, document.getElementById("tasks")!.lastElementChild, null);
432 makeTopPriority: function (task: Element | null = null) {
433 if (!task) task = this.currentTask();
435 ui.setPriority(task.getAttribute("data-created")!, clock.now(), Model.getPriority(task));
436 task instanceof HTMLElement && task.focus();
439 moveCursor: function (offset: number): boolean {
440 const active = this.currentTask();
441 if (!active) return false;
442 const dest = this.visibleTaskAtOffset(active, offset);
443 if (dest !== active && dest instanceof HTMLElement) {
450 moveTask: function (offset: number) {
451 const active = this.currentTask();
453 const dest = this.visibleTaskAtOffset(active, offset);
454 if (dest === active) return; // Already extremal
455 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
456 if (onePastDest == dest) onePastDest = null; // Will become extremal
458 this.setPriority(active, dest, onePastDest);
460 this.setPriority(active, onePastDest, dest);
464 removeTag: function () {
465 const target = this.currentTag();
467 ui.removeTag(target.parentElement!.getAttribute("data-created")!, target.textContent!);
470 resetTagView: function () {
471 currentTagView = null;
472 for (const task of document.getElementsByClassName("task")) {
473 task.classList.remove("hide");
477 resetView: function () {
478 this.setView("todo");
482 returnFocusAfterInput: function (): boolean {
483 if (taskFocusedBeforeJumpingToInput) {
484 taskFocusedBeforeJumpingToInput.focus();
490 // Change task's priority to be between other tasks a and b.
491 setPriority: function (task: Element, a: Element | null, b: Element | null) {
492 const aPriority = a === null ? clock.now() : Model.getPriority(a);
493 const bPriority = b === null ? 0 : Model.getPriority(b);
494 console.assert(aPriority > bPriority, aPriority, ">", bPriority);
495 const span = aPriority - bPriority;
496 const newPriority = bPriority + 0.1 * span + 0.8 * span * Math.random();
497 console.assert(aPriority > newPriority && newPriority > bPriority, aPriority, ">", newPriority, ">", bPriority);
498 const newPriorityRounded = Math.round(newPriority);
499 const okToRound = aPriority > newPriorityRounded && newPriorityRounded > bPriority;
500 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
501 task instanceof HTMLElement && task.focus();
504 setState: function (newState: string) {
505 const task = this.currentTask();
507 const oldState = task.getAttribute("data-state")!;
508 if (newState === oldState) return;
509 const createTimestamp = task.getAttribute("data-created")!;
510 if (currentViewState !== "all" || newState == "deleted") {
511 this.moveCursor(1) || this.moveCursor(-1);
513 return ui.setState(createTimestamp, newState, oldState);
516 setTagView: function () {
517 const target = this.currentTag();
519 const tag = target.textContent!;
520 for (const task of document.getElementsByClassName("task")) {
521 if (Model.hasTag(task, tag)) {
522 task.classList.remove("hide");
524 task.classList.add("hide");
527 currentTagView = tag;
530 setView: function (state: string) {
531 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
532 if (state === "all") {
533 sheet.insertRule(`.task[data-state=deleted] { display: none }`);
535 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
537 sheet.insertRule(`:root { --view-state-indicator-color: ${viewColors[state]}; }`);
540 currentViewState = state;
541 if (this.currentTask()?.getAttribute("data-state") !== state) {
542 this.firstVisibleTask()?.focus();
546 setUntaggedView: function () {
547 for (const task of document.getElementsByClassName("task")) {
548 if (task.getElementsByClassName("tag").length === 0) {
549 task.classList.remove("hide");
551 task.classList.add("hide");
557 const ret = ui.undo();
558 if (ret && ret instanceof HTMLElement) ret.focus();
561 const ret = ui.redo();
562 if (ret && ret instanceof HTMLElement) ret.focus();
566 const browserUI = BrowserUI();
568 const scrollIncrement = 60;
575 var inputState = InputState.Root;
576 var inputCount: number | null = null;
578 function handleKey(event: any) {
579 if (["Alt", "Control", "Meta", "Shift"].includes(event.key)) return;
580 if (event.target.tagName === "INPUT") {
581 if (event.target.id === "taskName") {
582 if (event.key == "Enter") return browserUI.addTask(event);
583 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
584 } else if (event.target.classList.contains("tag")) {
585 if (event.key == "Enter") return browserUI.completeTagEdit(event);
586 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
588 if (event.key == "Enter") return browserUI.completeEdit(event);
589 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
592 if (inputState === InputState.Root) {
593 if ("0" <= event.key && event.key <= "9") {
594 return (inputCount = (inputCount ?? 0) * 10 + parseInt(event.key));
598 if (event.key == "e") return window.scrollBy(0, (inputCount ?? 1) * scrollIncrement);
599 if (event.key == "y") return window.scrollBy(0, (inputCount ?? 1) * -scrollIncrement);
601 if (event.key == "j") return browserUI.moveCursor(inputCount ?? 1);
602 if (event.key == "k") return browserUI.moveCursor(-(inputCount ?? 1));
603 if (event.key == "J") return browserUI.moveTask(inputCount ?? 1);
604 if (event.key == "K") return browserUI.moveTask(-(inputCount ?? 1));
605 if (event.key == "G") return browserUI.jumpCursor(inputCount ?? MAX_SAFE_INTEGER);
606 if (event.key == "T") return browserUI.makeTopPriority();
607 if (event.key == "n") return browserUI.focusTaskNameInput(event);
608 if (event.key == "c") return browserUI.setState("cancelled");
609 if (event.key == "d") return browserUI.setState("done");
610 if (event.key == "q") return browserUI.setState("todo");
611 if (event.key == "s") return (inputState = InputState.S);
612 if (event.key == "w") return browserUI.setState("waiting");
613 if (event.key == "X") return browserUI.setState("deleted");
614 if (event.key == "x") return browserUI.removeTag();
615 if (event.key == "u") return browserUI.undo();
616 if (event.key == "r") return browserUI.redo();
617 if (event.key == "e") return browserUI.beginEdit(event);
618 if (event.key == "t") return browserUI.beginTagEdit(event);
619 if (event.key == "v") return (inputState = InputState.V);
624 } else if (inputState === InputState.S) {
625 inputState = InputState.Root;
626 if (event.key == "m") return browserUI.setState("someday-maybe");
627 } else if (inputState === InputState.V) {
628 inputState = InputState.Root;
629 if (event.key == "a") return browserUI.setView("all");
630 if (event.key == "c") return browserUI.setView("cancelled");
631 if (event.key == "d") return browserUI.setView("done");
632 if (event.key == "i") return browserUI.setUntaggedView();
633 if (event.key == "q") return browserUI.setView("todo");
634 if (event.key == "s") return (inputState = InputState.VS);
635 if (event.key == "T") return browserUI.resetTagView();
636 if (event.key == "t") return browserUI.setTagView();
637 if (event.key == "u") return browserUI.setUntaggedView();
638 if (event.key == "v") return browserUI.resetView();
639 if (event.key == "w") return browserUI.setView("waiting");
640 if (event.key == "x") return browserUI.setView("deleted");
641 } else if (inputState === InputState.VS) {
642 inputState = InputState.Root;
643 if (event.key == "m") return browserUI.setView("someday-maybe");
648 function browserInit() {
650 browserUI.firstVisibleTask()?.focus();
651 document.body.addEventListener("keydown", handleKey, { capture: false });