// Typescript doesn't know about MAX_SAFE_INTEGER?? This was supposed to be // fixed in typescript 2.0.1 in 2016, but is not working for me in typescript // 4.2.4 in 2022. :( https://github.com/microsoft/TypeScript/issues/9937 //const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; const MAX_SAFE_INTEGER = 9007199254740991; // A sane split that splits N *times*, leaving the last chunk unsplit. function splitN(str: string, delimiter: string, limit: number = MAX_SAFE_INTEGER): string[] { if (limit < 1) { return [str]; } const at = str.indexOf(delimiter); return at === -1 ? [str] : [str.substring(0, at)].concat(splitN(str.substring(at + delimiter.length), delimiter, limit - 1)); } // A clock that never goes backwards; monotonic. function Clock() { var previousNow = Date.now(); return { now: function (): number { const now = Date.now(); if (now > previousNow) { previousNow = now; return now; } return ++previousNow; }, }; } const clock = Clock(); const Model = { addTask: function (timestamp: string, description: string): Element { const task = document.createElement("div"); task.appendChild(document.createTextNode(description)); task.classList.add("task"); task.setAttribute("tabindex", "0"); task.setAttribute("data-created", timestamp); task.setAttribute("data-state", "todo"); document.getElementById("tasks")!.appendChild(task); return task; }, edit: function (createTimestamp: string, newDescription: string): Element | null { const target = this.getTask(createTimestamp); if (!target) return null; if (target.hasAttribute("data-description")) { // Oh no: An edit has arrived from a replica while a local edit is in progress. const input = target.children[0] as HTMLInputElement; if ( input.value === target.getAttribute("data-description") && input.selectionStart === input.value.length && input.selectionEnd === input.value.length ) { // No local changes have actually been made yet. Change the contents of the edit box! input.value = newDescription; } else { // No great options. // Prefer not to interrupt the local user's edit. // The remote edit is mostly lost; this mostly becomes last-write-wins. target.setAttribute("data-description", newDescription); } } else { target.textContent = newDescription; } return target; }, getPriority: function (task: Element): number { if (task.hasAttribute("data-priority")) { return parseFloat(task.getAttribute("data-priority")!); } return parseFloat(task.getAttribute("data-created")!); }, getTask: function (createTimestamp: string) { for (const task of document.getElementsByClassName("task")) { if (task.getAttribute("data-created") === createTimestamp) { return task; } } }, setPriority: function (createTimestamp: string, priority: number): Element | null { const target = this.getTask(createTimestamp); if (!target) return null; target.setAttribute("data-priority", `${priority}`); for (const task of document.getElementsByClassName("task")) { if (task !== target && this.getPriority(task) > priority) { task.parentElement!.insertBefore(target, task); return target; } } document.getElementById("tasks")!.appendChild(target); return target; }, setState: function (stateTimestamp: string, createTimestamp: string, state: string) { const task = this.getTask(createTimestamp); if (task) { task.setAttribute("data-state", state); } }, }; function Log(prefix: string = "vp-") { var next_log_index = 0; return { apply: function (entry: string) { const [timestamp, command, data] = splitN(entry, " ", 2); if (command == "Create") { return Model.addTask(timestamp, data); } if (command == "Edit") { const [createTimestamp, description] = splitN(data, " ", 1); return Model.edit(createTimestamp, description); } if (command == "State") { const [createTimestamp, state] = splitN(data, " ", 1); return Model.setState(timestamp, createTimestamp, state); } if (command == "Priority") { const [createTimestamp, newPriority] = splitN(data, " ", 1); return Model.setPriority(createTimestamp, parseFloat(newPriority)); } }, record: function (entry: string) { window.localStorage.setItem(`${prefix}${next_log_index++}`, entry); }, recordAndApply: function (entry: string) { this.record(entry); return this.apply(entry); }, replay: function () { while (true) { const entry = window.localStorage.getItem(`${prefix}${next_log_index}`); if (entry === null) { break; } this.apply(entry); next_log_index++; } }, }; } const log = Log(); function UI() { const undoLog: string[] = []; return { addTask: function (description: string): Element { const now = clock.now(); undoLog.push(`State ${now} deleted`); return log.recordAndApply(`${now} Create ${description}`); }, edit: function (createTimestamp: string, newDescription: string, oldDescription: string) { undoLog.push(`Edit ${createTimestamp} ${oldDescription}`); return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`); }, setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) { undoLog.push(`Priority ${createTimestamp} ${oldPriority}`); return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`); }, setState: function (createTimestamp: string, newState: string, oldState: string) { undoLog.push(`State ${createTimestamp} ${oldState}`); return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`); }, undo: function () { if (undoLog.length > 0) { return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`); } }, }; } const ui = UI(); enum CommitOrAbort { Commit, Abort, } function BrowserUI() { var currentViewState = "todo"; var taskFocusedBeforeJumpingToInput: HTMLElement | null = null; return { addTask: function (event: KeyboardEvent) { const input = document.getElementById("taskName"); if (input.value) { const task = ui.addTask(input.value); if (currentViewState === "todo") { task instanceof HTMLElement && task.focus(); } else if (this.returnFocusAfterInput()) { } else { this.firstVisibleTask()?.focus(); } input.value = ""; if (event.getModifierState("Control")) { this.setPriority(task, null, document.getElementsByClassName("task")[0]); } } }, beginEdit: function (event: Event) { const task = document.activeElement; if (!task) return; const input = document.createElement("input"); const oldDescription = task.textContent!; task.setAttribute("data-description", oldDescription); input.value = oldDescription; input.addEventListener("blur", this.completeEdit, { once: true }); task.textContent = ""; task.appendChild(input); input.focus(); event.preventDefault(); }, completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) { const input = event.target as HTMLInputElement; const task = input.parentElement!; const oldDescription = task.getAttribute("data-description")!; const newDescription = input.value; input.removeEventListener("blur", this.completeEdit); task.removeChild(task.children[0]); task.removeAttribute("data-description"); task.focus(); if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) { task.textContent = oldDescription; } else { ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription); } }, firstVisibleTask: function () { for (const task of document.getElementsByClassName("task")) { if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) { return task; } } }, focusTaskNameInput: function (event: Event) { if (document.activeElement instanceof HTMLElement) { taskFocusedBeforeJumpingToInput = document.activeElement; } document.getElementById("taskName")!.focus(); event.preventDefault(); }, visibleTaskAtOffset(task: Element, offset: number): Element { var cursor: Element | null = task; var valid_cursor = cursor; const increment = offset / Math.abs(offset); while (true) { cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling; if (!cursor || !(cursor instanceof HTMLElement)) break; if (cursor.getAttribute("data-state")! === currentViewState) { offset -= increment; valid_cursor = cursor; } if (Math.abs(offset) < 0.5) break; } return valid_cursor; }, moveCursor: function (offset: number): boolean { const active = document.activeElement; if (!active) return false; const dest = this.visibleTaskAtOffset(active, offset); if (dest !== active && dest instanceof HTMLElement) { dest.focus(); return true; } return false; }, moveTask: function (offset: number) { const active = document.activeElement; if (!active) return; const dest = this.visibleTaskAtOffset(active, offset); if (dest === active) return; // Already extremal var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset)); if (onePastDest == dest) onePastDest = null; // Will become extremal if (offset > 0) { this.setPriority(active, dest, onePastDest); } else { this.setPriority(active, onePastDest, dest); } }, returnFocusAfterInput: function (): boolean { if (taskFocusedBeforeJumpingToInput) { taskFocusedBeforeJumpingToInput.focus(); return true; } return false; }, // Change task's priority to be between other tasks a and b. setPriority: function (task: Element, a: Element | null, b: Element | null) { const aPriority = a === null ? 0 : Model.getPriority(a); const bPriority = b === null ? clock.now() : Model.getPriority(b); console.assert(aPriority < bPriority, aPriority, "<", bPriority); const span = bPriority - aPriority; const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random(); console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority); const newPriorityRounded = Math.round(newPriority); const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority; ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task)); task instanceof HTMLElement && task.focus(); }, setState: function (newState: string) { const task = document.activeElement; if (!task) return; const oldState = task.getAttribute("data-state")!; if (newState === oldState) return; const createTimestamp = task.getAttribute("data-created")!; this.moveCursor(1) || this.moveCursor(-1); return ui.setState(createTimestamp, newState, oldState); }, setView: function (state: string) { const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!; sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`); sheet.removeRule(1); currentViewState = state; if (document.activeElement?.getAttribute("data-state") !== state) { this.firstVisibleTask()?.focus(); } }, undo: function () { const ret = ui.undo(); if (ret && ret instanceof HTMLElement) ret.focus(); }, }; } const browserUI = BrowserUI(); enum InputState { Command, View, } var inputState = InputState.Command; function handleKey(event: any) { if (event.target.tagName === "INPUT") { if (event.target.id === "taskName") { if (event.key == "Enter") return browserUI.addTask(event); if (event.key == "Escape") return browserUI.returnFocusAfterInput(); } else { if (event.key == "Enter") return browserUI.completeEdit(event); if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort); } } else { if (inputState === InputState.Command) { if (event.key == "j") return browserUI.moveCursor(1); if (event.key == "k") return browserUI.moveCursor(-1); if (event.key == "J") return browserUI.moveTask(1); if (event.key == "K") return browserUI.moveTask(-1); if (event.key == "n") return browserUI.focusTaskNameInput(event); if (event.key == "c") return browserUI.setState("cancelled"); if (event.key == "d") return browserUI.setState("done"); if (event.key == "q") return browserUI.setState("todo"); if (event.key == "s") return browserUI.setState("someday-maybe"); if (event.key == "w") return browserUI.setState("waiting"); if (event.key == "X") return browserUI.setState("deleted"); if (event.key == "u") return browserUI.undo(); if (event.key == "e") return browserUI.beginEdit(event); if (event.key == "v") return (inputState = InputState.View); } else if (inputState === InputState.View) { inputState = InputState.Command; if (event.key == "c") return browserUI.setView("cancelled"); if (event.key == "d") return browserUI.setView("done"); if (event.key == "q") return browserUI.setView("todo"); if (event.key == "s") return browserUI.setView("someday-maybe"); if (event.key == "w") return browserUI.setView("waiting"); if (event.key == "x") return browserUI.setView("deleted"); } } } function browserInit() { document.body.addEventListener("keydown", handleKey, { capture: false }); log.replay(); browserUI.firstVisibleTask()?.focus(); }