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