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 getPriority: function (task: Element): number {
81 if (task.hasAttribute("data-priority")) {
82 return parseFloat(task.getAttribute("data-priority")!);
84 return parseFloat(task.getAttribute("data-created")!);
87 getTask: function (createTimestamp: string) {
88 for (const task of document.getElementsByClassName("task")) {
89 if (task.getAttribute("data-created") === createTimestamp) {
95 setPriority: function (createTimestamp: string, priority: number): Element | null {
96 const target = this.getTask(createTimestamp);
97 if (!target) return null;
98 target.setAttribute("data-priority", `${priority}`);
99 for (const task of document.getElementsByClassName("task")) {
100 if (task !== target && this.getPriority(task) > priority) {
101 task.parentElement!.insertBefore(target, task);
105 document.getElementById("tasks")!.appendChild(target);
109 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
110 const task = this.getTask(createTimestamp);
112 task.setAttribute("data-state", state);
117 function Log(prefix: string = "vp-") {
118 var next_log_index = 0;
120 apply: function (entry: string) {
121 const [timestamp, command, data] = splitN(entry, " ", 2);
122 if (command == "Create") {
123 return Model.addTask(timestamp, data);
125 if (command == "Edit") {
126 const [createTimestamp, description] = splitN(data, " ", 1);
127 return Model.edit(createTimestamp, description);
129 if (command == "Priority") {
130 const [createTimestamp, newPriority] = splitN(data, " ", 1);
131 return Model.setPriority(createTimestamp, parseFloat(newPriority));
133 if (command == "State") {
134 const [createTimestamp, state] = splitN(data, " ", 1);
135 return Model.setState(timestamp, createTimestamp, state);
137 if (command == "Tag") {
138 const [createTimestamp, tag] = splitN(data, " ", 1);
139 return Model.addTag(createTimestamp, tag);
143 record: function (entry: string) {
144 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
147 recordAndApply: function (entry: string) {
149 return this.apply(entry);
152 replay: function () {
154 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
155 if (entry === null) {
167 const undoLog: string[] = [];
169 addTask: function (description: string): Element {
170 const now = clock.now();
171 undoLog.push(`State ${now} deleted`);
172 return <Element>log.recordAndApply(`${now} Create ${description}`);
174 addTag: function (createTimestamp: string, tag: string) {
176 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
178 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
179 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
180 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
182 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
183 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
184 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
186 setState: function (createTimestamp: string, newState: string, oldState: string) {
187 undoLog.push(`State ${createTimestamp} ${oldState}`);
188 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
191 if (undoLog.length > 0) {
192 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
204 function BrowserUI() {
205 var currentViewState = "todo";
206 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
208 addTask: function (event: KeyboardEvent) {
209 const input = <HTMLInputElement>document.getElementById("taskName");
211 const task = ui.addTask(input.value);
212 if (currentViewState === "todo") {
213 task instanceof HTMLElement && task.focus();
214 } else if (this.returnFocusAfterInput()) {
216 this.firstVisibleTask()?.focus();
219 if (event.getModifierState("Control")) {
220 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
225 beginEdit: function (event: Event) {
226 const task = document.activeElement;
228 const input = document.createElement("input");
229 const oldDescription = task.textContent!;
230 task.setAttribute("data-description", oldDescription);
231 input.value = oldDescription;
232 input.addEventListener("blur", this.completeEdit, { once: true });
233 task.textContent = "";
234 task.insertBefore(input, task.firstChild);
236 event.preventDefault();
239 beginTagEdit: function (event: Event) {
240 const task = document.activeElement;
242 const input = document.createElement("input");
243 input.classList.add("tag");
244 input.addEventListener("blur", this.completeTagEdit, { once: true });
245 task.appendChild(input);
247 event.preventDefault();
250 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
251 const input = event.target as HTMLInputElement;
252 const task = input.parentElement!;
253 const oldDescription = task.getAttribute("data-description")!;
254 const newDescription = input.value;
255 input.removeEventListener("blur", this.completeEdit);
256 task.removeChild(input);
257 task.removeAttribute("data-description");
259 if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) {
260 task.textContent = oldDescription;
262 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
266 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
267 const input = event.target as HTMLInputElement;
268 const task = input.parentElement!;
269 const newTagName = input.value;
270 input.removeEventListener("blur", this.completeTagEdit);
271 task.removeChild(input);
273 ui.addTag(task.getAttribute("data-created")!, newTagName);
276 firstVisibleTask: function () {
277 for (const task of document.getElementsByClassName("task")) {
278 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
284 focusTaskNameInput: function (event: Event) {
285 if (document.activeElement instanceof HTMLElement) {
286 taskFocusedBeforeJumpingToInput = document.activeElement;
288 document.getElementById("taskName")!.focus();
289 event.preventDefault();
292 visibleTaskAtOffset(task: Element, offset: number): Element {
293 var cursor: Element | null = task;
294 var valid_cursor = cursor;
295 const increment = offset / Math.abs(offset);
297 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
298 if (!cursor || !(cursor instanceof HTMLElement)) break;
299 if (cursor.getAttribute("data-state")! === currentViewState) {
301 valid_cursor = cursor;
303 if (Math.abs(offset) < 0.5) break;
308 moveCursor: function (offset: number): boolean {
309 const active = document.activeElement;
310 if (!active) return false;
311 const dest = this.visibleTaskAtOffset(active, offset);
312 if (dest !== active && dest instanceof HTMLElement) {
319 moveTask: function (offset: number) {
320 const active = document.activeElement;
322 const dest = this.visibleTaskAtOffset(active, offset);
323 if (dest === active) return; // Already extremal
324 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
325 if (onePastDest == dest) onePastDest = null; // Will become extremal
327 this.setPriority(active, dest, onePastDest);
329 this.setPriority(active, onePastDest, dest);
333 returnFocusAfterInput: function (): boolean {
334 if (taskFocusedBeforeJumpingToInput) {
335 taskFocusedBeforeJumpingToInput.focus();
341 // Change task's priority to be between other tasks a and b.
342 setPriority: function (task: Element, a: Element | null, b: Element | null) {
343 const aPriority = a === null ? 0 : Model.getPriority(a);
344 const bPriority = b === null ? clock.now() : Model.getPriority(b);
345 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
346 const span = bPriority - aPriority;
347 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
348 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
349 const newPriorityRounded = Math.round(newPriority);
350 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
351 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
352 task instanceof HTMLElement && task.focus();
355 setState: function (newState: string) {
356 const task = document.activeElement;
358 const oldState = task.getAttribute("data-state")!;
359 if (newState === oldState) return;
360 const createTimestamp = task.getAttribute("data-created")!;
361 this.moveCursor(1) || this.moveCursor(-1);
362 return ui.setState(createTimestamp, newState, oldState);
365 setView: function (state: string) {
366 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
367 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
369 currentViewState = state;
370 if (document.activeElement?.getAttribute("data-state") !== state) {
371 this.firstVisibleTask()?.focus();
376 const ret = ui.undo();
377 if (ret && ret instanceof HTMLElement) ret.focus();
381 const browserUI = BrowserUI();
387 var inputState = InputState.Command;
389 function handleKey(event: any) {
390 if (event.target.tagName === "INPUT") {
391 if (event.target.id === "taskName") {
392 if (event.key == "Enter") return browserUI.addTask(event);
393 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
394 } else if (event.target.classList.contains("tag")) {
395 if (event.key == "Enter") return browserUI.completeTagEdit(event);
396 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
398 if (event.key == "Enter") return browserUI.completeEdit(event);
399 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
402 if (inputState === InputState.Command) {
403 if (event.key == "j") return browserUI.moveCursor(1);
404 if (event.key == "k") return browserUI.moveCursor(-1);
405 if (event.key == "J") return browserUI.moveTask(1);
406 if (event.key == "K") return browserUI.moveTask(-1);
407 if (event.key == "n") return browserUI.focusTaskNameInput(event);
408 if (event.key == "c") return browserUI.setState("cancelled");
409 if (event.key == "d") return browserUI.setState("done");
410 if (event.key == "q") return browserUI.setState("todo");
411 if (event.key == "s") return browserUI.setState("someday-maybe");
412 if (event.key == "w") return browserUI.setState("waiting");
413 if (event.key == "X") return browserUI.setState("deleted");
414 if (event.key == "u") return browserUI.undo();
415 if (event.key == "e") return browserUI.beginEdit(event);
416 if (event.key == "t") return browserUI.beginTagEdit(event);
417 if (event.key == "v") return (inputState = InputState.View);
418 } else if (inputState === InputState.View) {
419 inputState = InputState.Command;
420 if (event.key == "c") return browserUI.setView("cancelled");
421 if (event.key == "d") return browserUI.setView("done");
422 if (event.key == "q") return browserUI.setView("todo");
423 if (event.key == "s") return browserUI.setView("someday-maybe");
424 if (event.key == "w") return browserUI.setView("waiting");
425 if (event.key == "x") return browserUI.setView("deleted");
430 function browserInit() {
431 document.body.addEventListener("keydown", handleKey, { capture: false });
433 browserUI.firstVisibleTask()?.focus();