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