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.setAttribute("class", "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 edit: function (createTimestamp: string, newDescription: string): Element | null {
45 const target = this.getTask(createTimestamp);
46 if (!target) return null;
47 if (target.hasAttribute("data-description")) {
48 // Oh no: An edit has arrived from a replica while a local edit is in progress.
49 const input = target.children[0] as HTMLInputElement;
51 input.value === target.getAttribute("data-description") &&
52 input.selectionStart === 0 &&
53 input.selectionEnd === input.value.length
55 // No local changes have actually been made yet. Change the contents of the edit box!
56 input.value = newDescription;
60 // Prefer not to interrupt the local user's edit.
61 // The remote edit is mostly lost; this mostly becomes last-write-wins.
62 target.setAttribute("data-description", newDescription);
65 target.textContent = newDescription;
70 getPriority: function (task: Element): number {
71 if (task.hasAttribute("data-priority")) {
72 return parseFloat(task.getAttribute("data-priority")!);
74 return parseFloat(task.getAttribute("data-created")!);
77 getTask: function (createTimestamp: string) {
78 for (const task of document.getElementsByClassName("task")) {
79 if (task.getAttribute("data-created") === createTimestamp) {
85 setPriority: function (createTimestamp: string, priority: number): Element | null {
86 const target = this.getTask(createTimestamp);
87 if (!target) return null;
88 target.setAttribute("data-priority", `${priority}`);
89 for (const task of document.getElementsByClassName("task")) {
90 if (task !== target && this.getPriority(task) > priority) {
91 task.parentElement!.insertBefore(target, task);
95 document.getElementById("tasks")!.appendChild(target);
99 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
100 const task = this.getTask(createTimestamp);
102 task.setAttribute("data-state", state);
107 function Log(prefix: string = "vp-") {
108 var next_log_index = 0;
110 apply: function (entry: string) {
111 const [timestamp, command, data] = splitN(entry, " ", 2);
112 if (command == "Create") {
113 return Model.addTask(timestamp, data);
115 if (command == "Edit") {
116 const [createTimestamp, description] = splitN(data, " ", 1);
117 return Model.edit(createTimestamp, description);
119 if (command == "State") {
120 const [createTimestamp, state] = splitN(data, " ", 1);
121 return Model.setState(timestamp, createTimestamp, state);
123 if (command == "Priority") {
124 const [createTimestamp, newPriority] = splitN(data, " ", 1);
125 return Model.setPriority(createTimestamp, parseFloat(newPriority));
129 record: function (entry: string) {
130 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
133 recordAndApply: function (entry: string) {
135 return this.apply(entry);
138 replay: function () {
140 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
141 if (entry === null) {
152 const undoLog: string[] = [];
155 addTask: function (description: string): Element {
156 const now = clock.now();
157 undoLog.push(`State ${now} deleted`);
158 return <Element>log.recordAndApply(`${now} Create ${description}`);
160 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
161 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
162 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
164 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
165 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
166 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
168 setState: function (createTimestamp: string, newState: string, oldState: string) {
169 undoLog.push(`State ${createTimestamp} ${oldState}`);
170 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
173 if (undoLog.length > 0) {
174 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
179 function BrowserUI() {
180 var currentViewState = "todo";
182 addTask: function (event: KeyboardEvent) {
183 const input = <HTMLInputElement>document.getElementById("taskName");
185 const task = UI.addTask(input.value);
186 if (task && task instanceof HTMLElement) task.focus();
188 if (event.getModifierState("Control")) {
189 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
194 beginEdit: function (event: Event) {
195 const task = document.activeElement;
197 const input = document.createElement("input");
198 const oldDescription = task.textContent!;
199 task.setAttribute("data-description", oldDescription);
200 input.value = oldDescription;
201 input.addEventListener("blur", this.completeEdit, { once: true });
202 task.textContent = "";
203 task.appendChild(input);
206 event.preventDefault();
209 completeEdit: function (event: Event) {
210 const input = event.target as HTMLInputElement;
211 const task = input.parentElement!;
212 const oldDescription = task.getAttribute("data-description")!;
213 const newDescription = input.value;
214 input.removeEventListener("blur", this.completeEdit);
215 task.removeChild(task.children[0]);
216 task.removeAttribute("data-description");
218 if (newDescription === oldDescription) {
219 task.textContent = oldDescription;
221 UI.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
225 firstVisibleTask: function () {
226 for (const task of document.getElementsByClassName("task")) {
227 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
233 focusTaskNameInput: function (event: Event) {
234 document.getElementById("taskName")!.focus();
235 event.preventDefault();
238 visibleTaskAtOffset(task: Element, offset: number): Element {
239 var cursor: Element | null = task;
240 var valid_cursor = cursor;
241 const increment = offset / Math.abs(offset);
243 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
244 if (!cursor || !(cursor instanceof HTMLElement)) break;
245 if (cursor.getAttribute("data-state")! === currentViewState) {
247 valid_cursor = cursor;
249 if (Math.abs(offset) < 0.5) break;
254 moveCursor: function (offset: number): boolean {
255 const active = document.activeElement;
256 if (!active) return false;
257 const dest = this.visibleTaskAtOffset(active, offset);
258 if (dest !== active && dest instanceof HTMLElement) {
265 moveTask: function (offset: number) {
266 const active = document.activeElement;
268 const dest = this.visibleTaskAtOffset(active, offset);
269 if (dest === active) return; // Already extremal
270 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
271 if (onePastDest == dest) onePastDest = null; // Will become extremal
273 this.setPriority(active, dest, onePastDest);
275 this.setPriority(active, onePastDest, dest);
279 // Change task's priority to be between other tasks a and b.
280 setPriority: function (task: Element, a: Element | null, b: Element | null) {
281 const aPriority = a === null ? 0 : Model.getPriority(a);
282 const bPriority = b === null ? clock.now() : Model.getPriority(b);
283 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
284 const span = bPriority - aPriority;
285 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
286 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
287 const newPriorityRounded = Math.round(newPriority);
288 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
289 UI.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
290 task instanceof HTMLElement && task.focus();
293 setState: function (newState: string) {
294 const task = document.activeElement;
296 const oldState = task.getAttribute("data-state")!;
297 if (newState === oldState) return;
298 const createTimestamp = task.getAttribute("data-created")!;
299 this.moveCursor(1) || this.moveCursor(-1);
300 return UI.setState(createTimestamp, newState, oldState);
303 setView: function (state: string) {
304 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
305 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
307 currentViewState = state;
308 if (document.activeElement?.getAttribute("data-state") !== state) {
309 this.firstVisibleTask()?.focus();
314 const ret = UI.undo();
315 if (ret && ret instanceof HTMLElement) ret.focus();
319 const browserUI = BrowserUI();
325 var inputState = InputState.Command;
327 function handleKey(event: any) {
328 if (event.target.tagName === "INPUT") {
329 if (event.target.id === "taskName") {
330 if (event.key == "Enter") return browserUI.addTask(event);
332 if (event.key == "Enter") return browserUI.completeEdit(event);
335 if (inputState === InputState.Command) {
336 if (event.key == "j") return browserUI.moveCursor(1);
337 if (event.key == "k") return browserUI.moveCursor(-1);
338 if (event.key == "J") return browserUI.moveTask(1);
339 if (event.key == "K") return browserUI.moveTask(-1);
340 if (event.key == "n") return browserUI.focusTaskNameInput(event);
341 if (event.key == "c") return browserUI.setState("cancelled");
342 if (event.key == "d") return browserUI.setState("done");
343 if (event.key == "s") return browserUI.setState("someday-maybe");
344 if (event.key == "t") return browserUI.setState("todo");
345 if (event.key == "w") return browserUI.setState("waiting");
346 if (event.key == "X") return browserUI.setState("deleted");
347 if (event.key == "u") return browserUI.undo();
348 if (event.key == "e") return browserUI.beginEdit(event);
349 if (event.key == "v") return (inputState = InputState.View);
350 } else if (inputState === InputState.View) {
351 inputState = InputState.Command;
352 if (event.key == "c") return browserUI.setView("cancelled");
353 if (event.key == "d") return browserUI.setView("done");
354 if (event.key == "s") return browserUI.setView("someday-maybe");
355 if (event.key == "t") return browserUI.setView("todo");
356 if (event.key == "w") return browserUI.setView("waiting");
357 if (event.key == "x") return browserUI.setView("deleted");
362 function browserInit() {
363 document.body.addEventListener("keydown", handleKey, { capture: false });
365 browserUI.firstVisibleTask()?.focus();