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