]> git.scottworley.com Git - vopamoi/blame - vopamoi.ts
Use CSS for filtering the view
[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
SW
152const undoLog: string[] = [];
153
e88c099c 154const UI = {
6d01c406 155 addTask: function (description: string): Element {
27c67784 156 const now = clock.now();
43f3cc0c
SW
157 undoLog.push(`State ${now} deleted`);
158 return <Element>log.recordAndApply(`${now} Create ${description}`);
e88c099c 159 },
7b574407
SW
160 edit: function (createTimestamp: string, newDescription: string, oldDescription: string) {
161 undoLog.push(`Edit ${createTimestamp} ${oldDescription}`);
27c67784 162 return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`);
7b574407 163 },
43f3cc0c
SW
164 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
165 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
27c67784 166 return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`);
68a72fde 167 },
5350da9f
SW
168 setState: function (createTimestamp: string, newState: string, oldState: string) {
169 undoLog.push(`State ${createTimestamp} ${oldState}`);
27c67784 170 return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`);
01f41859 171 },
43f3cc0c
SW
172 undo: function () {
173 if (undoLog.length > 0) {
27c67784 174 return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`);
43f3cc0c
SW
175 }
176 },
e88c099c
SW
177};
178
caa93fd1 179const BrowserUI = {
bc7996fe 180 addTask: function (event: KeyboardEvent) {
a26b1f4b
SW
181 const input = <HTMLInputElement>document.getElementById("taskName");
182 if (input.value) {
6d01c406 183 const task = UI.addTask(input.value);
9f6be65e 184 if (task && task instanceof HTMLElement) task.focus();
a26b1f4b 185 input.value = "";
bc7996fe
SW
186 if (event.getModifierState("Control")) {
187 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
188 }
caa93fd1 189 }
caa93fd1 190 },
09657615 191
7b574407
SW
192 beginEdit: function (event: Event) {
193 const task = document.activeElement;
194 if (!task) return;
195 const input = document.createElement("input");
196 const oldDescription = task.textContent!;
197 task.setAttribute("data-description", oldDescription);
198 input.value = oldDescription;
199 input.addEventListener("blur", BrowserUI.completeEdit, { once: true });
200 task.textContent = "";
201 task.appendChild(input);
202 input.focus();
203 input.select();
204 event.preventDefault();
205 },
206
207 completeEdit: function (event: Event) {
208 const input = event.target as HTMLInputElement;
209 const task = input.parentElement!;
210 const oldDescription = task.getAttribute("data-description")!;
211 const newDescription = input.value;
8ca3cda9 212 input.removeEventListener("blur", BrowserUI.completeEdit);
7b574407
SW
213 task.removeChild(task.children[0]);
214 task.removeAttribute("data-description");
215 task.focus();
216 if (newDescription === oldDescription) {
217 task.textContent = oldDescription;
218 } else {
219 UI.edit(task.getAttribute("data-created")!, newDescription, oldDescription);
220 }
221 },
222
65a7510d
SW
223 firstVisibleTask: function () {
224 for (const task of document.getElementsByClassName("task")) {
8e91a18e 225 if (task instanceof HTMLElement && task.getAttribute("data-state")! === "todo") {
65a7510d
SW
226 return task;
227 }
228 }
799f4e89 229 },
caa93fd1 230
bc7996fe 231 focusTaskNameInput: function (event: Event) {
09657615
SW
232 document.getElementById("taskName")!.focus();
233 event.preventDefault();
234 },
235
23be73e3
SW
236 visibleTaskAtOffset(task: Element, offset: number): Element {
237 var cursor: Element | null = task;
5fa4704c
SW
238 var valid_cursor = cursor;
239 const increment = offset / Math.abs(offset);
240 while (true) {
241 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
242 if (!cursor || !(cursor instanceof HTMLElement)) break;
8e91a18e 243 if (cursor.getAttribute("data-state")! === "todo") {
5fa4704c
SW
244 offset -= increment;
245 valid_cursor = cursor;
246 }
247 if (Math.abs(offset) < 0.5) break;
09657615 248 }
23be73e3
SW
249 return valid_cursor;
250 },
251
252 moveCursor: function (offset: number): boolean {
253 const active = document.activeElement;
254 if (!active) return false;
255 const dest = this.visibleTaskAtOffset(active, offset);
256 if (dest !== active && dest instanceof HTMLElement) {
257 dest.focus();
09657615
SW
258 return true;
259 }
260 return false;
261 },
01f41859 262
68a72fde
SW
263 moveTask: function (offset: number) {
264 const active = document.activeElement;
265 if (!active) return;
266 const dest = this.visibleTaskAtOffset(active, offset);
267 if (dest === active) return; // Already extremal
268 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
269 if (onePastDest == dest) onePastDest = null; // Will become extremal
270 if (offset > 0) {
271 this.setPriority(active, dest, onePastDest);
272 } else {
273 this.setPriority(active, onePastDest, dest);
274 }
275 },
276
277 // Change task's priority to be between other tasks a and b.
278 setPriority: function (task: Element, a: Element | null, b: Element | null) {
279 const aPriority = a === null ? 0 : Model.getPriority(a);
27c67784 280 const bPriority = b === null ? clock.now() : Model.getPriority(b);
68a72fde
SW
281 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
282 const span = bPriority - aPriority;
283 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
284 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
285 const newPriorityRounded = Math.round(newPriority);
286 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
43f3cc0c 287 UI.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
9f6be65e 288 task instanceof HTMLElement && task.focus();
68a72fde
SW
289 },
290
da9a2716 291 setState: function (newState: string) {
5350da9f
SW
292 const task = document.activeElement;
293 if (!task) return;
8e91a18e 294 const oldState = task.getAttribute("data-state")!;
da9a2716 295 if (newState === oldState) return;
5350da9f 296 const createTimestamp = task.getAttribute("data-created")!;
01f41859 297 this.moveCursor(1) || this.moveCursor(-1);
da9a2716 298 return UI.setState(createTimestamp, newState, oldState);
01f41859 299 },
43f3cc0c
SW
300
301 undo: function () {
302 const ret = UI.undo();
303 if (ret && ret instanceof HTMLElement) ret.focus();
304 },
09657615 305};
06ee32a1 306
e94e9f27
SW
307enum InputState {
308 Command,
854992ec 309 View,
e94e9f27
SW
310}
311var inputState = InputState.Command;
312
f1afad9b 313function handleKey(event: any) {
a26b1f4b 314 if (event.target.tagName === "INPUT") {
7b574407
SW
315 if (event.target.id === "taskName") {
316 if (event.key == "Enter") return BrowserUI.addTask(event);
317 } else {
318 if (event.key == "Enter") return BrowserUI.completeEdit(event);
319 }
a26b1f4b 320 } else {
e94e9f27
SW
321 if (inputState === InputState.Command) {
322 if (event.key == "j") return BrowserUI.moveCursor(1);
323 if (event.key == "k") return BrowserUI.moveCursor(-1);
324 if (event.key == "J") return BrowserUI.moveTask(1);
325 if (event.key == "K") return BrowserUI.moveTask(-1);
326 if (event.key == "n") return BrowserUI.focusTaskNameInput(event);
327 if (event.key == "s") return BrowserUI.setState("someday-maybe");
328 if (event.key == "w") return BrowserUI.setState("waiting");
329 if (event.key == "d") return BrowserUI.setState("done");
330 if (event.key == "c") return BrowserUI.setState("cancelled");
331 if (event.key == "t") return BrowserUI.setState("todo");
332 if (event.key == "X") return BrowserUI.setState("deleted");
333 if (event.key == "u") return BrowserUI.undo();
334 if (event.key == "e") return BrowserUI.beginEdit(event);
854992ec
SW
335 if (event.key == "v") return (inputState = InputState.View);
336 } else if (inputState === InputState.View) {
337 return (inputState = InputState.Command);
e94e9f27 338 }
f1afad9b
SW
339 }
340}
341
f1afad9b
SW
342function browserInit() {
343 document.body.addEventListener("keydown", handleKey, { capture: false });
d03daa19 344 log.replay();
65a7510d 345 BrowserUI.firstVisibleTask()?.focus();
f1afad9b 346}