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 document.getElementById("tasks")!.appendChild(task);
53 addTag: function (createTimestamp: string, tagName: string): Element | null {
54 const task = this.getTask(createTimestamp);
55 if (!task) return null;
56 const existingTag = this.hasTag(task, tagName);
57 if (existingTag) return existingTag;
58 const tag = document.createElement("span");
59 tag.appendChild(document.createTextNode(tagName));
60 tag.classList.add("tag");
61 tag.setAttribute("tabindex", "0");
62 hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`));
63 for (const child of task.getElementsByClassName("tag")) {
64 if (tagName > child.textContent!) {
65 task.insertBefore(tag, child);
69 task.appendChild(tag);
73 edit: function (createTimestamp: string, newDescription: string): Element | null {
74 const target = this.getTask(createTimestamp);
75 if (!target) return null;
76 if (target.hasAttribute("data-description")) {
77 // Oh no: An edit has arrived from a replica while a local edit is in progress.
78 const input = target.firstChild as HTMLInputElement;
80 input.value === target.getAttribute("data-description") &&
81 input.selectionStart === input.value.length &&
82 input.selectionEnd === input.value.length
84 // No local changes have actually been made yet. Change the contents of the edit box!
85 input.value = newDescription;
88 // Prefer not to interrupt the local user's edit.
89 // The remote edit is mostly lost; this mostly becomes last-write-wins.
90 target.setAttribute("data-description", newDescription);
93 target.getElementsByClassName("desc")[0].textContent = newDescription;
98 hasTag: function (task: Element, tag: string): Element | null {
99 for (const child of task.getElementsByClassName("tag")) {
100 if (child.textContent === tag) {
107 getPriority: function (task: Element): number {
108 if (task.hasAttribute("data-priority")) {
109 return parseFloat(task.getAttribute("data-priority")!);
111 return parseFloat(task.getAttribute("data-created")!);
114 getTask: function (createTimestamp: string) {
115 for (const task of document.getElementsByClassName("task")) {
116 if (task.getAttribute("data-created") === createTimestamp) {
122 removeTag: function (createTimestamp: string, tagName: string) {
123 const task = this.getTask(createTimestamp);
124 if (!task) return null;
125 const tag = this.hasTag(task, tagName);
127 task.removeChild(tag);
128 if (task instanceof HTMLElement) task.focus();
131 setPriority: function (createTimestamp: string, priority: number): Element | null {
132 const target = this.getTask(createTimestamp);
133 if (!target) return null;
134 target.setAttribute("data-priority", `${priority}`);
135 for (const task of document.getElementsByClassName("task")) {
136 if (task !== target && this.getPriority(task) > priority) {
137 task.parentElement!.insertBefore(target, task);
141 document.getElementById("tasks")!.appendChild(target);
145 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
146 const task = this.getTask(createTimestamp);
148 task.setAttribute("data-state", state);
149 var date = task.getElementsByClassName("statedate")[0];
150 if (state === "todo") {
151 task.removeChild(date);
155 date = document.createElement("span");
156 date.classList.add("statedate");
157 task.insertBefore(date, task.firstChild);
159 const d = new Date(parseInt(stateTimestamp));
160 date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
164 function Log(prefix: string = "vp-") {
165 var next_log_index = 0;
167 apply: function (entry: string) {
168 const [timestamp, command, data] = splitN(entry, " ", 2);
169 if (command == "Create") {
170 return Model.addTask(timestamp, data);
172 if (command == "Edit") {
173 const [createTimestamp, description] = splitN(data, " ", 1);
174 return Model.edit(createTimestamp, description);
176 if (command == "Priority") {
177 const [createTimestamp, newPriority] = splitN(data, " ", 1);
178 return Model.setPriority(createTimestamp, parseFloat(newPriority));
180 if (command == "State") {
181 const [createTimestamp, state] = splitN(data, " ", 1);
182 return Model.setState(timestamp, createTimestamp, state);
184 if (command == "Tag") {
185 const [createTimestamp, tag] = splitN(data, " ", 1);
186 return Model.addTag(createTimestamp, tag);
188 if (command == "Untag") {
189 const [createTimestamp, tag] = splitN(data, " ", 1);
190 return Model.removeTag(createTimestamp, tag);
194 record: function (entry: string) {
195 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
198 recordAndApply: function (entry: string) {
200 return this.apply(entry);
203 replay: function () {
205 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
206 if (entry === null) {
218 const undoLog: string[][] = [];
219 const redoLog: string[][] = [];
220 function perform(forward: string, reverse: string) {
221 undoLog.push([reverse, forward]);
222 return log.recordAndApply(`${clock.now()} ${forward}`);
225 addTask: function (description: string): Element {
226 const now = clock.now();
227 undoLog.push([`State ${now} deleted`, `State ${now} todo`]);
228 return <Element>log.recordAndApply(`${now} Create ${description}`);
230 addTag: function (createTimestamp: string, tag: string) {
231 return perform(`Tag ${createTimestamp} ${tag}`, `Untag ${createTimestamp} ${tag}`);
233 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
234 return perform(`Edit ${createTimestamp} ${newDescription}`, `Edit ${createTimestamp} ${oldDescription}`);
236 removeTag: function (createTimestamp: string, tag: string) {
237 return perform(`Untag ${createTimestamp} ${tag}`, `Tag ${createTimestamp} ${tag}`);
239 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
240 return perform(`Priority ${createTimestamp} ${newPriority}`, `Priority ${createTimestamp} ${oldPriority}`);
242 setState: function (createTimestamp: string, newState: string, oldState: string) {
243 return perform(`State ${createTimestamp} ${newState}`, `State ${createTimestamp} ${oldState}`);
246 const entry = undoLog.pop();
249 return log.recordAndApply(`${clock.now()} ${entry[0]}`);
253 const entry = redoLog.pop();
256 return log.recordAndApply(`${clock.now()} ${entry[1]}`);
268 function BrowserUI() {
269 var currentViewState = "todo";
270 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
271 var lastTagNameEntered = "";
273 addTask: function (event: KeyboardEvent) {
274 const input = <HTMLInputElement>document.getElementById("taskName");
275 if (input.value.match(/^ *$/)) return;
276 const task = ui.addTask(input.value);
277 if (currentViewState === "todo" || currentViewState === "all") {
278 task instanceof HTMLElement && task.focus();
279 } else if (this.returnFocusAfterInput()) {
281 this.firstVisibleTask()?.focus();
284 if (event.getModifierState("Control")) {
285 this.makeTopPriority(task);
289 beginEdit: function (event: Event) {
290 const task = document.activeElement;
292 const input = document.createElement("input");
293 const desc = task.getElementsByClassName("desc")[0];
294 const oldDescription = desc.textContent!;
295 task.setAttribute("data-description", oldDescription);
296 input.value = oldDescription;
297 input.addEventListener("blur", this.completeEdit, { once: true });
298 desc.textContent = "";
299 task.insertBefore(input, task.firstChild);
301 event.preventDefault();
304 beginTagEdit: function (event: Event) {
305 const task = document.activeElement;
307 const input = document.createElement("input");
308 input.classList.add("tag");
309 input.addEventListener("blur", this.completeTagEdit, { once: true });
310 input.value = lastTagNameEntered;
311 task.appendChild(input);
314 event.preventDefault();
317 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
318 const input = event.target as HTMLInputElement;
319 const task = input.parentElement!;
320 const desc = task.getElementsByClassName("desc")[0];
321 const oldDescription = task.getAttribute("data-description")!;
322 const newDescription = input.value;
323 input.removeEventListener("blur", this.completeEdit);
324 task.removeChild(input);
325 task.removeAttribute("data-description");
327 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
328 desc.textContent = oldDescription;
330 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
334 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
335 const input = event.target as HTMLInputElement;
336 const task = input.parentElement!;
337 const newTagName = input.value;
338 input.removeEventListener("blur", this.completeTagEdit);
339 task.removeChild(input);
341 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !Model.hasTag(task, newTagName)) {
342 ui.addTag(task.getAttribute("data-created")!, newTagName);
343 lastTagNameEntered = newTagName;
347 firstVisibleTask: function () {
348 for (const task of document.getElementsByClassName("task")) {
349 const state = task.getAttribute("data-state");
350 if (task instanceof HTMLElement && (state === currentViewState || (currentViewState === "all" && state !== "deleted"))) {
356 focusTaskNameInput: function (event: Event) {
357 if (document.activeElement instanceof HTMLElement) {
358 taskFocusedBeforeJumpingToInput = document.activeElement;
360 document.getElementById("taskName")!.focus();
361 event.preventDefault();
364 visibleTaskAtOffset(task: Element, offset: number): Element {
365 var cursor: Element | null = task;
366 var valid_cursor = cursor;
367 const increment = offset / Math.abs(offset);
369 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
370 if (!cursor || !(cursor instanceof HTMLElement)) break;
371 const state = cursor.getAttribute("data-state")!;
372 if (state === currentViewState || (currentViewState === "all" && state !== "deleted")) {
374 valid_cursor = cursor;
376 if (Math.abs(offset) < 0.5) break;
381 makeTopPriority: function (task: Element | null = null) {
382 if (!task) task = document.activeElement;
384 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
387 moveCursor: function (offset: number): boolean {
388 const active = document.activeElement;
389 if (!active) return false;
390 const dest = this.visibleTaskAtOffset(active, offset);
391 if (dest !== active && dest instanceof HTMLElement) {
398 moveTask: function (offset: number) {
399 const active = document.activeElement;
401 const dest = this.visibleTaskAtOffset(active, offset);
402 if (dest === active) return; // Already extremal
403 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
404 if (onePastDest == dest) onePastDest = null; // Will become extremal
406 this.setPriority(active, dest, onePastDest);
408 this.setPriority(active, onePastDest, dest);
412 removeTag: function () {
413 var target = document.activeElement;
415 if (target.classList.contains("task")) {
416 const tags = target.getElementsByClassName("tag");
417 target = tags[tags.length - 1];
419 if (!target || !target.classList.contains("tag")) return;
420 ui.removeTag(target.parentElement!.getAttribute("data-created")!, target.textContent!);
423 returnFocusAfterInput: function (): boolean {
424 if (taskFocusedBeforeJumpingToInput) {
425 taskFocusedBeforeJumpingToInput.focus();
431 // Change task's priority to be between other tasks a and b.
432 setPriority: function (task: Element, a: Element | null, b: Element | null) {
433 const aPriority = a === null ? 0 : Model.getPriority(a);
434 const bPriority = b === null ? clock.now() : Model.getPriority(b);
435 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
436 const span = bPriority - aPriority;
437 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
438 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
439 const newPriorityRounded = Math.round(newPriority);
440 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
441 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
442 task instanceof HTMLElement && task.focus();
445 setState: function (newState: string) {
446 const task = document.activeElement;
448 const oldState = task.getAttribute("data-state")!;
449 if (newState === oldState) return;
450 const createTimestamp = task.getAttribute("data-created")!;
451 if (currentViewState !== "all" || newState == "deleted") {
452 this.moveCursor(1) || this.moveCursor(-1);
454 return ui.setState(createTimestamp, newState, oldState);
457 setView: function (state: string, color: string) {
458 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
459 if (state === "all") {
460 sheet.insertRule(`.task[data-state=deleted] { display: none }`);
462 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
464 sheet.insertRule(`:root { --view-state-indicator-color: ${color}; }`);
467 currentViewState = state;
468 if (document.activeElement?.getAttribute("data-state") !== state) {
469 this.firstVisibleTask()?.focus();
474 const ret = ui.undo();
475 if (ret && ret instanceof HTMLElement) ret.focus();
478 const ret = ui.redo();
479 if (ret && ret instanceof HTMLElement) ret.focus();
483 const browserUI = BrowserUI();
491 var inputState = InputState.Root;
492 var inputCount: number | null = null;
494 function handleKey(event: any) {
495 if (["Alt", "Control", "Meta", "Shift"].includes(event.key)) return;
496 if (event.target.tagName === "INPUT") {
497 if (event.target.id === "taskName") {
498 if (event.key == "Enter") return browserUI.addTask(event);
499 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
500 } else if (event.target.classList.contains("tag")) {
501 if (event.key == "Enter") return browserUI.completeTagEdit(event);
502 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
504 if (event.key == "Enter") return browserUI.completeEdit(event);
505 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
508 if (inputState === InputState.Root) {
509 if ("0" <= event.key && event.key <= "9") {
510 return (inputCount = (inputCount ?? 0) * 10 + parseInt(event.key));
513 if (event.key == "j") return browserUI.moveCursor(inputCount ?? 1);
514 if (event.key == "k") return browserUI.moveCursor(-(inputCount ?? 1));
515 if (event.key == "J") return browserUI.moveTask(inputCount ?? 1);
516 if (event.key == "K") return browserUI.moveTask(-(inputCount ?? 1));
517 if (event.key == "T") return browserUI.makeTopPriority();
518 if (event.key == "n") return browserUI.focusTaskNameInput(event);
519 if (event.key == "c") return browserUI.setState("cancelled");
520 if (event.key == "d") return browserUI.setState("done");
521 if (event.key == "q") return browserUI.setState("todo");
522 if (event.key == "s") return (inputState = InputState.S);
523 if (event.key == "w") return browserUI.setState("waiting");
524 if (event.key == "X") return browserUI.setState("deleted");
525 if (event.key == "x") return browserUI.removeTag();
526 if (event.key == "u") return browserUI.undo();
527 if (event.key == "r") return browserUI.redo();
528 if (event.key == "e") return browserUI.beginEdit(event);
529 if (event.key == "t") return browserUI.beginTagEdit(event);
530 if (event.key == "v") return (inputState = InputState.V);
534 } else if (inputState === InputState.S) {
535 inputState = InputState.Root;
536 if (event.key == "m") return browserUI.setState("someday-maybe");
537 } else if (inputState === InputState.V) {
538 inputState = InputState.Root;
539 if (event.key == "a") return browserUI.setView("all", "Gold");
540 if (event.key == "c") return browserUI.setView("cancelled", "Red");
541 if (event.key == "d") return browserUI.setView("done", "LawnGreen");
542 if (event.key == "q") return browserUI.setView("todo", "White");
543 if (event.key == "s") return (inputState = InputState.VS);
544 if (event.key == "v") return browserUI.setView("todo", "White");
545 if (event.key == "w") return browserUI.setView("waiting", "MediumOrchid");
546 if (event.key == "x") return browserUI.setView("deleted", "Black");
547 } else if (inputState === InputState.VS) {
548 inputState = InputState.Root;
549 if (event.key == "m") return browserUI.setView("someday-maybe", "DeepSkyBlue");
554 function browserInit() {
556 browserUI.firstVisibleTask()?.focus();
557 document.body.addEventListener("keydown", handleKey, { capture: false });