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 setPriority: function (createTimestamp: string, priority: number): Element | null {
123 const target = this.getTask(createTimestamp);
124 if (!target) return null;
125 target.setAttribute("data-priority", `${priority}`);
126 for (const task of document.getElementsByClassName("task")) {
127 if (task !== target && this.getPriority(task) > priority) {
128 task.parentElement!.insertBefore(target, task);
132 document.getElementById("tasks")!.appendChild(target);
136 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
137 const task = this.getTask(createTimestamp);
139 task.setAttribute("data-state", state);
144 function Log(prefix: string = "vp-") {
145 var next_log_index = 0;
147 apply: function (entry: string) {
148 const [timestamp, command, data] = splitN(entry, " ", 2);
149 if (command == "Create") {
150 return Model.addTask(timestamp, data);
152 if (command == "Edit") {
153 const [createTimestamp, description] = splitN(data, " ", 1);
154 return Model.edit(createTimestamp, description);
156 if (command == "Priority") {
157 const [createTimestamp, newPriority] = splitN(data, " ", 1);
158 return Model.setPriority(createTimestamp, parseFloat(newPriority));
160 if (command == "State") {
161 const [createTimestamp, state] = splitN(data, " ", 1);
162 return Model.setState(timestamp, createTimestamp, state);
164 if (command == "Tag") {
165 const [createTimestamp, tag] = splitN(data, " ", 1);
166 return Model.addTag(createTimestamp, tag);
170 record: function (entry: string) {
171 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
174 recordAndApply: function (entry: string) {
176 return this.apply(entry);
179 replay: function () {
181 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
182 if (entry === null) {
194 const undoLog: string[] = [];
196 addTask: function (description: string): Element {
197 const now = clock.now();
198 undoLog.push(`State ${now} deleted`);
199 return <Element>log.recordAndApply(`${now} Create ${description}`);
201 addTag: function (createTimestamp: string, tag: string) {
203 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
205 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
206 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
207 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
209 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
210 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
211 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
213 setState: function (createTimestamp: string, newState: string, oldState: string) {
214 undoLog.push(`State ${createTimestamp} ${oldState}`);
215 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
218 if (undoLog.length > 0) {
219 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
231 function BrowserUI() {
232 var currentViewState = "todo";
233 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
234 var lastTagNameEntered = "";
236 addTask: function (event: KeyboardEvent) {
237 const input = <HTMLInputElement>document.getElementById("taskName");
239 const task = ui.addTask(input.value);
240 if (currentViewState === "todo") {
241 task instanceof HTMLElement && task.focus();
242 } else if (this.returnFocusAfterInput()) {
244 this.firstVisibleTask()?.focus();
247 if (event.getModifierState("Control")) {
248 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
253 beginEdit: function (event: Event) {
254 const task = document.activeElement;
256 const input = document.createElement("input");
257 const desc = task.getElementsByClassName("desc")[0];
258 const oldDescription = desc.textContent!;
259 task.setAttribute("data-description", oldDescription);
260 input.value = oldDescription;
261 input.addEventListener("blur", this.completeEdit, { once: true });
262 desc.textContent = "";
263 task.insertBefore(input, task.firstChild);
265 event.preventDefault();
268 beginTagEdit: function (event: Event) {
269 const task = document.activeElement;
271 const input = document.createElement("input");
272 input.classList.add("tag");
273 input.addEventListener("blur", this.completeTagEdit, { once: true });
274 input.value = lastTagNameEntered;
275 task.appendChild(input);
278 event.preventDefault();
281 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
282 const input = event.target as HTMLInputElement;
283 const task = input.parentElement!;
284 const desc = task.getElementsByClassName("desc")[0];
285 const oldDescription = task.getAttribute("data-description")!;
286 const newDescription = input.value;
287 input.removeEventListener("blur", this.completeEdit);
288 task.removeChild(input);
289 task.removeAttribute("data-description");
291 if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) {
292 desc.textContent = oldDescription;
294 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
298 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
299 const input = event.target as HTMLInputElement;
300 const task = input.parentElement!;
301 const newTagName = input.value;
302 input.removeEventListener("blur", this.completeTagEdit);
303 task.removeChild(input);
305 if (resolution === CommitOrAbort.Commit && newTagName && !Model.hasTag(task, newTagName)) {
306 ui.addTag(task.getAttribute("data-created")!, newTagName);
307 lastTagNameEntered = newTagName;
311 firstVisibleTask: function () {
312 for (const task of document.getElementsByClassName("task")) {
313 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
319 focusTaskNameInput: function (event: Event) {
320 if (document.activeElement instanceof HTMLElement) {
321 taskFocusedBeforeJumpingToInput = document.activeElement;
323 document.getElementById("taskName")!.focus();
324 event.preventDefault();
327 visibleTaskAtOffset(task: Element, offset: number): Element {
328 var cursor: Element | null = task;
329 var valid_cursor = cursor;
330 const increment = offset / Math.abs(offset);
332 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
333 if (!cursor || !(cursor instanceof HTMLElement)) break;
334 if (cursor.getAttribute("data-state")! === currentViewState) {
336 valid_cursor = cursor;
338 if (Math.abs(offset) < 0.5) break;
343 moveCursor: function (offset: number): boolean {
344 const active = document.activeElement;
345 if (!active) return false;
346 const dest = this.visibleTaskAtOffset(active, offset);
347 if (dest !== active && dest instanceof HTMLElement) {
354 moveTask: function (offset: number) {
355 const active = document.activeElement;
357 const dest = this.visibleTaskAtOffset(active, offset);
358 if (dest === active) return; // Already extremal
359 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
360 if (onePastDest == dest) onePastDest = null; // Will become extremal
362 this.setPriority(active, dest, onePastDest);
364 this.setPriority(active, onePastDest, dest);
368 returnFocusAfterInput: function (): boolean {
369 if (taskFocusedBeforeJumpingToInput) {
370 taskFocusedBeforeJumpingToInput.focus();
376 // Change task's priority to be between other tasks a and b.
377 setPriority: function (task: Element, a: Element | null, b: Element | null) {
378 const aPriority = a === null ? 0 : Model.getPriority(a);
379 const bPriority = b === null ? clock.now() : Model.getPriority(b);
380 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
381 const span = bPriority - aPriority;
382 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
383 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
384 const newPriorityRounded = Math.round(newPriority);
385 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
386 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
387 task instanceof HTMLElement && task.focus();
390 setState: function (newState: string) {
391 const task = document.activeElement;
393 const oldState = task.getAttribute("data-state")!;
394 if (newState === oldState) return;
395 const createTimestamp = task.getAttribute("data-created")!;
396 this.moveCursor(1) || this.moveCursor(-1);
397 return ui.setState(createTimestamp, newState, oldState);
400 setView: function (state: string) {
401 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
402 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
404 currentViewState = state;
405 if (document.activeElement?.getAttribute("data-state") !== state) {
406 this.firstVisibleTask()?.focus();
411 const ret = ui.undo();
412 if (ret && ret instanceof HTMLElement) ret.focus();
416 const browserUI = BrowserUI();
422 var inputState = InputState.Command;
424 function handleKey(event: any) {
425 if (event.target.tagName === "INPUT") {
426 if (event.target.id === "taskName") {
427 if (event.key == "Enter") return browserUI.addTask(event);
428 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
429 } else if (event.target.classList.contains("tag")) {
430 if (event.key == "Enter") return browserUI.completeTagEdit(event);
431 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
433 if (event.key == "Enter") return browserUI.completeEdit(event);
434 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
437 if (inputState === InputState.Command) {
438 if (event.key == "j") return browserUI.moveCursor(1);
439 if (event.key == "k") return browserUI.moveCursor(-1);
440 if (event.key == "J") return browserUI.moveTask(1);
441 if (event.key == "K") return browserUI.moveTask(-1);
442 if (event.key == "n") return browserUI.focusTaskNameInput(event);
443 if (event.key == "c") return browserUI.setState("cancelled");
444 if (event.key == "d") return browserUI.setState("done");
445 if (event.key == "q") return browserUI.setState("todo");
446 if (event.key == "s") return browserUI.setState("someday-maybe");
447 if (event.key == "w") return browserUI.setState("waiting");
448 if (event.key == "X") return browserUI.setState("deleted");
449 if (event.key == "u") return browserUI.undo();
450 if (event.key == "e") return browserUI.beginEdit(event);
451 if (event.key == "t") return browserUI.beginTagEdit(event);
452 if (event.key == "v") return (inputState = InputState.View);
453 } else if (inputState === InputState.View) {
454 inputState = InputState.Command;
455 if (event.key == "c") return browserUI.setView("cancelled");
456 if (event.key == "d") return browserUI.setView("done");
457 if (event.key == "q") return browserUI.setView("todo");
458 if (event.key == "s") return browserUI.setView("someday-maybe");
459 if (event.key == "w") return browserUI.setView("waiting");
460 if (event.key == "x") return browserUI.setView("deleted");
465 function browserInit() {
466 document.body.addEventListener("keydown", handleKey, { capture: false });
468 browserUI.firstVisibleTask()?.focus();