+// 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();
+
+// Returns a promise for a hue based on a hash of the string
+function hashHue(str: string) {
+ // Using crypto for this is overkill
+ return crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)).then((buf) => (new Uint16Array(buf)[0] * 360) / 2 ** 16);
+}
+
+function Model() {
+ return {
+ addTask: function (timestamp: string, description: string): Element {
+ const task = document.createElement("div");
+ const desc = document.createElement("span");
+ desc.textContent = description;
+ desc.classList.add("desc");
+ task.appendChild(desc);
+ task.classList.add("task");
+ task.setAttribute("tabindex", "0");
+ task.setAttribute("id", timestamp);
+ task.setAttribute("data-state", "todo");
+ const tasks = document.getElementById("tasks")!;
+ tasks.insertBefore(task, tasks.firstElementChild);
+ return task;
+ },
+
+ addTag: function (createTimestamp: string, tagName: string): Element | null {
+ const task = this.getTask(createTimestamp);
+ if (!task) return null;
+ const existingTag = this.hasTag(task, tagName);
+ if (existingTag) return existingTag;
+ const tag = document.createElement("span");
+ tag.appendChild(document.createTextNode(tagName));
+ tag.classList.add("tag");
+ tag.setAttribute("tabindex", "0");
+ hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`));
+ for (const child of task.getElementsByClassName("tag")) {
+ if (tagName > child.textContent!) {
+ task.insertBefore(tag, child);
+ return tag;
+ }
+ }
+ task.insertBefore(tag, task.getElementsByClassName("desc")[0]!);
+ return tag;
+ },
+
+ 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.getElementsByTagName("input")[0]!;
+ 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.getElementsByClassName("desc")[0].textContent = newDescription;
+ }
+ return target;
+ },
+
+ editContent: function (createTimestamp: string, newContent: string): Element | null {
+ const target = this.getTask(createTimestamp);
+ if (!target) return null;
+ if (target.hasAttribute("data-content")) {
+ // Oh no: An edit has arrived from a replica while a local edit is in progress.
+ const input = target.getElementsByTagName("textarea")[0]!;
+ if (
+ input.value === target.getAttribute("data-content") &&
+ 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 = newContent;
+ } 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-content", newContent);
+ }
+ } else {
+ var content = target.getElementsByClassName("content")[0];
+ if (!content) {
+ content = document.createElement("div");
+ content.classList.add("content");
+ target.appendChild(content);
+ }
+ content.textContent = newContent;
+ }
+ return target;
+ },
+
+ hasTag: function (task: Element, tag: string): Element | null {
+ for (const child of task.getElementsByClassName("tag")) {
+ if (child.textContent === tag) {
+ return child;
+ }
+ }
+ return null;
+ },
+
+ getPriority: function (task: Element): number {
+ if (task.hasAttribute("data-priority")) {
+ return parseFloat(task.getAttribute("data-priority")!);
+ }
+ return parseFloat(task.getAttribute("id")!);
+ },
+
+ getTask: function (createTimestamp: string) {
+ return document.getElementById(createTimestamp);
+ },
+
+ insertInPriorityOrder: function (task: Element, dest: Element) {
+ const priority = this.getPriority(task);
+ for (const t of dest.children) {
+ if (t !== task && this.getPriority(t) < priority) {
+ dest.insertBefore(task, t);
+ return;
+ }
+ }
+ dest.appendChild(task);
+ },
+
+ removeTag: function (createTimestamp: string, tagName: string) {
+ const task = this.getTask(createTimestamp);
+ if (!task) return null;
+ const tag = this.hasTag(task, tagName);
+ if (!tag) return;
+ task.removeChild(tag);
+ if (task instanceof HTMLElement) task.focus();
+ },
+
+ setPriority: function (createTimestamp: string, priority: number): Element | null {
+ const target = this.getTask(createTimestamp);
+ if (!target) return null;
+ target.setAttribute("data-priority", `${priority}`);
+ this.insertInPriorityOrder(target, target.parentElement!);
+ return target;
+ },
+
+ setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
+ const task = this.getTask(createTimestamp);
+ if (!task) return;
+ task.setAttribute("data-state", state);
+ var date = task.getElementsByClassName("statedate")[0];
+ if (state === "todo") {
+ task.removeChild(date);
+ return;
+ }
+ if (!date) {
+ date = document.createElement("span");
+ date.classList.add("statedate");
+ task.insertBefore(date, task.firstChild);
+ }
+ const d = new Date(parseInt(stateTimestamp));
+ date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
+ },
+ };
+}
+const model = Model();
+
+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 == "EditContent") {
+ const [createTimestamp, content] = splitN(data, " ", 1);
+ return model.editContent(createTimestamp, content);
+ }
+ if (command == "Priority") {
+ const [createTimestamp, newPriority] = splitN(data, " ", 1);
+ return model.setPriority(createTimestamp, parseFloat(newPriority));
+ }
+ if (command == "State") {
+ const [createTimestamp, state] = splitN(data, " ", 1);
+ return model.setState(timestamp, createTimestamp, state);
+ }
+ if (command == "Tag") {
+ const [createTimestamp, tag] = splitN(data, " ", 1);
+ return model.addTag(createTimestamp, tag);
+ }
+ if (command == "Untag") {
+ const [createTimestamp, tag] = splitN(data, " ", 1);
+ return model.removeTag(createTimestamp, tag);
+ }
+ },
+
+ 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 () {
+ document.getElementById("tasks")!.style.display = "none";
+ while (true) {
+ const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
+ if (entry === null) {
+ break;
+ }
+ this.apply(entry);
+ next_log_index++;
+ }
+ document.getElementById("tasks")!.style.display = "";
+ },
+ };
+}
+const log = Log();
+
+function UI() {
+ const undoLog: string[][] = [];
+ const redoLog: string[][] = [];
+ function perform(forward: string, reverse: string) {
+ undoLog.push([reverse, forward]);
+ return log.recordAndApply(`${clock.now()} ${forward}`);
+ }
+ return {
+ addTask: function (description: string): Element {
+ const now = clock.now();
+ undoLog.push([`State ${now} deleted`, `State ${now} todo`]);
+ return <Element>log.recordAndApply(`${now} Create ${description}`);
+ },
+ addTag: function (createTimestamp: string, tag: string) {
+ return perform(`Tag ${createTimestamp} ${tag}`, `Untag ${createTimestamp} ${tag}`);
+ },
+ edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
+ return perform(`Edit ${createTimestamp} ${newDescription}`, `Edit ${createTimestamp} ${oldDescription}`);
+ },
+ editContent: function (createTimestamp: string, newContent: string, oldContent: string) {
+ return perform(`EditContent ${createTimestamp} ${newContent}`, `EditContent ${createTimestamp} ${oldContent}`);
+ },
+ removeTag: function (createTimestamp: string, tag: string) {
+ return perform(`Untag ${createTimestamp} ${tag}`, `Tag ${createTimestamp} ${tag}`);
+ },
+ setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
+ return perform(`Priority ${createTimestamp} ${newPriority}`, `Priority ${createTimestamp} ${oldPriority}`);
+ },
+ setState: function (createTimestamp: string, newState: string, oldState: string) {
+ return perform(`State ${createTimestamp} ${newState}`, `State ${createTimestamp} ${oldState}`);
+ },
+ undo: function () {
+ const entry = undoLog.pop();
+ if (entry) {
+ redoLog.push(entry);
+ return log.recordAndApply(`${clock.now()} ${entry[0]}`);
+ }
+ },
+ redo: function () {
+ const entry = redoLog.pop();
+ if (entry) {
+ undoLog.push(entry);
+ return log.recordAndApply(`${clock.now()} ${entry[1]}`);
+ }
+ },
+ };
+}
+const ui = UI();
+
+enum CommitOrAbort {
+ Commit,
+ Abort,
+}
+
+function BrowserUI() {
+ const viewColors: { [key: string]: string } = {
+ all: "Gold",
+ cancelled: "Red",
+ deleted: "Black",
+ done: "LawnGreen",
+ "someday-maybe": "DeepSkyBlue",
+ todo: "White",
+ waiting: "MediumOrchid",
+ };
+ var currentTagView: string | null = null;
+ var currentViewState = "todo";
+ var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
+ var lastTagNameEntered = "";
+ return {
+ addTask: function (event: KeyboardEvent) {
+ const input = <HTMLInputElement>document.getElementById("taskName");
+ if (input.value.match(/^ *$/)) return;
+ const task = ui.addTask(input.value);
+ if (currentViewState === "todo" || currentViewState === "all") {
+ task instanceof HTMLElement && task.focus();
+ } else if (this.returnFocusAfterInput()) {
+ } else {
+ this.firstVisibleTask()?.focus();
+ }
+ input.value = "";
+ if (event.getModifierState("Control")) {
+ this.makeBottomPriority(task);
+ }
+ },
+
+ beginEdit: function (event: Event) {
+ const task = this.currentTask();
+ if (!task) return;
+ const input = document.createElement("input");
+ const desc = task.getElementsByClassName("desc")[0];
+ const oldDescription = desc.textContent!;
+ task.setAttribute("data-description", oldDescription);
+ input.value = oldDescription;
+ input.addEventListener("blur", this.completeEdit, { once: true });
+ desc.textContent = "";
+ task.insertBefore(input, task.firstChild);
+ input.focus();
+ event.preventDefault();
+ },
+
+ beginEditContent: function (event: Event) {
+ const task = this.currentTask();
+ if (!task) return;
+ const input = document.createElement("textarea");
+ const content = task.getElementsByClassName("content")[0];
+ const oldContent = content?.textContent ?? "";
+ task.setAttribute("data-content", oldContent);
+ input.value = oldContent;
+ input.addEventListener("blur", this.completeContentEdit, { once: true });
+ if (content) content.textContent = "";
+ task.appendChild(input);
+ input.focus();
+ event.preventDefault();
+ },
+
+ beginTagEdit: function (event: Event) {
+ const task = this.currentTask();
+ if (!task) return;
+ const input = document.createElement("input");
+ input.classList.add("tag");
+ input.addEventListener("blur", this.completeTagEdit, { once: true });
+ input.value = lastTagNameEntered;
+ task.appendChild(input);
+ input.focus();
+ input.select();
+ event.preventDefault();
+ },
+
+ completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
+ const input = event.target as HTMLInputElement;
+ const task = input.parentElement!;
+ const desc = task.getElementsByClassName("desc")[0];
+ const oldDescription = task.getAttribute("data-description")!;
+ const newDescription = input.value;
+ input.removeEventListener("blur", this.completeEdit);
+ task.removeChild(input);
+ task.removeAttribute("data-description");
+ task.focus();
+ if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
+ desc.textContent = oldDescription;
+ } else {
+ ui.edit(task.getAttribute("id")!, newDescription, oldDescription);
+ }
+ },
+
+ completeContentEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
+ const input = event.target as HTMLInputElement;
+ const task = input.parentElement!;
+ const content = task.getElementsByClassName("content")[0];
+ const oldContent = task.getAttribute("data-content")!;
+ const newContent = input.value;
+ input.removeEventListener("blur", this.completeContentEdit);
+ task.removeChild(input);
+ task.removeAttribute("data-content");
+ task.focus();
+ if (resolution === CommitOrAbort.Abort || newContent === oldContent) {
+ if (content) content.textContent = oldContent;
+ } else {
+ ui.editContent(task.getAttribute("id")!, newContent, oldContent);
+ }
+ },
+
+ completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
+ const input = event.target as HTMLInputElement;
+ const task = input.parentElement!;
+ const newTagName = input.value;
+ input.removeEventListener("blur", this.completeTagEdit);
+ task.removeChild(input);
+ task.focus();
+ if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !model.hasTag(task, newTagName)) {
+ ui.addTag(task.getAttribute("id")!, newTagName);
+ lastTagNameEntered = newTagName;
+ }
+ },
+
+ currentTag: function (): Element | null {
+ var target = document.activeElement;
+ if (!target) return null;
+ if (target.classList.contains("task")) {
+ const tags = target.getElementsByClassName("tag");
+ target = tags[tags.length - 1];
+ }
+ if (!target || !target.classList.contains("tag")) return null;
+ return target;
+ },
+
+ currentTask: function (): HTMLElement | null {
+ var target = document.activeElement;
+ if (!target) return null;
+ if (target.classList.contains("tag")) target = target.parentElement!;
+ return target as HTMLElement;
+ },
+
+ firstVisibleTask: function (root: Element | null = null) {
+ if (root === null) root = document.body;
+ for (const task of root.getElementsByClassName("task")) {
+ const state = task.getAttribute("data-state");
+ if (
+ task instanceof HTMLElement &&
+ (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
+ !task.classList.contains("hide")
+ ) {
+ return task;
+ }
+ }
+ },
+
+ focusTaskNameInput: function (event: Event) {
+ taskFocusedBeforeJumpingToInput = this.currentTask();