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));
17 addTask: function (timestamp: string, description: string): Element {
18 const task = document.createElement("div");
19 task.appendChild(document.createTextNode(description));
20 task.setAttribute("class", "task");
21 task.setAttribute("tabindex", "0");
22 task.setAttribute("data-created", timestamp);
23 document.getElementById("tasks")!.appendChild(task);
27 edit: function (createTimestamp: string, newDescription: string): Element | null {
28 const target = this.getTask(createTimestamp);
29 if (!target) return null;
30 if (target.hasAttribute("data-description")) {
31 // Oh no: An edit has arrived from a replica while a local edit is in progress.
32 const input = target.children[0] as HTMLInputElement;
34 input.value === target.getAttribute("data-description") &&
35 input.selectionStart === 0 &&
36 input.selectionEnd === input.value.length
38 // No local changes have actually been made yet. Change the contents of the edit box!
39 input.value = newDescription;
43 // Prefer not to interrupt the local user's edit.
44 // The remote edit is mostly lost; this mostly becomes last-write-wins.
45 target.setAttribute("data-description", newDescription);
48 target.textContent = newDescription;
53 getPriority: function (task: Element): number {
54 if (task.hasAttribute("data-priority")) {
55 return parseFloat(task.getAttribute("data-priority")!);
57 return parseFloat(task.getAttribute("data-created")!);
60 getState: function (task: Element): string {
61 return task.getAttribute("data-state") ?? "todo";
64 getTask: function (createTimestamp: string) {
65 for (const task of document.getElementsByClassName("task")) {
66 if (task.getAttribute("data-created") === createTimestamp) {
72 setPriority: function (createTimestamp: string, priority: number): Element | null {
73 const target = this.getTask(createTimestamp);
74 if (!target) return null;
75 target.setAttribute("data-priority", `${priority}`);
76 for (const task of document.getElementsByClassName("task")) {
77 if (task !== target && this.getPriority(task) > priority) {
78 task.parentElement!.insertBefore(target, task);
82 document.getElementById("tasks")!.appendChild(target);
86 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
87 const task = this.getTask(createTimestamp);
89 task.setAttribute("data-state", state);
90 if (task instanceof HTMLElement) {
91 task.style.display = state == "todo" ? "block" : "none"; // Until view filtering
97 function Log(prefix: string = "vp-") {
98 var next_log_index = 0;
100 apply: function (entry: string) {
101 const [timestamp, command, data] = splitN(entry, " ", 2);
102 if (command == "Create") {
103 return Model.addTask(timestamp, data);
105 if (command == "Edit") {
106 const [createTimestamp, description] = splitN(data, " ", 1);
107 return Model.edit(createTimestamp, description);
109 if (command == "State") {
110 const [createTimestamp, state] = splitN(data, " ", 1);
111 return Model.setState(timestamp, createTimestamp, state);
113 if (command == "Priority") {
114 const [createTimestamp, newPriority] = splitN(data, " ", 1);
115 return Model.setPriority(createTimestamp, parseFloat(newPriority));
119 record: function (entry: string) {
120 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
123 recordAndApply: function (entry: string) {
125 return this.apply(entry);
128 replay: function () {
130 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
131 if (entry === null) {
142 const undoLog: string[] = [];
145 addTask: function (description: string): Element {
146 const now = Date.now();
147 undoLog.push(`State ${now} deleted`);
148 return <Element>log.recordAndApply(`${now} Create ${description}`);
150 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
151 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
152 return log.recordAndApply(`${Date.now()} Edit ${createTimestamp} ${newDescription}`);
154 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
155 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
156 return log.recordAndApply(`${Date.now()} Priority ${createTimestamp} ${newPriority}`);
158 setState: function (createTimestamp: string, newState: string, oldState: string) {
159 undoLog.push(`State ${createTimestamp} ${oldState}`);
160 return log.recordAndApply(`${Date.now()} State ${createTimestamp} ${newState}`);
163 if (undoLog.length > 0) {
164 return log.recordAndApply(`${Date.now()} ${undoLog.pop()}`);
170 addTask: function (event: KeyboardEvent) {
171 const input = <HTMLInputElement>document.getElementById("taskName");
173 const task = UI.addTask(input.value);
174 if (task && task instanceof HTMLElement) task.focus();
176 if (event.getModifierState("Control")) {
177 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
182 beginEdit: function (event: Event) {
183 const task = document.activeElement;
185 const input = document.createElement("input");
186 const oldDescription = task.textContent!;
187 task.setAttribute("data-description", oldDescription);
188 input.value = oldDescription;
189 input.addEventListener("blur", BrowserUI.completeEdit, { once: true });
190 task.textContent = "";
191 task.appendChild(input);
194 event.preventDefault();
197 completeEdit: function (event: Event) {
198 const input = event.target as HTMLInputElement;
199 const task = input.parentElement!;
200 const oldDescription = task.getAttribute("data-description")!;
201 const newDescription = input.value;
202 input.removeEventListener("blur", BrowserUI.completeEdit);
203 task.removeChild(task.children[0]);
204 task.removeAttribute("data-description");
206 if (newDescription === oldDescription) {
207 task.textContent = oldDescription;
209 UI.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
213 firstVisibleTask: function () {
214 for (const task of document.getElementsByClassName("task")) {
215 if (task instanceof HTMLElement && task.style.display !== "none") {
221 focusTaskNameInput: function (event: Event) {
222 document.getElementById("taskName")!.focus();
223 event.preventDefault();
226 visibleTaskAtOffset(task: Element, offset: number): Element {
227 var cursor: Element | null = task;
228 var valid_cursor = cursor;
229 const increment = offset / Math.abs(offset);
231 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
232 if (!cursor || !(cursor instanceof HTMLElement)) break;
233 if (cursor.style.display !== "none") {
235 valid_cursor = cursor;
237 if (Math.abs(offset) < 0.5) break;
242 moveCursor: function (offset: number): boolean {
243 const active = document.activeElement;
244 if (!active) return false;
245 const dest = this.visibleTaskAtOffset(active, offset);
246 if (dest !== active && dest instanceof HTMLElement) {
253 moveTask: function (offset: number) {
254 const active = document.activeElement;
256 const dest = this.visibleTaskAtOffset(active, offset);
257 if (dest === active) return; // Already extremal
258 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
259 if (onePastDest == dest) onePastDest = null; // Will become extremal
261 this.setPriority(active, dest, onePastDest);
263 this.setPriority(active, onePastDest, dest);
267 // Change task's priority to be between other tasks a and b.
268 setPriority: function (task: Element, a: Element | null, b: Element | null) {
269 const aPriority = a === null ? 0 : Model.getPriority(a);
270 const bPriority = b === null ? Date.now() : Model.getPriority(b);
271 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
272 const span = bPriority - aPriority;
273 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
274 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
275 const newPriorityRounded = Math.round(newPriority);
276 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
277 UI.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
278 task instanceof HTMLElement && task.focus();
281 setState: function (newState: string) {
282 const task = document.activeElement;
284 const oldState = Model.getState(task);
285 if (newState === oldState) return;
286 const createTimestamp = task.getAttribute("data-created")!;
287 this.moveCursor(1) || this.moveCursor(-1);
288 return UI.setState(createTimestamp, newState, oldState);
292 const ret = UI.undo();
293 if (ret && ret instanceof HTMLElement) ret.focus();
297 function handleKey(event: any) {
298 if (event.target.tagName === "INPUT") {
299 if (event.target.id === "taskName") {
300 if (event.key == "Enter") return BrowserUI.addTask(event);
302 if (event.key == "Enter") return BrowserUI.completeEdit(event);
305 if (event.key == "j") return BrowserUI.moveCursor(1);
306 if (event.key == "k") return BrowserUI.moveCursor(-1);
307 if (event.key == "J") return BrowserUI.moveTask(1);
308 if (event.key == "K") return BrowserUI.moveTask(-1);
309 if (event.key == "n") return BrowserUI.focusTaskNameInput(event);
310 if (event.key == "s") return BrowserUI.setState("someday-maybe");
311 if (event.key == "w") return BrowserUI.setState("waiting");
312 if (event.key == "d") return BrowserUI.setState("done");
313 if (event.key == "c") return BrowserUI.setState("cancelled");
314 if (event.key == "t") return BrowserUI.setState("todo");
315 if (event.key == "X") return BrowserUI.setState("deleted");
316 if (event.key == "u") return BrowserUI.undo();
317 if (event.key == "e") return BrowserUI.beginEdit(event);
321 function browserInit() {
322 document.body.addEventListener("keydown", handleKey, { capture: false });
324 BrowserUI.firstVisibleTask()?.focus();