]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
Add tags
[vopamoi] / vopamoi.ts
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;
5 const MAX_SAFE_INTEGER = 9007199254740991;
6
7 // A sane split that splits N *times*, leaving the last chunk unsplit.
8 function 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
16 // A clock that never goes backwards; monotonic.
17 function 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 }
30 const clock = Clock();
31
32 const Model = {
33 addTask: function (timestamp: string, description: string): Element {
34 const task = document.createElement("div");
35 task.appendChild(document.createTextNode(description));
36 task.classList.add("task");
37 task.setAttribute("tabindex", "0");
38 task.setAttribute("data-created", timestamp);
39 task.setAttribute("data-state", "todo");
40 document.getElementById("tasks")!.appendChild(task);
41 return task;
42 },
43
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
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.
60 const input = target.firstChild as HTMLInputElement;
61 if (
62 input.value === target.getAttribute("data-description") &&
63 input.selectionStart === input.value.length &&
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;
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
80 getPriority: function (task: Element): number {
81 if (task.hasAttribute("data-priority")) {
82 return parseFloat(task.getAttribute("data-priority")!);
83 }
84 return parseFloat(task.getAttribute("data-created")!);
85 },
86
87 getTask: function (createTimestamp: string) {
88 for (const task of document.getElementsByClassName("task")) {
89 if (task.getAttribute("data-created") === createTimestamp) {
90 return task;
91 }
92 }
93 },
94
95 setPriority: function (createTimestamp: string, priority: number): Element | null {
96 const target = this.getTask(createTimestamp);
97 if (!target) return null;
98 target.setAttribute("data-priority", `${priority}`);
99 for (const task of document.getElementsByClassName("task")) {
100 if (task !== target && this.getPriority(task) > priority) {
101 task.parentElement!.insertBefore(target, task);
102 return target;
103 }
104 }
105 document.getElementById("tasks")!.appendChild(target);
106 return target;
107 },
108
109 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
110 const task = this.getTask(createTimestamp);
111 if (task) {
112 task.setAttribute("data-state", state);
113 }
114 },
115 };
116
117 function Log(prefix: string = "vp-") {
118 var next_log_index = 0;
119 return {
120 apply: function (entry: string) {
121 const [timestamp, command, data] = splitN(entry, " ", 2);
122 if (command == "Create") {
123 return Model.addTask(timestamp, data);
124 }
125 if (command == "Edit") {
126 const [createTimestamp, description] = splitN(data, " ", 1);
127 return Model.edit(createTimestamp, description);
128 }
129 if (command == "Priority") {
130 const [createTimestamp, newPriority] = splitN(data, " ", 1);
131 return Model.setPriority(createTimestamp, parseFloat(newPriority));
132 }
133 if (command == "State") {
134 const [createTimestamp, state] = splitN(data, " ", 1);
135 return Model.setState(timestamp, createTimestamp, state);
136 }
137 if (command == "Tag") {
138 const [createTimestamp, tag] = splitN(data, " ", 1);
139 return Model.addTag(createTimestamp, tag);
140 }
141 },
142
143 record: function (entry: string) {
144 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
145 },
146
147 recordAndApply: function (entry: string) {
148 this.record(entry);
149 return this.apply(entry);
150 },
151
152 replay: function () {
153 while (true) {
154 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
155 if (entry === null) {
156 break;
157 }
158 this.apply(entry);
159 next_log_index++;
160 }
161 },
162 };
163 }
164 const log = Log();
165
166 function UI() {
167 const undoLog: string[] = [];
168 return {
169 addTask: function (description: string): Element {
170 const now = clock.now();
171 undoLog.push(`State ${now} deleted`);
172 return <Element>log.recordAndApply(`${now} Create ${description}`);
173 },
174 addTag: function (createTimestamp: string, tag: string) {
175 // TODO: undo
176 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
177 },
178 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
179 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
180 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
181 },
182 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
183 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
184 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
185 },
186 setState: function (createTimestamp: string, newState: string, oldState: string) {
187 undoLog.push(`State ${createTimestamp} ${oldState}`);
188 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
189 },
190 undo: function () {
191 if (undoLog.length > 0) {
192 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
193 }
194 },
195 };
196 }
197 const ui = UI();
198
199 enum CommitOrAbort {
200 Commit,
201 Abort,
202 }
203
204 function BrowserUI() {
205 var currentViewState = "todo";
206 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
207 return {
208 addTask: function (event: KeyboardEvent) {
209 const input = <HTMLInputElement>document.getElementById("taskName");
210 if (input.value) {
211 const task = ui.addTask(input.value);
212 if (currentViewState === "todo") {
213 task instanceof HTMLElement && task.focus();
214 } else if (this.returnFocusAfterInput()) {
215 } else {
216 this.firstVisibleTask()?.focus();
217 }
218 input.value = "";
219 if (event.getModifierState("Control")) {
220 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
221 }
222 }
223 },
224
225 beginEdit: function (event: Event) {
226 const task = document.activeElement;
227 if (!task) return;
228 const input = document.createElement("input");
229 const oldDescription = task.textContent!;
230 task.setAttribute("data-description", oldDescription);
231 input.value = oldDescription;
232 input.addEventListener("blur", this.completeEdit, { once: true });
233 task.textContent = "";
234 task.insertBefore(input, task.firstChild);
235 input.focus();
236 event.preventDefault();
237 },
238
239 beginTagEdit: function (event: Event) {
240 const task = document.activeElement;
241 if (!task) return;
242 const input = document.createElement("input");
243 input.classList.add("tag");
244 input.addEventListener("blur", this.completeTagEdit, { once: true });
245 task.appendChild(input);
246 input.focus();
247 event.preventDefault();
248 },
249
250 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
251 const input = event.target as HTMLInputElement;
252 const task = input.parentElement!;
253 const oldDescription = task.getAttribute("data-description")!;
254 const newDescription = input.value;
255 input.removeEventListener("blur", this.completeEdit);
256 task.removeChild(input);
257 task.removeAttribute("data-description");
258 task.focus();
259 if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) {
260 task.textContent = oldDescription;
261 } else {
262 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
263 }
264 },
265
266 completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
267 const input = event.target as HTMLInputElement;
268 const task = input.parentElement!;
269 const newTagName = input.value;
270 input.removeEventListener("blur", this.completeTagEdit);
271 task.removeChild(input);
272 task.focus();
273 ui.addTag(task.getAttribute("data-created")!, newTagName);
274 },
275
276 firstVisibleTask: function () {
277 for (const task of document.getElementsByClassName("task")) {
278 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
279 return task;
280 }
281 }
282 },
283
284 focusTaskNameInput: function (event: Event) {
285 if (document.activeElement instanceof HTMLElement) {
286 taskFocusedBeforeJumpingToInput = document.activeElement;
287 }
288 document.getElementById("taskName")!.focus();
289 event.preventDefault();
290 },
291
292 visibleTaskAtOffset(task: Element, offset: number): Element {
293 var cursor: Element | null = task;
294 var valid_cursor = cursor;
295 const increment = offset / Math.abs(offset);
296 while (true) {
297 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
298 if (!cursor || !(cursor instanceof HTMLElement)) break;
299 if (cursor.getAttribute("data-state")! === currentViewState) {
300 offset -= increment;
301 valid_cursor = cursor;
302 }
303 if (Math.abs(offset) < 0.5) break;
304 }
305 return valid_cursor;
306 },
307
308 moveCursor: function (offset: number): boolean {
309 const active = document.activeElement;
310 if (!active) return false;
311 const dest = this.visibleTaskAtOffset(active, offset);
312 if (dest !== active && dest instanceof HTMLElement) {
313 dest.focus();
314 return true;
315 }
316 return false;
317 },
318
319 moveTask: function (offset: number) {
320 const active = document.activeElement;
321 if (!active) return;
322 const dest = this.visibleTaskAtOffset(active, offset);
323 if (dest === active) return; // Already extremal
324 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
325 if (onePastDest == dest) onePastDest = null; // Will become extremal
326 if (offset > 0) {
327 this.setPriority(active, dest, onePastDest);
328 } else {
329 this.setPriority(active, onePastDest, dest);
330 }
331 },
332
333 returnFocusAfterInput: function (): boolean {
334 if (taskFocusedBeforeJumpingToInput) {
335 taskFocusedBeforeJumpingToInput.focus();
336 return true;
337 }
338 return false;
339 },
340
341 // Change task's priority to be between other tasks a and b.
342 setPriority: function (task: Element, a: Element | null, b: Element | null) {
343 const aPriority = a === null ? 0 : Model.getPriority(a);
344 const bPriority = b === null ? clock.now() : Model.getPriority(b);
345 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
346 const span = bPriority - aPriority;
347 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
348 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
349 const newPriorityRounded = Math.round(newPriority);
350 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
351 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
352 task instanceof HTMLElement && task.focus();
353 },
354
355 setState: function (newState: string) {
356 const task = document.activeElement;
357 if (!task) return;
358 const oldState = task.getAttribute("data-state")!;
359 if (newState === oldState) return;
360 const createTimestamp = task.getAttribute("data-created")!;
361 this.moveCursor(1) || this.moveCursor(-1);
362 return ui.setState(createTimestamp, newState, oldState);
363 },
364
365 setView: function (state: string) {
366 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
367 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
368 sheet.removeRule(1);
369 currentViewState = state;
370 if (document.activeElement?.getAttribute("data-state") !== state) {
371 this.firstVisibleTask()?.focus();
372 }
373 },
374
375 undo: function () {
376 const ret = ui.undo();
377 if (ret && ret instanceof HTMLElement) ret.focus();
378 },
379 };
380 }
381 const browserUI = BrowserUI();
382
383 enum InputState {
384 Command,
385 View,
386 }
387 var inputState = InputState.Command;
388
389 function handleKey(event: any) {
390 if (event.target.tagName === "INPUT") {
391 if (event.target.id === "taskName") {
392 if (event.key == "Enter") return browserUI.addTask(event);
393 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
394 } else if (event.target.classList.contains("tag")) {
395 if (event.key == "Enter") return browserUI.completeTagEdit(event);
396 if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort);
397 } else {
398 if (event.key == "Enter") return browserUI.completeEdit(event);
399 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
400 }
401 } else {
402 if (inputState === InputState.Command) {
403 if (event.key == "j") return browserUI.moveCursor(1);
404 if (event.key == "k") return browserUI.moveCursor(-1);
405 if (event.key == "J") return browserUI.moveTask(1);
406 if (event.key == "K") return browserUI.moveTask(-1);
407 if (event.key == "n") return browserUI.focusTaskNameInput(event);
408 if (event.key == "c") return browserUI.setState("cancelled");
409 if (event.key == "d") return browserUI.setState("done");
410 if (event.key == "q") return browserUI.setState("todo");
411 if (event.key == "s") return browserUI.setState("someday-maybe");
412 if (event.key == "w") return browserUI.setState("waiting");
413 if (event.key == "X") return browserUI.setState("deleted");
414 if (event.key == "u") return browserUI.undo();
415 if (event.key == "e") return browserUI.beginEdit(event);
416 if (event.key == "t") return browserUI.beginTagEdit(event);
417 if (event.key == "v") return (inputState = InputState.View);
418 } else if (inputState === InputState.View) {
419 inputState = InputState.Command;
420 if (event.key == "c") return browserUI.setView("cancelled");
421 if (event.key == "d") return browserUI.setView("done");
422 if (event.key == "q") return browserUI.setView("todo");
423 if (event.key == "s") return browserUI.setView("someday-maybe");
424 if (event.key == "w") return browserUI.setView("waiting");
425 if (event.key == "x") return browserUI.setView("deleted");
426 }
427 }
428 }
429
430 function browserInit() {
431 document.body.addEventListener("keydown", handleKey, { capture: false });
432 log.replay();
433 browserUI.firstVisibleTask()?.focus();
434 }