]> git.scottworley.com Git - vopamoi/blame - vopamoi.ts
Provide a visual indicator of the current view-state
[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");
ef7ebad4 49 document.getElementById("tasks")!.appendChild(task);
6d01c406 50 return task;
13c97b99 51 },
974848d3 52
7b5b90b9
SW
53 addTag: function (createTimestamp: string, tagName: string): Element | null {
54 const task = this.getTask(createTimestamp);
55 if (!task) return null;
3916a89c
SW
56 const existingTag = this.hasTag(task, tagName);
57 if (existingTag) return existingTag;
7b5b90b9
SW
58 const tag = document.createElement("span");
59 tag.appendChild(document.createTextNode(tagName));
60 tag.classList.add("tag");
61 tag.setAttribute("tabindex", "0");
c70b3eed 62 hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`));
360beccb
SW
63 for (const child of task.getElementsByClassName("tag")) {
64 if (tagName > child.textContent!) {
65 task.insertBefore(tag, child);
66 return tag;
67 }
68 }
7b5b90b9
SW
69 task.appendChild(tag);
70 return tag;
71 },
72
7b574407
SW
73 edit: function (createTimestamp: string, newDescription: string): Element | null {
74 const target = this.getTask(createTimestamp);
75 if (!target) return null;
76 if (target.hasAttribute("data-description")) {
77 // Oh no: An edit has arrived from a replica while a local edit is in progress.
132921e6 78 const input = target.firstChild as HTMLInputElement;
7b574407
SW
79 if (
80 input.value === target.getAttribute("data-description") &&
3a731557 81 input.selectionStart === input.value.length &&
7b574407
SW
82 input.selectionEnd === input.value.length
83 ) {
84 // No local changes have actually been made yet. Change the contents of the edit box!
85 input.value = newDescription;
7b574407
SW
86 } else {
87 // No great options.
88 // Prefer not to interrupt the local user's edit.
89 // The remote edit is mostly lost; this mostly becomes last-write-wins.
90 target.setAttribute("data-description", newDescription);
91 }
92 } else {
26737687 93 target.getElementsByClassName("desc")[0].textContent = newDescription;
7b574407
SW
94 }
95 return target;
96 },
97
3916a89c 98 hasTag: function (task: Element, tag: string): Element | null {
54c19180
SW
99 for (const child of task.getElementsByClassName("tag")) {
100 if (child.textContent === tag) {
3916a89c 101 return child;
e1eb33ad
SW
102 }
103 }
3916a89c 104 return null;
e1eb33ad
SW
105 },
106
68a72fde
SW
107 getPriority: function (task: Element): number {
108 if (task.hasAttribute("data-priority")) {
109 return parseFloat(task.getAttribute("data-priority")!);
110 }
111 return parseFloat(task.getAttribute("data-created")!);
112 },
113
799f4e89
SW
114 getTask: function (createTimestamp: string) {
115 for (const task of document.getElementsByClassName("task")) {
116 if (task.getAttribute("data-created") === createTimestamp) {
117 return task;
118 }
119 }
120 },
121
43f3cc0c 122 setPriority: function (createTimestamp: string, priority: number): Element | null {
68a72fde 123 const target = this.getTask(createTimestamp);
43f3cc0c 124 if (!target) return null;
68a72fde
SW
125 target.setAttribute("data-priority", `${priority}`);
126 for (const task of document.getElementsByClassName("task")) {
127 if (task !== target && this.getPriority(task) > priority) {
128 task.parentElement!.insertBefore(target, task);
43f3cc0c 129 return target;
68a72fde
SW
130 }
131 }
132 document.getElementById("tasks")!.appendChild(target);
43f3cc0c 133 return target;
68a72fde
SW
134 },
135
01f41859
SW
136 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
137 const task = this.getTask(createTimestamp);
138 if (task) {
5350da9f 139 task.setAttribute("data-state", state);
01f41859 140 }
799f4e89 141 },
13c97b99 142};
f1afad9b 143
d03daa19 144function Log(prefix: string = "vp-") {
60a63831
SW
145 var next_log_index = 0;
146 return {
e88c099c 147 apply: function (entry: string) {
60a63831
SW
148 const [timestamp, command, data] = splitN(entry, " ", 2);
149 if (command == "Create") {
6d01c406 150 return Model.addTask(timestamp, data);
60a63831 151 }
7b574407
SW
152 if (command == "Edit") {
153 const [createTimestamp, description] = splitN(data, " ", 1);
154 return Model.edit(createTimestamp, description);
155 }
68a72fde
SW
156 if (command == "Priority") {
157 const [createTimestamp, newPriority] = splitN(data, " ", 1);
6d01c406 158 return Model.setPriority(createTimestamp, parseFloat(newPriority));
68a72fde 159 }
6a5644f3
SW
160 if (command == "State") {
161 const [createTimestamp, state] = splitN(data, " ", 1);
162 return Model.setState(timestamp, createTimestamp, state);
163 }
7b5b90b9
SW
164 if (command == "Tag") {
165 const [createTimestamp, tag] = splitN(data, " ", 1);
166 return Model.addTag(createTimestamp, tag);
167 }
60a63831
SW
168 },
169
e88c099c 170 record: function (entry: string) {
d03daa19 171 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
60a63831
SW
172 },
173
e88c099c
SW
174 recordAndApply: function (entry: string) {
175 this.record(entry);
6d01c406 176 return this.apply(entry);
60a63831
SW
177 },
178
179 replay: function () {
180 while (true) {
d03daa19 181 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
60a63831
SW
182 if (entry === null) {
183 break;
184 }
e88c099c 185 this.apply(entry);
60a63831
SW
186 next_log_index++;
187 }
188 },
189 };
d03daa19
SW
190}
191const log = Log();
262705dd 192
b56a37d3
SW
193function UI() {
194 const undoLog: string[] = [];
195 return {
196 addTask: function (description: string): Element {
197 const now = clock.now();
198 undoLog.push(`State ${now} deleted`);
199 return <Element>log.recordAndApply(`${now} Create ${description}`);
200 },
7b5b90b9
SW
201 addTag: function (createTimestamp: string, tag: string) {
202 // TODO: undo
203 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
204 },
b56a37d3
SW
205 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
206 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
207 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
208 },
209 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
210 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
211 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
212 },
213 setState: function (createTimestamp: string, newState: string, oldState: string) {
214 undoLog.push(`State ${createTimestamp} ${oldState}`);
215 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
216 },
217 undo: function () {
218 if (undoLog.length > 0) {
219 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
220 }
221 },
222 };
223}
224const ui = UI();
e88c099c 225
ad72cd51
SW
226enum CommitOrAbort {
227 Commit,
228 Abort,
229}
230
ada060d7 231function BrowserUI() {
868667c1 232 var currentViewState = "todo";
a59fbe41 233 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
09cd65ad 234 var lastTagNameEntered = "";
ada060d7
SW
235 return {
236 addTask: function (event: KeyboardEvent) {
237 const input = <HTMLInputElement>document.getElementById("taskName");
238 if (input.value) {
b56a37d3 239 const task = ui.addTask(input.value);
a59fbe41
SW
240 if (currentViewState === "todo") {
241 task instanceof HTMLElement && task.focus();
242 } else if (this.returnFocusAfterInput()) {
243 } else {
244 this.firstVisibleTask()?.focus();
245 }
ada060d7
SW
246 input.value = "";
247 if (event.getModifierState("Control")) {
248 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
249 }
bc7996fe 250 }
ada060d7 251 },
09657615 252
ada060d7
SW
253 beginEdit: function (event: Event) {
254 const task = document.activeElement;
255 if (!task) return;
256 const input = document.createElement("input");
26737687
SW
257 const desc = task.getElementsByClassName("desc")[0];
258 const oldDescription = desc.textContent!;
ada060d7
SW
259 task.setAttribute("data-description", oldDescription);
260 input.value = oldDescription;
261 input.addEventListener("blur", this.completeEdit, { once: true });
26737687 262 desc.textContent = "";
7b5b90b9
SW
263 task.insertBefore(input, task.firstChild);
264 input.focus();
265 event.preventDefault();
266 },
267
268 beginTagEdit: function (event: Event) {
269 const task = document.activeElement;
270 if (!task) return;
271 const input = document.createElement("input");
272 input.classList.add("tag");
273 input.addEventListener("blur", this.completeTagEdit, { once: true });
09cd65ad 274 input.value = lastTagNameEntered;
ada060d7
SW
275 task.appendChild(input);
276 input.focus();
09cd65ad 277 input.select();
ada060d7
SW
278 event.preventDefault();
279 },
7b574407 280
ad72cd51 281 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
ada060d7
SW
282 const input = event.target as HTMLInputElement;
283 const task = input.parentElement!;
26737687 284 const desc = task.getElementsByClassName("desc")[0];
ada060d7
SW
285 const oldDescription = task.getAttribute("data-description")!;
286 const newDescription = input.value;
287 input.removeEventListener("blur", this.completeEdit);
132921e6 288 task.removeChild(input);
ada060d7
SW
289 task.removeAttribute("data-description");
290 task.focus();
ad72cd51 291 if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) {
26737687 292 desc.textContent = oldDescription;
ada060d7 293 } else {
b56a37d3 294 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
ada060d7
SW
295 }
296 },
7b574407 297
7b5b90b9
SW
298 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
299 const input = event.target as HTMLInputElement;
300 const task = input.parentElement!;
301 const newTagName = input.value;
302 input.removeEventListener("blur", this.completeTagEdit);
303 task.removeChild(input);
304 task.focus();
187164d5 305 if (resolution === CommitOrAbort.Commit && newTagName && !Model.hasTag(task, newTagName)) {
e1eb33ad 306 ui.addTag(task.getAttribute("data-created")!, newTagName);
09cd65ad 307 lastTagNameEntered = newTagName;
e1eb33ad 308 }
7b5b90b9
SW
309 },
310
ada060d7
SW
311 firstVisibleTask: function () {
312 for (const task of document.getElementsByClassName("task")) {
868667c1 313 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
ada060d7
SW
314 return task;
315 }
65a7510d 316 }
ada060d7 317 },
caa93fd1 318
ada060d7 319 focusTaskNameInput: function (event: Event) {
a59fbe41
SW
320 if (document.activeElement instanceof HTMLElement) {
321 taskFocusedBeforeJumpingToInput = document.activeElement;
322 }
ada060d7
SW
323 document.getElementById("taskName")!.focus();
324 event.preventDefault();
325 },
09657615 326
ada060d7
SW
327 visibleTaskAtOffset(task: Element, offset: number): Element {
328 var cursor: Element | null = task;
329 var valid_cursor = cursor;
330 const increment = offset / Math.abs(offset);
331 while (true) {
332 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
333 if (!cursor || !(cursor instanceof HTMLElement)) break;
868667c1 334 if (cursor.getAttribute("data-state")! === currentViewState) {
ada060d7
SW
335 offset -= increment;
336 valid_cursor = cursor;
337 }
338 if (Math.abs(offset) < 0.5) break;
5fa4704c 339 }
ada060d7
SW
340 return valid_cursor;
341 },
23be73e3 342
ada060d7
SW
343 moveCursor: function (offset: number): boolean {
344 const active = document.activeElement;
345 if (!active) return false;
346 const dest = this.visibleTaskAtOffset(active, offset);
347 if (dest !== active && dest instanceof HTMLElement) {
348 dest.focus();
349 return true;
350 }
351 return false;
352 },
01f41859 353
ada060d7
SW
354 moveTask: function (offset: number) {
355 const active = document.activeElement;
356 if (!active) return;
357 const dest = this.visibleTaskAtOffset(active, offset);
358 if (dest === active) return; // Already extremal
359 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
360 if (onePastDest == dest) onePastDest = null; // Will become extremal
361 if (offset > 0) {
362 this.setPriority(active, dest, onePastDest);
363 } else {
364 this.setPriority(active, onePastDest, dest);
365 }
366 },
68a72fde 367
a59fbe41
SW
368 returnFocusAfterInput: function (): boolean {
369 if (taskFocusedBeforeJumpingToInput) {
370 taskFocusedBeforeJumpingToInput.focus();
371 return true;
372 }
373 return false;
374 },
375
ada060d7
SW
376 // Change task's priority to be between other tasks a and b.
377 setPriority: function (task: Element, a: Element | null, b: Element | null) {
378 const aPriority = a === null ? 0 : Model.getPriority(a);
379 const bPriority = b === null ? clock.now() : Model.getPriority(b);
380 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
381 const span = bPriority - aPriority;
382 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
383 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
384 const newPriorityRounded = Math.round(newPriority);
385 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
b56a37d3 386 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
ada060d7
SW
387 task instanceof HTMLElement && task.focus();
388 },
68a72fde 389
ada060d7
SW
390 setState: function (newState: string) {
391 const task = document.activeElement;
392 if (!task) return;
393 const oldState = task.getAttribute("data-state")!;
394 if (newState === oldState) return;
395 const createTimestamp = task.getAttribute("data-created")!;
396 this.moveCursor(1) || this.moveCursor(-1);
b56a37d3 397 return ui.setState(createTimestamp, newState, oldState);
ada060d7 398 },
43f3cc0c 399
4c532769 400 setView: function (state: string, color: string) {
868667c1
SW
401 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
402 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
4c532769
SW
403 sheet.insertRule(`:root { --view-state-indicator-color: ${color}; }`);
404 sheet.removeRule(2);
405 sheet.removeRule(2);
868667c1
SW
406 currentViewState = state;
407 if (document.activeElement?.getAttribute("data-state") !== state) {
408 this.firstVisibleTask()?.focus();
409 }
410 },
411
ada060d7 412 undo: function () {
b56a37d3 413 const ret = ui.undo();
ada060d7
SW
414 if (ret && ret instanceof HTMLElement) ret.focus();
415 },
416 };
417}
418const browserUI = BrowserUI();
06ee32a1 419
e94e9f27
SW
420enum InputState {
421 Command,
854992ec 422 View,
e94e9f27
SW
423}
424var inputState = InputState.Command;
425
f1afad9b 426function handleKey(event: any) {
a26b1f4b 427 if (event.target.tagName === "INPUT") {
7b574407 428 if (event.target.id === "taskName") {
ada060d7 429 if (event.key == "Enter") return browserUI.addTask(event);
a59fbe41 430 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
7b5b90b9
SW
431 } else if (event.target.classList.contains("tag")) {
432 if (event.key == "Enter") return browserUI.completeTagEdit(event);
433 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
7b574407 434 } else {
ada060d7 435 if (event.key == "Enter") return browserUI.completeEdit(event);
ad72cd51 436 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
7b574407 437 }
a26b1f4b 438 } else {
e94e9f27 439 if (inputState === InputState.Command) {
ada060d7
SW
440 if (event.key == "j") return browserUI.moveCursor(1);
441 if (event.key == "k") return browserUI.moveCursor(-1);
442 if (event.key == "J") return browserUI.moveTask(1);
443 if (event.key == "K") return browserUI.moveTask(-1);
444 if (event.key == "n") return browserUI.focusTaskNameInput(event);
ada060d7 445 if (event.key == "c") return browserUI.setState("cancelled");
868667c1 446 if (event.key == "d") return browserUI.setState("done");
1f300e10 447 if (event.key == "q") return browserUI.setState("todo");
868667c1 448 if (event.key == "s") return browserUI.setState("someday-maybe");
868667c1 449 if (event.key == "w") return browserUI.setState("waiting");
ada060d7
SW
450 if (event.key == "X") return browserUI.setState("deleted");
451 if (event.key == "u") return browserUI.undo();
452 if (event.key == "e") return browserUI.beginEdit(event);
7b5b90b9 453 if (event.key == "t") return browserUI.beginTagEdit(event);
854992ec
SW
454 if (event.key == "v") return (inputState = InputState.View);
455 } else if (inputState === InputState.View) {
868667c1 456 inputState = InputState.Command;
4c532769
SW
457 if (event.key == "c") return browserUI.setView("cancelled", "Red");
458 if (event.key == "d") return browserUI.setView("done", "LawnGreen");
459 if (event.key == "q") return browserUI.setView("todo", "White");
460 if (event.key == "s") return browserUI.setView("someday-maybe", "DeepSkyBlue");
461 if (event.key == "w") return browserUI.setView("waiting", "MediumOrchid");
462 if (event.key == "x") return browserUI.setView("deleted", "Black");
e94e9f27 463 }
f1afad9b
SW
464 }
465}
466
f1afad9b
SW
467function browserInit() {
468 document.body.addEventListener("keydown", handleKey, { capture: false });
d03daa19 469 log.replay();
ada060d7 470 browserUI.firstVisibleTask()?.focus();
f1afad9b 471}