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 tag = document.createElement("span");
48 tag.appendChild(document.createTextNode(tagName));
49 tag.classList.add("tag");
50 tag.setAttribute("tabindex", "0");
51 task.appendChild(tag);
55 edit: function (createTimestamp: string, newDescription: string): Element | null {
56 const target = this.getTask(createTimestamp);
57 if (!target) return null;
58 if (target.hasAttribute("data-description")) {
59 // Oh no: An edit has arrived from a replica while a local edit is in progress.
60 const input = target.firstChild as HTMLInputElement;
62 input.value === target.getAttribute("data-description") &&
63 input.selectionStart === input.value.length &&
64 input.selectionEnd === input.value.length
66 // No local changes have actually been made yet. Change the contents of the edit box!
67 input.value = newDescription;
70 // Prefer not to interrupt the local user's edit.
71 // The remote edit is mostly lost; this mostly becomes last-write-wins.
72 target.setAttribute("data-description", newDescription);
75 target.textContent = newDescription;
80 hasTag: function (task: Element, tag: string) {
81 for (const child of task.children) {
82 if (child.classList.contains("tag") && child.textContent === tag) {
89 getPriority: function (task: Element): number {
90 if (task.hasAttribute("data-priority")) {
91 return parseFloat(task.getAttribute("data-priority")!);
93 return parseFloat(task.getAttribute("data-created")!);
96 getTask: function (createTimestamp: string) {
97 for (const task of document.getElementsByClassName("task")) {
98 if (task.getAttribute("data-created") === createTimestamp) {
104 setPriority: function (createTimestamp: string, priority: number): Element | null {
105 const target = this.getTask(createTimestamp);
106 if (!target) return null;
107 target.setAttribute("data-priority", `${priority}`);
108 for (const task of document.getElementsByClassName("task")) {
109 if (task !== target && this.getPriority(task) > priority) {
110 task.parentElement!.insertBefore(target, task);
114 document.getElementById("tasks")!.appendChild(target);
118 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
119 const task = this.getTask(createTimestamp);
121 task.setAttribute("data-state", state);
126 function Log(prefix: string = "vp-") {
127 var next_log_index = 0;
129 apply: function (entry: string) {
130 const [timestamp, command, data] = splitN(entry, " ", 2);
131 if (command == "Create") {
132 return Model.addTask(timestamp, data);
134 if (command == "Edit") {
135 const [createTimestamp, description] = splitN(data, " ", 1);
136 return Model.edit(createTimestamp, description);
138 if (command == "Priority") {
139 const [createTimestamp, newPriority] = splitN(data, " ", 1);
140 return Model.setPriority(createTimestamp, parseFloat(newPriority));
142 if (command == "State") {
143 const [createTimestamp, state] = splitN(data, " ", 1);
144 return Model.setState(timestamp, createTimestamp, state);
146 if (command == "Tag") {
147 const [createTimestamp, tag] = splitN(data, " ", 1);
148 return Model.addTag(createTimestamp, tag);
152 record: function (entry: string) {
153 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
156 recordAndApply: function (entry: string) {
158 return this.apply(entry);
161 replay: function () {
163 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
164 if (entry === null) {
176 const undoLog: string[] = [];
178 addTask: function (description: string): Element {
179 const now = clock.now();
180 undoLog.push(`State ${now} deleted`);
181 return <Element>log.recordAndApply(`${now} Create ${description}`);
183 addTag: function (createTimestamp: string, tag: string) {
185 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
187 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
188 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
189 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
191 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
192 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
193 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
195 setState: function (createTimestamp: string, newState: string, oldState: string) {
196 undoLog.push(`State ${createTimestamp} ${oldState}`);
197 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
200 if (undoLog.length > 0) {
201 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
213 function BrowserUI() {
214 var currentViewState = "todo";
215 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
217 addTask: function (event: KeyboardEvent) {
218 const input = <HTMLInputElement>document.getElementById("taskName");
220 const task = ui.addTask(input.value);
221 if (currentViewState === "todo") {
222 task instanceof HTMLElement && task.focus();
223 } else if (this.returnFocusAfterInput()) {
225 this.firstVisibleTask()?.focus();
228 if (event.getModifierState("Control")) {
229 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
234 beginEdit: function (event: Event) {
235 const task = document.activeElement;
237 const input = document.createElement("input");
238 const oldDescription = task.textContent!;
239 task.setAttribute("data-description", oldDescription);
240 input.value = oldDescription;
241 input.addEventListener("blur", this.completeEdit, { once: true });
242 task.textContent = "";
243 task.insertBefore(input, task.firstChild);
245 event.preventDefault();
248 beginTagEdit: function (event: Event) {
249 const task = document.activeElement;
251 const input = document.createElement("input");
252 input.classList.add("tag");
253 input.addEventListener("blur", this.completeTagEdit, { once: true });
254 task.appendChild(input);
256 event.preventDefault();
259 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
260 const input = event.target as HTMLInputElement;
261 const task = input.parentElement!;
262 const oldDescription = task.getAttribute("data-description")!;
263 const newDescription = input.value;
264 input.removeEventListener("blur", this.completeEdit);
265 task.removeChild(input);
266 task.removeAttribute("data-description");
268 if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) {
269 task.textContent = oldDescription;
271 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
275 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
276 const input = event.target as HTMLInputElement;
277 const task = input.parentElement!;
278 const newTagName = input.value;
279 input.removeEventListener("blur", this.completeTagEdit);
280 task.removeChild(input);
282 if (!Model.hasTag(task, newTagName)) {
283 ui.addTag(task.getAttribute("data-created")!, newTagName);
287 firstVisibleTask: function () {
288 for (const task of document.getElementsByClassName("task")) {
289 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
295 focusTaskNameInput: function (event: Event) {
296 if (document.activeElement instanceof HTMLElement) {
297 taskFocusedBeforeJumpingToInput = document.activeElement;
299 document.getElementById("taskName")!.focus();
300 event.preventDefault();
303 visibleTaskAtOffset(task: Element, offset: number): Element {
304 var cursor: Element | null = task;
305 var valid_cursor = cursor;
306 const increment = offset / Math.abs(offset);
308 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
309 if (!cursor || !(cursor instanceof HTMLElement)) break;
310 if (cursor.getAttribute("data-state")! === currentViewState) {
312 valid_cursor = cursor;
314 if (Math.abs(offset) < 0.5) break;
319 moveCursor: function (offset: number): boolean {
320 const active = document.activeElement;
321 if (!active) return false;
322 const dest = this.visibleTaskAtOffset(active, offset);
323 if (dest !== active && dest instanceof HTMLElement) {
330 moveTask: function (offset: number) {
331 const active = document.activeElement;
333 const dest = this.visibleTaskAtOffset(active, offset);
334 if (dest === active) return; // Already extremal
335 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
336 if (onePastDest == dest) onePastDest = null; // Will become extremal
338 this.setPriority(active, dest, onePastDest);
340 this.setPriority(active, onePastDest, dest);
344 returnFocusAfterInput: function (): boolean {
345 if (taskFocusedBeforeJumpingToInput) {
346 taskFocusedBeforeJumpingToInput.focus();
352 // Change task's priority to be between other tasks a and b.
353 setPriority: function (task: Element, a: Element | null, b: Element | null) {
354 const aPriority = a === null ? 0 : Model.getPriority(a);
355 const bPriority = b === null ? clock.now() : Model.getPriority(b);
356 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
357 const span = bPriority - aPriority;
358 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
359 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
360 const newPriorityRounded = Math.round(newPriority);
361 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
362 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
363 task instanceof HTMLElement && task.focus();
366 setState: function (newState: string) {
367 const task = document.activeElement;
369 const oldState = task.getAttribute("data-state")!;
370 if (newState === oldState) return;
371 const createTimestamp = task.getAttribute("data-created")!;
372 this.moveCursor(1) || this.moveCursor(-1);
373 return ui.setState(createTimestamp, newState, oldState);
376 setView: function (state: string) {
377 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
378 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
380 currentViewState = state;
381 if (document.activeElement?.getAttribute("data-state") !== state) {
382 this.firstVisibleTask()?.focus();
387 const ret = ui.undo();
388 if (ret && ret instanceof HTMLElement) ret.focus();
392 const browserUI = BrowserUI();
398 var inputState = InputState.Command;
400 function handleKey(event: any) {
401 if (event.target.tagName === "INPUT") {
402 if (event.target.id === "taskName") {
403 if (event.key == "Enter") return browserUI.addTask(event);
404 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
405 } else if (event.target.classList.contains("tag")) {
406 if (event.key == "Enter") return browserUI.completeTagEdit(event);
407 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
409 if (event.key == "Enter") return browserUI.completeEdit(event);
410 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
413 if (inputState === InputState.Command) {
414 if (event.key == "j") return browserUI.moveCursor(1);
415 if (event.key == "k") return browserUI.moveCursor(-1);
416 if (event.key == "J") return browserUI.moveTask(1);
417 if (event.key == "K") return browserUI.moveTask(-1);
418 if (event.key == "n") return browserUI.focusTaskNameInput(event);
419 if (event.key == "c") return browserUI.setState("cancelled");
420 if (event.key == "d") return browserUI.setState("done");
421 if (event.key == "q") return browserUI.setState("todo");
422 if (event.key == "s") return browserUI.setState("someday-maybe");
423 if (event.key == "w") return browserUI.setState("waiting");
424 if (event.key == "X") return browserUI.setState("deleted");
425 if (event.key == "u") return browserUI.undo();
426 if (event.key == "e") return browserUI.beginEdit(event);
427 if (event.key == "t") return browserUI.beginTagEdit(event);
428 if (event.key == "v") return (inputState = InputState.View);
429 } else if (inputState === InputState.View) {
430 inputState = InputState.Command;
431 if (event.key == "c") return browserUI.setView("cancelled");
432 if (event.key == "d") return browserUI.setView("done");
433 if (event.key == "q") return browserUI.setView("todo");
434 if (event.key == "s") return browserUI.setView("someday-maybe");
435 if (event.key == "w") return browserUI.setView("waiting");
436 if (event.key == "x") return browserUI.setView("deleted");
441 function browserInit() {
442 document.body.addEventListener("keydown", handleKey, { capture: false });
444 browserUI.firstVisibleTask()?.focus();