]>
Commit | Line | Data |
---|---|---|
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 | // A clock that never goes backwards; monotonic. | |
17 | function 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 | } | |
30 | const clock = Clock(); | |
31 | ||
32 | // Returns a promise for a hue based on a hash of the string | |
33 | function hashHue(str: string) { | |
34 | // Using crypto for this is overkill | |
35 | return crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)).then((buf) => (new Uint16Array(buf)[0] * 360) / 2 ** 16); | |
36 | } | |
37 | ||
38 | const Model = { | |
39 | addTask: function (timestamp: string, description: string): Element { | |
40 | const task = document.createElement("div"); | |
41 | const desc = document.createElement("span"); | |
42 | desc.textContent = description; | |
43 | desc.classList.add("desc"); | |
44 | task.appendChild(desc); | |
45 | task.classList.add("task"); | |
46 | task.setAttribute("tabindex", "0"); | |
47 | task.setAttribute("data-created", timestamp); | |
48 | task.setAttribute("data-state", "todo"); | |
49 | document.getElementById("tasks")!.appendChild(task); | |
50 | return task; | |
51 | }, | |
52 | ||
53 | addTag: function (createTimestamp: string, tagName: string): Element | null { | |
54 | const task = this.getTask(createTimestamp); | |
55 | if (!task) return null; | |
56 | const existingTag = this.hasTag(task, tagName); | |
57 | if (existingTag) return existingTag; | |
58 | const tag = document.createElement("span"); | |
59 | tag.appendChild(document.createTextNode(tagName)); | |
60 | tag.classList.add("tag"); | |
61 | tag.setAttribute("tabindex", "0"); | |
62 | hashHue(tagName).then((hue) => (tag.style.backgroundColor = `hsl(${hue},90%,45%)`)); | |
63 | task.appendChild(tag); | |
64 | return tag; | |
65 | }, | |
66 | ||
67 | edit: function (createTimestamp: string, newDescription: string): Element | null { | |
68 | const target = this.getTask(createTimestamp); | |
69 | if (!target) return null; | |
70 | if (target.hasAttribute("data-description")) { | |
71 | // Oh no: An edit has arrived from a replica while a local edit is in progress. | |
72 | const input = target.firstChild as HTMLInputElement; | |
73 | if ( | |
74 | input.value === target.getAttribute("data-description") && | |
75 | input.selectionStart === input.value.length && | |
76 | input.selectionEnd === input.value.length | |
77 | ) { | |
78 | // No local changes have actually been made yet. Change the contents of the edit box! | |
79 | input.value = newDescription; | |
80 | } else { | |
81 | // No great options. | |
82 | // Prefer not to interrupt the local user's edit. | |
83 | // The remote edit is mostly lost; this mostly becomes last-write-wins. | |
84 | target.setAttribute("data-description", newDescription); | |
85 | } | |
86 | } else { | |
87 | target.getElementsByClassName("desc")[0].textContent = newDescription; | |
88 | } | |
89 | return target; | |
90 | }, | |
91 | ||
92 | hasTag: function (task: Element, tag: string): Element | null { | |
93 | for (const child of task.getElementsByClassName("tag")) { | |
94 | if (child.textContent === tag) { | |
95 | return child; | |
96 | } | |
97 | } | |
98 | return null; | |
99 | }, | |
100 | ||
101 | getPriority: function (task: Element): number { | |
102 | if (task.hasAttribute("data-priority")) { | |
103 | return parseFloat(task.getAttribute("data-priority")!); | |
104 | } | |
105 | return parseFloat(task.getAttribute("data-created")!); | |
106 | }, | |
107 | ||
108 | getTask: function (createTimestamp: string) { | |
109 | for (const task of document.getElementsByClassName("task")) { | |
110 | if (task.getAttribute("data-created") === createTimestamp) { | |
111 | return task; | |
112 | } | |
113 | } | |
114 | }, | |
115 | ||
116 | setPriority: function (createTimestamp: string, priority: number): Element | null { | |
117 | const target = this.getTask(createTimestamp); | |
118 | if (!target) return null; | |
119 | target.setAttribute("data-priority", `${priority}`); | |
120 | for (const task of document.getElementsByClassName("task")) { | |
121 | if (task !== target && this.getPriority(task) > priority) { | |
122 | task.parentElement!.insertBefore(target, task); | |
123 | return target; | |
124 | } | |
125 | } | |
126 | document.getElementById("tasks")!.appendChild(target); | |
127 | return target; | |
128 | }, | |
129 | ||
130 | setState: function (stateTimestamp: string, createTimestamp: string, state: string) { | |
131 | const task = this.getTask(createTimestamp); | |
132 | if (task) { | |
133 | task.setAttribute("data-state", state); | |
134 | } | |
135 | }, | |
136 | }; | |
137 | ||
138 | function Log(prefix: string = "vp-") { | |
139 | var next_log_index = 0; | |
140 | return { | |
141 | apply: function (entry: string) { | |
142 | const [timestamp, command, data] = splitN(entry, " ", 2); | |
143 | if (command == "Create") { | |
144 | return Model.addTask(timestamp, data); | |
145 | } | |
146 | if (command == "Edit") { | |
147 | const [createTimestamp, description] = splitN(data, " ", 1); | |
148 | return Model.edit(createTimestamp, description); | |
149 | } | |
150 | if (command == "Priority") { | |
151 | const [createTimestamp, newPriority] = splitN(data, " ", 1); | |
152 | return Model.setPriority(createTimestamp, parseFloat(newPriority)); | |
153 | } | |
154 | if (command == "State") { | |
155 | const [createTimestamp, state] = splitN(data, " ", 1); | |
156 | return Model.setState(timestamp, createTimestamp, state); | |
157 | } | |
158 | if (command == "Tag") { | |
159 | const [createTimestamp, tag] = splitN(data, " ", 1); | |
160 | return Model.addTag(createTimestamp, tag); | |
161 | } | |
162 | }, | |
163 | ||
164 | record: function (entry: string) { | |
165 | window.localStorage.setItem(`${prefix}${next_log_index++}`, entry); | |
166 | }, | |
167 | ||
168 | recordAndApply: function (entry: string) { | |
169 | this.record(entry); | |
170 | return this.apply(entry); | |
171 | }, | |
172 | ||
173 | replay: function () { | |
174 | while (true) { | |
175 | const entry = window.localStorage.getItem(`${prefix}${next_log_index}`); | |
176 | if (entry === null) { | |
177 | break; | |
178 | } | |
179 | this.apply(entry); | |
180 | next_log_index++; | |
181 | } | |
182 | }, | |
183 | }; | |
184 | } | |
185 | const log = Log(); | |
186 | ||
187 | function UI() { | |
188 | const undoLog: string[] = []; | |
189 | return { | |
190 | addTask: function (description: string): Element { | |
191 | const now = clock.now(); | |
192 | undoLog.push(`State ${now} deleted`); | |
193 | return <Element>log.recordAndApply(`${now} Create ${description}`); | |
194 | }, | |
195 | addTag: function (createTimestamp: string, tag: string) { | |
196 | // TODO: undo | |
197 | return log.recordAndApply(`${clock.now()} Tag ${createTimestamp} ${tag}`); | |
198 | }, | |
199 | edit: function (createTimestamp: string, newDescription: string, oldDescription: string) { | |
200 | undoLog.push(`Edit ${createTimestamp} ${oldDescription}`); | |
201 | return log.recordAndApply(`${clock.now()} Edit ${createTimestamp} ${newDescription}`); | |
202 | }, | |
203 | setPriority: function (createTimestamp: string, newPriority: number, oldPriority: number) { | |
204 | undoLog.push(`Priority ${createTimestamp} ${oldPriority}`); | |
205 | return log.recordAndApply(`${clock.now()} Priority ${createTimestamp} ${newPriority}`); | |
206 | }, | |
207 | setState: function (createTimestamp: string, newState: string, oldState: string) { | |
208 | undoLog.push(`State ${createTimestamp} ${oldState}`); | |
209 | return log.recordAndApply(`${clock.now()} State ${createTimestamp} ${newState}`); | |
210 | }, | |
211 | undo: function () { | |
212 | if (undoLog.length > 0) { | |
213 | return log.recordAndApply(`${clock.now()} ${undoLog.pop()}`); | |
214 | } | |
215 | }, | |
216 | }; | |
217 | } | |
218 | const ui = UI(); | |
219 | ||
220 | enum CommitOrAbort { | |
221 | Commit, | |
222 | Abort, | |
223 | } | |
224 | ||
225 | function BrowserUI() { | |
226 | var currentViewState = "todo"; | |
227 | var taskFocusedBeforeJumpingToInput: HTMLElement | null = null; | |
228 | var lastTagNameEntered = ""; | |
229 | return { | |
230 | addTask: function (event: KeyboardEvent) { | |
231 | const input = <HTMLInputElement>document.getElementById("taskName"); | |
232 | if (input.value) { | |
233 | const task = ui.addTask(input.value); | |
234 | if (currentViewState === "todo") { | |
235 | task instanceof HTMLElement && task.focus(); | |
236 | } else if (this.returnFocusAfterInput()) { | |
237 | } else { | |
238 | this.firstVisibleTask()?.focus(); | |
239 | } | |
240 | input.value = ""; | |
241 | if (event.getModifierState("Control")) { | |
242 | this.setPriority(task, null, document.getElementsByClassName("task")[0]); | |
243 | } | |
244 | } | |
245 | }, | |
246 | ||
247 | beginEdit: function (event: Event) { | |
248 | const task = document.activeElement; | |
249 | if (!task) return; | |
250 | const input = document.createElement("input"); | |
251 | const desc = task.getElementsByClassName("desc")[0]; | |
252 | const oldDescription = desc.textContent!; | |
253 | task.setAttribute("data-description", oldDescription); | |
254 | input.value = oldDescription; | |
255 | input.addEventListener("blur", this.completeEdit, { once: true }); | |
256 | desc.textContent = ""; | |
257 | task.insertBefore(input, task.firstChild); | |
258 | input.focus(); | |
259 | event.preventDefault(); | |
260 | }, | |
261 | ||
262 | beginTagEdit: function (event: Event) { | |
263 | const task = document.activeElement; | |
264 | if (!task) return; | |
265 | const input = document.createElement("input"); | |
266 | input.classList.add("tag"); | |
267 | input.addEventListener("blur", this.completeTagEdit, { once: true }); | |
268 | input.value = lastTagNameEntered; | |
269 | task.appendChild(input); | |
270 | input.focus(); | |
271 | input.select(); | |
272 | event.preventDefault(); | |
273 | }, | |
274 | ||
275 | completeEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) { | |
276 | const input = event.target as HTMLInputElement; | |
277 | const task = input.parentElement!; | |
278 | const desc = task.getElementsByClassName("desc")[0]; | |
279 | const oldDescription = task.getAttribute("data-description")!; | |
280 | const newDescription = input.value; | |
281 | input.removeEventListener("blur", this.completeEdit); | |
282 | task.removeChild(input); | |
283 | task.removeAttribute("data-description"); | |
284 | task.focus(); | |
285 | if (newDescription === oldDescription || resolution === CommitOrAbort.Abort) { | |
286 | desc.textContent = oldDescription; | |
287 | } else { | |
288 | ui.edit(task.getAttribute("data-created")!, newDescription, oldDescription); | |
289 | } | |
290 | }, | |
291 | ||
292 | completeTagEdit: function (event: Event, resolution: CommitOrAbort = CommitOrAbort.Commit) { | |
293 | const input = event.target as HTMLInputElement; | |
294 | const task = input.parentElement!; | |
295 | const newTagName = input.value; | |
296 | input.removeEventListener("blur", this.completeTagEdit); | |
297 | task.removeChild(input); | |
298 | task.focus(); | |
299 | if (resolution === CommitOrAbort.Commit && newTagName && !Model.hasTag(task, newTagName)) { | |
300 | ui.addTag(task.getAttribute("data-created")!, newTagName); | |
301 | lastTagNameEntered = newTagName; | |
302 | } | |
303 | }, | |
304 | ||
305 | firstVisibleTask: function () { | |
306 | for (const task of document.getElementsByClassName("task")) { | |
307 | if (task instanceof HTMLElement && task.getAttribute("data-state") === currentViewState) { | |
308 | return task; | |
309 | } | |
310 | } | |
311 | }, | |
312 | ||
313 | focusTaskNameInput: function (event: Event) { | |
314 | if (document.activeElement instanceof HTMLElement) { | |
315 | taskFocusedBeforeJumpingToInput = document.activeElement; | |
316 | } | |
317 | document.getElementById("taskName")!.focus(); | |
318 | event.preventDefault(); | |
319 | }, | |
320 | ||
321 | visibleTaskAtOffset(task: Element, offset: number): Element { | |
322 | var cursor: Element | null = task; | |
323 | var valid_cursor = cursor; | |
324 | const increment = offset / Math.abs(offset); | |
325 | while (true) { | |
326 | cursor = increment > 0 ? cursor.nextElementSibling : cursor.previousElementSibling; | |
327 | if (!cursor || !(cursor instanceof HTMLElement)) break; | |
328 | if (cursor.getAttribute("data-state")! === currentViewState) { | |
329 | offset -= increment; | |
330 | valid_cursor = cursor; | |
331 | } | |
332 | if (Math.abs(offset) < 0.5) break; | |
333 | } | |
334 | return valid_cursor; | |
335 | }, | |
336 | ||
337 | moveCursor: function (offset: number): boolean { | |
338 | const active = document.activeElement; | |
339 | if (!active) return false; | |
340 | const dest = this.visibleTaskAtOffset(active, offset); | |
341 | if (dest !== active && dest instanceof HTMLElement) { | |
342 | dest.focus(); | |
343 | return true; | |
344 | } | |
345 | return false; | |
346 | }, | |
347 | ||
348 | moveTask: function (offset: number) { | |
349 | const active = document.activeElement; | |
350 | if (!active) return; | |
351 | const dest = this.visibleTaskAtOffset(active, offset); | |
352 | if (dest === active) return; // Already extremal | |
353 | var onePastDest: Element | null = this.visibleTaskAtOffset(dest, offset / Math.abs(offset)); | |
354 | if (onePastDest == dest) onePastDest = null; // Will become extremal | |
355 | if (offset > 0) { | |
356 | this.setPriority(active, dest, onePastDest); | |
357 | } else { | |
358 | this.setPriority(active, onePastDest, dest); | |
359 | } | |
360 | }, | |
361 | ||
362 | returnFocusAfterInput: function (): boolean { | |
363 | if (taskFocusedBeforeJumpingToInput) { | |
364 | taskFocusedBeforeJumpingToInput.focus(); | |
365 | return true; | |
366 | } | |
367 | return false; | |
368 | }, | |
369 | ||
370 | // Change task's priority to be between other tasks a and b. | |
371 | setPriority: function (task: Element, a: Element | null, b: Element | null) { | |
372 | const aPriority = a === null ? 0 : Model.getPriority(a); | |
373 | const bPriority = b === null ? clock.now() : Model.getPriority(b); | |
374 | console.assert(aPriority < bPriority, aPriority, "<", bPriority); | |
375 | const span = bPriority - aPriority; | |
376 | const newPriority = aPriority + 0.1 * span + 0.8 * span * Math.random(); | |
377 | console.assert(aPriority < newPriority && newPriority < bPriority, aPriority, "<", newPriority, "<", bPriority); | |
378 | const newPriorityRounded = Math.round(newPriority); | |
379 | const okToRound = aPriority < newPriorityRounded && newPriorityRounded < bPriority; | |
380 | ui.setPriority(task.getAttribute("data-created")!, okToRound ? newPriorityRounded : newPriority, Model.getPriority(task)); | |
381 | task instanceof HTMLElement && task.focus(); | |
382 | }, | |
383 | ||
384 | setState: function (newState: string) { | |
385 | const task = document.activeElement; | |
386 | if (!task) return; | |
387 | const oldState = task.getAttribute("data-state")!; | |
388 | if (newState === oldState) return; | |
389 | const createTimestamp = task.getAttribute("data-created")!; | |
390 | this.moveCursor(1) || this.moveCursor(-1); | |
391 | return ui.setState(createTimestamp, newState, oldState); | |
392 | }, | |
393 | ||
394 | setView: function (state: string) { | |
395 | const sheet = (document.getElementById("viewStyle") as HTMLStyleElement).sheet!; | |
396 | sheet.insertRule(`.task:not([data-state=${state}]) { display: none }`); | |
397 | sheet.removeRule(1); | |
398 | currentViewState = state; | |
399 | if (document.activeElement?.getAttribute("data-state") !== state) { | |
400 | this.firstVisibleTask()?.focus(); | |
401 | } | |
402 | }, | |
403 | ||
404 | undo: function () { | |
405 | const ret = ui.undo(); | |
406 | if (ret && ret instanceof HTMLElement) ret.focus(); | |
407 | }, | |
408 | }; | |
409 | } | |
410 | const browserUI = BrowserUI(); | |
411 | ||
412 | enum InputState { | |
413 | Command, | |
414 | View, | |
415 | } | |
416 | var inputState = InputState.Command; | |
417 | ||
418 | function handleKey(event: any) { | |
419 | if (event.target.tagName === "INPUT") { | |
420 | if (event.target.id === "taskName") { | |
421 | if (event.key == "Enter") return browserUI.addTask(event); | |
422 | if (event.key == "Escape") return browserUI.returnFocusAfterInput(); | |
423 | } else if (event.target.classList.contains("tag")) { | |
424 | if (event.key == "Enter") return browserUI.completeTagEdit(event); | |
425 | if (event.key == "Escape") return browserUI.completeTagEdit(event, CommitOrAbort.Abort); | |
426 | } else { | |
427 | if (event.key == "Enter") return browserUI.completeEdit(event); | |
428 | if (event.key == "Escape") return browserUI.completeEdit(event, CommitOrAbort.Abort); | |
429 | } | |
430 | } else { | |
431 | if (inputState === InputState.Command) { | |
432 | if (event.key == "j") return browserUI.moveCursor(1); | |
433 | if (event.key == "k") return browserUI.moveCursor(-1); | |
434 | if (event.key == "J") return browserUI.moveTask(1); | |
435 | if (event.key == "K") return browserUI.moveTask(-1); | |
436 | if (event.key == "n") return browserUI.focusTaskNameInput(event); | |
437 | if (event.key == "c") return browserUI.setState("cancelled"); | |
438 | if (event.key == "d") return browserUI.setState("done"); | |
439 | if (event.key == "q") return browserUI.setState("todo"); | |
440 | if (event.key == "s") return browserUI.setState("someday-maybe"); | |
441 | if (event.key == "w") return browserUI.setState("waiting"); | |
442 | if (event.key == "X") return browserUI.setState("deleted"); | |
443 | if (event.key == "u") return browserUI.undo(); | |
444 | if (event.key == "e") return browserUI.beginEdit(event); | |
445 | if (event.key == "t") return browserUI.beginTagEdit(event); | |
446 | if (event.key == "v") return (inputState = InputState.View); | |
447 | } else if (inputState === InputState.View) { | |
448 | inputState = InputState.Command; | |
449 | if (event.key == "c") return browserUI.setView("cancelled"); | |
450 | if (event.key == "d") return browserUI.setView("done"); | |
451 | if (event.key == "q") return browserUI.setView("todo"); | |
452 | if (event.key == "s") return browserUI.setView("someday-maybe"); | |
453 | if (event.key == "w") return browserUI.setView("waiting"); | |
454 | if (event.key == "x") return browserUI.setView("deleted"); | |
455 | } | |
456 | } | |
457 | } | |
458 | ||
459 | function browserInit() { | |
460 | document.body.addEventListener("keydown", handleKey, { capture: false }); | |
461 | log.replay(); | |
462 | browserUI.firstVisibleTask()?.focus(); | |
463 | } |