]> git.scottworley.com Git - vopamoi/blame_incremental - vopamoi.ts
Don't attempt to create duplicate tags
[vopamoi] / vopamoi.ts
... / ...
CommitLineData
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
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
32const 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 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
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
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
104 setPriority: function (createTimestamp: string, priority: number): Element | null {
105 const target = this.getTask(createTimestamp);
106 if (!target) return null;
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);
111 return target;
112 }
113 }
114 document.getElementById("tasks")!.appendChild(target);
115 return target;
116 },
117
118 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
119 const task = this.getTask(createTimestamp);
120 if (task) {
121 task.setAttribute("data-state", state);
122 }
123 },
124};
125
126function Log(prefix: string = "vp-") {
127 var next_log_index = 0;
128 return {
129 apply: function (entry: string) {
130 const [timestamp, command, data] = splitN(entry, " ", 2);
131 if (command == "Create") {
132 return Model.addTask(timestamp, data);
133 }
134 if (command == "Edit") {
135 const [createTimestamp, description] = splitN(data, " ", 1);
136 return Model.edit(createTimestamp, description);
137 }
138 if (command == "Priority") {
139 const [createTimestamp, newPriority] = splitN(data, " ", 1);
140 return Model.setPriority(createTimestamp, parseFloat(newPriority));
141 }
142 if (command == "State") {
143 const [createTimestamp, state] = splitN(data, " ", 1);
144 return Model.setState(timestamp, createTimestamp, state);
145 }
146 if (command == "Tag") {
147 const [createTimestamp, tag] = splitN(data, " ", 1);
148 return Model.addTag(createTimestamp, tag);
149 }
150 },
151
152 record: function (entry: string) {
153 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
154 },
155
156 recordAndApply: function (entry: string) {
157 this.record(entry);
158 return this.apply(entry);
159 },
160
161 replay: function () {
162 while (true) {
163 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
164 if (entry === null) {
165 break;
166 }
167 this.apply(entry);
168 next_log_index++;
169 }
170 },
171 };
172}
173const log = Log();
174
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 },
183 addTag: function (createTimestamp: string, tag: string) {
184 // TODO: undo
185 return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`);
186 },
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();
207
208enum CommitOrAbort {
209 Commit,
210 Abort,
211}
212
213function BrowserUI() {
214 var currentViewState = "todo";
215 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
216 return {
217 addTask: function (event: KeyboardEvent) {
218 const input = <HTMLInputElement>document.getElementById("taskName");
219 if (input.value) {
220 const task = ui.addTask(input.value);
221 if (currentViewState === "todo") {
222 task instanceof HTMLElement && task.focus();
223 } else if (this.returnFocusAfterInput()) {
224 } else {
225 this.firstVisibleTask()?.focus();
226 }
227 input.value = "";
228 if (event.getModifierState("Control")) {
229 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
230 }
231 }
232 },
233
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 = "";
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 });
254 task.appendChild(input);
255 input.focus();
256 event.preventDefault();
257 },
258
259 completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) {
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);
265 task.removeChild(input);
266 task.removeAttribute("data-description");
267 task.focus();
268 if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) {
269 task.textContent = oldDescription;
270 } else {
271 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
272 }
273 },
274
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();
282 if (!Model.hasTag(task, newTagName)) {
283 ui.addTag(task.getAttribute("data-created")!, newTagName);
284 }
285 },
286
287 firstVisibleTask: function () {
288 for (const task of document.getElementsByClassName("task")) {
289 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
290 return task;
291 }
292 }
293 },
294
295 focusTaskNameInput: function (event: Event) {
296 if (document.activeElement instanceof HTMLElement) {
297 taskFocusedBeforeJumpingToInput = document.activeElement;
298 }
299 document.getElementById("taskName")!.focus();
300 event.preventDefault();
301 },
302
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;
310 if (cursor.getAttribute("data-state")! === currentViewState) {
311 offset -= increment;
312 valid_cursor = cursor;
313 }
314 if (Math.abs(offset) < 0.5) break;
315 }
316 return valid_cursor;
317 },
318
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 },
329
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 },
343
344 returnFocusAfterInput: function (): boolean {
345 if (taskFocusedBeforeJumpingToInput) {
346 taskFocusedBeforeJumpingToInput.focus();
347 return true;
348 }
349 return false;
350 },
351
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;
362 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
363 task instanceof HTMLElement && task.focus();
364 },
365
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);
373 return ui.setState(createTimestamp, newState, oldState);
374 },
375
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
386 undo: function () {
387 const ret = ui.undo();
388 if (ret && ret instanceof HTMLElement) ret.focus();
389 },
390 };
391}
392const browserUI = BrowserUI();
393
394enum InputState {
395 Command,
396 View,
397}
398var inputState = InputState.Command;
399
400function handleKey(event: any) {
401 if (event.target.tagName === "INPUT") {
402 if (event.target.id === "taskName") {
403 if (event.key == "Enter") return browserUI.addTask(event);
404 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
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);
408 } else {
409 if (event.key == "Enter") return browserUI.completeEdit(event);
410 if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort);
411 }
412 } else {
413 if (inputState === InputState.Command) {
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);
419 if (event.key == "c") return browserUI.setState("cancelled");
420 if (event.key == "d") return browserUI.setState("done");
421 if (event.key == "q") return browserUI.setState("todo");
422 if (event.key == "s") return browserUI.setState("someday-maybe");
423 if (event.key == "w") return browserUI.setState("waiting");
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);
427 if (event.key == "t") return browserUI.beginTagEdit(event);
428 if (event.key == "v") return (inputState = InputState.View);
429 } else if (inputState === InputState.View) {
430 inputState = InputState.Command;
431 if (event.key == "c") return browserUI.setView("cancelled");
432 if (event.key == "d") return browserUI.setView("done");
433 if (event.key == "q") return browserUI.setView("todo");
434 if (event.key == "s") return browserUI.setView("someday-maybe");
435 if (event.key == "w") return browserUI.setView("waiting");
436 if (event.key == "x") return browserUI.setView("deleted");
437 }
438 }
439}
440
441function browserInit() {
442 document.body.addEventListener("keydown", handleKey, { capture: false });
443 log.replay();
444 browserUI.firstVisibleTask()?.focus();
445}