// Makes the server-rendered TodoMVC behave like the reference app. // // Every change is still the form POST the page uses with JavaScript off. // This module sends that same POST in the background with an // X-Todo-Fragment header, and the server answers with fresh HTML for the // list and footer instead of a redirect. The server stays the only place // that decides what the page shows. const app = document.querySelector('.todoapp'); const newTodo = app.querySelector('.new-todo'); // Requests run one at a time, so their answers land in the order they // were made. let queue = Promise.resolve(); let swapping = false; function send(form) { const body = new URLSearchParams(new FormData(form)); const url = form.action; queue = queue .then(async () => { const res = await fetch(url, { method: 'POST', body, headers: { 'X-Todo-Fragment': '1' }, }); if (!res.ok) throw new Error(`${res.status} from ${url}`); swap(await res.text()); }) .catch((err) => { // Something is out of step (an expired list, a lost connection). // The server's page is the truth, so load it. console.error(err); location.reload(); }); } // Replaces section.main and footer.footer with the server's HTML, keeping // keyboard focus on the same control where it still exists, and keeping // any edit still in progress (one not yet being saved) open with its // draft intact. function swap(html) { const again = focusSelector(document.activeElement); const drafts = [...app.querySelectorAll('.todo-list li.editing:not([data-saving])')].map((li) => { const input = li.querySelector('.edit'); return { id: li.dataset.id, value: input.value, focused: input === document.activeElement, start: input.selectionStart, end: input.selectionEnd, }; }); // Removing a focused field can fire focusout; that isn't the visitor // leaving the field, so it mustn't save. swapping = true; for (const el of app.querySelectorAll(':scope > .main, :scope > .footer')) el.remove(); swapping = false; const t = document.createElement('template'); t.innerHTML = html; app.append(t.content); for (const d of drafts) { const li = app.querySelector(`.todo-list li[data-id="${CSS.escape(d.id)}"]`); if (!li) continue; // the item is gone, so is its edit const input = li.querySelector('.edit'); li.classList.add('editing'); input.value = d.value; if (d.focused) { input.focus(); input.setSelectionRange(d.start, d.end); } } if (again && !drafts.some((d) => d.focused)) app.querySelector(again)?.focus(); } function focusSelector(el) { if (!el || !app.contains(el) || el === newTodo) return null; if (el.id) return `#${CSS.escape(el.id)}`; const li = el.closest('li[data-id]'); if (li && el.classList.length) { return `li[data-id="${CSS.escape(li.dataset.id)}"] .${CSS.escape(el.classList[0])}`; } return null; } // Adding, deleting, clearing completed, and saving an edit with Enter all // arrive here as ordinary form submissions. app.addEventListener('submit', (e) => { const form = e.target; e.preventDefault(); const edit = form.querySelector('.edit'); if (edit) { saveEdit(edit); return; } send(form); if (form.contains(newTodo)) newTodo.value = ''; }); // The checkboxes have no submit button of their own: a change submits the // form they sit in. app.addEventListener('change', (e) => { if (e.target.matches('.toggle, .toggle-all')) send(e.target.form); }); // Double-click a title to edit it. app.addEventListener('dblclick', (e) => { const label = e.target.closest('.todo-list label'); if (!label) return; const li = label.closest('li'); const input = li.querySelector('.edit'); li.classList.add('editing'); input.focus(); input.setSelectionRange(input.value.length, input.value.length); }); // Escape cancels the edit; leaving the field saves it. app.addEventListener('keydown', (e) => { if (e.key !== 'Escape' || !e.target.matches('.edit')) return; const input = e.target; input.value = input.defaultValue; input.closest('li').classList.remove('editing'); }); app.addEventListener('focusout', (e) => { if (!swapping && e.target.matches('.edit')) saveEdit(e.target); }); // Saves an edit once, however many ways it was finished (Enter, then the // blur that follows when the item is redrawn). function saveEdit(input) { const li = input.closest('li'); if (!li.classList.contains('editing') || li.dataset.saving) return; li.dataset.saving = '1'; if (input.value.trim() === input.defaultValue) { // Unchanged: nothing to send, just leave edit mode. input.value = input.defaultValue; li.classList.remove('editing'); delete li.dataset.saving; return; } send(input.form); }