carlos / todomvc-bakeoff Public

Clone
git clone https://amadan.net/carlos/todomvc-bakeoff

Plain git — no account needed to clone.

Download

Download this file

1// Makes the server-rendered TodoMVC behave like the reference app.
2//
3// Every change is still the form POST the page uses with JavaScript off.
4// This module sends that same POST in the background with an
5// X-Todo-Fragment header, and the server answers with fresh HTML for the
6// list and footer instead of a redirect. The server stays the only place
7// that decides what the page shows.
8
9const app = document.querySelector('.todoapp');
10const newTodo = app.querySelector('.new-todo');
11
12// Requests run one at a time, so their answers land in the order they
13// were made.
14let queue = Promise.resolve();
15let swapping = false;
16
17function send(form) {
18 const body = new URLSearchParams(new FormData(form));
19 const url = form.action;
20 queue = queue
21 .then(async () => {
22 const res = await fetch(url, {
23 method: 'POST',
24 body,
25 headers: { 'X-Todo-Fragment': '1' },
26 });
27 if (!res.ok) throw new Error(`${res.status} from ${url}`);
28 swap(await res.text());
29 })
30 .catch((err) => {
31 // Something is out of step (an expired list, a lost connection).
32 // The server's page is the truth, so load it.
33 console.error(err);
34 location.reload();
35 });
36}
37
38// Replaces section.main and footer.footer with the server's HTML, keeping
39// keyboard focus on the same control where it still exists, and keeping
40// any edit still in progress (one not yet being saved) open with its
41// draft intact.
42function swap(html) {
43 const again = focusSelector(document.activeElement);
44 const drafts = [...app.querySelectorAll('.todo-list li.editing:not([data-saving])')].map((li) => {
45 const input = li.querySelector('.edit');
46 return {
47 id: li.dataset.id,
48 value: input.value,
49 focused: input === document.activeElement,
50 start: input.selectionStart,
51 end: input.selectionEnd,
52 };
53 });
54 // Removing a focused field can fire focusout; that isn't the visitor
55 // leaving the field, so it mustn't save.
56 swapping = true;
57 for (const el of app.querySelectorAll(':scope > .main, :scope > .footer')) el.remove();
58 swapping = false;
59 const t = document.createElement('template');
60 t.innerHTML = html;
61 app.append(t.content);
62 for (const d of drafts) {
63 const li = app.querySelector(`.todo-list li[data-id="${CSS.escape(d.id)}"]`);
64 if (!li) continue; // the item is gone, so is its edit
65 const input = li.querySelector('.edit');
66 li.classList.add('editing');
67 input.value = d.value;
68 if (d.focused) {
69 input.focus();
70 input.setSelectionRange(d.start, d.end);
71 }
72 }
73 if (again && !drafts.some((d) => d.focused)) app.querySelector(again)?.focus();
74}
75
76function focusSelector(el) {
77 if (!el || !app.contains(el) || el === newTodo) return null;
78 if (el.id) return `#${CSS.escape(el.id)}`;
79 const li = el.closest('li[data-id]');
80 if (li && el.classList.length) {
81 return `li[data-id="${CSS.escape(li.dataset.id)}"] .${CSS.escape(el.classList[0])}`;
82 }
83 return null;
84}
85
86// Adding, deleting, clearing completed, and saving an edit with Enter all
87// arrive here as ordinary form submissions.
88app.addEventListener('submit', (e) => {
89 const form = e.target;
90 e.preventDefault();
91 const edit = form.querySelector('.edit');
92 if (edit) {
93 saveEdit(edit);
94 return;
95 }
96 send(form);
97 if (form.contains(newTodo)) newTodo.value = '';
98});
99
100// The checkboxes have no submit button of their own: a change submits the
101// form they sit in.
102app.addEventListener('change', (e) => {
103 if (e.target.matches('.toggle, .toggle-all')) send(e.target.form);
104});
105
106// Double-click a title to edit it.
107app.addEventListener('dblclick', (e) => {
108 const label = e.target.closest('.todo-list label');
109 if (!label) return;
110 const li = label.closest('li');
111 const input = li.querySelector('.edit');
112 li.classList.add('editing');
113 input.focus();
114 input.setSelectionRange(input.value.length, input.value.length);
115});
116
117// Escape cancels the edit; leaving the field saves it.
118app.addEventListener('keydown', (e) => {
119 if (e.key !== 'Escape' || !e.target.matches('.edit')) return;
120 const input = e.target;
121 input.value = input.defaultValue;
122 input.closest('li').classList.remove('editing');
123});
124
125app.addEventListener('focusout', (e) => {
126 if (!swapping && e.target.matches('.edit')) saveEdit(e.target);
127});
128
129// Saves an edit once, however many ways it was finished (Enter, then the
130// blur that follows when the item is redrawn).
131function saveEdit(input) {
132 const li = input.closest('li');
133 if (!li.classList.contains('editing') || li.dataset.saving) return;
134 li.dataset.saving = '1';
135 if (input.value.trim() === input.defaultValue) {
136 // Unchanged: nothing to send, just leave edit mode.
137 input.value = input.defaultValue;
138 li.classList.remove('editing');
139 delete li.dataset.saving;
140 return;
141 }
142 send(input.form);
143}
144