// client/app.js: the page's script, calling the backend on its own address. // The rows' names, and the route that adds, lists, and deletes the signed-in user's rows. const PLURAL = 'notes'; const SINGULAR = 'note'; const ROUTE = '/api/notes'; // The fields of one row, each with its kind. The first text field is the row's // text: the list shows its first line, and the reader shows it whole. const FIELDS = [{ name: 'body', kind: 'text' }]; const INPUT_TYPES = { text: 'text', integer: 'number', boolean: 'checkbox', timestamp: 'datetime-local' }; const TEXT = FIELDS.find((field) => field.kind === 'text') ?? null; const $ = (id) => document.getElementById(id); const say = (id, text) => { $(id).textContent = text; }; const inputs = []; let rows = []; let selected = null; let busy = false; const dateOf = (value, full) => new Intl.DateTimeFormat(undefined, full ? { month: 'long', day: 'numeric', year: 'numeric' } : { month: 'short', day: 'numeric' }).format(new Date(value)); function valueOf(field, input) { if (field.kind === 'boolean') return input.checked; if (input.value === '') return field.kind === 'text' ? '' : null; if (field.kind === 'integer') return Number(input.value); return field.kind === 'timestamp' ? new Date(input.value).toISOString() : input.value; } const shown = (field, value) => (field.kind === 'boolean' ? (value ? 'yes' : 'no') : field.kind === 'timestamp' && value ? dateOf(value, true) : String(value ?? '')); function setBusy(value) { busy = value; for (const input of inputs) input[input.type === 'checkbox' ? 'disabled' : 'readOnly'] = value; $('delete-row').disabled = value; $('save').disabled = value; } async function act(work) { setBusy(true); say('status', ''); try { await work(); } catch (error) { say('status', error.message); } finally { setBusy(false); } } function signedOut(message = `Sign in to save your ${PLURAL} and come back to them anywhere.`) { $('workspace').hidden = true; $('welcome').hidden = false; $('sign-in').hidden = false; say('who', message); } async function api(path, options) { const response = await fetch(path, options); if (response.status === 401) { signedOut(`Please sign in to open your ${PLURAL}.`); throw new Error('Please sign in again. Your unsaved text is still here.'); } if (!response.ok) throw new Error(response.status === 404 ? `This ${SINGULAR} no longer exists. Reload the page to see your ${PLURAL}.` : 'That did not work. Please try again.'); return response.status === 204 ? null : response.json(); } function renderList() { const list = $('row-list'); say('count', rows.length); list.replaceChildren(); $('empty').hidden = rows.length > 0; for (const row of rows) { const entry = $('row-template').content.firstElementChild.cloneNode(true); const button = entry.querySelector('button'); button.setAttribute('aria-current', String(row.id === selected)); entry.querySelector('.excerpt').textContent = TEXT ? String(row[TEXT.name] ?? '').split('\n')[0] : FIELDS.map((field) => `${field.name}: ${shown(field, row[field.name])}`).join(', '); entry.querySelector('.row-date').textContent = dateOf(row.created_at); button.addEventListener('click', () => busy || showRow(row.id)); list.append(entry); } } function showRow(id) { const row = rows.find((held) => held.id === id); if (!row) return compose(); selected = id; $('reader').hidden = false; $('composer').hidden = true; say('row-date', dateOf(row.created_at, true)); const others = FIELDS.filter((field) => field !== TEXT).map((field) => `${field.name}: ${shown(field, row[field.name])}`); say('reader-body', [TEXT ? String(row[TEXT.name] ?? '') : '', others.join('\n')].filter(Boolean).join('\n\n')); say('status', ''); renderList(); } function compose() { if (busy) return; selected = null; renderList(); $('reader').hidden = true; $('composer').hidden = false; $('cancel').hidden = rows.length === 0; say('status', ''); inputs[0]?.focus(); } const clearInputs = () => inputs.forEach((input) => (input.type === 'checkbox' ? (input.checked = false) : (input.value = ''))); for (const field of FIELDS) { const input = document.createElement(field === TEXT ? 'textarea' : 'input'); if (field === TEXT) { input.maxLength = 20000; input.placeholder = "What's on your mind?"; input.addEventListener('keydown', (event) => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); $('composer').requestSubmit(); } }); } else input.type = INPUT_TYPES[field.kind]; input.name = field.name; input.required = field.kind !== 'boolean'; input.addEventListener('input', () => input.setCustomValidity('')); if (FIELDS.length === 1) input.setAttribute('aria-labelledby', 'composer-title'); const label = document.createElement('label'); label.append(FIELDS.length === 1 ? '' : field.name, input); $('fields').append(label); inputs.push(input); } $('new-row').addEventListener('click', compose); $('cancel').addEventListener('click', () => { if (busy) return; clearInputs(); if (rows.length) showRow(rows[0].id); }); $('composer').addEventListener('submit', (event) => { event.preventDefault(); const row = Object.fromEntries(FIELDS.map((field, index) => [field.name, valueOf(field, inputs[index])])); const text = TEXT && inputs[FIELDS.indexOf(TEXT)]; if (text && !String(row[TEXT.name]).trim()) { text.setCustomValidity(`Enter a ${SINGULAR} before saving.`); return text.reportValidity(); } if (!busy) act(async () => { const added = await api(ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(row) }); rows.unshift(added); clearInputs(); busy = false; showRow(added.id); $('new-row').focus(); }); }); $('delete-row').addEventListener('click', async () => { const dialog = $('confirm-dialog'); if (busy || !selected) return; say('confirm-message', `Delete this ${SINGULAR}?`); dialog.returnValue = ''; dialog.showModal(); await new Promise((resolve) => dialog.addEventListener('close', resolve, { once: true })); if (dialog.returnValue !== 'confirm') return; const index = rows.findIndex((held) => held.id === selected); await act(async () => { await api(`${ROUTE}/${encodeURIComponent(selected)}`, { method: 'DELETE' }); rows.splice(index, 1); busy = false; if (rows.length) showRow(rows[Math.min(index, rows.length - 1)].id); else { clearInputs(); compose(); } }); }); async function start() { // The page's words that name the rows, from the rows' names. say('list-title', `Your ${PLURAL}`); say('new-row-label', `New ${SINGULAR}`); say('composer-title', `Enter a ${SINGULAR.charAt(0).toUpperCase()}${SINGULAR.slice(1)}`); say('save', `Save ${SINGULAR}`); say('private', `Your ${PLURAL} are private to your account.`); say('empty', `Your ${PLURAL} will appear here.`); $('delete-row').setAttribute('aria-label', `Delete this ${SINGULAR}`); try { const response = await fetch('/__account/me'); if (response.status === 404) { return say('who', "Sign-in is unavailable at this address. For a local run, start with --sign-in and the application's hostname. Otherwise sign in at the application's deployed address."); } const user = response.status === 200 ? (await response.json()).user : null; if (!user) return signedOut(); rows = await api(ROUTE); $('welcome').hidden = true; $('workspace').hidden = false; $('sign-out').hidden = false; if (rows.length) showRow(rows[0].id); else compose(); } catch { $('welcome').hidden = false; say('who', `Your ${PLURAL} could not be opened. Please reload to try again.`); } } start();