]> git.scottworley.com Git - vopamoi/blob - vopamoi.ts
Tasks have one state. Enables undo for state changes
[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 const Model = {
17 addTask: function (timestamp: string, description: string): Element {
18 const task = document.createElement("div");
19 task.appendChild(document.createTextNode(description));
20 task.setAttribute("class", "task");
21 task.setAttribute("tabindex", "0");
22 task.setAttribute("data-created", timestamp);
23 document.getElementById("tasks")!.appendChild(task);
24 task.focus();
25 return task;
26 },
27
28 getPriority: function (task: Element): number {
29 if (task.hasAttribute("data-priority")) {
30 return parseFloat(task.getAttribute("data-priority")!);
31 }
32 return parseFloat(task.getAttribute("data-created")!);
33 },
34
35 getState: function (task: Element): string {
36 return task.getAttribute("data-state") ?? "todo";
37 },
38
39 getTask: function (createTimestamp: string) {
40 for (const task of document.getElementsByClassName("task")) {
41 if (task.getAttribute("data-created") === createTimestamp) {
42 return task;
43 }
44 }
45 },
46
47 setPriority: function (createTimestamp: string, priority: number): Element | null {
48 const target = this.getTask(createTimestamp);
49 if (!target) return null;
50 target.setAttribute("data-priority", `${priority}`);
51 for (const task of document.getElementsByClassName("task")) {
52 if (task !== target && this.getPriority(task) > priority) {
53 task.parentElement!.insertBefore(target, task);
54 target instanceof HTMLElement && target.focus();
55 return target;
56 }
57 }
58 document.getElementById("tasks")!.appendChild(target);
59 target instanceof HTMLElement && target.focus();
60 return target;
61 },
62
63 setState: function (stateTimestamp: string, createTimestamp: string, state: string) {
64 const task = this.getTask(createTimestamp);
65 if (task) {
66 task.setAttribute("data-state", state);
67 if (task instanceof HTMLElement) {
68 task.style.display = state == "todo" ? "block" : "none"; // Until view filtering
69 }
70 }
71 },
72 };
73
74 function Log(prefix: string = "vp-") {
75 var next_log_index = 0;
76 return {
77 apply: function (entry: string) {
78 const [timestamp, command, data] = splitN(entry, " ", 2);
79 if (command == "Create") {
80 return Model.addTask(timestamp, data);
81 }
82 if (command == "State") {
83 const [createTimestamp, state] = splitN(data, " ", 1);
84 return Model.setState(timestamp, createTimestamp, state);
85 }
86 if (command == "Priority") {
87 const [createTimestamp, newPriority] = splitN(data, " ", 1);
88 return Model.setPriority(createTimestamp, parseFloat(newPriority));
89 }
90 },
91
92 record: function (entry: string) {
93 window.localStorage.setItem(`${prefix}${next_log_index++}`, entry);
94 },
95
96 recordAndApply: function (entry: string) {
97 this.record(entry);
98 return this.apply(entry);
99 },
100
101 replay: function () {
102 while (true) {
103 const entry = window.localStorage.getItem(`${prefix}${next_log_index}`);
104 if (entry === null) {
105 break;
106 }
107 this.apply(entry);
108 next_log_index++;
109 }
110 },
111 };
112 }
113 const log = Log();
114
115 const undoLog: string[] = [];
116
117 const UI = {
118 addTask: function (description: string): Element {
119 const now = Date.now();
120 undoLog.push(`State ${now} deleted`);
121 return <Element>log.recordAndApply(`${now} Create ${description}`);
122 },
123 setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) {
124 undoLog.push(`Priority ${createTimestamp} ${oldPriority}`);
125 return log.recordAndApply(`${Date.now()} Priority ${createTimestamp} ${newPriority}`);
126 },
127 setState: function (createTimestamp: string, newState: string, oldState: string) {
128 undoLog.push(`State ${createTimestamp} ${oldState}`);
129 return log.recordAndApply(`${Date.now()} State ${createTimestamp} ${newState}`);
130 },
131 undo: function () {
132 if (undoLog.length > 0) {
133 return log.recordAndApply(`${Date.now()} ${undoLog.pop()}`);
134 }
135 },
136 };
137
138 const BrowserUI = {
139 addTask: function (event: KeyboardEvent) {
140 const input = <HTMLInputElement>document.getElementById("taskName");
141 if (input.value) {
142 const task = UI.addTask(input.value);
143 input.value = "";
144 if (event.getModifierState("Control")) {
145 this.setPriority(task, null, document.getElementsByClassName("task")[0]);
146 }
147 }
148 },
149
150 firstVisibleTask: function () {
151 for (const task of document.getElementsByClassName("task")) {
152 if (task instanceof HTMLElement && task.style.display !== "none") {
153 return task;
154 }
155 }
156 },
157
158 focusTaskNameInput: function (event: Event) {
159 document.getElementById("taskName")!.focus();
160 event.preventDefault();
161 },
162
163 visibleTaskAtOffset(task: Element, offset: number): Element {
164 var cursor: Element | null = task;
165 var valid_cursor = cursor;
166 const increment = offset / Math.abs(offset);
167 while (true) {
168 cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling;
169 if (!cursor || !(cursor instanceof HTMLElement)) break;
170 if (cursor.style.display !== "none") {
171 offset -= increment;
172 valid_cursor = cursor;
173 }
174 if (Math.abs(offset) < 0.5) break;
175 }
176 return valid_cursor;
177 },
178
179 moveCursor: function (offset: number): boolean {
180 const active = document.activeElement;
181 if (!active) return false;
182 const dest = this.visibleTaskAtOffset(active, offset);
183 if (dest !== active && dest instanceof HTMLElement) {
184 dest.focus();
185 return true;
186 }
187 return false;
188 },
189
190 moveTask: function (offset: number) {
191 const active = document.activeElement;
192 if (!active) return;
193 const dest = this.visibleTaskAtOffset(active, offset);
194 if (dest === active) return; // Already extremal
195 var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset));
196 if (onePastDest == dest) onePastDest = null; // Will become extremal
197 if (offset > 0) {
198 this.setPriority(active, dest, onePastDest);
199 } else {
200 this.setPriority(active, onePastDest, dest);
201 }
202 },
203
204 // Change task's priority to be between other tasks a and b.
205 setPriority: function (task: Element, a: Element | null, b: Element | null) {
206 const aPriority = a === null ? 0 : Model.getPriority(a);
207 const bPriority = b === null ? Date.now() : Model.getPriority(b);
208 console.assert(aPriority < bPriority, aPriority, "<", bPriority);
209 const span = bPriority - aPriority;
210 const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random();
211 console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority);
212 const newPriorityRounded = Math.round(newPriority);
213 const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority;
214 UI.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task));
215 },
216
217 setState: function (state: string) {
218 const task = document.activeElement;
219 if (!task) return;
220 const createTimestamp = task.getAttribute("data-created")!;
221 this.moveCursor(1) || this.moveCursor(-1);
222 return UI.setState(createTimestamp, state, Model.getState(task));
223 },
224
225 undo: function () {
226 const ret = UI.undo();
227 if (ret && ret instanceof HTMLElement) ret.focus();
228 },
229 };
230
231 function handleKey(event: any) {
232 if (event.target.tagName === "INPUT") {
233 if (event.key == "Enter") return BrowserUI.addTask(event);
234 } else {
235 if (event.key == "j") return BrowserUI.moveCursor(1);
236 if (event.key == "k") return BrowserUI.moveCursor(-1);
237 if (event.key == "J") return BrowserUI.moveTask(1);
238 if (event.key == "K") return BrowserUI.moveTask(-1);
239 if (event.key == "n") return BrowserUI.focusTaskNameInput(event);
240 if (event.key == "s") return BrowserUI.setState("someday-maybe");
241 if (event.key == "w") return BrowserUI.setState("waiting");
242 if (event.key == "d") return BrowserUI.setState("done");
243 if (event.key == "c") return BrowserUI.setState("cancelled");
244 if (event.key == "X") return BrowserUI.setState("deleted");
245 if (event.key == "u") return BrowserUI.undo();
246 }
247 }
248
249 function browserInit() {
250 document.body.addEventListener("keydown", handleKey, { capture: false });
251 log.replay();
252 BrowserUI.firstVisibleTask()?.focus();
253 }