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