]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
Use a monotonic clock
[vopamoi] / vopamoi.ts
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;
6
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[] {
9 if (limit < 1) {
10 return [str];
11 }
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));
14 }
15
16 // A clock that never goes backwards; monotonic.
17 function Clock() {
18 var previousNow = Date.now();
19 return {
20 now: function (): number {
21 const now = Date.now();
22 if (now > previousNow) {
23 previousNow = now;
24 return now;
25 }
26 return ++previousNow;
27 },
28 };
29 }
30 const clock = Clock();
31
32 const Model = {
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 document.getElementById("tasks")!.appendChild(task);
40 return task;
41 },
42
43 edit: function (createTimestamp: string, newDescription: string): Element | null {
44 const target = this.getTask(createTimestamp);
45 if (!target) return null;
46 if (target.hasAttribute("data-description")) {
47 // Oh no: An edit has arrived from a replica while a local edit is in progress.
48 const input = target.children[0] as HTMLInputElement;
49 if (
50 input.value === target.getAttribute("data-description") &&
51 input.selectionStart === 0 &&
52 input.selectionEnd === input.value.length
53 ) {
54 // No local changes have actually been made yet. Change the contents of the edit box!
55 input.value = newDescription;
56 input.select();
57 } else {
58 // No great options.
59 // Prefer not to interrupt the local user's edit.
60 // The remote edit is mostly lost; this mostly becomes last-write-wins.
61 target.setAttribute("data-description", newDescription);
62 }
63 } else {
64 target.textContent = newDescription;
65 }
66 return target;
67 },
68
69 getPriority: function (task: Element): number {
70 if (task.hasAttribute("data-priority")) {
71 return parseFloat(task.getAttribute("data-priority")!);
72 }
73 return parseFloat(task.getAttribute("data-created")!);
74 },
75
76 getState: function (task: Element): string {
77 return task.getAttribute("data-state") ?? "todo";
78 },
79
80 getTask: function (createTimestamp: string) {
81 for (const task of document.getElementsByClassName("task")) {
82 if (task.getAttribute("data-created") === createTimestamp) {
83 return task;
84 }
85 }
86 },
87
88 setPriority: function (createTimestamp: string, priority: number): Element | null {
89 const target = this.getTask(createTimestamp);
90 if (!target) return null;
91 target.setAttribute("data-priority", `${priority}`);
92 for (const task of document.getElementsByClassName("task")) {
93 if (task !== target && this.getPriority(task) > priority) {
94 task.parentElement!.insertBefore(target, task);
95 return target;
96 }
97 }
98 document.getElementById("tasks")!.appendChild(target);
99 return target;
100 },
101
102 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
103 const task = this.getTask(createTimestamp);
104 if (task) {
105 task.setAttribute("data-state", state);
106 if (task instanceof HTMLElement) {
107 task.style.display = state == "todo" ? "block" : "none"; // Until view filtering
108 }
109 }
110 },
111 };
112
113 function Log(prefix: string = "vp-") {
114 var next_log_index = 0;
115 return {
116 apply: function (entry: string) {
117 const [timestamp, command, data] = splitN(entry, " ", 2);
118 if (command == "Create") {
119 return Model.addTask(timestamp, data);
120 }
121 if (command == "Edit") {
122 const [createTimestamp, description] = splitN(data, " ", 1);
123 return Model.edit(createTimestamp, description);
124 }
125 if (command == "State") {
126 const [createTimestamp, state] = splitN(data, " ", 1);
127 return Model.setState(timestamp, createTimestamp, state);
128 }
129 if (command == "Priority") {
130 const [createTimestamp, newPriority] = splitN(data, " ", 1);
131 return Model.setPriority(createTimestamp, parseFloat(newPriority));
132 }
133 },
134
135 record: function (entry: string) {
136 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
137 },
138
139 recordAndApply: function (entry: string) {
140 this.record(entry);
141 return this.apply(entry);
142 },
143
144 replay: function () {
145 while (true) {
146 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
147 if (entry === null) {
148 break;
149 }
150 this.apply(entry);
151 next_log_index++;
152 }
153 },
154 };
155 }
156 const log = Log();
157
158 const undoLog: string[] = [];
159
160 const UI = {
161 addTask: function (description: string): Element {
162 const now = clock.now();
163 undoLog.push(`State ${now} deleted`);
164 return <Element>log.recordAndApply(`${now} Create ${description}`);
165 },
166 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
167 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
168 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
169 },
170 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
171 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
172 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
173 },
174 setState: function (createTimestamp: string, newState: string, oldState: string) {
175 undoLog.push(`State ${createTimestamp} ${oldState}`);
176 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
177 },
178 undo: function () {
179 if (undoLog.length > 0) {
180 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
181 }
182 },
183 };
184
185 const BrowserUI = {
186 addTask: function (event: KeyboardEvent) {
187 const input = <HTMLInputElement>document.getElementById("taskName");
188 if (input.value) {
189 const task = UI.addTask(input.value);
190 if (task && task instanceof HTMLElement) task.focus();
191 input.value = "";
192 if (event.getModifierState("Control")) {
193 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
194 }
195 }
196 },
197
198 beginEdit: function (event: Event) {
199 const task = document.activeElement;
200 if (!task) return;
201 const input = document.createElement("input");
202 const oldDescription = task.textContent!;
203 task.setAttribute("data-description", oldDescription);
204 input.value = oldDescription;
205 input.addEventListener("blur", BrowserUI.completeEdit, { once: true });
206 task.textContent = "";
207 task.appendChild(input);
208 input.focus();
209 input.select();
210 event.preventDefault();
211 },
212
213 completeEdit: function (event: Event) {
214 const input = event.target as HTMLInputElement;
215 const task = input.parentElement!;
216 const oldDescription = task.getAttribute("data-description")!;
217 const newDescription = input.value;
218 input.removeEventListener("blur", BrowserUI.completeEdit);
219 task.removeChild(task.children[0]);
220 task.removeAttribute("data-description");
221 task.focus();
222 if (newDescription === oldDescription) {
223 task.textContent = oldDescription;
224 } else {
225 UI.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
226 }
227 },
228
229 firstVisibleTask: function () {
230 for (const task of document.getElementsByClassName("task")) {
231 if (task instanceof HTMLElement && task.style.display !== "none") {
232 return task;
233 }
234 }
235 },
236
237 focusTaskNameInput: function (event: Event) {
238 document.getElementById("taskName")!.focus();
239 event.preventDefault();
240 },
241
242 visibleTaskAtOffset(task: Element, offset: number): Element {
243 var cursor: Element | null = task;
244 var valid_cursor = cursor;
245 const increment = offset / Math.abs(offset);
246 while (true) {
247 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
248 if (!cursor || !(cursor instanceof HTMLElement)) break;
249 if (cursor.style.display !== "none") {
250 offset -= increment;
251 valid_cursor = cursor;
252 }
253 if (Math.abs(offset) < 0.5) break;
254 }
255 return valid_cursor;
256 },
257
258 moveCursor: function (offset: number): boolean {
259 const active = document.activeElement;
260 if (!active) return false;
261 const dest = this.visibleTaskAtOffset(active, offset);
262 if (dest !== active && dest instanceof HTMLElement) {
263 dest.focus();
264 return true;
265 }
266 return false;
267 },
268
269 moveTask: function (offset: number) {
270 const active = document.activeElement;
271 if (!active) return;
272 const dest = this.visibleTaskAtOffset(active, offset);
273 if (dest === active) return; // Already extremal
274 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
275 if (onePastDest == dest) onePastDest = null; // Will become extremal
276 if (offset > 0) {
277 this.setPriority(active, dest, onePastDest);
278 } else {
279 this.setPriority(active, onePastDest, dest);
280 }
281 },
282
283 // Change task's priority to be between other tasks a and b.
284 setPriority: function (task: Element, a: Element | null, b: Element | null) {
285 const aPriority = a === null ? 0 : Model.getPriority(a);
286 const bPriority = b === null ? clock.now() : Model.getPriority(b);
287 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
288 const span = bPriority - aPriority;
289 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
290 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
291 const newPriorityRounded = Math.round(newPriority);
292 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
293 UI.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
294 task instanceof HTMLElement && task.focus();
295 },
296
297 setState: function (newState: string) {
298 const task = document.activeElement;
299 if (!task) return;
300 const oldState = Model.getState(task);
301 if (newState === oldState) return;
302 const createTimestamp = task.getAttribute("data-created")!;
303 this.moveCursor(1) || this.moveCursor(-1);
304 return UI.setState(createTimestamp, newState, oldState);
305 },
306
307 undo: function () {
308 const ret = UI.undo();
309 if (ret && ret instanceof HTMLElement) ret.focus();
310 },
311 };
312
313 function handleKey(event: any) {
314 if (event.target.tagName === "INPUT") {
315 if (event.target.id === "taskName") {
316 if (event.key == "Enter") return BrowserUI.addTask(event);
317 } else {
318 if (event.key == "Enter") return BrowserUI.completeEdit(event);
319 }
320 } else {
321 if (event.key == "j") return BrowserUI.moveCursor(1);
322 if (event.key == "k") return BrowserUI.moveCursor(-1);
323 if (event.key == "J") return BrowserUI.moveTask(1);
324 if (event.key == "K") return BrowserUI.moveTask(-1);
325 if (event.key == "n") return BrowserUI.focusTaskNameInput(event);
326 if (event.key == "s") return BrowserUI.setState("someday-maybe");
327 if (event.key == "w") return BrowserUI.setState("waiting");
328 if (event.key == "d") return BrowserUI.setState("done");
329 if (event.key == "c") return BrowserUI.setState("cancelled");
330 if (event.key == "t") return BrowserUI.setState("todo");
331 if (event.key == "X") return BrowserUI.setState("deleted");
332 if (event.key == "u") return BrowserUI.undo();
333 if (event.key == "e") return BrowserUI.beginEdit(event);
334 }
335 }
336
337 function browserInit() {
338 document.body.addEventListener("keydown", handleKey, { capture: false });
339 log.replay();
340 BrowserUI.firstVisibleTask()?.focus();
341 }