]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
Keep description in its own span
[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 const desc = document.createElement("span");
36 desc.textContent = description;
37 desc.classList.add("desc");
38 task.appendChild(desc);
39 task.classList.add("task");
40 task.setAttribute("tabindex", "0");
41 task.setAttribute("data-created", timestamp);
42 task.setAttribute("data-state", "todo");
43 document.getElementById("tasks")!.appendChild(task);
44 return task;
45 },
46
47 addTag: function (createTimestamp: string, tagName: string): Element | null {
48 const task = this.getTask(createTimestamp);
49 if (!task) return null;
50 const existingTag = this.hasTag(task, tagName);
51 if (existingTag) return existingTag;
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
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.
65 const input = target.firstChild as HTMLInputElement;
66 if (
67 input.value === target.getAttribute("data-description") &&
68 input.selectionStart === input.value.length &&
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;
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 {
80 target.getElementsByClassName("desc")[0].textContent = newDescription;
81 }
82 return target;
83 },
84
85 hasTag: function (task: Element, tag: string): Element | null {
86 for (const child of task.getElementsByClassName("tag")) {
87 if (child.textContent === tag) {
88 return child;
89 }
90 }
91 return null;
92 },
93
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
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
109 setPriority: function (createTimestamp: string, priority: number): Element | null {
110 const target = this.getTask(createTimestamp);
111 if (!target) return null;
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);
116 return target;
117 }
118 }
119 document.getElementById("tasks")!.appendChild(target);
120 return target;
121 },
122
123 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
124 const task = this.getTask(createTimestamp);
125 if (task) {
126 task.setAttribute("data-state", state);
127 }
128 },
129 };
130
131 function Log(prefix: string = "vp-") {
132 var next_log_index = 0;
133 return {
134 apply: function (entry: string) {
135 const [timestamp, command, data] = splitN(entry, " ", 2);
136 if (command == "Create") {
137 return Model.addTask(timestamp, data);
138 }
139 if (command == "Edit") {
140 const [createTimestamp, description] = splitN(data, " ", 1);
141 return Model.edit(createTimestamp, description);
142 }
143 if (command == "Priority") {
144 const [createTimestamp, newPriority] = splitN(data, " ", 1);
145 return Model.setPriority(createTimestamp, parseFloat(newPriority));
146 }
147 if (command == "State") {
148 const [createTimestamp, state] = splitN(data, " ", 1);
149 return Model.setState(timestamp, createTimestamp, state);
150 }
151 if (command == "Tag") {
152 const [createTimestamp, tag] = splitN(data, " ", 1);
153 return Model.addTag(createTimestamp, tag);
154 }
155 },
156
157 record: function (entry: string) {
158 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
159 },
160
161 recordAndApply: function (entry: string) {
162 this.record(entry);
163 return this.apply(entry);
164 },
165
166 replay: function () {
167 while (true) {
168 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
169 if (entry === null) {
170 break;
171 }
172 this.apply(entry);
173 next_log_index++;
174 }
175 },
176 };
177 }
178 const log = Log();
179
180 function 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 },
188 addTag: function (createTimestamp: string, tag: string) {
189 // TODO: undo
190 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
191 },
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 }
211 const ui = UI();
212
213 enum CommitOrAbort {
214 Commit,
215 Abort,
216 }
217
218 function BrowserUI() {
219 var currentViewState = "todo";
220 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
221 var lastTagNameEntered = "";
222 return {
223 addTask: function (event: KeyboardEvent) {
224 const input = <HTMLInputElement>document.getElementById("taskName");
225 if (input.value) {
226 const task = ui.addTask(input.value);
227 if (currentViewState === "todo") {
228 task instanceof HTMLElement && task.focus();
229 } else if (this.returnFocusAfterInput()) {
230 } else {
231 this.firstVisibleTask()?.focus();
232 }
233 input.value = "";
234 if (event.getModifierState("Control")) {
235 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
236 }
237 }
238 },
239
240 beginEdit: function (event: Event) {
241 const task = document.activeElement;
242 if (!task) return;
243 const input = document.createElement("input");
244 const desc = task.getElementsByClassName("desc")[0];
245 const oldDescription = desc.textContent!;
246 task.setAttribute("data-description", oldDescription);
247 input.value = oldDescription;
248 input.addEventListener("blur", this.completeEdit, { once: true });
249 desc.textContent = "";
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 });
261 input.value = lastTagNameEntered;
262 task.appendChild(input);
263 input.focus();
264 input.select();
265 event.preventDefault();
266 },
267
268 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
269 const input = event.target as HTMLInputElement;
270 const task = input.parentElement!;
271 const desc = task.getElementsByClassName("desc")[0];
272 const oldDescription = task.getAttribute("data-description")!;
273 const newDescription = input.value;
274 input.removeEventListener("blur", this.completeEdit);
275 task.removeChild(input);
276 task.removeAttribute("data-description");
277 task.focus();
278 if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) {
279 desc.textContent = oldDescription;
280 } else {
281 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
282 }
283 },
284
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();
292 if (resolution === CommitOrAbort.Commit && newTagName && !Model.hasTag(task, newTagName)) {
293 ui.addTag(task.getAttribute("data-created")!, newTagName);
294 lastTagNameEntered = newTagName;
295 }
296 },
297
298 firstVisibleTask: function () {
299 for (const task of document.getElementsByClassName("task")) {
300 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
301 return task;
302 }
303 }
304 },
305
306 focusTaskNameInput: function (event: Event) {
307 if (document.activeElement instanceof HTMLElement) {
308 taskFocusedBeforeJumpingToInput = document.activeElement;
309 }
310 document.getElementById("taskName")!.focus();
311 event.preventDefault();
312 },
313
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;
321 if (cursor.getAttribute("data-state")! === currentViewState) {
322 offset -= increment;
323 valid_cursor = cursor;
324 }
325 if (Math.abs(offset) < 0.5) break;
326 }
327 return valid_cursor;
328 },
329
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 },
340
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 },
354
355 returnFocusAfterInput: function (): boolean {
356 if (taskFocusedBeforeJumpingToInput) {
357 taskFocusedBeforeJumpingToInput.focus();
358 return true;
359 }
360 return false;
361 },
362
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;
373 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
374 task instanceof HTMLElement && task.focus();
375 },
376
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);
384 return ui.setState(createTimestamp, newState, oldState);
385 },
386
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
397 undo: function () {
398 const ret = ui.undo();
399 if (ret && ret instanceof HTMLElement) ret.focus();
400 },
401 };
402 }
403 const browserUI = BrowserUI();
404
405 enum InputState {
406 Command,
407 View,
408 }
409 var inputState = InputState.Command;
410
411 function handleKey(event: any) {
412 if (event.target.tagName === "INPUT") {
413 if (event.target.id === "taskName") {
414 if (event.key == "Enter") return browserUI.addTask(event);
415 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
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);
419 } else {
420 if (event.key == "Enter") return browserUI.completeEdit(event);
421 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
422 }
423 } else {
424 if (inputState === InputState.Command) {
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);
430 if (event.key == "c") return browserUI.setState("cancelled");
431 if (event.key == "d") return browserUI.setState("done");
432 if (event.key == "q") return browserUI.setState("todo");
433 if (event.key == "s") return browserUI.setState("someday-maybe");
434 if (event.key == "w") return browserUI.setState("waiting");
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);
438 if (event.key == "t") return browserUI.beginTagEdit(event);
439 if (event.key == "v") return (inputState = InputState.View);
440 } else if (inputState === InputState.View) {
441 inputState = InputState.Command;
442 if (event.key == "c") return browserUI.setView("cancelled");
443 if (event.key == "d") return browserUI.setView("done");
444 if (event.key == "q") return browserUI.setView("todo");
445 if (event.key == "s") return browserUI.setView("someday-maybe");
446 if (event.key == "w") return browserUI.setView("waiting");
447 if (event.key == "x") return browserUI.setView("deleted");
448 }
449 }
450 }
451
452 function browserInit() {
453 document.body.addEventListener("keydown", handleKey, { capture: false });
454 log.replay();
455 browserUI.firstVisibleTask()?.focus();
456 }