]> git.scottworley.com Git - vopamoi/blame_incremental - vopamoi.ts
Scroll to top when entering a new task
[vopamoi] / vopamoi.ts
... / ...
CommitLineData
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;
5const MAX_SAFE_INTEGER = 9007199254740991;
6
7// A sane split that splits N *times*, leaving the last chunk unsplit.
8function 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.
17function 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}
30const clock = Clock();
31
32// Returns a promise for a hue based on a hash of the string
33function 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
38const 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 if (task instanceof HTMLElement) task.focus();
129 },
130
131 setPriority: function (createTimestamp: string, priority: number): Element | null {
132 const target = this.getTask(createTimestamp);
133 if (!target) return null;
134 target.setAttribute("data-priority", `${priority}`);
135 for (const task of document.getElementsByClassName("task")) {
136 if (task !== target && this.getPriority(task) > priority) {
137 task.parentElement!.insertBefore(target, task);
138 return target;
139 }
140 }
141 document.getElementById("tasks")!.appendChild(target);
142 return target;
143 },
144
145 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
146 const task = this.getTask(createTimestamp);
147 if (!task) return;
148 task.setAttribute("data-state", state);
149 var date = task.getElementsByClassName("statedate")[0];
150 if (state === "todo") {
151 task.removeChild(date);
152 return;
153 }
154 if (!date) {
155 date = document.createElement("span");
156 date.classList.add("statedate");
157 task.insertBefore(date, task.firstChild);
158 }
159 const d = new Date(parseInt(stateTimestamp));
160 date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
161 },
162};
163
164function Log(prefix: string = "vp-") {
165 var next_log_index = 0;
166 return {
167 apply: function (entry: string) {
168 const [timestamp, command, data] = splitN(entry, " ", 2);
169 if (command == "Create") {
170 return Model.addTask(timestamp, data);
171 }
172 if (command == "Edit") {
173 const [createTimestamp, description] = splitN(data, " ", 1);
174 return Model.edit(createTimestamp, description);
175 }
176 if (command == "Priority") {
177 const [createTimestamp, newPriority] = splitN(data, " ", 1);
178 return Model.setPriority(createTimestamp, parseFloat(newPriority));
179 }
180 if (command == "State") {
181 const [createTimestamp, state] = splitN(data, " ", 1);
182 return Model.setState(timestamp, createTimestamp, state);
183 }
184 if (command == "Tag") {
185 const [createTimestamp, tag] = splitN(data, " ", 1);
186 return Model.addTag(createTimestamp, tag);
187 }
188 if (command == "Untag") {
189 const [createTimestamp, tag] = splitN(data, " ", 1);
190 return Model.removeTag(createTimestamp, tag);
191 }
192 },
193
194 record: function (entry: string) {
195 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
196 },
197
198 recordAndApply: function (entry: string) {
199 this.record(entry);
200 return this.apply(entry);
201 },
202
203 replay: function () {
204 while (true) {
205 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
206 if (entry === null) {
207 break;
208 }
209 this.apply(entry);
210 next_log_index++;
211 }
212 },
213 };
214}
215const log = Log();
216
217function UI() {
218 const undoLog: string[][] = [];
219 const redoLog: string[][] = [];
220 function perform(forward: string, reverse: string) {
221 undoLog.push([reverse, forward]);
222 return log.recordAndApply(`${clock.now()} ${forward}`);
223 }
224 return {
225 addTask: function (description: string): Element {
226 const now = clock.now();
227 undoLog.push([`State ${now} deleted`, `State ${now} todo`]);
228 return <Element>log.recordAndApply(`${now} Create ${description}`);
229 },
230 addTag: function (createTimestamp: string, tag: string) {
231 return perform(`Tag ${createTimestamp} ${tag}`, `Untag ${createTimestamp} ${tag}`);
232 },
233 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
234 return perform(`Edit ${createTimestamp} ${newDescription}`, `Edit ${createTimestamp} ${oldDescription}`);
235 },
236 removeTag: function (createTimestamp: string, tag: string) {
237 return perform(`Untag ${createTimestamp} ${tag}`, `Tag ${createTimestamp} ${tag}`);
238 },
239 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
240 return perform(`Priority ${createTimestamp} ${newPriority}`, `Priority ${createTimestamp} ${oldPriority}`);
241 },
242 setState: function (createTimestamp: string, newState: string, oldState: string) {
243 return perform(`State ${createTimestamp} ${newState}`, `State ${createTimestamp} ${oldState}`);
244 },
245 undo: function () {
246 const entry = undoLog.pop();
247 if (entry) {
248 redoLog.push(entry);
249 return log.recordAndApply(`${clock.now()} ${entry[0]}`);
250 }
251 },
252 redo: function () {
253 const entry = redoLog.pop();
254 if (entry) {
255 undoLog.push(entry);
256 return log.recordAndApply(`${clock.now()} ${entry[1]}`);
257 }
258 },
259 };
260}
261const ui = UI();
262
263enum CommitOrAbort {
264 Commit,
265 Abort,
266}
267
268function BrowserUI() {
269 var currentViewState = "todo";
270 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
271 var lastTagNameEntered = "";
272 return {
273 addTask: function (event: KeyboardEvent) {
274 const input = <HTMLInputElement>document.getElementById("taskName");
275 if (input.value.match(/^ *$/)) return;
276 const task = ui.addTask(input.value);
277 if (currentViewState === "todo" || currentViewState === "all") {
278 task instanceof HTMLElement && task.focus();
279 } else if (this.returnFocusAfterInput()) {
280 } else {
281 this.firstVisibleTask()?.focus();
282 }
283 input.value = "";
284 if (event.getModifierState("Control")) {
285 this.makeTopPriority(task);
286 }
287 },
288
289 beginEdit: function (event: Event) {
290 var task = document.activeElement;
291 if (!task) return;
292 if (task.classList.contains("tag")) task = task.parentElement!;
293 const input = document.createElement("input");
294 const desc = task.getElementsByClassName("desc")[0];
295 const oldDescription = desc.textContent!;
296 task.setAttribute("data-description", oldDescription);
297 input.value = oldDescription;
298 input.addEventListener("blur", this.completeEdit, { once: true });
299 desc.textContent = "";
300 task.insertBefore(input, task.firstChild);
301 input.focus();
302 event.preventDefault();
303 },
304
305 beginTagEdit: function (event: Event) {
306 const task = document.activeElement;
307 if (!task) return;
308 const input = document.createElement("input");
309 input.classList.add("tag");
310 input.addEventListener("blur", this.completeTagEdit, { once: true });
311 input.value = lastTagNameEntered;
312 task.appendChild(input);
313 input.focus();
314 input.select();
315 event.preventDefault();
316 },
317
318 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
319 const input = event.target as HTMLInputElement;
320 const task = input.parentElement!;
321 const desc = task.getElementsByClassName("desc")[0];
322 const oldDescription = task.getAttribute("data-description")!;
323 const newDescription = input.value;
324 input.removeEventListener("blur", this.completeEdit);
325 task.removeChild(input);
326 task.removeAttribute("data-description");
327 task.focus();
328 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
329 desc.textContent = oldDescription;
330 } else {
331 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
332 }
333 },
334
335 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
336 const input = event.target as HTMLInputElement;
337 const task = input.parentElement!;
338 const newTagName = input.value;
339 input.removeEventListener("blur", this.completeTagEdit);
340 task.removeChild(input);
341 task.focus();
342 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !Model.hasTag(task, newTagName)) {
343 ui.addTag(task.getAttribute("data-created")!, newTagName);
344 lastTagNameEntered = newTagName;
345 }
346 },
347
348 firstVisibleTask: function () {
349 for (const task of document.getElementsByClassName("task")) {
350 const state = task.getAttribute("data-state");
351 if (task instanceof HTMLElement && (state === currentViewState || (currentViewState === "all" && state !== "deleted"))) {
352 return task;
353 }
354 }
355 },
356
357 focusTaskNameInput: function (event: Event) {
358 if (document.activeElement instanceof HTMLElement) {
359 taskFocusedBeforeJumpingToInput = document.activeElement;
360 }
361 document.getElementById("taskName")!.focus();
362 window.scroll(0, 0);
363 event.preventDefault();
364 },
365
366 visibleTaskAtOffset(task: Element, offset: number): Element {
367 var cursor: Element | null = task;
368 var valid_cursor = cursor;
369 const increment = offset / Math.abs(offset);
370 while (true) {
371 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
372 if (!cursor || !(cursor instanceof HTMLElement)) break;
373 const state = cursor.getAttribute("data-state")!;
374 if (state === currentViewState || (currentViewState === "all" && state !== "deleted")) {
375 offset -= increment;
376 valid_cursor = cursor;
377 }
378 if (Math.abs(offset) < 0.5) break;
379 }
380 return valid_cursor;
381 },
382
383 jumpCursor: function (position: number) {
384 const first = this.firstVisibleTask();
385 if (!first) return;
386 const dest = this.visibleTaskAtOffset(first, position - 1);
387 if (dest instanceof HTMLElement) dest.focus();
388 },
389
390 makeTopPriority: function (task: Element | null = null) {
391 if (!task) task = document.activeElement;
392 if (!task) return;
393 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
394 },
395
396 moveCursor: function (offset: number): boolean {
397 const active = document.activeElement;
398 if (!active) return false;
399 const dest = this.visibleTaskAtOffset(active, offset);
400 if (dest !== active && dest instanceof HTMLElement) {
401 dest.focus();
402 return true;
403 }
404 return false;
405 },
406
407 moveTask: function (offset: number) {
408 const active = document.activeElement;
409 if (!active) return;
410 const dest = this.visibleTaskAtOffset(active, offset);
411 if (dest === active) return; // Already extremal
412 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
413 if (onePastDest == dest) onePastDest = null; // Will become extremal
414 if (offset > 0) {
415 this.setPriority(active, dest, onePastDest);
416 } else {
417 this.setPriority(active, onePastDest, dest);
418 }
419 },
420
421 removeTag: function () {
422 var target = document.activeElement;
423 if (!target) return;
424 if (target.classList.contains("task")) {
425 const tags = target.getElementsByClassName("tag");
426 target = tags[tags.length - 1];
427 }
428 if (!target || !target.classList.contains("tag")) return;
429 ui.removeTag(target.parentElement!.getAttribute("data-created")!, target.textContent!);
430 },
431
432 returnFocusAfterInput: function (): boolean {
433 if (taskFocusedBeforeJumpingToInput) {
434 taskFocusedBeforeJumpingToInput.focus();
435 return true;
436 }
437 return false;
438 },
439
440 // Change task's priority to be between other tasks a and b.
441 setPriority: function (task: Element, a: Element | null, b: Element | null) {
442 const aPriority = a === null ? 0 : Model.getPriority(a);
443 const bPriority = b === null ? clock.now() : Model.getPriority(b);
444 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
445 const span = bPriority - aPriority;
446 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
447 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
448 const newPriorityRounded = Math.round(newPriority);
449 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
450 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
451 task instanceof HTMLElement && task.focus();
452 },
453
454 setState: function (newState: string) {
455 const task = document.activeElement;
456 if (!task) return;
457 const oldState = task.getAttribute("data-state")!;
458 if (newState === oldState) return;
459 const createTimestamp = task.getAttribute("data-created")!;
460 if (currentViewState !== "all" || newState == "deleted") {
461 this.moveCursor(1) || this.moveCursor(-1);
462 }
463 return ui.setState(createTimestamp, newState, oldState);
464 },
465
466 setView: function (state: string, color: string) {
467 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
468 if (state === "all") {
469 sheet.insertRule(`.task[data-state=deleted] { display: none }`);
470 } else {
471 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
472 }
473 sheet.insertRule(`:root { --view-state-indicator-color: ${color}; }`);
474 sheet.removeRule(2);
475 sheet.removeRule(2);
476 currentViewState = state;
477 if (document.activeElement?.getAttribute("data-state") !== state) {
478 this.firstVisibleTask()?.focus();
479 }
480 },
481
482 undo: function () {
483 const ret = ui.undo();
484 if (ret && ret instanceof HTMLElement) ret.focus();
485 },
486 redo: function () {
487 const ret = ui.redo();
488 if (ret && ret instanceof HTMLElement) ret.focus();
489 },
490 };
491}
492const browserUI = BrowserUI();
493
494const scrollIncrement = 60;
495enum InputState {
496 Root,
497 S,
498 V,
499 VS,
500}
501var inputState = InputState.Root;
502var inputCount: number | null = null;
503
504function handleKey(event: any) {
505 if (["Alt", "Control", "Meta", "Shift"].includes(event.key)) return;
506 if (event.target.tagName === "INPUT") {
507 if (event.target.id === "taskName") {
508 if (event.key == "Enter") return browserUI.addTask(event);
509 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
510 } else if (event.target.classList.contains("tag")) {
511 if (event.key == "Enter") return browserUI.completeTagEdit(event);
512 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
513 } else {
514 if (event.key == "Enter") return browserUI.completeEdit(event);
515 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
516 }
517 } else {
518 if (inputState === InputState.Root) {
519 if ("0" <= event.key && event.key <= "9") {
520 return (inputCount = (inputCount ?? 0) * 10 + parseInt(event.key));
521 }
522 try {
523 if (event.ctrlKey) {
524 if (event.key == "e") return window.scrollBy(0, (inputCount ?? 1) * scrollIncrement);
525 if (event.key == "y") return window.scrollBy(0, (inputCount ?? 1) * -scrollIncrement);
526 } else {
527 if (event.key == "j") return browserUI.moveCursor(inputCount ?? 1);
528 if (event.key == "k") return browserUI.moveCursor(-(inputCount ?? 1));
529 if (event.key == "J") return browserUI.moveTask(inputCount ?? 1);
530 if (event.key == "K") return browserUI.moveTask(-(inputCount ?? 1));
531 if (event.key == "G") return browserUI.jumpCursor(inputCount ?? MAX_SAFE_INTEGER);
532 if (event.key == "T") return browserUI.makeTopPriority();
533 if (event.key == "n") return browserUI.focusTaskNameInput(event);
534 if (event.key == "c") return browserUI.setState("cancelled");
535 if (event.key == "d") return browserUI.setState("done");
536 if (event.key == "q") return browserUI.setState("todo");
537 if (event.key == "s") return (inputState = InputState.S);
538 if (event.key == "w") return browserUI.setState("waiting");
539 if (event.key == "X") return browserUI.setState("deleted");
540 if (event.key == "x") return browserUI.removeTag();
541 if (event.key == "u") return browserUI.undo();
542 if (event.key == "r") return browserUI.redo();
543 if (event.key == "e") return browserUI.beginEdit(event);
544 if (event.key == "t") return browserUI.beginTagEdit(event);
545 if (event.key == "v") return (inputState = InputState.V);
546 }
547 } finally {
548 inputCount = null;
549 }
550 } else if (inputState === InputState.S) {
551 inputState = InputState.Root;
552 if (event.key == "m") return browserUI.setState("someday-maybe");
553 } else if (inputState === InputState.V) {
554 inputState = InputState.Root;
555 if (event.key == "a") return browserUI.setView("all", "Gold");
556 if (event.key == "c") return browserUI.setView("cancelled", "Red");
557 if (event.key == "d") return browserUI.setView("done", "LawnGreen");
558 if (event.key == "q") return browserUI.setView("todo", "White");
559 if (event.key == "s") return (inputState = InputState.VS);
560 if (event.key == "v") return browserUI.setView("todo", "White");
561 if (event.key == "w") return browserUI.setView("waiting", "MediumOrchid");
562 if (event.key == "x") return browserUI.setView("deleted", "Black");
563 } else if (inputState === InputState.VS) {
564 inputState = InputState.Root;
565 if (event.key == "m") return browserUI.setView("someday-maybe", "DeepSkyBlue");
566 }
567 }
568}
569
570function browserInit() {
571 log.replay();
572 browserUI.firstVisibleTask()?.focus();
573 document.body.addEventListener("keydown", handleKey, { capture: false });
574}