]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
c17a2f00139a51ad44af27269f6ade1e1f80519c
[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 // Returns a promise for a hue based on a hash of the string
33 function hashHue(str: string) {
34 // Using crypto for this is overkill
35 return crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)).then((buf) => (new Uint16Array(buf)[0] * 360) / 2 ** 16);
36 }
37
38 const Model = {
39 addTask: function (timestamp: string, description: string): Element {
40 const task = document.createElement("div");
41 const desc = document.createElement("span");
42 desc.textContent = description;
43 desc.classList.add("desc");
44 task.appendChild(desc);
45 task.classList.add("task");
46 task.setAttribute("tabindex", "0");
47 task.setAttribute("data-created", timestamp);
48 task.setAttribute("data-state", "todo");
49 document.getElementById("tasks")!.appendChild(task);
50 return task;
51 },
52
53 addTag: function (createTimestamp: string, tagName: string): Element | null {
54 const task = this.getTask(createTimestamp);
55 if (!task) return null;
56 const existingTag = this.hasTag(task, tagName);
57 if (existingTag) return existingTag;
58 const tag = document.createElement("span");
59 tag.appendChild(document.createTextNode(tagName));
60 tag.classList.add("tag");
61 tag.setAttribute("tabindex", "0");
62 hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`));
63 for (const child of task.getElementsByClassName("tag")) {
64 if (tagName > child.textContent!) {
65 task.insertBefore(tag, child);
66 return tag;
67 }
68 }
69 task.appendChild(tag);
70 return tag;
71 },
72
73 edit: function (createTimestamp: string, newDescription: string): Element | null {
74 const target = this.getTask(createTimestamp);
75 if (!target) return null;
76 if (target.hasAttribute("data-description")) {
77 // Oh no: An edit has arrived from a replica while a local edit is in progress.
78 const input = target.firstChild as HTMLInputElement;
79 if (
80 input.value === target.getAttribute("data-description") &&
81 input.selectionStart === input.value.length &&
82 input.selectionEnd === input.value.length
83 ) {
84 // No local changes have actually been made yet. Change the contents of the edit box!
85 input.value = newDescription;
86 } else {
87 // No great options.
88 // Prefer not to interrupt the local user's edit.
89 // The remote edit is mostly lost; this mostly becomes last-write-wins.
90 target.setAttribute("data-description", newDescription);
91 }
92 } else {
93 target.getElementsByClassName("desc")[0].textContent = newDescription;
94 }
95 return target;
96 },
97
98 hasTag: function (task: Element, tag: string): Element | null {
99 for (const child of task.getElementsByClassName("tag")) {
100 if (child.textContent === tag) {
101 return child;
102 }
103 }
104 return null;
105 },
106
107 getPriority: function (task: Element): number {
108 if (task.hasAttribute("data-priority")) {
109 return parseFloat(task.getAttribute("data-priority")!);
110 }
111 return parseFloat(task.getAttribute("data-created")!);
112 },
113
114 getTask: function (createTimestamp: string) {
115 for (const task of document.getElementsByClassName("task")) {
116 if (task.getAttribute("data-created") === createTimestamp) {
117 return task;
118 }
119 }
120 },
121
122 removeTag: function (createTimestamp: string, tagName: string) {
123 const task = this.getTask(createTimestamp);
124 if (!task) return null;
125 const tag = this.hasTag(task, tagName);
126 if (!tag) return;
127 task.removeChild(tag);
128 },
129
130 setPriority: function (createTimestamp: string, priority: number): Element | null {
131 const target = this.getTask(createTimestamp);
132 if (!target) return null;
133 target.setAttribute("data-priority", `${priority}`);
134 for (const task of document.getElementsByClassName("task")) {
135 if (task !== target && this.getPriority(task) > priority) {
136 task.parentElement!.insertBefore(target, task);
137 return target;
138 }
139 }
140 document.getElementById("tasks")!.appendChild(target);
141 return target;
142 },
143
144 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
145 const task = this.getTask(createTimestamp);
146 if (task) {
147 task.setAttribute("data-state", state);
148 }
149 },
150 };
151
152 function Log(prefix: string = "vp-") {
153 var next_log_index = 0;
154 return {
155 apply: function (entry: string) {
156 const [timestamp, command, data] = splitN(entry, " ", 2);
157 if (command == "Create") {
158 return Model.addTask(timestamp, data);
159 }
160 if (command == "Edit") {
161 const [createTimestamp, description] = splitN(data, " ", 1);
162 return Model.edit(createTimestamp, description);
163 }
164 if (command == "Priority") {
165 const [createTimestamp, newPriority] = splitN(data, " ", 1);
166 return Model.setPriority(createTimestamp, parseFloat(newPriority));
167 }
168 if (command == "State") {
169 const [createTimestamp, state] = splitN(data, " ", 1);
170 return Model.setState(timestamp, createTimestamp, state);
171 }
172 if (command == "Tag") {
173 const [createTimestamp, tag] = splitN(data, " ", 1);
174 return Model.addTag(createTimestamp, tag);
175 }
176 if (command == "Untag") {
177 const [createTimestamp, tag] = splitN(data, " ", 1);
178 return Model.removeTag(createTimestamp, tag);
179 }
180 },
181
182 record: function (entry: string) {
183 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
184 },
185
186 recordAndApply: function (entry: string) {
187 this.record(entry);
188 return this.apply(entry);
189 },
190
191 replay: function () {
192 while (true) {
193 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
194 if (entry === null) {
195 break;
196 }
197 this.apply(entry);
198 next_log_index++;
199 }
200 },
201 };
202 }
203 const log = Log();
204
205 function UI() {
206 const undoLog: string[] = [];
207 return {
208 addTask: function (description: string): Element {
209 const now = clock.now();
210 undoLog.push(`State ${now} deleted`);
211 return <Element>log.recordAndApply(`${now} Create ${description}`);
212 },
213 addTag: function (createTimestamp: string, tag: string) {
214 undoLog.push(`Untag ${createTimestamp} ${tag}`);
215 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
216 },
217 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
218 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
219 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
220 },
221 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
222 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
223 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
224 },
225 setState: function (createTimestamp: string, newState: string, oldState: string) {
226 undoLog.push(`State ${createTimestamp} ${oldState}`);
227 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
228 },
229 undo: function () {
230 if (undoLog.length > 0) {
231 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
232 }
233 },
234 };
235 }
236 const ui = UI();
237
238 enum CommitOrAbort {
239 Commit,
240 Abort,
241 }
242
243 function BrowserUI() {
244 var currentViewState = "todo";
245 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
246 var lastTagNameEntered = "";
247 return {
248 addTask: function (event: KeyboardEvent) {
249 const input = <HTMLInputElement>document.getElementById("taskName");
250 if (input.value.match(/^ *$/)) return;
251 const task = ui.addTask(input.value);
252 if (currentViewState === "todo") {
253 task instanceof HTMLElement && task.focus();
254 } else if (this.returnFocusAfterInput()) {
255 } else {
256 this.firstVisibleTask()?.focus();
257 }
258 input.value = "";
259 if (event.getModifierState("Control")) {
260 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
261 }
262 },
263
264 beginEdit: function (event: Event) {
265 const task = document.activeElement;
266 if (!task) return;
267 const input = document.createElement("input");
268 const desc = task.getElementsByClassName("desc")[0];
269 const oldDescription = desc.textContent!;
270 task.setAttribute("data-description", oldDescription);
271 input.value = oldDescription;
272 input.addEventListener("blur", this.completeEdit, { once: true });
273 desc.textContent = "";
274 task.insertBefore(input, task.firstChild);
275 input.focus();
276 event.preventDefault();
277 },
278
279 beginTagEdit: function (event: Event) {
280 const task = document.activeElement;
281 if (!task) return;
282 const input = document.createElement("input");
283 input.classList.add("tag");
284 input.addEventListener("blur", this.completeTagEdit, { once: true });
285 input.value = lastTagNameEntered;
286 task.appendChild(input);
287 input.focus();
288 input.select();
289 event.preventDefault();
290 },
291
292 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
293 const input = event.target as HTMLInputElement;
294 const task = input.parentElement!;
295 const desc = task.getElementsByClassName("desc")[0];
296 const oldDescription = task.getAttribute("data-description")!;
297 const newDescription = input.value;
298 input.removeEventListener("blur", this.completeEdit);
299 task.removeChild(input);
300 task.removeAttribute("data-description");
301 task.focus();
302 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
303 desc.textContent = oldDescription;
304 } else {
305 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
306 }
307 },
308
309 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
310 const input = event.target as HTMLInputElement;
311 const task = input.parentElement!;
312 const newTagName = input.value;
313 input.removeEventListener("blur", this.completeTagEdit);
314 task.removeChild(input);
315 task.focus();
316 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !Model.hasTag(task, newTagName)) {
317 ui.addTag(task.getAttribute("data-created")!, newTagName);
318 lastTagNameEntered = newTagName;
319 }
320 },
321
322 firstVisibleTask: function () {
323 for (const task of document.getElementsByClassName("task")) {
324 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
325 return task;
326 }
327 }
328 },
329
330 focusTaskNameInput: function (event: Event) {
331 if (document.activeElement instanceof HTMLElement) {
332 taskFocusedBeforeJumpingToInput = document.activeElement;
333 }
334 document.getElementById("taskName")!.focus();
335 event.preventDefault();
336 },
337
338 visibleTaskAtOffset(task: Element, offset: number): Element {
339 var cursor: Element | null = task;
340 var valid_cursor = cursor;
341 const increment = offset / Math.abs(offset);
342 while (true) {
343 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
344 if (!cursor || !(cursor instanceof HTMLElement)) break;
345 if (cursor.getAttribute("data-state")! === currentViewState) {
346 offset -= increment;
347 valid_cursor = cursor;
348 }
349 if (Math.abs(offset) < 0.5) break;
350 }
351 return valid_cursor;
352 },
353
354 moveCursor: function (offset: number): boolean {
355 const active = document.activeElement;
356 if (!active) return false;
357 const dest = this.visibleTaskAtOffset(active, offset);
358 if (dest !== active && dest instanceof HTMLElement) {
359 dest.focus();
360 return true;
361 }
362 return false;
363 },
364
365 moveTask: function (offset: number) {
366 const active = document.activeElement;
367 if (!active) return;
368 const dest = this.visibleTaskAtOffset(active, offset);
369 if (dest === active) return; // Already extremal
370 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
371 if (onePastDest == dest) onePastDest = null; // Will become extremal
372 if (offset > 0) {
373 this.setPriority(active, dest, onePastDest);
374 } else {
375 this.setPriority(active, onePastDest, dest);
376 }
377 },
378
379 returnFocusAfterInput: function (): boolean {
380 if (taskFocusedBeforeJumpingToInput) {
381 taskFocusedBeforeJumpingToInput.focus();
382 return true;
383 }
384 return false;
385 },
386
387 // Change task's priority to be between other tasks a and b.
388 setPriority: function (task: Element, a: Element | null, b: Element | null) {
389 const aPriority = a === null ? 0 : Model.getPriority(a);
390 const bPriority = b === null ? clock.now() : Model.getPriority(b);
391 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
392 const span = bPriority - aPriority;
393 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
394 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
395 const newPriorityRounded = Math.round(newPriority);
396 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
397 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
398 task instanceof HTMLElement && task.focus();
399 },
400
401 setState: function (newState: string) {
402 const task = document.activeElement;
403 if (!task) return;
404 const oldState = task.getAttribute("data-state")!;
405 if (newState === oldState) return;
406 const createTimestamp = task.getAttribute("data-created")!;
407 this.moveCursor(1) || this.moveCursor(-1);
408 return ui.setState(createTimestamp, newState, oldState);
409 },
410
411 setView: function (state: string, color: string) {
412 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
413 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
414 sheet.insertRule(`:root { --view-state-indicator-color: ${color}; }`);
415 sheet.removeRule(2);
416 sheet.removeRule(2);
417 currentViewState = state;
418 if (document.activeElement?.getAttribute("data-state") !== state) {
419 this.firstVisibleTask()?.focus();
420 }
421 },
422
423 undo: function () {
424 const ret = ui.undo();
425 if (ret && ret instanceof HTMLElement) ret.focus();
426 },
427 };
428 }
429 const browserUI = BrowserUI();
430
431 enum InputState {
432 Command,
433 View,
434 }
435 var inputState = InputState.Command;
436
437 function handleKey(event: any) {
438 if (event.target.tagName === "INPUT") {
439 if (event.target.id === "taskName") {
440 if (event.key == "Enter") return browserUI.addTask(event);
441 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
442 } else if (event.target.classList.contains("tag")) {
443 if (event.key == "Enter") return browserUI.completeTagEdit(event);
444 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
445 } else {
446 if (event.key == "Enter") return browserUI.completeEdit(event);
447 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
448 }
449 } else {
450 if (inputState === InputState.Command) {
451 if (event.key == "j") return browserUI.moveCursor(1);
452 if (event.key == "k") return browserUI.moveCursor(-1);
453 if (event.key == "J") return browserUI.moveTask(1);
454 if (event.key == "K") return browserUI.moveTask(-1);
455 if (event.key == "n") return browserUI.focusTaskNameInput(event);
456 if (event.key == "c") return browserUI.setState("cancelled");
457 if (event.key == "d") return browserUI.setState("done");
458 if (event.key == "q") return browserUI.setState("todo");
459 if (event.key == "s") return browserUI.setState("someday-maybe");
460 if (event.key == "w") return browserUI.setState("waiting");
461 if (event.key == "X") return browserUI.setState("deleted");
462 if (event.key == "u") return browserUI.undo();
463 if (event.key == "e") return browserUI.beginEdit(event);
464 if (event.key == "t") return browserUI.beginTagEdit(event);
465 if (event.key == "v") return (inputState = InputState.View);
466 } else if (inputState === InputState.View) {
467 inputState = InputState.Command;
468 if (event.key == "c") return browserUI.setView("cancelled", "Red");
469 if (event.key == "d") return browserUI.setView("done", "LawnGreen");
470 if (event.key == "q") return browserUI.setView("todo", "White");
471 if (event.key == "s") return browserUI.setView("someday-maybe", "DeepSkyBlue");
472 if (event.key == "v") return browserUI.setView("todo", "White");
473 if (event.key == "w") return browserUI.setView("waiting", "MediumOrchid");
474 if (event.key == "x") return browserUI.setView("deleted", "Black");
475 }
476 }
477 }
478
479 function browserInit() {
480 log.replay();
481 browserUI.firstVisibleTask()?.focus();
482 document.body.addEventListener("keydown", handleKey, { capture: false });
483 }