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();
33 addTask: function (timestamp: string, description: string): Element {
34 const task = document.createElement("div");
35 task.appendChild(document.createTextNode(description));
36 task.classList.add("task");
37 task.setAttribute("tabindex", "0");
38 task.setAttribute("data-created", timestamp);
39 task.setAttribute("data-state", "todo");
40 document.getElementById("tasks")!.appendChild(task);
44 addTag: function (createTimestamp: string, tagName: string): Element | null {
45 const task = this.getTask(createTimestamp);
46 if (!task) return null;
47 const existingTag = this.hasTag(task, tagName);
48 if (existingTag) return existingTag;
49 const tag = document.createElement("span");
50 tag.appendChild(document.createTextNode(tagName));
51 tag.classList.add("tag");
52 tag.setAttribute("tabindex", "0");
53 task.appendChild(tag);
57 edit: function (createTimestamp: string, newDescription: string): Element | null {
58 const target = this.getTask(createTimestamp);
59 if (!target) return null;
60 if (target.hasAttribute("data-description")) {
61 // Oh no: An edit has arrived from a replica while a local edit is in progress.
62 const input = target.firstChild as HTMLInputElement;
64 input.value === target.getAttribute("data-description") &&
65 input.selectionStart === input.value.length &&
66 input.selectionEnd === input.value.length
68 // No local changes have actually been made yet. Change the contents of the edit box!
69 input.value = newDescription;
72 // Prefer not to interrupt the local user's edit.
73 // The remote edit is mostly lost; this mostly becomes last-write-wins.
74 target.setAttribute("data-description", newDescription);
77 target.textContent = newDescription;
82 hasTag: function (task: Element, tag: string): Element | null {
83 for (const child of task.getElementsByClassName("tag")) {
84 if (child.textContent === tag) {
91 getPriority: function (task: Element): number {
92 if (task.hasAttribute("data-priority")) {
93 return parseFloat(task.getAttribute("data-priority")!);
95 return parseFloat(task.getAttribute("data-created")!);
98 getTask: function (createTimestamp: string) {
99 for (const task of document.getElementsByClassName("task")) {
100 if (task.getAttribute("data-created") === createTimestamp) {
106 setPriority: function (createTimestamp: string, priority: number): Element | null {
107 const target = this.getTask(createTimestamp);
108 if (!target) return null;
109 target.setAttribute("data-priority", `${priority}`);
110 for (const task of document.getElementsByClassName("task")) {
111 if (task !== target && this.getPriority(task) > priority) {
112 task.parentElement!.insertBefore(target, task);
116 document.getElementById("tasks")!.appendChild(target);
120 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
121 const task = this.getTask(createTimestamp);
123 task.setAttribute("data-state", state);
128 function Log(prefix: string = "vp-") {
129 var next_log_index = 0;
131 apply: function (entry: string) {
132 const [timestamp, command, data] = splitN(entry, " ", 2);
133 if (command == "Create") {
134 return Model.addTask(timestamp, data);
136 if (command == "Edit") {
137 const [createTimestamp, description] = splitN(data, " ", 1);
138 return Model.edit(createTimestamp, description);
140 if (command == "Priority") {
141 const [createTimestamp, newPriority] = splitN(data, " ", 1);
142 return Model.setPriority(createTimestamp, parseFloat(newPriority));
144 if (command == "State") {
145 const [createTimestamp, state] = splitN(data, " ", 1);
146 return Model.setState(timestamp, createTimestamp, state);
148 if (command == "Tag") {
149 const [createTimestamp, tag] = splitN(data, " ", 1);
150 return Model.addTag(createTimestamp, tag);
154 record: function (entry: string) {
155 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
158 recordAndApply: function (entry: string) {
160 return this.apply(entry);
163 replay: function () {
165 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
166 if (entry === null) {
178 const undoLog: string[] = [];
180 addTask: function (description: string): Element {
181 const now = clock.now();
182 undoLog.push(`State ${now} deleted`);
183 return <Element>log.recordAndApply(`${now} Create ${description}`);
185 addTag: function (createTimestamp: string, tag: string) {
187 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
189 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
190 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
191 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
193 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
194 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
195 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
197 setState: function (createTimestamp: string, newState: string, oldState: string) {
198 undoLog.push(`State ${createTimestamp} ${oldState}`);
199 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
202 if (undoLog.length > 0) {
203 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
215 function BrowserUI() {
216 var currentViewState = "todo";
217 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
218 var lastTagNameEntered = "";
220 addTask: function (event: KeyboardEvent) {
221 const input = <HTMLInputElement>document.getElementById("taskName");
223 const task = ui.addTask(input.value);
224 if (currentViewState === "todo") {
225 task instanceof HTMLElement && task.focus();
226 } else if (this.returnFocusAfterInput()) {
228 this.firstVisibleTask()?.focus();
231 if (event.getModifierState("Control")) {
232 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
237 beginEdit: function (event: Event) {
238 const task = document.activeElement;
240 const input = document.createElement("input");
241 const oldDescription = task.textContent!;
242 task.setAttribute("data-description", oldDescription);
243 input.value = oldDescription;
244 input.addEventListener("blur", this.completeEdit, { once: true });
245 task.textContent = "";
246 task.insertBefore(input, task.firstChild);
248 event.preventDefault();
251 beginTagEdit: function (event: Event) {
252 const task = document.activeElement;
254 const input = document.createElement("input");
255 input.classList.add("tag");
256 input.addEventListener("blur", this.completeTagEdit, { once: true });
257 input.value = lastTagNameEntered;
258 task.appendChild(input);
261 event.preventDefault();
264 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
265 const input = event.target as HTMLInputElement;
266 const task = input.parentElement!;
267 const oldDescription = task.getAttribute("data-description")!;
268 const newDescription = input.value;
269 input.removeEventListener("blur", this.completeEdit);
270 task.removeChild(input);
271 task.removeAttribute("data-description");
273 if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) {
274 task.textContent = oldDescription;
276 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
280 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
281 const input = event.target as HTMLInputElement;
282 const task = input.parentElement!;
283 const newTagName = input.value;
284 input.removeEventListener("blur", this.completeTagEdit);
285 task.removeChild(input);
287 if (resolution === CommitOrAbort.Commit && newTagName && !Model.hasTag(task, newTagName)) {
288 ui.addTag(task.getAttribute("data-created")!, newTagName);
289 lastTagNameEntered = newTagName;
293 firstVisibleTask: function () {
294 for (const task of document.getElementsByClassName("task")) {
295 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
301 focusTaskNameInput: function (event: Event) {
302 if (document.activeElement instanceof HTMLElement) {
303 taskFocusedBeforeJumpingToInput = document.activeElement;
305 document.getElementById("taskName")!.focus();
306 event.preventDefault();
309 visibleTaskAtOffset(task: Element, offset: number): Element {
310 var cursor: Element | null = task;
311 var valid_cursor = cursor;
312 const increment = offset / Math.abs(offset);
314 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
315 if (!cursor || !(cursor instanceof HTMLElement)) break;
316 if (cursor.getAttribute("data-state")! === currentViewState) {
318 valid_cursor = cursor;
320 if (Math.abs(offset) < 0.5) break;
325 moveCursor: function (offset: number): boolean {
326 const active = document.activeElement;
327 if (!active) return false;
328 const dest = this.visibleTaskAtOffset(active, offset);
329 if (dest !== active && dest instanceof HTMLElement) {
336 moveTask: function (offset: number) {
337 const active = document.activeElement;
339 const dest = this.visibleTaskAtOffset(active, offset);
340 if (dest === active) return; // Already extremal
341 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
342 if (onePastDest == dest) onePastDest = null; // Will become extremal
344 this.setPriority(active, dest, onePastDest);
346 this.setPriority(active, onePastDest, dest);
350 returnFocusAfterInput: function (): boolean {
351 if (taskFocusedBeforeJumpingToInput) {
352 taskFocusedBeforeJumpingToInput.focus();
358 // Change task's priority to be between other tasks a and b.
359 setPriority: function (task: Element, a: Element | null, b: Element | null) {
360 const aPriority = a === null ? 0 : Model.getPriority(a);
361 const bPriority = b === null ? clock.now() : Model.getPriority(b);
362 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
363 const span = bPriority - aPriority;
364 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
365 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
366 const newPriorityRounded = Math.round(newPriority);
367 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
368 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
369 task instanceof HTMLElement && task.focus();
372 setState: function (newState: string) {
373 const task = document.activeElement;
375 const oldState = task.getAttribute("data-state")!;
376 if (newState === oldState) return;
377 const createTimestamp = task.getAttribute("data-created")!;
378 this.moveCursor(1) || this.moveCursor(-1);
379 return ui.setState(createTimestamp, newState, oldState);
382 setView: function (state: string) {
383 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
384 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
386 currentViewState = state;
387 if (document.activeElement?.getAttribute("data-state") !== state) {
388 this.firstVisibleTask()?.focus();
393 const ret = ui.undo();
394 if (ret && ret instanceof HTMLElement) ret.focus();
398 const browserUI = BrowserUI();
404 var inputState = InputState.Command;
406 function handleKey(event: any) {
407 if (event.target.tagName === "INPUT") {
408 if (event.target.id === "taskName") {
409 if (event.key == "Enter") return browserUI.addTask(event);
410 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
411 } else if (event.target.classList.contains("tag")) {
412 if (event.key == "Enter") return browserUI.completeTagEdit(event);
413 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
415 if (event.key == "Enter") return browserUI.completeEdit(event);
416 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
419 if (inputState === InputState.Command) {
420 if (event.key == "j") return browserUI.moveCursor(1);
421 if (event.key == "k") return browserUI.moveCursor(-1);
422 if (event.key == "J") return browserUI.moveTask(1);
423 if (event.key == "K") return browserUI.moveTask(-1);
424 if (event.key == "n") return browserUI.focusTaskNameInput(event);
425 if (event.key == "c") return browserUI.setState("cancelled");
426 if (event.key == "d") return browserUI.setState("done");
427 if (event.key == "q") return browserUI.setState("todo");
428 if (event.key == "s") return browserUI.setState("someday-maybe");
429 if (event.key == "w") return browserUI.setState("waiting");
430 if (event.key == "X") return browserUI.setState("deleted");
431 if (event.key == "u") return browserUI.undo();
432 if (event.key == "e") return browserUI.beginEdit(event);
433 if (event.key == "t") return browserUI.beginTagEdit(event);
434 if (event.key == "v") return (inputState = InputState.View);
435 } else if (inputState === InputState.View) {
436 inputState = InputState.Command;
437 if (event.key == "c") return browserUI.setView("cancelled");
438 if (event.key == "d") return browserUI.setView("done");
439 if (event.key == "q") return browserUI.setView("todo");
440 if (event.key == "s") return browserUI.setView("someday-maybe");
441 if (event.key == "w") return browserUI.setView("waiting");
442 if (event.key == "x") return browserUI.setView("deleted");
447 function browserInit() {
448 document.body.addEventListener("keydown", handleKey, { capture: false });
450 browserUI.firstVisibleTask()?.focus();