]> git.scottworley.com Git - vopamoi/blame - vopamoi.ts
A space for extra notes for each task
[vopamoi] / vopamoi.ts
CommitLineData
121d9948
SW
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
27c67784
SW
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
c70b3eed
SW
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
ef12457b
SW
38function Model() {
39 return {
40 addTask: function (timestamp: string, description: string): Element {
41 const task = document.createElement("div");
42 const desc = document.createElement("span");
43 desc.textContent = description;
44 desc.classList.add("desc");
45 task.appendChild(desc);
46 task.classList.add("task");
47 task.setAttribute("tabindex", "0");
b6712c31 48 task.setAttribute("id", timestamp);
ef12457b
SW
49 task.setAttribute("data-state", "todo");
50 const tasks = document.getElementById("tasks")!;
51 tasks.insertBefore(task, tasks.firstElementChild);
52 return task;
53 },
54
55 addTag: function (createTimestamp: string, tagName: string): Element | null {
56 const task = this.getTask(createTimestamp);
57 if (!task) return null;
58 const existingTag = this.hasTag(task, tagName);
59 if (existingTag) return existingTag;
60 const tag = document.createElement("span");
61 tag.appendChild(document.createTextNode(tagName));
62 tag.classList.add("tag");
63 tag.setAttribute("tabindex", "0");
64 hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`));
65 for (const child of task.getElementsByClassName("tag")) {
66 if (tagName > child.textContent!) {
67 task.insertBefore(tag, child);
68 return tag;
69 }
70 }
71 task.insertBefore(tag, task.getElementsByClassName("desc")[0]!);
72 return tag;
73 },
74
75 edit: function (createTimestamp: string, newDescription: string): Element | null {
76 const target = this.getTask(createTimestamp);
77 if (!target) return null;
78 if (target.hasAttribute("data-description")) {
79 // Oh no: An edit has arrived from a replica while a local edit is in progress.
80 const input = target.getElementsByTagName("input")[0]!;
81 if (
82 input.value === target.getAttribute("data-description") &&
83 input.selectionStart === input.value.length &&
84 input.selectionEnd === input.value.length
85 ) {
86 // No local changes have actually been made yet. Change the contents of the edit box!
87 input.value = newDescription;
88 } else {
89 // No great options.
90 // Prefer not to interrupt the local user's edit.
91 // The remote edit is mostly lost; this mostly becomes last-write-wins.
92 target.setAttribute("data-description", newDescription);
93 }
7b574407 94 } else {
ef12457b
SW
95 target.getElementsByClassName("desc")[0].textContent = newDescription;
96 }
97 return target;
98 },
99
b9f7e989
SW
100 editContent: function (createTimestamp: string, newContent: string): Element | null {
101 const target = this.getTask(createTimestamp);
102 if (!target) return null;
103 if (target.hasAttribute("data-content")) {
104 // Oh no: An edit has arrived from a replica while a local edit is in progress.
105 const input = target.getElementsByTagName("textarea")[0]!;
106 if (
107 input.value === target.getAttribute("data-content") &&
108 input.selectionStart === input.value.length &&
109 input.selectionEnd === input.value.length
110 ) {
111 // No local changes have actually been made yet. Change the contents of the edit box!
112 input.value = newContent;
113 } else {
114 // No great options.
115 // Prefer not to interrupt the local user's edit.
116 // The remote edit is mostly lost; this mostly becomes last-write-wins.
117 target.setAttribute("data-content", newContent);
118 }
119 } else {
120 var content = target.getElementsByClassName("content")[0];
121 if (!content) {
122 content = document.createElement("div");
123 content.classList.add("content");
124 target.appendChild(content);
125 }
126 content.textContent = newContent;
127 }
128 return target;
129 },
130
ef12457b
SW
131 hasTag: function (task: Element, tag: string): Element | null {
132 for (const child of task.getElementsByClassName("tag")) {
133 if (child.textContent === tag) {
134 return child;
135 }
136 }
137 return null;
138 },
139
140 getPriority: function (task: Element): number {
141 if (task.hasAttribute("data-priority")) {
142 return parseFloat(task.getAttribute("data-priority")!);
143 }
b6712c31 144 return parseFloat(task.getAttribute("id")!);
ef12457b
SW
145 },
146
147 getTask: function (createTimestamp: string) {
b6712c31 148 return document.getElementById(createTimestamp);
ef12457b
SW
149 },
150
151 insertInPriorityOrder: function (task: Element, dest: Element) {
152 const priority = this.getPriority(task);
153 for (const t of dest.children) {
154 if (t !== task && this.getPriority(t) < priority) {
155 dest.insertBefore(task, t);
156 return;
157 }
158 }
159 dest.appendChild(task);
160 },
161
162 removeTag: function (createTimestamp: string, tagName: string) {
163 const task = this.getTask(createTimestamp);
164 if (!task) return null;
165 const tag = this.hasTag(task, tagName);
166 if (!tag) return;
167 task.removeChild(tag);
168 if (task instanceof HTMLElement) task.focus();
169 },
170
171 setPriority: function (createTimestamp: string, priority: number): Element | null {
172 const target = this.getTask(createTimestamp);
173 if (!target) return null;
174 target.setAttribute("data-priority", `${priority}`);
175 this.insertInPriorityOrder(target, target.parentElement!);
176 return target;
177 },
178
179 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
180 const task = this.getTask(createTimestamp);
181 if (!task) return;
182 task.setAttribute("data-state", state);
183 var date = task.getElementsByClassName("statedate")[0];
184 if (state === "todo") {
185 task.removeChild(date);
1804fd5a
SW
186 return;
187 }
ef12457b
SW
188 if (!date) {
189 date = document.createElement("span");
190 date.classList.add("statedate");
191 task.insertBefore(date, task.firstChild);
192 }
193 const d = new Date(parseInt(stateTimestamp));
194 date.textContent = `${d.getFullYear()}-${`${d.getMonth() + 1}`.padStart(2, "0")}-${`${d.getDate()}`.padStart(2, "0")}`;
195 },
196 };
197}
198const model = Model();
f1afad9b 199
d03daa19 200function Log(prefix: string = "vp-") {
60a63831
SW
201 var next_log_index = 0;
202 return {
e88c099c 203 apply: function (entry: string) {
60a63831
SW
204 const [timestamp, command, data] = splitN(entry, " ", 2);
205 if (command == "Create") {
ef12457b 206 return model.addTask(timestamp, data);
60a63831 207 }
7b574407
SW
208 if (command == "Edit") {
209 const [createTimestamp, description] = splitN(data, " ", 1);
ef12457b 210 return model.edit(createTimestamp, description);
7b574407 211 }
b9f7e989
SW
212 if (command == "EditContent") {
213 const [createTimestamp, content] = splitN(data, " ", 1);
214 return model.editContent(createTimestamp, content);
215 }
68a72fde
SW
216 if (command == "Priority") {
217 const [createTimestamp, newPriority] = splitN(data, " ", 1);
ef12457b 218 return model.setPriority(createTimestamp, parseFloat(newPriority));
68a72fde 219 }
6a5644f3
SW
220 if (command == "State") {
221 const [createTimestamp, state] = splitN(data, " ", 1);
ef12457b 222 return model.setState(timestamp, createTimestamp, state);
6a5644f3 223 }
7b5b90b9
SW
224 if (command == "Tag") {
225 const [createTimestamp, tag] = splitN(data, " ", 1);
ef12457b 226 return model.addTag(createTimestamp, tag);
7b5b90b9 227 }
0726872b
SW
228 if (command == "Untag") {
229 const [createTimestamp, tag] = splitN(data, " ", 1);
ef12457b 230 return model.removeTag(createTimestamp, tag);
0726872b 231 }
60a63831
SW
232 },
233
e88c099c 234 record: function (entry: string) {
d03daa19 235 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
60a63831
SW
236 },
237
e88c099c
SW
238 recordAndApply: function (entry: string) {
239 this.record(entry);
6d01c406 240 return this.apply(entry);
60a63831
SW
241 },
242
243 replay: function () {
9db534f6 244 document.getElementById("tasks")!.style.display = "none";
60a63831 245 while (true) {
d03daa19 246 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
60a63831
SW
247 if (entry === null) {
248 break;
249 }
e88c099c 250 this.apply(entry);
60a63831
SW
251 next_log_index++;
252 }
9db534f6 253 document.getElementById("tasks")!.style.display = "";
60a63831
SW
254 },
255 };
d03daa19
SW
256}
257const log = Log();
262705dd 258
b56a37d3 259function UI() {
0d1c27a8
SW
260 const undoLog: string[][] = [];
261 const redoLog: string[][] = [];
76825ecd 262 function perform(forward: string, reverse: string) {
0d1c27a8 263 undoLog.push([reverse, forward]);
76825ecd
SW
264 return log.recordAndApply(`${clock.now()} ${forward}`);
265 }
b56a37d3
SW
266 return {
267 addTask: function (description: string): Element {
268 const now = clock.now();
0d1c27a8 269 undoLog.push([`State ${now} deleted`, `State ${now} todo`]);
b56a37d3
SW
270 return <Element>log.recordAndApply(`${now} Create ${description}`);
271 },
7b5b90b9 272 addTag: function (createTimestamp: string, tag: string) {
76825ecd 273 return perform(`Tag ${createTimestamp} ${tag}`, `Untag ${createTimestamp} ${tag}`);
7b5b90b9 274 },
b56a37d3 275 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
76825ecd 276 return perform(`Edit ${createTimestamp} ${newDescription}`, `Edit ${createTimestamp} ${oldDescription}`);
b56a37d3 277 },
b9f7e989
SW
278 editContent: function (createTimestamp: string, newContent: string, oldContent: string) {
279 return perform(`EditContent ${createTimestamp} ${newContent}`, `EditContent ${createTimestamp} ${oldContent}`);
280 },
b5f15e0e 281 removeTag: function (createTimestamp: string, tag: string) {
76825ecd 282 return perform(`Untag ${createTimestamp} ${tag}`, `Tag ${createTimestamp} ${tag}`);
b5f15e0e 283 },
b56a37d3 284 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
76825ecd 285 return perform(`Priority ${createTimestamp} ${newPriority}`, `Priority ${createTimestamp} ${oldPriority}`);
b56a37d3
SW
286 },
287 setState: function (createTimestamp: string, newState: string, oldState: string) {
76825ecd 288 return perform(`State ${createTimestamp} ${newState}`, `State ${createTimestamp} ${oldState}`);
b56a37d3
SW
289 },
290 undo: function () {
0d1c27a8
SW
291 const entry = undoLog.pop();
292 if (entry) {
293 redoLog.push(entry);
294 return log.recordAndApply(`${clock.now()} ${entry[0]}`);
295 }
296 },
297 redo: function () {
298 const entry = redoLog.pop();
299 if (entry) {
300 undoLog.push(entry);
301 return log.recordAndApply(`${clock.now()} ${entry[1]}`);
b56a37d3
SW
302 }
303 },
304 };
305}
306const ui = UI();
e88c099c 307
ad72cd51
SW
308enum CommitOrAbort {
309 Commit,
310 Abort,
311}
312
ada060d7 313function BrowserUI() {
c2226333
SW
314 const viewColors: { [key: string]: string } = {
315 all: "Gold",
316 cancelled: "Red",
317 deleted: "Black",
318 done: "LawnGreen",
319 "someday-maybe": "DeepSkyBlue",
320 todo: "White",
321 waiting: "MediumOrchid",
322 };
c948f3b4 323 var currentTagView: string | null = null;
868667c1 324 var currentViewState = "todo";
a59fbe41 325 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
09cd65ad 326 var lastTagNameEntered = "";
ada060d7
SW
327 return {
328 addTask: function (event: KeyboardEvent) {
329 const input = <HTMLInputElement>document.getElementById("taskName");
fb19ac80
SW
330 if (input.value.match(/^ *$/)) return;
331 const task = ui.addTask(input.value);
cddbdce1 332 if (currentViewState === "todo" || currentViewState === "all") {
fb19ac80
SW
333 task instanceof HTMLElement && task.focus();
334 } else if (this.returnFocusAfterInput()) {
335 } else {
336 this.firstVisibleTask()?.focus();
337 }
338 input.value = "";
339 if (event.getModifierState("Control")) {
88bd89ef 340 this.makeBottomPriority(task);
bc7996fe 341 }
ada060d7 342 },
09657615 343
ada060d7 344 beginEdit: function (event: Event) {
32808c9a 345 const task = this.currentTask();
ada060d7
SW
346 if (!task) return;
347 const input = document.createElement("input");
26737687
SW
348 const desc = task.getElementsByClassName("desc")[0];
349 const oldDescription = desc.textContent!;
ada060d7
SW
350 task.setAttribute("data-description", oldDescription);
351 input.value = oldDescription;
352 input.addEventListener("blur", this.completeEdit, { once: true });
26737687 353 desc.textContent = "";
7b5b90b9
SW
354 task.insertBefore(input, task.firstChild);
355 input.focus();
356 event.preventDefault();
357 },
358
b9f7e989
SW
359 beginEditContent: function (event: Event) {
360 const task = this.currentTask();
361 if (!task) return;
362 const input = document.createElement("textarea");
363 const content = task.getElementsByClassName("content")[0];
364 const oldContent = content?.textContent ?? "";
365 task.setAttribute("data-content", oldContent);
366 input.value = oldContent;
367 input.addEventListener("blur", this.completeContentEdit, { once: true });
368 if (content) content.textContent = "";
369 task.appendChild(input);
370 input.focus();
371 event.preventDefault();
372 },
373
7b5b90b9 374 beginTagEdit: function (event: Event) {
32808c9a 375 const task = this.currentTask();
7b5b90b9
SW
376 if (!task) return;
377 const input = document.createElement("input");
378 input.classList.add("tag");
379 input.addEventListener("blur", this.completeTagEdit, { once: true });
09cd65ad 380 input.value = lastTagNameEntered;
ada060d7
SW
381 task.appendChild(input);
382 input.focus();
09cd65ad 383 input.select();
ada060d7
SW
384 event.preventDefault();
385 },
7b574407 386
ad72cd51 387 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
ada060d7
SW
388 const input = event.target as HTMLInputElement;
389 const task = input.parentElement!;
26737687 390 const desc = task.getElementsByClassName("desc")[0];
ada060d7
SW
391 const oldDescription = task.getAttribute("data-description")!;
392 const newDescription = input.value;
393 input.removeEventListener("blur", this.completeEdit);
132921e6 394 task.removeChild(input);
ada060d7
SW
395 task.removeAttribute("data-description");
396 task.focus();
fb19ac80 397 if (resolution === CommitOrAbort.Abort || newDescription.match(/^ *$/) || newDescription === oldDescription) {
26737687 398 desc.textContent = oldDescription;
ada060d7 399 } else {
b6712c31 400 ui.edit(task.getAttribute("id")!, newDescription, oldDescription);
ada060d7
SW
401 }
402 },
7b574407 403
b9f7e989
SW
404 completeContentEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
405 const input = event.target as HTMLInputElement;
406 const task = input.parentElement!;
407 const content = task.getElementsByClassName("content")[0];
408 const oldContent = task.getAttribute("data-content")!;
409 const newContent = input.value;
410 input.removeEventListener("blur", this.completeContentEdit);
411 task.removeChild(input);
412 task.removeAttribute("data-content");
413 task.focus();
414 if (resolution === CommitOrAbort.Abort || newContent === oldContent) {
415 if (content) content.textContent = oldContent;
416 } else {
417 ui.editContent(task.getAttribute("id")!, newContent, oldContent);
418 }
419 },
420
7b5b90b9
SW
421 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
422 const input = event.target as HTMLInputElement;
423 const task = input.parentElement!;
424 const newTagName = input.value;
425 input.removeEventListener("blur", this.completeTagEdit);
426 task.removeChild(input);
427 task.focus();
ef12457b 428 if (resolution === CommitOrAbort.Commit && !newTagName.match(/^ *$/) && !model.hasTag(task, newTagName)) {
b6712c31 429 ui.addTag(task.getAttribute("id")!, newTagName);
09cd65ad 430 lastTagNameEntered = newTagName;
e1eb33ad 431 }
7b5b90b9
SW
432 },
433
5800003c
SW
434 currentTag: function (): Element | null {
435 var target = document.activeElement;
436 if (!target) return null;
437 if (target.classList.contains("task")) {
438 const tags = target.getElementsByClassName("tag");
439 target = tags[tags.length - 1];
440 }
441 if (!target || !target.classList.contains("tag")) return null;
442 return target;
443 },
444
32808c9a
SW
445 currentTask: function (): HTMLElement | null {
446 var target = document.activeElement;
447 if (!target) return null;
448 if (target.classList.contains("tag")) target = target.parentElement!;
449 return target as HTMLElement;
450 },
451
f36b20d6
SW
452 firstVisibleTask: function (root: Element | null = null) {
453 if (root === null) root = document.body;
454 for (const task of root.getElementsByClassName("task")) {
cddbdce1 455 const state = task.getAttribute("data-state");
312acaa8
SW
456 if (
457 task instanceof HTMLElement &&
458 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
459 !task.classList.contains("hide")
460 ) {
ada060d7
SW
461 return task;
462 }
65a7510d 463 }
ada060d7 464 },
caa93fd1 465
ada060d7 466 focusTaskNameInput: function (event: Event) {
32808c9a 467 taskFocusedBeforeJumpingToInput = this.currentTask();
ada060d7 468 document.getElementById("taskName")!.focus();
a1aa43d8 469 window.scroll(0, 0);
ada060d7
SW
470 event.preventDefault();
471 },
09657615 472
ada060d7
SW
473 visibleTaskAtOffset(task: Element, offset: number): Element {
474 var cursor: Element | null = task;
475 var valid_cursor = cursor;
476 const increment = offset / Math.abs(offset);
477 while (true) {
478 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
479 if (!cursor || !(cursor instanceof HTMLElement)) break;
cddbdce1 480 const state = cursor.getAttribute("data-state")!;
312acaa8
SW
481 if (
482 (state === currentViewState || (currentViewState === "all" && state !== "deleted")) &&
483 !cursor.classList.contains("hide")
484 ) {
ada060d7
SW
485 offset -= increment;
486 valid_cursor = cursor;
487 }
488 if (Math.abs(offset) < 0.5) break;
5fa4704c 489 }
ada060d7
SW
490 return valid_cursor;
491 },
23be73e3 492
40025d12
SW
493 jumpCursor: function (position: number) {
494 const first = this.firstVisibleTask();
495 if (!first) return;
496 const dest = this.visibleTaskAtOffset(first, position - 1);
497 if (dest instanceof HTMLElement) dest.focus();
498 },
499
88bd89ef 500 makeBottomPriority: function (task: Element | null = null) {
32808c9a 501 if (!task) task = this.currentTask();
88bd89ef
SW
502 if (!task) return;
503 this.setPriority(task, document.getElementById("tasks")!.lastElementChild, null);
504 },
505
55a4baa8 506 makeTopPriority: function (task: Element | null = null) {
32808c9a 507 if (!task) task = this.currentTask();
55a4baa8 508 if (!task) return;
b6712c31 509 ui.setPriority(task.getAttribute("id")!, clock.now(), model.getPriority(task));
88bd89ef 510 task instanceof HTMLElement && task.focus();
792b8a18
SW
511 },
512
cadeba34
SW
513 moveCursorLeft: function () {
514 const active = this.currentTask();
515 if (!active) return false;
516 if (active.parentElement!.classList.contains("task")) {
517 active.parentElement!.focus();
518 }
519 },
520
521 moveCursorRight: function () {
f36b20d6
SW
522 const active = this.currentTask();
523 if (!active) return false;
524 (this.firstVisibleTask(active) as HTMLElement | null)?.focus();
cadeba34
SW
525 },
526
109d4bc2 527 moveCursorVertically: function (offset: number): boolean {
32808c9a 528 const active = this.currentTask();
ada060d7
SW
529 if (!active) return false;
530 const dest = this.visibleTaskAtOffset(active, offset);
531 if (dest !== active && dest instanceof HTMLElement) {
532 dest.focus();
533 return true;
534 }
535 return false;
536 },
01f41859 537
ada060d7 538 moveTask: function (offset: number) {
32808c9a 539 const active = this.currentTask();
ada060d7
SW
540 if (!active) return;
541 const dest = this.visibleTaskAtOffset(active, offset);
542 if (dest === active) return; // Already extremal
543 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
544 if (onePastDest == dest) onePastDest = null; // Will become extremal
545 if (offset > 0) {
546 this.setPriority(active, dest, onePastDest);
547 } else {
548 this.setPriority(active, onePastDest, dest);
549 }
550 },
68a72fde 551
b5f15e0e 552 removeTag: function () {
5800003c 553 const target = this.currentTag();
4ccaa1d6 554 if (!target) return;
b6712c31 555 ui.removeTag(target.parentElement!.getAttribute("id")!, target.textContent!);
b5f15e0e
SW
556 },
557
312acaa8 558 resetTagView: function () {
c948f3b4 559 currentTagView = null;
3a164930
SW
560 const taskList = document.getElementById("tasks")!;
561 for (const task of Array.from(document.getElementsByClassName("task"))) {
312acaa8 562 task.classList.remove("hide");
3a164930 563 if (task.parentElement !== taskList) {
ef12457b 564 model.insertInPriorityOrder(task, taskList);
3a164930 565 }
312acaa8
SW
566 }
567 },
568
58b569ce
SW
569 resetView: function () {
570 this.setView("todo");
312acaa8 571 this.resetTagView();
58b569ce
SW
572 },
573
a59fbe41
SW
574 returnFocusAfterInput: function (): boolean {
575 if (taskFocusedBeforeJumpingToInput) {
576 taskFocusedBeforeJumpingToInput.focus();
577 return true;
578 }
579 return false;
580 },
581
ada060d7
SW
582 // Change task's priority to be between other tasks a and b.
583 setPriority: function (task: Element, a: Element | null, b: Element | null) {
ef12457b
SW
584 const aPriority = a === null ? clock.now() : model.getPriority(a);
585 const bPriority = b === null ? 0 : model.getPriority(b);
88bd89ef
SW
586 console.assert(aPriority > bPriority, aPriority, ">", bPriority);
587 const span = aPriority - bPriority;
588 const newPriority = bPriority + 0.1 * span + 0.8 * span * Math.random();
589 console.assert(aPriority > newPriority && newPriority > bPriority, aPriority, ">", newPriority, ">", bPriority);
ada060d7 590 const newPriorityRounded = Math.round(newPriority);
88bd89ef 591 const okToRound = aPriority > newPriorityRounded && newPriorityRounded > bPriority;
b6712c31 592 ui.setPriority(task.getAttribute("id")!, okToRound ? newPriorityRounded : newPriority, model.getPriority(task));
ada060d7
SW
593 task instanceof HTMLElement && task.focus();
594 },
68a72fde 595
ada060d7 596 setState: function (newState: string) {
32808c9a 597 const task = this.currentTask();
ada060d7
SW
598 if (!task) return;
599 const oldState = task.getAttribute("data-state")!;
600 if (newState === oldState) return;
b6712c31 601 const createTimestamp = task.getAttribute("id")!;
cddbdce1 602 if (currentViewState !== "all" || newState == "deleted") {
109d4bc2 603 this.moveCursorVertically(1) || this.moveCursorVertically(-1);
cddbdce1 604 }
b56a37d3 605 return ui.setState(createTimestamp, newState, oldState);
ada060d7 606 },
43f3cc0c 607
68d69314
SW
608 setTagView: function (tag: string | null = null) {
609 if (tag === null) {
610 const target = this.currentTag();
611 if (!target) return;
612 tag = target.textContent!;
613 }
3a164930
SW
614
615 if (currentTagView !== null) {
616 this.resetTagView();
617 }
618
619 const tasksWithTag = new Map();
312acaa8 620 for (const task of document.getElementsByClassName("task")) {
ef12457b
SW
621 if (model.hasTag(task, tag)) {
622 tasksWithTag.set(task.getElementsByClassName("desc")[0].textContent, [model.getPriority(task), task]);
3a164930
SW
623 }
624 }
625
626 function highestPrioritySuperTask(t: Element) {
627 var maxPriority = -1;
628 var superTask = null;
629 for (const child of t.getElementsByClassName("tag")) {
630 const e = tasksWithTag.get(child.textContent);
631 if (e !== undefined && e[0] > maxPriority) {
632 maxPriority = e[0];
633 superTask = e[1];
634 }
635 }
636 return superTask;
637 }
638
639 for (const task of Array.from(document.getElementsByClassName("task"))) {
ef12457b 640 if (model.hasTag(task, tag)) {
312acaa8
SW
641 task.classList.remove("hide");
642 } else {
3a164930
SW
643 const superTask = highestPrioritySuperTask(task);
644 if (superTask !== null) {
ef12457b 645 model.insertInPriorityOrder(task, superTask);
3a164930
SW
646 } else {
647 task.classList.add("hide");
648 }
312acaa8
SW
649 }
650 }
3a164930 651
c948f3b4 652 currentTagView = tag;
312acaa8
SW
653 },
654
c2226333 655 setView: function (state: string) {
868667c1 656 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
cddbdce1
SW
657 if (state === "all") {
658 sheet.insertRule(`.task[data-state=deleted] { display: none }`);
659 } else {
660 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
661 }
c2226333 662 sheet.insertRule(`:root { --view-state-indicator-color: ${viewColors[state]}; }`);
4c532769
SW
663 sheet.removeRule(2);
664 sheet.removeRule(2);
868667c1 665 currentViewState = state;
32808c9a 666 if (this.currentTask()?.getAttribute("data-state") !== state) {
868667c1
SW
667 this.firstVisibleTask()?.focus();
668 }
669 },
670
84849dfa 671 setUntaggedView: function () {
3a164930
SW
672 if (currentTagView !== null) {
673 this.resetTagView();
674 }
84849dfa
SW
675 for (const task of document.getElementsByClassName("task")) {
676 if (task.getElementsByClassName("tag").length === 0) {
677 task.classList.remove("hide");
678 } else {
679 task.classList.add("hide");
680 }
681 }
682 },
683
ada060d7 684 undo: function () {
b56a37d3 685 const ret = ui.undo();
ada060d7
SW
686 if (ret && ret instanceof HTMLElement) ret.focus();
687 },
0d1c27a8
SW
688 redo: function () {
689 const ret = ui.redo();
690 if (ret && ret instanceof HTMLElement) ret.focus();
691 },
ada060d7
SW
692 };
693}
694const browserUI = BrowserUI();
06ee32a1 695
90381b6d 696const scrollIncrement = 60;
e94e9f27 697enum InputState {
02c8a409 698 Root,
36ddfad1 699 S,
02c8a409 700 V,
36ddfad1 701 VS,
e94e9f27 702}
02c8a409 703var inputState = InputState.Root;
36fa06f4 704var inputCount: number | null = null;
e94e9f27 705
f1afad9b 706function handleKey(event: any) {
f1d8d0ed 707 if (["Alt", "Control", "Meta", "Shift"].includes(event.key)) return;
b9f7e989
SW
708 if (event.target.tagName === "TEXTAREA") {
709 if (event.key == "Enter" && event.ctrlKey) return browserUI.completeContentEdit(event);
710 if (event.key == "Escape") return browserUI.completeContentEdit(event, CommitOrAbort.Abort);
711 } else if (event.target.tagName === "INPUT") {
7b574407 712 if (event.target.id === "taskName") {
ada060d7 713 if (event.key == "Enter") return browserUI.addTask(event);
a59fbe41 714 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
7b5b90b9
SW
715 } else if (event.target.classList.contains("tag")) {
716 if (event.key == "Enter") return browserUI.completeTagEdit(event);
717 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
7b574407 718 } else {
ada060d7 719 if (event.key == "Enter") return browserUI.completeEdit(event);
ad72cd51 720 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
7b574407 721 }
a26b1f4b 722 } else {
02c8a409 723 if (inputState === InputState.Root) {
36fa06f4
SW
724 if ("0" <= event.key && event.key <= "9") {
725 return (inputCount = (inputCount ?? 0) * 10 + parseInt(event.key));
726 }
727 try {
90381b6d
SW
728 if (event.ctrlKey) {
729 if (event.key == "e") return window.scrollBy(0, (inputCount ?? 1) * scrollIncrement);
730 if (event.key == "y") return window.scrollBy(0, (inputCount ?? 1) * -scrollIncrement);
731 } else {
cadeba34
SW
732 if (event.key == "h") return browserUI.moveCursorLeft();
733 if (event.key == "l") return browserUI.moveCursorRight();
109d4bc2
SW
734 if (event.key == "j") return browserUI.moveCursorVertically(inputCount ?? 1);
735 if (event.key == "k") return browserUI.moveCursorVertically(-(inputCount ?? 1));
90381b6d
SW
736 if (event.key == "J") return browserUI.moveTask(inputCount ?? 1);
737 if (event.key == "K") return browserUI.moveTask(-(inputCount ?? 1));
738 if (event.key == "G") return browserUI.jumpCursor(inputCount ?? MAX_SAFE_INTEGER);
739 if (event.key == "T") return browserUI.makeTopPriority();
740 if (event.key == "n") return browserUI.focusTaskNameInput(event);
741 if (event.key == "c") return browserUI.setState("cancelled");
742 if (event.key == "d") return browserUI.setState("done");
743 if (event.key == "q") return browserUI.setState("todo");
744 if (event.key == "s") return (inputState = InputState.S);
745 if (event.key == "w") return browserUI.setState("waiting");
746 if (event.key == "X") return browserUI.setState("deleted");
747 if (event.key == "x") return browserUI.removeTag();
748 if (event.key == "u") return browserUI.undo();
749 if (event.key == "r") return browserUI.redo();
b9f7e989 750 if (event.key == "E") return browserUI.beginEditContent(event);
90381b6d
SW
751 if (event.key == "e") return browserUI.beginEdit(event);
752 if (event.key == "t") return browserUI.beginTagEdit(event);
753 if (event.key == "v") return (inputState = InputState.V);
754 }
36fa06f4
SW
755 } finally {
756 inputCount = null;
757 }
36ddfad1
SW
758 } else if (inputState === InputState.S) {
759 inputState = InputState.Root;
760 if (event.key == "m") return browserUI.setState("someday-maybe");
02c8a409
SW
761 } else if (inputState === InputState.V) {
762 inputState = InputState.Root;
c2226333
SW
763 if (event.key == "a") return browserUI.setView("all");
764 if (event.key == "c") return browserUI.setView("cancelled");
765 if (event.key == "d") return browserUI.setView("done");
84849dfa 766 if (event.key == "i") return browserUI.setUntaggedView();
68d69314 767 if (event.key == "p") return browserUI.setTagView("Project");
c2226333 768 if (event.key == "q") return browserUI.setView("todo");
36ddfad1 769 if (event.key == "s") return (inputState = InputState.VS);
312acaa8
SW
770 if (event.key == "T") return browserUI.resetTagView();
771 if (event.key == "t") return browserUI.setTagView();
84849dfa 772 if (event.key == "u") return browserUI.setUntaggedView();
58b569ce 773 if (event.key == "v") return browserUI.resetView();
c2226333
SW
774 if (event.key == "w") return browserUI.setView("waiting");
775 if (event.key == "x") return browserUI.setView("deleted");
36ddfad1
SW
776 } else if (inputState === InputState.VS) {
777 inputState = InputState.Root;
c2226333 778 if (event.key == "m") return browserUI.setView("someday-maybe");
e94e9f27 779 }
f1afad9b
SW
780 }
781}
782
f1afad9b 783function browserInit() {
d03daa19 784 log.replay();
ada060d7 785 browserUI.firstVisibleTask()?.focus();
bd267c29 786 document.body.addEventListener("keydown", handleKey, { capture: false });
f1afad9b 787}