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