]> git.scottworley.com Git - vopamoi/blame_incremental - vopamoi.ts
Always return to command mode (leave input box) after creating a task
[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.setAttribute("class", "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 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
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
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
85 setPriority: function (createTimestamp: string, priority: number): Element | null {
86 const target = this.getTask(createTimestamp);
87 if (!target) return null;
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);
92 return target;
93 }
94 }
95 document.getElementById("tasks")!.appendChild(target);
96 return target;
97 },
98
99 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
100 const task = this.getTask(createTimestamp);
101 if (task) {
102 task.setAttribute("data-state", state);
103 }
104 },
105};
106
107function Log(prefix: string = "vp-") {
108 var next_log_index = 0;
109 return {
110 apply: function (entry: string) {
111 const [timestamp, command, data] = splitN(entry, " ", 2);
112 if (command == "Create") {
113 return Model.addTask(timestamp, data);
114 }
115 if (command == "Edit") {
116 const [createTimestamp, description] = splitN(data, " ", 1);
117 return Model.edit(createTimestamp, description);
118 }
119 if (command == "State") {
120 const [createTimestamp, state] = splitN(data, " ", 1);
121 return Model.setState(timestamp, createTimestamp, state);
122 }
123 if (command == "Priority") {
124 const [createTimestamp, newPriority] = splitN(data, " ", 1);
125 return Model.setPriority(createTimestamp, parseFloat(newPriority));
126 }
127 },
128
129 record: function (entry: string) {
130 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
131 },
132
133 recordAndApply: function (entry: string) {
134 this.record(entry);
135 return this.apply(entry);
136 },
137
138 replay: function () {
139 while (true) {
140 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
141 if (entry === null) {
142 break;
143 }
144 this.apply(entry);
145 next_log_index++;
146 }
147 },
148 };
149}
150const log = Log();
151
152function UI() {
153 const undoLog: string[] = [];
154 return {
155 addTask: function (description: string): Element {
156 const now = clock.now();
157 undoLog.push(`State ${now} deleted`);
158 return <Element>log.recordAndApply(`${now} Create ${description}`);
159 },
160 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
161 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
162 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
163 },
164 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
165 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
166 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
167 },
168 setState: function (createTimestamp: string, newState: string, oldState: string) {
169 undoLog.push(`State ${createTimestamp} ${oldState}`);
170 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
171 },
172 undo: function () {
173 if (undoLog.length > 0) {
174 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
175 }
176 },
177 };
178}
179const ui = UI();
180
181function BrowserUI() {
182 var currentViewState = "todo";
183 var taskFocusedBeforeJumpingToInput: HTMLElement | null = null;
184 return {
185 addTask: function (event: KeyboardEvent) {
186 const input = <HTMLInputElement>document.getElementById("taskName");
187 if (input.value) {
188 const task = ui.addTask(input.value);
189 if (currentViewState === "todo") {
190 task instanceof HTMLElement && task.focus();
191 } else if (this.returnFocusAfterInput()) {
192 } else {
193 this.firstVisibleTask()?.focus();
194 }
195 input.value = "";
196 if (event.getModifierState("Control")) {
197 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
198 }
199 }
200 },
201
202 beginEdit: function (event: Event) {
203 const task = document.activeElement;
204 if (!task) return;
205 const input = document.createElement("input");
206 const oldDescription = task.textContent!;
207 task.setAttribute("data-description", oldDescription);
208 input.value = oldDescription;
209 input.addEventListener("blur", this.completeEdit, { once: true });
210 task.textContent = "";
211 task.appendChild(input);
212 input.focus();
213 input.select();
214 event.preventDefault();
215 },
216
217 completeEdit: function (event: Event) {
218 const input = event.target as HTMLInputElement;
219 const task = input.parentElement!;
220 const oldDescription = task.getAttribute("data-description")!;
221 const newDescription = input.value;
222 input.removeEventListener("blur", this.completeEdit);
223 task.removeChild(task.children[0]);
224 task.removeAttribute("data-description");
225 task.focus();
226 if (newDescription === oldDescription) {
227 task.textContent = oldDescription;
228 } else {
229 ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
230 }
231 },
232
233 firstVisibleTask: function () {
234 for (const task of document.getElementsByClassName("task")) {
235 if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) {
236 return task;
237 }
238 }
239 },
240
241 focusTaskNameInput: function (event: Event) {
242 if (document.activeElement instanceof HTMLElement) {
243 taskFocusedBeforeJumpingToInput = document.activeElement;
244 }
245 document.getElementById("taskName")!.focus();
246 event.preventDefault();
247 },
248
249 visibleTaskAtOffset(task: Element, offset: number): Element {
250 var cursor: Element | null = task;
251 var valid_cursor = cursor;
252 const increment = offset / Math.abs(offset);
253 while (true) {
254 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
255 if (!cursor || !(cursor instanceof HTMLElement)) break;
256 if (cursor.getAttribute("data-state")! === currentViewState) {
257 offset -= increment;
258 valid_cursor = cursor;
259 }
260 if (Math.abs(offset) < 0.5) break;
261 }
262 return valid_cursor;
263 },
264
265 moveCursor: function (offset: number): boolean {
266 const active = document.activeElement;
267 if (!active) return false;
268 const dest = this.visibleTaskAtOffset(active, offset);
269 if (dest !== active && dest instanceof HTMLElement) {
270 dest.focus();
271 return true;
272 }
273 return false;
274 },
275
276 moveTask: function (offset: number) {
277 const active = document.activeElement;
278 if (!active) return;
279 const dest = this.visibleTaskAtOffset(active, offset);
280 if (dest === active) return; // Already extremal
281 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
282 if (onePastDest == dest) onePastDest = null; // Will become extremal
283 if (offset > 0) {
284 this.setPriority(active, dest, onePastDest);
285 } else {
286 this.setPriority(active, onePastDest, dest);
287 }
288 },
289
290 returnFocusAfterInput: function (): boolean {
291 if (taskFocusedBeforeJumpingToInput) {
292 taskFocusedBeforeJumpingToInput.focus();
293 return true;
294 }
295 return false;
296 },
297
298 // Change task's priority to be between other tasks a and b.
299 setPriority: function (task: Element, a: Element | null, b: Element | null) {
300 const aPriority = a === null ? 0 : Model.getPriority(a);
301 const bPriority = b === null ? clock.now() : Model.getPriority(b);
302 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
303 const span = bPriority - aPriority;
304 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
305 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
306 const newPriorityRounded = Math.round(newPriority);
307 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
308 ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
309 task instanceof HTMLElement && task.focus();
310 },
311
312 setState: function (newState: string) {
313 const task = document.activeElement;
314 if (!task) return;
315 const oldState = task.getAttribute("data-state")!;
316 if (newState === oldState) return;
317 const createTimestamp = task.getAttribute("data-created")!;
318 this.moveCursor(1) || this.moveCursor(-1);
319 return ui.setState(createTimestamp, newState, oldState);
320 },
321
322 setView: function (state: string) {
323 const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!;
324 sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`);
325 sheet.removeRule(1);
326 currentViewState = state;
327 if (document.activeElement?.getAttribute("data-state") !== state) {
328 this.firstVisibleTask()?.focus();
329 }
330 },
331
332 undo: function () {
333 const ret = ui.undo();
334 if (ret && ret instanceof HTMLElement) ret.focus();
335 },
336 };
337}
338const browserUI = BrowserUI();
339
340enum InputState {
341 Command,
342 View,
343}
344var inputState = InputState.Command;
345
346function handleKey(event: any) {
347 if (event.target.tagName === "INPUT") {
348 if (event.target.id === "taskName") {
349 if (event.key == "Enter") return browserUI.addTask(event);
350 if (event.key == "Escape") return browserUI.returnFocusAfterInput();
351 } else {
352 if (event.key == "Enter") return browserUI.completeEdit(event);
353 }
354 } else {
355 if (inputState === InputState.Command) {
356 if (event.key == "j") return browserUI.moveCursor(1);
357 if (event.key == "k") return browserUI.moveCursor(-1);
358 if (event.key == "J") return browserUI.moveTask(1);
359 if (event.key == "K") return browserUI.moveTask(-1);
360 if (event.key == "n") return browserUI.focusTaskNameInput(event);
361 if (event.key == "c") return browserUI.setState("cancelled");
362 if (event.key == "d") return browserUI.setState("done");
363 if (event.key == "s") return browserUI.setState("someday-maybe");
364 if (event.key == "t") return browserUI.setState("todo");
365 if (event.key == "w") return browserUI.setState("waiting");
366 if (event.key == "X") return browserUI.setState("deleted");
367 if (event.key == "u") return browserUI.undo();
368 if (event.key == "e") return browserUI.beginEdit(event);
369 if (event.key == "v") return (inputState = InputState.View);
370 } else if (inputState === InputState.View) {
371 inputState = InputState.Command;
372 if (event.key == "c") return browserUI.setView("cancelled");
373 if (event.key == "d") return browserUI.setView("done");
374 if (event.key == "s") return browserUI.setView("someday-maybe");
375 if (event.key == "t") return browserUI.setView("todo");
376 if (event.key == "w") return browserUI.setView("waiting");
377 if (event.key == "x") return browserUI.setView("deleted");
378 }
379 }
380}
381
382function browserInit() {
383 document.body.addEventListener("keydown", handleKey, { capture: false });
384 log.replay();
385 browserUI.firstVisibleTask()?.focus();
386}