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