repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

1704 lines · 95.9 KB · download this file

// The admin's script, loaded on every admin screen. Each screen's part starts
// with `(() => { ... })();` (a function run at once, so its variables stay
// its own) and returns straight away when its screen's elements aren't on the
// page. Everything also works without the script, as plain forms and links;
// this adds saving as you type, previews, uploads in pieces, dragging and the
// like. Shared helpers: Admin (unsaved changes), adminPost (send an action),
// choosePicture (the picture chooser), adminToast (a short message) and
// previewFrame (a live preview).
// The picture folder the library screen is showing, as a query-string part.
const libraryFolder = () => { const f = document.getElementById('library')?.dataset.folder; return f ? '&folder=' + encodeURIComponent(f) : ''; };
// Shared by every admin screen: anything with unsaved changes registers a
// saver, so other forms, Ctrl+S and leaving the page all save (or warn) first.
document.documentElement.classList.add('js');
const Admin = {
  savers: [],
  busy: false,
  leaving: false,   // set once the person chose to leave (unsaved edits saved or discarded)
  // Forms that are submitted by hand (adding a link or a page) only warn.
  typedIn: new Set(),
  unsaved() { return this.savers.some(s => s.unsaved()); },
  async saveAll() { return (await Promise.all(this.savers.filter(s => s.unsaved()).map(s => s.save()))).every(Boolean); },
};
window.addEventListener('beforeunload', event => {
  if (Admin.leaving) return;
  if (Admin.busy || Admin.unsaved() || Admin.typedIn.size) { event.preventDefault(); event.returnValue = ''; }
});
document.querySelectorAll('form[data-warn-unsaved]').forEach(form => {
  form.addEventListener('input', () => Admin.typedIn.add(form));
  form.addEventListener('submit', () => Admin.typedIn.delete(form));
});
document.addEventListener('keydown', event => {
  if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's' && Admin.savers.length) { event.preventDefault(); Admin.saveAll(); }
});
// An address pointing at something inside a folded part (#share-link inside
// "Make a tagged link") unfolds it, on arrival and when the link is followed.
(() => {
  const unfold = () => {
    const target = location.hash.length > 1 && document.getElementById(decodeURIComponent(location.hash.slice(1)));
    const fold = target && target.closest('details');
    if (fold && !fold.open) { fold.open = true; target.scrollIntoView(); }
  };
  unfold(); window.addEventListener('hashchange', unfold);
})();
// A message after an action comes in the address (?notice=...). Once it's on
// the screen it's taken out of the address, so reloading or bookmarking the
// page doesn't show it again.
(() => {
  const url = new URL(location.href);
  if (!url.searchParams.has('notice')) return;
  url.searchParams.delete('notice');
  history.replaceState(history.state, '', url.pathname + url.search + url.hash);
})();

// Markdown boxes (textarea[data-markdown], data-markdown="pictures" for one
// with a picture button): a toolbar above each, and shortcuts in it:
// Ctrl/⌘+B, I and K; Enter carries a list or quote on (and ends it on an
// empty item); Tab and Shift+Tab move list items in and out. Edits go
// through insertText where the browser has it, so its own undo takes them
// back. A box added later (a list's new entry) gets its toolbar when first
// focused. Markdown.wrapIn is shared with the page editor's canvas.
const Markdown = (() => {
  const mod = /Mac|iP(hone|ad)/.test(navigator.platform) ? '⌘' : 'Ctrl+';
  // Puts text in place of [start, end), then selects [a, b] of it; tells the form it changed.
  function put(box, start, end, text, a = text.length, b = a) {
    box.focus();
    box.setSelectionRange(start, end);
    let typed = false;
    try { typed = document.execCommand('insertText', false, text); } catch {}
    if (!typed || box.value.slice(start, start + text.length) !== text) {
      box.setRangeText(text, start, end, 'end');
      box.dispatchEvent(new Event('input', {bubbles: true}));
    }
    box.setSelectionRange(start + a, start + b);
  }
  // The marks around a piece of text (**bold**), or taken off again when already there.
  function wrapIn(text, before, after = before) {
    if (text.length >= before.length + after.length && text.startsWith(before) && text.endsWith(after)) return text.slice(before.length, text.length - after.length);
    // Spaces selected at either end stay outside the marks.
    const [, lead, core, trail] = text.match(/^(\s*)([\s\S]*?)(\s*)$/);
    return lead + before + core + after + trail;
  }
  function wrap(box, mark, placeholder) {
    const {selectionStart: s, selectionEnd: e, value: v} = box;
    const sel = v.slice(s, e);
    // Marks just outside the selection: take them off.
    if (v.slice(s - mark.length, s) === mark && v.slice(e, e + mark.length) === mark && (mark !== '*' || (v[s - 2] !== '*' && v[e + 1] !== '*'))) {
      put(box, s - mark.length, e + mark.length, sel, 0, sel.length); return;
    }
    if (!sel) { put(box, s, e, mark + placeholder + mark, mark.length, mark.length + placeholder.length); return; }
    const out = wrapIn(sel, mark);
    put(box, s, e, out, 0, out.length);
  }
  // The whole lines the selection touches: [start, end) in the text.
  function lineSpan(box) {
    const v = box.value; let {selectionStart: s, selectionEnd: e} = box;
    if (e > s && v[e - 1] === '\n') e--;
    const a = v.lastIndexOf('\n', s - 1) + 1; let b = v.indexOf('\n', e); if (b < 0) b = v.length;
    return [a, b];
  }
  const listMark = /^(\s*)([-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?/;
  // Every line starts with this kind of mark, or loses it: a list, numbered
  // list, tick boxes, a quote. A heading goes ## → ### → none.
  function prefix(box, kind) {
    const [a, b] = lineSpan(box);
    const lines = box.value.slice(a, b).split('\n');
    const has = {bullet: /^\s*[-*+]\s+(?!\[[ xX]\])/, number: /^\s*\d+[.)]\s+/, task: /^\s*[-*+]\s+\[[ xX]\]\s+/, quote: /^\s*>\s?/}[kind];
    let out;
    if (kind === 'heading') {
      out = lines.map(l => { const m = l.match(/^(#{1,6})\s+/); return !m ? '## ' + l : m[1].length === 2 ? '###' + l.slice(2) : l.slice(m[0].length); });
    } else if (lines.filter(l => l.trim()).every(l => has.test(l))) {
      // Already that kind: take the marks off (a list item keeps its indent).
      out = lines.map(l => kind === 'quote' ? l.replace(has, '') : l.replace(listMark, '$1'));
    } else {
      let n = 0;
      out = lines.map(l => {
        if (!l.trim() && lines.length > 1) return l;
        if (kind === 'quote') return '> ' + l;
        const [indent, rest] = [l.match(/^\s*/)[0], l.replace(listMark, '').trimStart()];
        return indent + (kind === 'number' ? `${++n}. ` : kind === 'task' ? '- [ ] ' : '- ') + rest;
      });
    }
    const text = out.join('\n');
    put(box, a, b, text, lines.length > 1 ? 0 : text.length, text.length);
  }
  // Something on lines of its own (a table, a block of code), with a blank line around it.
  function block(box, text, a = 0, b = a) {
    const {selectionStart: s, selectionEnd: e, value: v} = box;
    const before = v.slice(0, s), after = v.slice(e);
    const lead = before === '' || before.endsWith('\n\n') ? '' : before.endsWith('\n') ? '\n' : '\n\n';
    const tail = after === '' || after.startsWith('\n\n') ? '' : after.startsWith('\n') ? '\n' : '\n\n';
    put(box, s, e, lead + text + tail, lead.length + a, lead.length + b);
  }
  function link(box) {
    const {selectionStart: s, selectionEnd: e, value: v} = box;
    const sel = v.slice(s, e).trim();
    if (/^(https?:\/\/|\/|#|mailto:)\S*$/.test(sel)) { put(box, s, e, `[link text](${sel})`, 1, 10); return; }
    const text = sel || 'link text', out = `[${text}](https://)`;
    put(box, s, e, out, text.length + 3, out.length - 1);
  }
  function code(box) {
    const {selectionStart: s, selectionEnd: e, value: v} = box;
    const sel = v.slice(s, e);
    if (sel.includes('\n')) block(box, '```\n' + sel.replace(/\n$/, '') + '\n```', 4, 4 + sel.replace(/\n$/, '').length);
    else wrap(box, '`', 'code');
  }
  function table(box) { block(box, '| Column | Column |\n|:-------|-------:|\n| Text | Text |', 2, 8); }
  // A footnote: its mark at the cursor, its note at the end of the text, the cursor in the note.
  function footnote(box) {
    const used = new Set([...box.value.matchAll(/\[\^(\d+)\]/g)].map(m => +m[1]));
    let n = 1; while (used.has(n)) n++;
    put(box, box.selectionEnd, box.selectionEnd, `[^${n}]`);
    const v = box.value, end = v.length;
    put(box, end, end, (v === '' || v.endsWith('\n\n') ? '' : v.endsWith('\n') ? '\n' : '\n\n') + `[^${n}]: `);
  }
  // A picture from the library as a figure on its own line; a caption, if
  // given, is its title (shown under it). The chooser opens in the box's
  // data-picture-folder (an article's: Articles).
  async function picture(box, caption = '') {
    const {selectionStart: s, selectionEnd: e} = box;
    const chosen = await choosePicture({folder: box.dataset.pictureFolder || '', title: 'Insert a picture'});
    box.focus(); box.setSelectionRange(s, e);
    if (!chosen) return;
    const title = caption ? ` "${caption.replace(/"/g, '”')}"` : '';
    block(box, `![${(chosen.description || chosen.title).replace(/[\r\n[\]\\]/g, ' ')}](${chosen.url}${title})`);
  }
  function help() {
    const fold = document.getElementById('md-help'); if (!fold) return;
    fold.open = true; fold.scrollIntoView({block: 'nearest', behavior: 'smooth'}); fold.querySelector('summary')?.focus();
  }
  // Enter in a list (or quote) starts the next item; on an empty item it ends the list.
  function enter(box, event) {
    const {selectionStart: s, selectionEnd: e, value: v} = box;
    if (s !== e) return;
    const a = v.lastIndexOf('\n', s - 1) + 1, line = v.slice(a, s);
    const m = line.match(listMark) || line.match(/^(\s*(?:>\s?)+)/);
    if (!m) return;
    event.preventDefault();
    // An empty item: a nested one moves out a level; otherwise the list ends,
    // with a blank line after it so what follows isn't part of it.
    if (line.trim() === m[0].trim()) {
      if (m[2] !== undefined && m[1].length) put(box, a, s, line.replace(/^ {1,2}/, ''));
      else put(box, a, s, '\n');
      return;
    }
    const next = m[2] === undefined ? m[1] : m[1] + (/\d/.test(m[2]) ? `${parseInt(m[2], 10) + 1}${m[2].slice(-1)}` : m[2]) + ' ' + (m[3] ? '[ ] ' : '');
    put(box, s, s, '\n' + next);
  }
  // Tab and Shift+Tab move list items in and out; elsewhere Tab moves on as usual.
  function indent(box, event) {
    const [a, b] = lineSpan(box);
    const lines = box.value.slice(a, b).split('\n');
    if (!lines.every(l => listMark.test(l))) return;
    event.preventDefault();
    const out = lines.map(l => event.shiftKey ? l.replace(/^ {1,2}/, '') : '  ' + l).join('\n');
    // One line: the cursor stays where it was in the text; several: they stay selected.
    const caret = Math.max(0, box.selectionStart - a + out.length - (b - a));
    put(box, a, b, out, lines.length > 1 ? 0 : caret, lines.length > 1 ? out.length : caret);
  }
  // The "more…" menu: the page tools, each put in as an example around the
  // selection (or with words to type over).
  const picked = box => box.value.slice(box.selectionStart, box.selectionEnd).replace(/\n+$/, '');
  const inBox = (box, open, close, text) => block(box, `${open}\n${text}\n${close}`, open.length + 1, open.length + 1 + text.length);
  const quoted = text => text.split('\n').map(l => '> ' + l).join('\n');
  const more = [
    ['Note box', box => block(box, '> [!NOTE]\n' + quoted(picked(box) || 'Something worth knowing.'))],
    ['Tip box', box => block(box, '> [!TIP]\n' + quoted(picked(box) || 'A helpful hint.'))],
    ['Warning box', box => block(box, '> [!WARNING]\n' + quoted(picked(box) || 'Something to watch out for.'))],
    ['Button', box => { const t = picked(box) || 'Button text'; put(box, box.selectionStart, box.selectionEnd, `[${t}](/contact/){.button}`, t.length + 3, t.length + 12); }],
    ['Fold-out (question and answer)', box => { const t = picked(box) || 'The answer.'; block(box, `+++ A question\n${t}\n+++`, 4, 14); }],
    ['Two columns', box => inBox(box, '::: columns', '|||\nSecond column.\n:::', picked(box) || 'First column.')],
    ['Three columns', box => inBox(box, '::: columns', '|||\nSecond column.\n|||\nThird column.\n:::', picked(box) || 'First column.')],
    ['Centred', box => inBox(box, '::: center', ':::', picked(box) || 'Centred text.')],
    ['Large introduction', box => inBox(box, '::: lead', ':::', picked(box) || 'A few words, larger.')],
    ['Small print', box => inBox(box, '::: small muted', ':::', picked(box) || 'The small print.')],
    ['Box', box => inBox(box, '::: box', ':::', picked(box) || 'Text in a box.')],
    ['Tinted panel', box => inBox(box, '::: soft', ':::', picked(box) || 'Text on a soft tint.')],
    ['Definitions', box => block(box, `${picked(box) || 'A term'}\n: What it means.`)],
    ['Highlight', box => wrap(box, '==', 'highlighted')],
    ['Keyboard key', box => { const t = picked(box) || 'Ctrl'; put(box, box.selectionStart, box.selectionEnd, `[[${t}]]`, 2, 2 + t.length); }],
  ];
  // The site's libraries (the editor's #md-library data block): Pictures,
  // then every library a text can embed, each {ref, label, one, items}.
  const libraries = (() => { try { return JSON.parse(document.getElementById('md-library')?.textContent || '[]'); } catch { return []; } })();
  // What a box can take from them: pictures where it has the picture button,
  // the other libraries once they hold something.
  const librariesFor = box => libraries.filter(l => l.ref === 'picture' ? box.dataset.markdown === 'pictures' : l.items?.length && /^[a-z]+$/.test(l.ref));
  // The "library" button: choose a library, one of its items and a caption
  // if you like. A video, track or file goes in as ![Caption](/video/ID/)
  // on a line of its own, drawn as its block draws it; for a picture, the
  // picture chooser opens, and it goes in as a figure.
  function fromLibrary(box) {
    const {selectionStart: s, selectionEnd: e} = box;
    const offered = librariesFor(box);
    if (!offered.length) return;
    const dialog = document.createElement('dialog');
    dialog.className = 'md-library';
    dialog.innerHTML = '<form method="dialog"><h2>Add from the library</h2><label>Library<select data-library></select></label>'
      + '<label data-item-label><span></span><select data-item></select></label>'
      + '<label>Caption <span class="optional">optional; shown under it</span><input maxlength="200"></label>'
      + '<p class="md-library__buttons"><button class="buttonlike" value="cancel" formnovalidate>cancel</button> <button class="buttonlike is-primary" value="add">add</button></p></form>';
    const kinds = dialog.querySelector('[data-library]'), select = dialog.querySelector('[data-item]'), itemLabel = dialog.querySelector('[data-item-label]');
    const caption = dialog.querySelector('input'), add = dialog.querySelector('[value=add]');
    offered.forEach((l, i) => kinds.append(new Option(l.label, String(i))));
    // The library chosen last time in this editor, if it's still offered.
    kinds.value = String(Math.max(0, offered.findIndex(l => l.ref === fromLibrary.last)));
    function show() {
      const lib = offered[+kinds.value], pictures = lib.ref === 'picture';
      itemLabel.hidden = pictures; select.required = !pictures;
      itemLabel.firstElementChild.textContent = lib.one.charAt(0).toUpperCase() + lib.one.slice(1);
      select.replaceChildren(...(lib.items || []).map(i => new Option((i.title || '(no title)') + (i.note ? ' · ' + i.note : ''), i.id)));
      add.textContent = pictures ? 'choose picture' : 'add';
    }
    kinds.addEventListener('change', show);
    show();
    document.body.append(dialog);
    dialog.addEventListener('close', () => {
      const lib = offered[+kinds.value], id = select.value, words = caption.value.replace(/[\r\n[\]\\]/g, ' ').trim();
      const go = dialog.returnValue === 'add';
      dialog.remove();
      if (go) fromLibrary.last = lib.ref;
      box.focus(); box.setSelectionRange(s, e);
      if (go && lib.ref === 'picture') { picture(box, words); return; }
      if (go && /^[a-f0-9]{32}$/.test(id)) block(box, `![${words}](/${lib.ref}/${id}/)`);
    });
    dialog.showModal();
  }
  const tools = [
    ['bold', '<strong>B</strong>', `Bold (${mod}B)`, box => wrap(box, '**', 'bold text')],
    ['italic', '<em>I</em>', `Italic (${mod}I)`, box => wrap(box, '*', 'italic text')],
    ['strike', '<s>S</s>', 'Struck through', box => wrap(box, '~~', 'struck text')],
    ['heading', 'H', 'Heading (again for a smaller one, again for none)', box => prefix(box, 'heading')],
    ['link', 'link', `Link (${mod}K)`, link],
    ['bullet', '•&#8239;list', 'List', box => prefix(box, 'bullet')],
    ['number', '1.&#8239;list', 'Numbered list', box => prefix(box, 'number')],
    ['task', '☐&#8239;list', 'Tick boxes', box => prefix(box, 'task')],
    ['quote', '“ ”', 'Quotation', box => prefix(box, 'quote')],
    ['code', '&lt;/&gt;', 'Code', code],
    ['table', 'table', 'Table', table],
    ['footnote', 'note¹', 'Footnote', footnote],
    ['picture', 'picture', 'Picture from the library', box => picture(box)],
    ['library', 'library', 'From the library', fromLibrary],
    ['help', '?', 'Markdown help', help],
  ];
  function attach(box) {
    if (box.dataset.mdReady) return;
    box.dataset.mdReady = '1';
    const bar = document.createElement('div');
    bar.className = 'md-tools';
    bar.setAttribute('role', 'toolbar'); bar.setAttribute('aria-label', 'Formatting');
    for (const [name, label, title, act] of tools) {
      if (name === 'picture' && box.dataset.markdown !== 'pictures') continue;
      // "library" names what it offers here: "From the library: pictures, videos, music".
      const offered = name === 'library' ? librariesFor(box) : null;
      if (offered && !offered.length) continue;
      if (name === 'help') {
        const menu = document.createElement('select');
        menu.className = 'md-tools__more'; menu.setAttribute('aria-label', 'More: boxes, buttons, columns…'); menu.tabIndex = -1;
        menu.append(new Option('more…', ''), ...more.map(([text], i) => new Option(text, String(i))));
        menu.addEventListener('change', () => { const tool = more[+menu.value]; menu.value = ''; if (tool) tool[1](box); });
        bar.append(menu);
        if (!document.getElementById('md-help')) continue;
      }
      const button = document.createElement('button');
      button.type = 'button'; button.className = 'md-tools__button'; button.innerHTML = label;
      const buttonName = offered ? `${title}: ${offered.map(l => l.label.toLowerCase()).join(', ')}` : title;
      button.title = buttonName; button.setAttribute('aria-label', buttonName); button.tabIndex = bar.childElementCount ? -1 : 0;
      // Keep the box's selection: the button acts on it without taking focus first.
      button.addEventListener('mousedown', event => event.preventDefault());
      button.addEventListener('click', () => act(box));
      bar.append(button);
    }
    // One stop in the tab order; the arrow keys move along the toolbar.
    bar.addEventListener('keydown', event => {
      const buttons = [...bar.children], i = buttons.indexOf(document.activeElement);
      const to = {ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: buttons.length - 1}[event.key];
      if (to === undefined || i < 0) return;
      event.preventDefault();
      const next = buttons[(to + buttons.length) % buttons.length];
      buttons.forEach(b => { b.tabIndex = b === next ? 0 : -1; }); next.focus();
    });
    // In a <label>, the toolbar's words would join the box's name: name it from the label first.
    const label = box.closest('label');
    // (The label's own words only: its text holds the box's starting text too.)
    const named = label && [...label.childNodes].filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent).join(' ').trim();
    if (named && !box.hasAttribute('aria-label')) box.setAttribute('aria-label', named);
    box.before(bar);
    box.addEventListener('keydown', event => {
      if (event.isComposing) return;
      const key = event.key.toLowerCase();
      if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && ['b', 'i', 'k'].includes(key)) {
        event.preventDefault();
        if (key === 'b') wrap(box, '**', 'bold text'); else if (key === 'i') wrap(box, '*', 'italic text'); else link(box);
        return;
      }
      if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey && !event.metaKey && !event.altKey) enter(box, event);
      if (event.key === 'Tab' && !event.ctrlKey && !event.metaKey && !event.altKey) indent(box, event);
    });
  }
  document.querySelectorAll('textarea[data-markdown]').forEach(attach);
  document.addEventListener('focusin', event => { if (event.target.matches?.('textarea[data-markdown]')) attach(event.target); });
  return {wrapIn, attach};
})();

(() => {
  // Page builder: every block and setting saves together with "save".
  const bulk = document.getElementById('bulk-edit');
  if (!bulk) return;
  const status = document.getElementById('edit-status');
  let dirty = false, saving = null;
  document.querySelectorAll('[form="bulk-edit"]:not(button)').forEach(input => input.addEventListener('input', () => {
    dirty = true; status.textContent = 'Unsaved changes';
  }));
  function saveAll() {
    if (saving) return saving;
    if (!bulk.reportValidity()) return Promise.resolve(false);
    const buttons = document.querySelectorAll('button[form="bulk-edit"]');
    buttons.forEach(button => { button.disabled = true; });
    status.textContent = 'Saving…';
    // Snapshot a version so typing while a request is in flight stays marked unsaved.
    const snapshot = new URLSearchParams(new FormData(bulk)).toString();
    saving = (async () => {
      try {
        const response = await fetch('/admin/', {method:'POST', body:new FormData(bulk), headers:{'X-Requested-With':'fetch'}});
        const result = await response.json();
        if (!response.ok || !result.ok) throw new Error(result.message || 'Could not save.');
        dirty = snapshot !== new URLSearchParams(new FormData(bulk)).toString();
        status.textContent = dirty ? 'Unsaved changes' : 'All changes saved';
        return !dirty;
      } catch (error) { status.textContent = 'Not saved: ' + (error.message || 'your edits are still here.'); return false; }
      finally { buttons.forEach(button => { button.disabled = false; }); saving = null; }
    })();
    return saving;
  }
  Admin.savers.push({unsaved: () => dirty, save: saveAll});
  bulk.addEventListener('submit', event => { event.preventDefault(); saveAll(); });
})();

(() => {
  // Ordinary forms: confirm deletes, save pending edits first, and come back to
  // the same scroll position after the page reloads.
  const scrollKey = 'bf-admin-scroll:' + (new URLSearchParams(location.search).get('kind') || '');
  try { const y = sessionStorage.getItem(scrollKey); if (y !== null) { sessionStorage.removeItem(scrollKey); if (!location.hash) requestAnimationFrame(() => window.scrollTo(0,Number(y))); } } catch {}
  document.querySelectorAll('form:not(#bulk-edit):not(#upload-form):not(.lib-edit):not(.lib-move):not(.move-form):not(#article-editor):not(#theme-editor)').forEach(form => form.addEventListener('submit', async event => {
    if (form.dataset.resubmitting) {
      delete form.dataset.resubmitting;
      try { sessionStorage.setItem(scrollKey, String(window.scrollY)); } catch {}
      return;
    }
    if (form.classList.contains('delete-form') && !confirm(form.dataset.confirm || 'Delete this item? This cannot be undone.')) { event.preventDefault(); return; }
    if (Admin.unsaved()) {
      event.preventDefault();
      if (!await Admin.saveAll()) return;
      form.dataset.resubmitting = '1';
      form.requestSubmit(event.submitter);
      return;
    }
    try { sessionStorage.setItem(scrollKey, String(window.scrollY)); } catch {}
  }));
})();

// Filters and pickers that apply as soon as one is chosen (the Comments and
// Analytics filters, a user's role): their button is for browsers without
// the script only.
document.querySelectorAll('form[data-auto-submit]').forEach(form => form.addEventListener('change', () => form.requestSubmit()));

// Sends an admin action and returns its JSON answer. Errors carry retry: true
// when trying again may help (a dropped connection, a server hiccup) and false
// when the server refused with a message for you.
async function adminPost(fields) {
  const body = fields instanceof FormData ? fields : new FormData();
  if (!(fields instanceof FormData)) {
    body.append('csrf', document.querySelector('input[name=csrf]').value);
    for (const [k, v] of Object.entries(fields)) {
      if (Array.isArray(v)) v.forEach(x => body.append(k, x));
      else if (v instanceof Blob) body.append(k, v, v.name || 'piece');
      else if (v !== undefined && v !== null) body.append(k, v);
    }
  }
  let response, result;
  try { response = await fetch('/admin/', {method: 'POST', body, headers: {'X-Requested-With': 'fetch'}}); }
  catch { throw Object.assign(new Error('The connection dropped.'), {retry: true}); }
  try { result = await response.json(); } catch { result = {}; }
  if (response.ok && result.ok) return result;
  throw Object.assign(new Error(result.message || `The server answered ${response.status}.`), {retry: response.status !== 400});
}
// The picture chooser: browse the library's folders, upload into the one being
// viewed, and pick a picture. Resolves with the picture ({id, url, thumb,
// title, description, width, height, folder}) or null when cancelled; with
// multiple: true, an array of pictures (empty when cancelled).
function choosePicture({folder = '', title = 'Choose a picture', multiple = false} = {}) {
  return new Promise(resolve => {
    const dialog = document.createElement('dialog');
    dialog.className = 'picker';
    dialog.innerHTML = `<form method="dialog" class="picker__head"><h2></h2><button class="picker__close" value="cancel" aria-label="Close">×</button></form>
      <div class="picker__bar"><nav class="picker__trail" aria-label="Folder"></nav>
      <input type="search" class="picker__search" placeholder="Search this folder" aria-label="Search this folder">
      <label class="buttonlike picker__upload">upload here<input type="file" accept="image/jpeg,image/png,image/webp" multiple hidden></label></div>
      <p class="picker__status" role="status"></p><div class="picker__body"><ul class="picker__folders"></ul><ul class="picker__grid"></ul><p class="picker__empty" hidden>No pictures in this folder yet. Upload some, or open another folder.</p></div>`
      + (multiple ? '<div class="picker__foot"><button type="button" class="buttonlike is-primary" data-add disabled>add pictures</button></div>' : '');
    if (multiple) dialog.querySelector('.picker__grid').classList.add('picker__grid--many');
    dialog.querySelector('h2').textContent = title;
    document.body.append(dialog);
    const trail = dialog.querySelector('.picker__trail'), folders = dialog.querySelector('.picker__folders');
    const grid = dialog.querySelector('.picker__grid'), empty = dialog.querySelector('.picker__empty');
    const status = dialog.querySelector('.picker__status'), search = dialog.querySelector('.picker__search');
    const input = dialog.querySelector('input[type=file]');
    let current = folder, pictures = [], chosen = null;
    const picked = new Map();  // multiple: chosen pictures, in the order chosen
    const add = dialog.querySelector('[data-add]');
    const count = () => { if (add) { add.disabled = !picked.size; add.textContent = picked.size ? `add ${picked.size} picture${picked.size === 1 ? '' : 's'}` : 'add pictures'; } };
    add?.addEventListener('click', () => dialog.close('chosen'));
    const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; };
    function showPictures() {
      const words = search.value.toLowerCase().split(/\s+/).filter(Boolean);
      grid.replaceChildren(...pictures.filter(p => words.every(w => (p.title + ' ' + p.description).toLowerCase().includes(w))).map(p => {
        const li = el('li'), button = el('button', 'picker__pick'); button.type = 'button';
        const img = el('img'); img.src = p.thumb; img.alt = ''; img.loading = 'lazy';
        button.append(img, el('span', 'picker__name', p.title));
        button.setAttribute('aria-label', 'Choose ' + p.title);
        if (multiple) {
          button.setAttribute('aria-pressed', String(picked.has(p.id)));
          button.addEventListener('click', () => { picked.has(p.id) ? picked.delete(p.id) : picked.set(p.id, p); button.setAttribute('aria-pressed', String(picked.has(p.id))); count(); });
        } else button.addEventListener('click', () => { chosen = p; dialog.close('chosen'); });
        li.append(button); return li;
      }));
      empty.hidden = pictures.length > 0;
    }
    async function open(path) {
      status.textContent = 'Loading…';
      try {
        const response = await fetch('/admin/?kind=photography&picker=1&folder=' + encodeURIComponent(path), {headers: {'X-Requested-With': 'fetch'}});
        const view = await response.json();
        if (!view.ok) throw new Error(view.message || 'The library could not be opened.');
        current = view.folder; pictures = view.pictures;
        trail.replaceChildren(...view.trail.flatMap((step, i) => {
          const last = i === view.trail.length - 1;
          const link = last ? el('strong', '', step.name) : el('button', 'text-button', step.name);
          if (!last) { link.type = 'button'; link.addEventListener('click', () => open(step.path)); }
          return i ? [el('span', '', '›'), link] : [link];
        }));
        folders.replaceChildren(...view.folders.map(f => {
          const li = el('li'), button = el('button', 'folder-tile'); button.type = 'button';
          button.append(el('span', 'folder-tile__icon'), el('span', 'folder-tile__name', f.name), el('span', 'folder-tile__count', f.count === 1 ? '1 picture' : f.count + ' pictures'));
          button.addEventListener('click', () => open(f.path));
          li.append(button); return li;
        }));
        search.value = ''; status.textContent = ''; showPictures();
      } catch (error) { status.textContent = error.message; }
    }
    search.addEventListener('input', showPictures);
    input.addEventListener('change', async () => {
      const files = [...input.files]; input.value = '';
      let last = null;
      for (const [i, file] of files.entries()) {
        status.textContent = `Uploading ${file.name} (${i + 1} of ${files.length})…`;
        try { last = (await adminPost({kind: 'photography', action: 'picture_upload', folder: current, picture: file})).picture; }
        catch (error) { status.textContent = `${file.name}: ${error.message}`; return; }
      }
      await open(current);
      // One picture uploaded: that's the one wanted.
      if (files.length === 1 && last && !multiple) { chosen = last; dialog.close('chosen'); }
    });
    dialog.addEventListener('close', () => { dialog.remove(); const ok = dialog.returnValue === 'chosen'; resolve(multiple ? (ok ? [...picked.values()] : []) : (ok ? chosen : null)); });
    dialog.showModal();
    open(folder);
  });
}
// A short message at the foot of the screen, gone after 4 seconds.
function adminToast(text) {
  let toast = document.querySelector('.admin-toast');
  if (!toast) { toast = document.createElement('p'); toast.className = 'admin-toast'; toast.setAttribute('role', 'status'); document.body.append(toast); }
  toast.textContent = text; toast.hidden = false;
  clearTimeout(toast.timer); toast.timer = setTimeout(() => { toast.hidden = true; }, 4000);
}

// Putting things in order by dragging, the one way every list does it (the
// server's side is list_order in Admin.pm): the rows of a [data-reorder]
// list, and the libraries' cards. items() gives the things in their order;
// idOf(item) its id; grid: side by side (a drop goes by left and right
// rather than above and below); send(ids) saves the new order. moved() runs
// whenever the order on screen changes (to renumber). A drag can't start on
// what skip matches (by default a link, button or field inside an item), so
// those still work as usual.
// A press inside a field never starts a drag, so text in an item can still
// be selected. local: the order is saved with the item's form later (a
// block's list of entries), so nothing is sent now.
// Returns commit(before): saves after the caller moved items itself (the
// move buttons), putting them back as they were if saving fails.
function makeReorderable(list, {items, idOf = item => item.dataset.reorderId, grid = false, send, moved = () => {}, skip = 'a,button,input,select,textarea,summary', local = false}) {
  let dragging = null;
  items().forEach(item => { item.draggable = true; });
  list.classList.add('can-reorder');
  list.addEventListener('pointerdown', event => {
    const item = items().find(i => i.contains(event.target));
    if (item) item.draggable = !event.target.closest('input,textarea,select,[contenteditable]');
  });
  async function commit(before) {
    const ids = items().map(idOf), was = before.map(idOf);
    if (ids.length === was.length && ids.every((id, i) => id === was[i])) return;
    moved();
    if (local) { list.dispatchEvent(new CustomEvent('reordered', {detail: {ids}})); return; }
    adminToast('Saving the order…');
    try { await send(ids); adminToast('Order saved.'); list.dispatchEvent(new CustomEvent('reordered', {detail: {ids}})); }
    catch (error) { before.forEach(item => list.append(item)); moved(); adminToast('Order not saved: ' + error.message); }
  }
  list.addEventListener('dragstart', event => {
    const item = event.target.closest?.('[draggable="true"]');
    if (!item || !items().includes(item) || event.target.closest(skip)) return;
    dragging = {item, before: items()};
    item.classList.add('is-dragging');
    event.dataTransfer.effectAllowed = 'move';
    event.dataTransfer.setData('text/plain', idOf(item));
  });
  list.addEventListener('dragover', event => {
    if (!dragging) return;
    event.preventDefault();
    const over = items().find(item => item.contains(event.target));
    if (!over || over === dragging.item) return;
    const box = over.getBoundingClientRect();
    const after = grid ? event.clientX > box.left + box.width / 2 : event.clientY > box.top + box.height / 2;
    over[after ? 'after' : 'before'](dragging.item);
  });
  list.addEventListener('drop', event => { if (dragging) event.preventDefault(); });
  list.addEventListener('dragend', () => {
    if (!dragging) return;
    const {item, before} = dragging; dragging = null;
    item.classList.remove('is-dragging');
    commit(before);
  });
  return commit;
}

(() => {
  // Theme editor: keep each colour picker in step with its text field. Text
  // fields accept any CSS colour; the picker only understands #rrggbb.
  const toHex = value => {
    const v = value.trim();
    if (/^#[0-9a-f]{6}$/i.test(v)) return v.toLowerCase();
    if (/^#[0-9a-f]{3}$/i.test(v)) return '#' + [...v.slice(1)].map(c => c + c).join('').toLowerCase();
    if (/^#[0-9a-f]{8}$/i.test(v)) return v.slice(0, 7).toLowerCase();
    if (/^#[0-9a-f]{4}$/i.test(v)) return '#' + [...v.slice(1, 4)].map(c => c + c).join('').toLowerCase();
    return null;
  };
  document.querySelectorAll('[data-color-for]').forEach(picker => {
    const text = picker.form.elements[picker.dataset.colorFor];
    const sync = () => { const hex = toHex(text.value); if (hex) picker.value = hex; picker.title = text.value; };
    picker.addEventListener('input', () => { text.value = picker.value; });
    text.addEventListener('input', sync);
    sync();
  });
  // The Themes list's colour dots, drawn from each variant's colours.
  document.querySelectorAll('[data-swatches]').forEach(holder => {
    holder.dataset.swatches.split(' ').filter(Boolean).forEach(color => {
      const dot = document.createElement('span');
      dot.style.background = color;
      holder.append(dot);
    });
  });
})();

(() => {
  // Page builder: open the block named in the address (after adding or moving one).
  const open = () => { const card = location.hash.startsWith('#block-') && document.getElementById(location.hash.slice(1)); if (card) card.querySelector('details').open = true; };
  open(); window.addEventListener('hashchange', open);
})();


(() => {
  // Libraries (Pictures, Music, Videos, Files). Each item's edit panel is in the
  // page; without JavaScript it opens through #edit-ID (CSS :target).
  const lib = document.getElementById('library');
  const box = document.getElementById('upload');
  document.querySelectorAll('[data-open-upload]').forEach(link => link.addEventListener('click', event => {
    if (!box) return;
    event.preventDefault(); box.open = true;
    box.scrollIntoView({behavior: 'smooth', block: 'start'});
    box.querySelector('input:not([type=hidden])')?.focus({preventScroll: true});
  }));
  if (box && location.hash === '#upload') box.open = true;
  if (!lib || !lib.querySelector('.lib-items')) return;
  lib.classList.add('js');
  const kind = lib.dataset.kind, one = lib.dataset.one, many = lib.dataset.many;
  const list = lib.querySelector('.lib-items');
  const cards = () => [...list.children];
  const cardFor = id => document.getElementById('item-' + id);
  const go = message => location.assign(`/admin/?kind=${kind}` + libraryFolder() + '&notice=' + encodeURIComponent(message));

  // ---- Panels ----
  let current = null;
  function open(panel) {
    if (current === panel) return;
    if (current) close(false);
    current = panel;
    panel.classList.add('is-open'); lib.classList.add('has-panel');
    cardFor(panel.id.slice(5))?.classList.add('is-current');
    history.replaceState(null, '', '#' + panel.id);
    panel.querySelector('.lib-edit input:not([type=hidden])')?.focus({preventScroll: true});
  }
  function close(updateAddress = true) {
    if (!current) return;
    const panel = current; current = null;
    const form = panel.querySelector('.lib-edit');
    if (dirty.has(form)) save(form);
    panel.classList.remove('is-open'); lib.classList.remove('has-panel');
    panel.querySelectorAll('video,audio').forEach(media => media.pause());
    const card = cardFor(panel.id.slice(5));
    card?.classList.remove('is-current');
    if (updateAddress) { history.replaceState(null, '', location.pathname + location.search); card?.querySelector('.lib-item__open').focus({preventScroll: true}); }
  }
  lib.addEventListener('click', event => {
    const link = event.target.closest('.lib-item__open');
    if (link) { event.preventDefault(); open(document.getElementById(link.hash.slice(1))); return; }
    if (event.target.closest('.lib-panel__close')) { event.preventDefault(); close(); }
  });
  document.addEventListener('keydown', event => {
    if (event.key === 'Escape' && current && !event.target.matches('input[type=search]')) close();
  });
  if (location.hash.startsWith('#edit-')) { const panel = document.getElementById(location.hash.slice(1)); if (panel) open(panel); }

  // ---- Saving ----
  // Like every screen that changes what visitors see, edits wait for a save:
  // the panel's save button, Ctrl+S, closing the panel or opening another one.
  // Leaving the page with edits still unsaved asks first.
  const dirty = new Set(), pending = new Map();
  const statusOf = form => form.querySelector('.lib-edit__status');
  function save(form) {
    if (pending.has(form)) return pending.get(form).then(() => dirty.has(form) ? save(form) : true);
    const invalid = form.querySelector(':invalid');
    if (invalid) { statusOf(form).textContent = `Not saved: ${invalid.labels?.[0]?.firstChild?.textContent.trim() || 'a field'} — ${invalid.validationMessage}`; return Promise.resolve(false); }
    const snapshot = new URLSearchParams(new FormData(form)).toString();
    dirty.delete(form); statusOf(form).textContent = 'Saving…';
    const run = (async () => {
      try {
        const {item} = await adminPost(new FormData(form));
        // Typing during the request leaves newer changes to save.
        if (new URLSearchParams(new FormData(form)).toString() !== snapshot) dirty.add(form);
        update(form, item);
        statusOf(form).textContent = dirty.has(form) ? 'Unsaved changes' : 'All changes saved';
        return true;
      } catch (error) { dirty.add(form); statusOf(form).textContent = 'Not saved: ' + error.message; return false; }
      finally { pending.delete(form); }
    })();
    pending.set(form, run);
    return run;
  }
  // Shows the saved values on the item's card.
  function update(form, item) {
    const card = cardFor(form.elements.id.value);
    if (!card || !item) return;
    // A picture moved to another folder leaves this one.
    if ('folder' in item && item.folder !== (lib.dataset.folder || '')) { card.remove(); form.closest('.lib-panel')?.remove(); if (location.hash) history.replaceState(null, '', '#library'); return; }
    card.querySelector('.lib-item__title').textContent = item.title;
    card.querySelector('.lib-item__meta').textContent = [item.collection, card.dataset.extra].filter(Boolean).join(' · ');
    if ('collection' in item) card.dataset.collection = item.collection;
    card.dataset.text = [item.title, item.collection, item.description].filter(Boolean).join(' ').toLowerCase();
    card.querySelector('.lib-check input').setAttribute('aria-label', 'Select ' + item.title);
  }
  lib.querySelectorAll('.lib-edit').forEach(form => {
    form.addEventListener('input', () => {
      dirty.add(form); statusOf(form).textContent = 'Unsaved changes';
    });
    form.addEventListener('submit', event => { event.preventDefault(); save(form); });
  });
  Admin.savers.push({
    unsaved: () => dirty.size > 0 || pending.size > 0,
    save: async () => (await Promise.all([...new Set([...dirty, ...pending.keys()])].map(save))).every(Boolean),
  });

  // ---- Search and collection filter ----
  const tools = lib.querySelector('.lib-tools');
  const search = tools.querySelector('.lib-search'), filter = tools.querySelector('.lib-filter');
  const count = tools.querySelector('.lib-count'), none = lib.querySelector('.lib-none');
  tools.hidden = false;
  const filtering = () => search.value.trim() !== '' || (filter && filter.value !== '');
  function applyFilter() {
    const words = search.value.toLowerCase().split(/\s+/).filter(Boolean);
    const want = filter ? filter.value : '';
    let shown = 0;
    for (const card of cards()) {
      const ok = words.every(word => card.dataset.text.includes(word)) &&
        (want === '' || (want === ':none' ? card.dataset.collection === '' : card.dataset.collection === want));
      card.hidden = !ok; if (ok) shown++;
    }
    const total = cards().length;
    count.textContent = filtering() ? `${shown} of ${total} ${many}` : `${total} ${total === 1 ? one : many}`;
    none.hidden = shown > 0;
  }
  search.addEventListener('input', applyFilter);
  filter?.addEventListener('change', applyFilter);

  // ---- Selection and bulk actions ----
  const bulk = lib.querySelector('.lib-bulk');
  const boxes = () => cards().map(card => card.querySelector('.lib-check input'));
  const selected = () => boxes().filter(box => box.checked).map(box => box.value);
  let anchor = null;
  function showSelection() {
    const n = selected().length;
    bulk.hidden = n === 0; lib.classList.toggle('is-selecting', n > 0);
    bulk.querySelector('.lib-bulk__count').textContent = `${n} ${n === 1 ? one : many} selected`;
    cards().forEach(card => card.classList.toggle('is-selected', card.querySelector('.lib-check input').checked));
  }
  list.addEventListener('click', event => {
    const box = event.target.closest('.lib-check input');
    if (!box) return;
    // Shift-click selects everything (visible) between this and the last box clicked.
    const visible = boxes().filter(b => !b.closest('.lib-item').hidden);
    if (event.shiftKey && anchor && visible.includes(anchor)) {
      const [from, to] = [visible.indexOf(anchor), visible.indexOf(box)].sort((a, b) => a - b);
      visible.slice(from, to + 1).forEach(b => { b.checked = box.checked; });
    }
    anchor = box; showSelection();
  });
  bulk.addEventListener('click', async event => {
    const button = event.target.closest('[data-bulk]');
    if (!button) return;
    const op = button.dataset.bulk, ids = selected();
    if (op === 'clear') { boxes().forEach(box => { box.checked = false; }); showSelection(); return; }
    if (op === 'delete' && !confirm(`Delete ${ids.length} ${ids.length === 1 ? one : many}? This cannot be undone.`)) return;
    if (!await Admin.saveAll()) { adminToast('Some edits could not be saved; nothing was changed.'); return; }
    button.disabled = true;
    try { go((await adminPost({kind, action: 'bulk', op, ids, collection: bulk.querySelector('.lib-bulk__collection')?.value ?? '', folder: bulk.querySelector('.lib-bulk__folder')?.value ?? '', tags: bulk.querySelector('.lib-bulk__tags')?.value ?? ''})).message); }
    catch (error) { adminToast(error.message); button.disabled = false; }
  });

  // ---- Order: drag cards, or use the panel's position controls ----
  const grid = lib.classList.contains('lib--grid');
  function renumber() {
    const all = cards();
    all.forEach((card, i) => {
      const form = document.getElementById('edit-' + card.dataset.id)?.querySelector('.lib-move');
      if (!form) return;
      form.elements.position.value = i + 1;
      form.querySelector('[value=up]').disabled = i === 0;
      form.querySelector('[value=down]').disabled = i === all.length - 1;
    });
  }
  // A card is a link to its panel, so a drag can start anywhere on it but its tick box.
  const commit = makeReorderable(list, {items: cards, idOf: card => card.dataset.id, grid, moved: renumber, skip: 'input,button',
    send: ids => adminPost({kind, action: 'reorder', ids})});
  lib.querySelectorAll('.lib-move').forEach(form => form.addEventListener('submit', event => {
    event.preventDefault();
    const card = cardFor(form.elements.id.value), all = cards(), from = all.indexOf(card);
    const direction = event.submitter?.value || 'position';
    let to = direction === 'up' ? from - 1 : direction === 'down' ? from + 1 : (parseInt(form.elements.position.value, 10) || 1) - 1;
    to = Math.max(0, Math.min(all.length - 1, to));
    if (to === from) { renumber(); return; }
    const rest = all.filter(c => c !== card);
    if (to >= rest.length) list.append(card); else rest[to].before(card);
    commit(all);
  }));
})();

(() => {
  // Uploads: files go up one after another, each in pieces. Each file's upload
  // id is remembered, so choosing the same file again after a pause, a dropped
  // connection or a closed page continues where it stopped.
  const form = document.getElementById('upload-form');
  if (!form) return;
  const kind = form.dataset.kind, max = Number(form.dataset.max), exts = form.dataset.exts ? form.dataset.exts.split(' ') : [];
  const lib = document.getElementById('library');
  const one = lib?.dataset.one || 'file', many = lib?.dataset.many || 'files';
  const box = document.getElementById('upload'), status = document.getElementById('upload-status');
  const pause = document.getElementById('upload-pause'), queueList = document.getElementById('upload-queue');
  const button = form.querySelector('button[type=submit]');
  const store = {
    get: k => { try { return localStorage.getItem(k); } catch { return null; } },
    set: (k, v) => { try { localStorage.setItem(k, v); } catch {} },
    drop: k => { try { localStorage.removeItem(k); } catch {} },
  };
  const size = n => n >= 1073741824 ? (n / 1073741824).toFixed(2) + ' GB' : n >= 1048576 ? Math.round(n / 1048576) + ' MB' : Math.max(1, Math.round(n / 1024)) + ' KB';
  const queue = [];
  const done = [], failed = [];
  let running = false, stopping = false;

  function add(files) {
    if (!files.length) return;
    // Settings at the moment of choosing apply to these files.
    const batch = {
      collection: form.elements.collection?.value ?? '', folder: form.elements.folder?.value ?? '', description: form.elements.description.value,
      artwork: form.elements.artwork?.files[0] || null, artworkName: '',
      poster: files.length === 1 ? form.elements.poster?.files[0] || null : null,
    };
    for (const file of files) {
      const row = document.createElement('li');
      const name = document.createElement('span'); name.className = 'upload-queue__name'; name.textContent = `${file.name} · ${size(file.size)}`;
      const bar = document.createElement('progress'); bar.max = 100; bar.value = 0;
      const state = document.createElement('span'); state.className = 'upload-queue__state'; state.textContent = 'Waiting';
      row.append(name, bar, state); queueList.append(row);
      const ext = (file.name.match(/\.([^.]+)$/) || [])[1]?.toLowerCase();
      if (exts.length && !exts.includes(ext)) { state.textContent = `Not a ${exts.join(', ').toUpperCase()} file; skipped.`; row.className = 'is-failed'; continue; }
      if (file.size > max) { state.textContent = `Larger than ${size(max)}; skipped.`; row.className = 'is-failed'; continue; }
      queue.push({file, batch, row, bar, state});
    }
    queueList.hidden = false; box.open = true;
    if (form.elements.artwork) form.elements.artwork.value = '';
    if (form.elements.poster) form.elements.poster.value = '';
    run();
  }

  async function send(job) {
    const {file, batch, bar, state} = job;
    const key = `bf-upload:${kind}:` + [file.name, file.size, file.lastModified].join(':');
    let upload = null;
    if (store.get(key)) {
      try { upload = await adminPost({kind, action: 'upload_status', upload: store.get(key)}); state.textContent = 'Resuming…'; }
      catch { store.drop(key); }
    }
    if (!upload) {
      upload = await adminPost({kind, action: 'upload_start', name: file.name, size: String(file.size), collection: batch.collection, folder: batch.folder, description: batch.description});
      store.set(key, upload.upload);
    }
    let offset = upload.received, failures = 0;
    const started = Date.now(), first = offset;
    try {
      while (offset < file.size) {
        if (stopping) throw Object.assign(new Error('Paused'), {paused: true});
        try {
          offset = (await adminPost({kind, action: 'upload_chunk', upload: upload.upload, offset: String(offset), chunk: file.slice(offset, offset + upload.chunk)})).received;
          failures = 0;
        } catch (error) {
          if (!error.retry && !/out of order/.test(error.message)) throw error;
          if (++failures >= 6) throw Object.assign(new Error('The connection keeps dropping. Choose the file again to continue where it stopped.'), {paused: true});
          state.textContent = 'Connection trouble; retrying…';
          await new Promise(resolve => setTimeout(resolve, 1500 * failures));
          // Find out what actually arrived, then carry on from there.
          try { offset = (await adminPost({kind, action: 'upload_status', upload: upload.upload})).received; }
          catch (inner) { if (!inner.retry) throw inner; }
          continue;
        }
        bar.value = Math.floor(offset / file.size * 100);
        const rate = (offset - first) / Math.max((Date.now() - started) / 1000, 1);
        const left = rate > 0 ? (file.size - offset) / rate : 0;
        state.textContent = `${bar.value}%` + (left > 10 ? ` · about ${left > 90 ? Math.round(left / 60) + ' min' : Math.round(left) + ' s'} left` : '');
      }
      state.textContent = kind === 'video' ? 'Checking the video…' : 'Processing…';
      const fields = {kind, action: 'upload_finish', upload: upload.upload};
      if (batch.artworkName) fields.artwork_name = batch.artworkName; else if (batch.artwork) fields.artwork = batch.artwork;
      if (batch.poster) fields.poster = batch.poster;
      const result = await adminPost(fields);
      if (result.artwork) batch.artworkName = result.artwork;
      store.drop(key);
      return result.message;
    } catch (error) {
      // A refused file can't be resumed; a pause or a dropped connection can.
      if (!error.paused && !error.retry) store.drop(key);
      throw error;
    }
  }

  async function run() {
    if (running) return;
    running = true; stopping = false; Admin.busy = true;
    button.disabled = true; pause.hidden = false; pause.disabled = false;
    while (queue.length) {
      const job = queue[0];
      status.textContent = `Uploading ${done.length + failed.length + 1} of ${done.length + failed.length + queue.length}…`;
      try { done.push(await send(job)); job.state.textContent = 'Published'; job.bar.value = 100; job.row.className = 'is-done'; queue.shift(); }
      catch (error) {
        if (error.paused) { job.state.textContent = error.message === 'Paused' ? 'Paused' : error.message; break; }
        job.state.textContent = error.message; job.row.className = 'is-failed'; failed.push(job); queue.shift();
      }
    }
    running = false; Admin.busy = false; button.disabled = false; pause.hidden = true;
    if (queue.length) { status.textContent = `Paused with ${queue.length} left. Press upload & publish to continue.`; return; }
    if (done.length && !failed.length) { go(done.length === 1 ? done[0] : `${done.length} ${many} published.`); return; }
    status.textContent = `${done.length} published, ${failed.length} not uploaded (see the list).`;
    if (done.length) {
      const reload = document.createElement('button');
      reload.type = 'button'; reload.className = 'text-button'; reload.textContent = 'show the new ' + (done.length === 1 ? one : many);
      reload.addEventListener('click', () => location.assign(`/admin/?kind=${kind}`));
      status.append(' ', reload);
    }
  }
  const go = message => location.assign(`/admin/?kind=${kind}` + libraryFolder() + '&notice=' + encodeURIComponent(message));

  pause.addEventListener('click', () => { stopping = true; pause.disabled = true; });
  form.addEventListener('submit', event => {
    event.preventDefault();
    const files = [...form.elements.media.files];
    form.elements.media.value = '';
    if (files.length) add(files);
    else if (queue.length) run();
    else status.textContent = `Choose ${many} first, or drop them anywhere on this page.`;
  });
  form.elements.media.required = false;
  // The +picture button at the top: choosing files uploads them straight away.
  document.querySelectorAll('[data-upload-input]').forEach(input => input.addEventListener('change', () => {
    const files = [...input.files]; input.value = '';
    if (!files.length) return;
    box.open = true; add(files);
    box.scrollIntoView({behavior: 'smooth', block: 'start'});
  }));

  // Drop files anywhere on the page.
  const overlay = document.createElement('div');
  overlay.className = 'drop-overlay'; overlay.hidden = true;
  overlay.textContent = `Drop ${many} to upload them`;
  document.body.append(overlay);
  const hasFiles = event => [...(event.dataTransfer?.types || [])].includes('Files');
  let depth = 0;
  document.addEventListener('dragenter', event => { if (hasFiles(event)) { depth++; overlay.hidden = false; } });
  document.addEventListener('dragleave', event => { if (hasFiles(event) && --depth <= 0) { depth = 0; overlay.hidden = true; } });
  document.addEventListener('dragover', event => { if (hasFiles(event)) { event.preventDefault(); event.dataTransfer.dropEffect = 'copy'; } });
  document.addEventListener('drop', event => {
    if (!hasFiles(event)) return;
    event.preventDefault(); depth = 0; overlay.hidden = true;
    box.open = true; add([...event.dataTransfer.files]);
    box.scrollIntoView({behavior: 'smooth', block: 'start'});
  });
})();

// A live preview: shows a public page's HTML (from the server) in a frame,
// either at desktop width scaled down to fit, or at phone width.
function previewFrame(holder, label, natural = false) {
  const bar = document.createElement('div'); bar.className = 'preview-frame__bar';
  const note = document.createElement('span'); note.className = 'preview-frame__note'; note.setAttribute('role', 'status');
  const modes = document.createElement('div'); modes.className = 'preview-frame__modes';
  const view = document.createElement('div'); view.className = 'preview-frame__view';
  const frame = document.createElement('iframe');
  frame.title = 'Preview';
  view.append(frame);
  let mode = 'desktop';
  try { mode = localStorage.getItem('bf-preview-mode') || mode; } catch {}
  for (const name of ['desktop', 'phone']) {
    const button = document.createElement('button');
    button.type = 'button'; button.className = 'text-button'; button.textContent = name; button.dataset.mode = name;
    button.addEventListener('click', () => { mode = name; try { localStorage.setItem('bf-preview-mode', name); } catch {} fit(); });
    modes.append(button);
  }
  bar.append(note, modes); holder.append(bar, view);
  if (label) frame.title = label;
  function fit() {
    // The site's widest layout, scaled to fit; or, for the page editor, the
    // room there is (so texts are edited at their real size).
    const width = mode === 'phone' ? 390 : natural ? Math.max(320, view.clientWidth) : 1180;
    const scale = Math.min(1, view.clientWidth / width);
    frame.style.width = width + 'px';
    frame.style.height = (view.clientHeight / scale) + 'px';
    frame.style.transform = `scale(${scale})`;
    frame.style.marginLeft = Math.max(0, (view.clientWidth - width * scale) / 2) + 'px';
    modes.querySelectorAll('button').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.mode === mode)));
  }
  new ResizeObserver(fit).observe(view);
  fit();
  let scrollY = 0;
  frame.addEventListener('load', () => { try { frame.contentWindow.scrollTo(0, scrollY); } catch {} });
  return {
    show(html) {
      try { scrollY = frame.contentWindow.scrollY || 0; } catch {}
      frame.srcdoc = html; note.textContent = 'Not saved yet: this is how it will look.';
    },
    note(text) { note.textContent = text; },
    frame, view,
    scale() { return frame.getBoundingClientRect().width / (frame.offsetWidth || 1); },
  };
}

(() => {
  // Articles list: search and the status filter.
  const list = document.getElementById('articles');
  if (!list) return;
  const tools = list.querySelector('.lib-tools'), search = tools.querySelector('.lib-search'), filter = tools.querySelector('.lib-filter');
  const count = tools.querySelector('.lib-count'), none = list.querySelector('.lib-none');
  const rows = [...list.querySelectorAll('.lib-item')];
  tools.hidden = false;
  function apply() {
    const words = search.value.toLowerCase().split(/\s+/).filter(Boolean);
    let shown = 0;
    for (const row of rows) {
      const ok = words.every(word => row.dataset.text.includes(word)) && (filter.value === '' || row.dataset.collection === filter.value);
      row.hidden = !ok; if (ok) shown++;
    }
    count.textContent = shown === rows.length ? `${rows.length} ${rows.length === 1 ? 'article' : 'articles'}` : `${shown} of ${rows.length} articles`;
    none.hidden = shown > 0;
  }
  search.addEventListener('input', apply); filter.addEventListener('change', apply); apply();
})();

(() => {
  // Writing an article: live preview, drafts saved as you type, and images
  // dropped, pasted or chosen are uploaded and inserted where the cursor is.
  const form = document.getElementById('article-editor');
  if (!form) return;
  form.classList.add('has-js');
  const status = document.getElementById('article-status');
  const body = form.elements.body, title = form.elements.title;
  const published = form.dataset.published === '1';
  const pane = form.querySelector('.article-editor__preview'); pane.hidden = false;
  const preview = previewFrame(pane.querySelector('[data-preview]'));
  const buttons = [...document.querySelectorAll('button[form="article-editor"]')];
  const time = () => new Date().toLocaleTimeString([], {hour: 'numeric', minute: '2-digit'});
  let dirty = false, saving = null, autosaveTimer, previewTimer, previewSeq = 0, uploads = 0;
  const formData = action => { const data = new FormData(form); data.set('action', action); data.delete('image'); return data; };
  const snapshot = () => title.value + '\u0000' + body.value;

  async function refreshPreview() {
    const seq = ++previewSeq;
    try { const {html} = await adminPost(formData('preview_html')); if (seq === previewSeq) preview.show(html); }
    catch (error) { preview.note('Preview unavailable: ' + error.message); }
  }
  function changed() {
    dirty = true;
    clearTimeout(previewTimer); previewTimer = setTimeout(refreshPreview, 400);
    if (published) { status.textContent = 'Unsaved changes · press update to publish them'; return; }
    status.textContent = 'Unsaved changes';
    clearTimeout(autosaveTimer); autosaveTimer = setTimeout(save, 1500);
  }
  // Drafts: saved quietly. Published articles: "update" (or Ctrl+S) saves them.
  function save() {
    clearTimeout(autosaveTimer);
    if (saving) return saving.then(() => dirty ? save() : true);
    if (!title.value.trim()) { status.textContent = 'Add a title to save this draft'; return Promise.resolve(false); }
    if (uploads) { status.textContent = 'Waiting for images to finish uploading…'; autosaveTimer = setTimeout(save, 1000); return Promise.resolve(false); }
    const sent = snapshot();
    status.textContent = 'Saving…';
    saving = (async () => {
      try {
        const result = await adminPost(formData(published ? 'publish' : 'autosave'));
        if (!form.elements.id.value) {
          form.elements.id.value = result.id;
          history.replaceState(null, '', `/admin/?kind=blog&id=${result.id}`);
        }
        dirty = snapshot() !== sent;
        status.textContent = dirty ? 'Unsaved changes' : `${published ? 'Published changes saved' : 'Draft saved'} at ${time()}`;
        if (dirty && !published) autosaveTimer = setTimeout(save, 1500);
        return !dirty;
      } catch (error) { status.textContent = 'Not saved: ' + error.message; return false; }
      finally { saving = null; }
    })();
    return saving;
  }
  Admin.savers.push({unsaved: () => dirty, save});
  form.addEventListener('input', event => { if (event.target.type !== 'file') changed(); });
  form.addEventListener('submit', event => { event.preventDefault(); save(); });
  const heading = document.querySelector('.admin-top h1');
  title.addEventListener('input', () => { heading.textContent = title.value.trim() || 'New article'; });

  // Publishing, unpublishing and the first save of a draft reload the page.
  buttons.forEach(button => button.addEventListener('click', async event => {
    event.preventDefault();
    const action = button.value;
    if (action === 'publish' && published) { save(); return; }
    if (action === 'save_draft' && published && !confirm('Unpublish this article? Visitors will no longer see it.')) return;
    if (!form.reportValidity()) return;
    if (saving) await saving;
    buttons.forEach(b => { b.disabled = true; });
    try {
      const result = await adminPost(formData(action));
      dirty = false;
      location.assign(`/admin/?kind=blog&id=${result.id}&notice=` + encodeURIComponent(result.message));
    } catch (error) { status.textContent = error.message; buttons.forEach(b => { b.disabled = false; }); }
  }));

  // Images: a placeholder marks the spot while the image uploads.
  let n = 0;
  async function insertImages(files) {
    for (const file of files) {
      if (!/^image\/(jpeg|png|webp)$/.test(file.type)) { status.textContent = `${file.name}: use a JPEG, PNG or WebP image.`; continue; }
      const mark = `![Uploading ${file.name.replace(/[[\]]/g, '')} (${++n})…]()`;
      const start = body.selectionStart, before = body.value.slice(0, start);
      const lead = before === '' || before.endsWith('\n\n') ? '' : before.endsWith('\n') ? '\n' : '\n\n';
      body.setRangeText(lead + mark + '\n\n', start, body.selectionEnd, 'end');
      uploads++; changed();
      try {
        const {markdown} = await adminPost({kind: 'blog', action: 'image_upload', image: file});
        const at = body.value.indexOf(mark), caret = body.selectionStart;
        if (at >= 0) { body.setRangeText(markdown, at, at + mark.length, 'preserve'); if (caret > at) body.setSelectionRange(caret + markdown.length - mark.length, caret + markdown.length - mark.length); }
      } catch (error) {
        const at = body.value.indexOf(mark);
        if (at >= 0) body.setRangeText('', at, at + mark.length + 2, 'preserve');
        status.textContent = `${file.name} not uploaded: ${error.message}`;
      } finally { uploads--; changed(); }
    }
  }
  const imageInput = form.elements.image;
  imageInput.addEventListener('change', () => { const files = [...imageInput.files]; imageInput.value = ''; body.focus(); insertImages(files); });
  const hasFiles = event => [...(event.dataTransfer?.types || [])].includes('Files');
  body.addEventListener('dragover', event => { if (hasFiles(event)) { event.preventDefault(); body.classList.add('is-dropping'); } });
  body.addEventListener('dragleave', () => body.classList.remove('is-dropping'));
  body.addEventListener('drop', event => {
    if (!hasFiles(event)) return;
    event.preventDefault(); body.classList.remove('is-dropping'); body.focus();
    insertImages([...event.dataTransfer.files]);
  });
  body.addEventListener('paste', event => {
    const files = [...(event.clipboardData?.files || [])];
    if (files.length) { event.preventDefault(); insertImages(files); }
  });
  refreshPreview();
})();

(() => {
  // Theme editor: the site drawn with the unsaved theme beside the form.
  // Saving (the button or Ctrl+S) happens in the background.
  const form = document.getElementById('theme-editor');
  if (!form) return;
  const status = document.getElementById('theme-status');
  const pane = document.querySelector('.theme-workspace__preview'); pane.hidden = false;
  const preview = previewFrame(pane.querySelector('[data-preview]'));
  const page = document.getElementById('theme-preview-page');
  const time = () => new Date().toLocaleTimeString([], {hour: 'numeric', minute: '2-digit'});
  const snapshot = () => new URLSearchParams(new FormData(form)).toString();
  let dirty = false, timer, seq = 0, saving = null;
  async function refresh() {
    const data = new FormData(form); data.set('action', 'theme_preview'); data.set('preview_page', page.value);
    const mine = ++seq;
    try { const {html} = await adminPost(data); if (mine === seq) preview.show(html); }
    catch (error) { if (mine === seq) preview.note('Preview not updated: ' + error.message); }
  }
  form.addEventListener('input', () => {
    dirty = true; status.textContent = 'Unsaved changes';
    clearTimeout(timer); timer = setTimeout(refresh, 450);
  });
  page.addEventListener('change', refresh);
  function save() {
    if (saving) return saving;
    if (!form.reportValidity()) return Promise.resolve(false);
    const sent = snapshot();
    status.textContent = 'Saving…';
    saving = (async () => {
      try {
        const result = await adminPost(new FormData(form));
        dirty = snapshot() !== sent;
        status.textContent = dirty ? 'Unsaved changes' : `All changes saved at ${time()}`;
        return !dirty;
      } catch (error) { status.textContent = 'Not saved: ' + error.message; return false; }
      finally { saving = null; }
    })();
    return saving;
  }
  form.addEventListener('submit', event => { event.preventDefault(); save(); });
  Admin.savers.push({unsaved: () => dirty, save});
  refresh();
})();

(() => {
  // Picture fields in the page builder: one picture (Text and picture) or an
  // ordered list (a gallery of chosen pictures). Both fill a hidden input the
  // page form sends; firing "input" marks the page as changed.
  const changed = input => input.dispatchEvent(new Event('input', {bubbles: true}));
  const bindPicture = field => {
    if (field.dataset.bound) return; field.dataset.bound = '1';
    const input = field.querySelector('input[type=hidden]'), preview = field.querySelector('.picture-field__preview');
    const choose = field.querySelector('[data-choose-picture]'), clear = field.querySelector('[data-clear-picture]');
    const show = picture => {
      preview.replaceChildren();
      if (picture) { const img = document.createElement('img'); img.src = picture.thumb; img.alt = ''; const name = document.createElement('span'); name.textContent = picture.title; preview.append(img, name); }
      else { const none = document.createElement('span'); none.className = 'optional'; none.textContent = 'No picture chosen.'; preview.append(none); }
      choose.textContent = picture ? 'change picture' : 'choose picture'; clear.hidden = !picture;
    };
    choose.addEventListener('click', async () => {
      const picture = await choosePicture({title: 'Choose the picture'});
      if (!picture) return;
      input.value = picture.id; show(picture); changed(input);
    });
    clear.addEventListener('click', () => { input.value = ''; show(null); changed(input); });
  };
  window.bindPictureField = bindPicture;
  document.querySelectorAll('[data-picture-field]').forEach(bindPicture);
  document.querySelectorAll('[data-pictures-field]').forEach(field => {
    const input = field.querySelector('input[type=hidden]'), list = field.querySelector('.picture-list');
    const sync = () => { input.value = [...list.children].map(li => li.dataset.id).join(','); changed(input); };
    const item = picture => {
      const li = document.createElement('li'); li.dataset.id = picture.id;
      const img = document.createElement('img'); img.src = picture.thumb; img.alt = ''; img.title = picture.title;
      const tools = document.createElement('span'); tools.className = 'picture-list__tools';
      for (const [label, attr, value, cls] of [['←', 'data-move', '-1', 'text-button'], ['→', 'data-move', '1', 'text-button'], ['×', 'data-remove', '', 'text-button danger']]) {
        const b = document.createElement('button'); b.type = 'button'; b.className = cls; b.textContent = label; b.setAttribute(attr, value);
        b.setAttribute('aria-label', (attr === 'data-remove' ? 'Remove ' : value === '-1' ? 'Move earlier: ' : 'Move later: ') + picture.title);
        tools.append(b);
      }
      li.append(img, tools); return li;
    };
    list.addEventListener('click', event => {
      const button = event.target.closest('button'); if (!button) return;
      const li = button.closest('li');
      if (button.hasAttribute('data-remove')) li.remove();
      else if (button.dataset.move === '-1' && li.previousElementSibling) li.previousElementSibling.before(li);
      else if (button.dataset.move === '1' && li.nextElementSibling) li.nextElementSibling.after(li);
      sync();
    });
    field.querySelector('[data-add-pictures]').addEventListener('click', async () => {
      const chosen = await choosePicture({title: 'Add pictures to the gallery', multiple: true});
      const have = new Set([...list.children].map(li => li.dataset.id));
      chosen.filter(p => !have.has(p.id)).forEach(p => list.append(item(p)));
      if (chosen.length) sync();
    });
  });
})();

(() => {
  // Block settings that only matter once another is filled in (field_depends
  // in Blocks.pm): [data-show-when] names that setting's input, and the
  // setting is set aside (is-moot) while it's empty or 0, or set aside itself.
  // A class rather than "hidden", which the page editor uses for texts edited
  // on the page.
  const fields = [...document.querySelectorAll('[data-show-when]')];
  if (!fields.length) return;
  const filled = name => {
    const el = document.querySelector(`[name="${CSS.escape(name)}"]`);
    if (!el) return true;
    const own = el.closest('[data-show-when]');
    return !['', '0'].includes(el.value.trim()) && !(own && own.classList.contains('is-moot'));
  };
  // Three passes settle chains (a link's new tab, under a picture's link).
  const apply = () => { for (let i = 0; i < 3; i++) fields.forEach(f => f.classList.toggle('is-moot', !filled(f.dataset.showWhen))); };
  document.addEventListener('input', apply);
  document.addEventListener('change', apply);
  apply();
})();

(() => {
  // A gallery card shows the settings for what it shows: a folder, or chosen pictures.
  document.querySelectorAll('select[name$=".source"]').forEach(source => {
    const card = source.closest('.block-card__fields'); if (!card) return;
    const id = source.name.slice(0, -'.source'.length);
    const folderBits = [card.querySelector(`[name="${id}.folder"]`)?.closest('label'), card.querySelector(`[name="${id}.subfolders"]`)?.closest('label')];
    const picked = card.querySelector('[data-pictures-field]');
    const apply = () => { const p = source.value === 'picked'; folderBits.forEach(el => { if (el) el.hidden = p; }); if (picked) picked.hidden = !p; };
    source.addEventListener('change', apply); apply();
  });
})();

(() => {
  // A screen waiting on the server (the System screen) refreshes itself every few seconds.
  const wait = Number(document.querySelector('[data-refresh]')?.dataset.refresh || 0);
  if (wait > 0) setTimeout(() => { if (!Admin.unsaved()) location.reload(); }, wait * 1000);
})();

(() => {
  // "or choose from Pictures" beside a file field: the chosen library picture
  // is sent instead of a file (the server copies it, as it would an upload).
  for (const button of document.querySelectorAll('[data-choose-into]')) {
    button.hidden = false;
    button.addEventListener('click', async () => {
      const picture = await choosePicture({title: button.dataset.title || 'Choose a picture'});
      if (!picture) return;
      const form = button.closest('form');
      form.querySelector('input[name="picture"]').value = picture.id;
      for (const file of form.querySelectorAll('input[type="file"]')) { file.required = false; file.value = ''; }
      if (form.dataset.chooseSubmit === 'no') {
        button.textContent = `chosen: ${picture.title || 'a picture'} (change)`;
      } else {
        form.requestSubmit();
      }
    });
  }
})();

(() => {
  // Pages: the navigation as a tree. A page is dragged among the others, into
  // a menu group (onto its row, or among its pages) and out again; a group is
  // dragged by its row, its pages with it. The whole menu is then saved at
  // once (nav_tree: every page in order, each with its group). Without the
  // script, each page's "…" menu has move up / down and its menu group.
  const tree = document.querySelector('[data-nav-tree]');
  if (!tree) return;
  tree.classList.add('can-reorder');
  const pageRows = () => [...tree.querySelectorAll('.theme-row[data-reorder-id]')];
  const groups = () => [...tree.querySelectorAll(':scope > [data-nav-group]')];
  const draggables = () => [...pageRows(), ...groups()];
  draggables().forEach(el => { el.draggable = true; });
  tree.addEventListener('pointerdown', event => {
    const el = event.target.closest('.theme-row[data-reorder-id], [data-nav-group]');
    if (el) el.draggable = !event.target.closest('input,textarea,select,[contenteditable]');
  });
  const structure = () => [...tree.children].map(el => el.dataset.navGroup ? 'g:' + el.dataset.navGroup + '(' + [...el.querySelectorAll('[data-reorder-id]')].map(r => r.dataset.reorderId).join() + ')' : el.dataset.reorderId).join();
  const refresh = () => groups().forEach(g => {
    const n = g.querySelectorAll('.theme-row[data-reorder-id]').length;
    g.classList.toggle('is-empty', n === 0);
    const meta = g.querySelector('.nav-group-row__head .media-label');
    if (meta) meta.textContent = n ? `${n} ${n === 1 ? 'page drops' : 'pages drop'} down from it` : 'empty: drag pages here, or choose it in a page’s “…” menu';
  });
  let dragging = null;
  tree.addEventListener('dragstart', event => {
    const el = event.target.closest?.('.theme-row[data-reorder-id], [data-nav-group]');
    if (!el || !draggables().includes(el)) return;
    event.stopPropagation();
    dragging = {el, group: !!el.dataset.navGroup, before: structure()};
    el.classList.add('is-dragging');
    event.dataTransfer.effectAllowed = 'move';
    event.dataTransfer.setData('text/plain', el.dataset.reorderId || el.dataset.navGroup);
  });
  const half = (el, event) => { const box = el.getBoundingClientRect(); return event.clientY > box.top + box.height / 2; };
  tree.addEventListener('dragover', event => {
    if (!dragging) return;
    event.preventDefault();
    const {el} = dragging;
    if (dragging.group) {
      // A group moves among the menu's top-level items only.
      const over = [...tree.children].find(c => c.contains(event.target));
      if (over && over !== el) over[half(over, event) ? 'after' : 'before'](el);
      return;
    }
    const row = event.target.closest('.theme-row[data-reorder-id]');
    if (row && row !== el && !el.contains(row)) { row[half(row, event) ? 'after' : 'before'](el); return; }
    // Onto a group's own row, or its empty space: into it, at the end.
    const group = event.target.closest('[data-nav-group]');
    if (group && event.target.closest('.nav-group-row__head, .nav-group-pages')) {
      const list = group.querySelector('[data-nav-group-pages]');
      if (el.parentElement !== list) list.append(el);
    }
  });
  tree.addEventListener('drop', event => { if (dragging) event.preventDefault(); });
  tree.addEventListener('dragend', async () => {
    if (!dragging) return;
    const {el, before} = dragging; dragging = null;
    el.classList.remove('is-dragging');
    refresh();
    if (structure() === before) return;
    const order = [], within = [];
    for (const top of tree.children) {
      if (top.dataset.navGroup) top.querySelectorAll('.theme-row[data-reorder-id]').forEach(r => { order.push(r.dataset.reorderId); within.push(top.dataset.navGroup); });
      else if (top.dataset.reorderId) { order.push(top.dataset.reorderId); within.push(''); }
    }
    adminToast('Saving the menu…');
    try { await adminPost({kind: 'pages', action: 'nav_tree', order, in: within}); adminToast('Menu saved.'); }
    catch (error) { adminToast('Menu not saved: ' + error.message); setTimeout(() => location.reload(), 1500); }
  });
})();

(() => {
  // Lists put in order (Pages, theme variants, a page's blocks, add-ons'
  // lists): drag a row, or use its move buttons, which then move it here
  // without reloading the page. data-reorder names the screen (kind) and
  // data-reorder-fields any other fields its action needs. (An add-on made
  // before 0.41 names its action in data-reorder and the screen in
  // data-reorder-kind.)
  for (const list of document.querySelectorAll('[data-reorder]')) {
    const rows = () => [...list.querySelectorAll(':scope > [data-reorder-id]')];
    const older = list.dataset.reorderKind;
    const kind = older || list.dataset.reorder, action = older ? list.dataset.reorder : 'order';
    const fields = Object.fromEntries(new URLSearchParams(list.dataset.reorderFields || ''));
    // The first row can't go up, nor the last down.
    const moved = () => rows().forEach((row, i, all) => row.querySelectorAll('.move-form').forEach(form => {
      const up = form.querySelector('[value=up]'), down = form.querySelector('[value=down]');
      if (up) up.disabled = i === 0;
      if (down) down.disabled = i === all.length - 1;
    }));
    const commit = makeReorderable(list, {items: rows, moved, send: ids => adminPost({...fields, kind, action, order: ids})});
    list.addEventListener('submit', event => {
      const form = event.target.closest('.move-form'), row = form?.closest('[data-reorder-id]');
      if (!row || row.parentElement !== list) return;
      event.preventDefault();
      const before = rows(), i = before.indexOf(row), up = event.submitter?.value === 'up';
      const other = before[i + (up ? -1 : 1)];
      if (!other) return;
      other[up ? 'before' : 'after'](row);
      form.closest('details[open]')?.removeAttribute('open');
      event.submitter?.focus();
      commit(before);
    });
  }
  // A row's "…" menu is placed against the screen, not its row, so a window's
  // edge can't cut it off: below the button when there's room, above it when
  // not, and kept inside the screen. It follows scrolling and resizing, and
  // closes on Escape, on a click elsewhere, or when another opens.
  const placeMenu = menu => {
    const items = menu.querySelector('.row-menu__items');
    if (!items || !menu.open) return;
    const button = menu.querySelector('summary').getBoundingClientRect();
    items.classList.add('is-placed');
    const width = items.offsetWidth, height = items.offsetHeight, gap = 4, edge = 8;
    const below = window.innerHeight - button.bottom - gap - edge;
    const above = button.top - gap - edge;
    const up = height > below && above > below;
    let top = up ? button.top - gap - height : button.bottom + gap;
    top = Math.max(edge, Math.min(top, window.innerHeight - height - edge));
    let left = button.right - width;
    left = Math.max(edge, Math.min(left, window.innerWidth - width - edge));
    items.style.top = `${top}px`;
    items.style.left = `${left}px`;
    items.style.maxHeight = `${window.innerHeight - 2 * edge}px`;
  };
  const openMenus = () => [...document.querySelectorAll('details.row-menu[open]')];
  for (const menu of document.querySelectorAll('details.row-menu')) {
    menu.addEventListener('toggle', () => {
      if (!menu.open) return;
      for (const other of openMenus()) if (other !== menu) other.open = false;
      placeMenu(menu);
    });
  }
  const follow = () => openMenus().forEach(placeMenu);
  window.addEventListener('scroll', follow, {passive: true, capture: true});
  window.addEventListener('resize', follow);
  document.addEventListener('click', event => {
    for (const menu of openMenus()) if (!menu.contains(event.target)) menu.open = false;
  });
  document.addEventListener('keydown', event => {
    if (event.key !== 'Escape') return;
    for (const menu of openMenus()) { menu.open = false; menu.querySelector('summary').focus(); }
  });
})();

// A field that needs fixing inside a folded section opens the section, so the browser can point at it.
document.addEventListener('invalid', event => { const fold = event.target.closest?.('details'); if (fold) fold.open = true; }, true);

// Copy buttons (recovery codes).
for (const button of document.querySelectorAll('[data-copy]')) {
  button.addEventListener('click', async () => {
    try { await navigator.clipboard.writeText(button.dataset.copy); button.textContent = 'copied'; }
    catch { button.textContent = 'select and copy them instead'; }
  });
}

// Notification pop-ups: each can be closed; they leave by themselves after a while.
document.querySelectorAll('[data-toast]').forEach((toast, i) => {
  const close = () => { toast.classList.add('is-leaving'); setTimeout(() => toast.remove(), 250); };
  toast.querySelector('[data-toast-close]')?.addEventListener('click', close);
  let timer = setTimeout(close, 15000 + i * 2000);
  toast.addEventListener('mouseenter', () => clearTimeout(timer));
  toast.addEventListener('focusin', () => clearTimeout(timer));
});

// Icon menus (a new folder, a folder's options): one open at a time; a click elsewhere or Escape closes them.
document.addEventListener('click', event => {
  document.querySelectorAll('details.icon-menu[open]').forEach(menu => { if (!menu.contains(event.target)) menu.open = false; });
});
document.addEventListener('keydown', event => {
  if (event.key === 'Escape') document.querySelectorAll('details.icon-menu[open]').forEach(menu => { menu.open = false; menu.querySelector('summary')?.focus(); });
});
document.querySelectorAll('details.icon-menu').forEach(menu => menu.addEventListener('toggle', () => {
  if (menu.open) menu.querySelector('input:not([type=hidden])')?.focus();
}));

// List fields in blocks (questions, timeline entries, cards): add, remove and
// reorder entries; their fields are renumbered so the order saved is the order shown.
(() => {
  document.querySelectorAll('[data-items-field]').forEach(field => {
    const list = field.querySelector('.items-field__list'), template = field.querySelector('template[data-items-template]');
    const renumber = () => {
      [...list.children].forEach((li, i) => li.querySelectorAll('[name]').forEach(el => {
        el.name = el.name.replace(/\.(\d+|__N__)\.(\w+)$/, `.${i}.$2`);
      }));
      const any = list.querySelector('[name]');
      any?.dispatchEvent(new Event('input', {bubbles: true}));
    };
    // Dragged by its handle like every other list; saved with the form, so
    // nothing is sent until then. (An entry's ids are its place, so idOf is
    // the element itself.)
    makeReorderable(list, {items: () => [...list.children], idOf: li => li, local: true, moved: renumber});
    field.querySelector('[data-items-add]').addEventListener('click', () => {
      const li = template.content.firstElementChild.cloneNode(true);
      list.append(li); li.draggable = true; renumber();
      li.querySelectorAll('[data-picture-field]').forEach(f => window.bindPictureField?.(f));
      li.querySelector('input:not([type=hidden]),textarea')?.focus();
    });
    list.addEventListener('click', event => {
      const button = event.target.closest('button'); if (!button) return;
      const li = button.closest('.items-field__item'); if (!li || !list.contains(li)) return;
      if (button.hasAttribute('data-item-remove')) li.remove();
      else if (button.dataset.itemMove === '-1' && li.previousElementSibling) li.previousElementSibling.before(li);
      else if (button.dataset.itemMove === '1' && li.nextElementSibling) li.nextElementSibling.after(li);
      else return;
      renumber();
    });
  });
})();

(() => {
  // The page editor: the page itself is the editing surface. Its texts are
  // typed into where they are; clicking a block selects it and opens a card
  // beside it with its other settings. Everything still lives in the one
  // #bulk-edit form, so saving works as before.
  const root = document.querySelector('[data-page-editor]');
  const bulk = document.getElementById('bulk-edit');
  if (!root || !bulk) return;
  root.classList.add('is-live');
  const holder = root.querySelector('[data-pe-preview]');
  const preview = previewFrame(holder, 'The page, editable', true);
  const frame = preview.frame;
  const panels = root.querySelector('.pe-panels');
  // Whether the browser can edit plain text only (no formatting) in place.
  const plain = (() => { const d = document.createElement('div'); d.contentEditable = 'plaintext-only'; return d.contentEditable === 'plaintext-only'; })();
  let selected = null, editing = null, timer = 0, seq = 0, first = true;
  const shownInCard = new Set();
  // Moving to another page: the preview's menu and the switcher at the top
  // of the bar open it here. Unsaved edits are saved or discarded first,
  // as the person chooses; the address bar follows (so back and reload work).
  let pages = {}; try { pages = JSON.parse(root.dataset.pePages || '{}'); } catch (e) {}
  const here = new URLSearchParams(location.search).get('page');
  function slugFor(href) {
    let url; try { url = new URL(href, location.origin); } catch (e) { return ''; }
    if (url.origin !== location.origin || url.search) return '';
    return pages[url.pathname] || pages[url.pathname.replace(/\/?$/, '/')] || '';
  }
  // Asks what to do with unsaved edits before opening another page: save,
  // discard or stay.
  function leaveChoice() {
    return new Promise(done => {
      const dialog = document.createElement('dialog'); dialog.className = 'pe-leave';
      const text = document.createElement('p'); text.textContent = 'This page has changes that aren’t saved yet.';
      const actions = document.createElement('div'); actions.className = 'pe-leave__actions';
      for (const [value, label, cls] of [['save', 'save and open', 'buttonlike'], ['discard', 'discard and open', 'buttonlike danger'], ['stay', 'stay here', 'text-button']]) {
        const b = document.createElement('button'); b.type = 'button'; b.className = cls; b.textContent = label;
        b.addEventListener('click', () => { dialog.returnValue = value; dialog.close(); });
        actions.append(b);
      }
      dialog.append(text, actions); document.body.append(dialog);
      dialog.addEventListener('close', () => { done(dialog.returnValue || 'stay'); dialog.remove(); });
      dialog.showModal(); actions.querySelector('button').focus();
    });
  }
  async function openPage(slug) {
    if (!slug || slug === here) return false;
    if (Admin.unsaved()) {
      const choice = await leaveChoice();
      if (choice === 'stay') return false;
      if (choice === 'save' && !(await Admin.saveAll())) return false;
    }
    Admin.leaving = true;
    location.assign('/admin/?kind=page&page=' + encodeURIComponent(slug));
    return true;
  }
  const switcher = root.querySelector('[data-pe-switch]');
  if (switcher) {
    const pick = switcher.elements.page;
    switcher.addEventListener('submit', event => { event.preventDefault(); openPage(pick.value); });
    pick.addEventListener('change', async () => { if (!(await openPage(pick.value))) pick.value = here; });
  }
  const input = name => [...document.querySelectorAll('[form="bulk-edit"][name]')].find(el => el.name === name && el.type !== 'hidden');
  async function refresh() {
    if (editing) return;
    const data = new FormData(bulk); data.set('action', 'page_preview'); data.set('edit', '1');
    const mine = ++seq;
    try {
      const {html} = await adminPost(data);
      if (mine === seq && !editing) preview.show(html);
    } catch (error) { preview.note('Preview unavailable: ' + error.message); }
  }
  const later = (ms = 450) => { clearTimeout(timer); timer = setTimeout(refresh, ms); };
  frame.addEventListener('load', () => {
    const doc = frame.contentDocument; if (!doc) return;
    preview.note(first ? 'Click a text to change it, or a block for its settings.' : 'Not saved yet: press save when you’re done.');
    first = false;
    doc.addEventListener('click', event => {
      const link = event.target.closest('a, button, input[type=submit]');
      if (link && !event.target.closest('[data-pe-field]')) event.preventDefault();
      if (link && link.tagName === 'A') event.preventDefault();
      const block = event.target.closest('[data-pe-block]');
      if (block) select(block.dataset.peBlock, 'card');
      else if (link && link.hasAttribute('data-pe-open')) openPage(link.dataset.peOpen);
    }, true);
    // Links outside the blocks (the menu, the logo, the footer) to another
    // page of the site open that page in the editor.
    doc.querySelectorAll('a[href]').forEach(a => {
      if (a.closest('[data-pe-block], [data-pe-field]')) return;
      const slug = slugFor(a.getAttribute('href'));
      if (slug && slug !== here) { a.dataset.peOpen = slug; a.title = 'Open this page in the editor'; }
    });
    doc.addEventListener('submit', event => event.preventDefault(), true);
    doc.querySelectorAll('[data-pe-field]').forEach(el => {
      const md = el.hasAttribute('data-pe-md');
      el.contentEditable = plain ? 'plaintext-only' : 'true';
      el.spellcheck = true;
      el.addEventListener('focus', () => {
        editing = el;
        if (md) { const field = input(el.dataset.peField); el.classList.add('is-source'); el.textContent = field ? field.value : el.textContent; }
      });
      el.addEventListener('input', () => {
        const field = input(el.dataset.peField); if (!field) return;
        field.value = md ? el.innerText.replace(/\n$/, '') : el.textContent.replace(/\s+/g, ' ');
        field.dispatchEvent(new Event('input', {bubbles: true}));
      });
      el.addEventListener('keydown', event => {
        if (event.key === 'Escape' || (!md && event.key === 'Enter')) { event.preventDefault(); el.blur(); }
        // In a Markdown text on the page: Ctrl/⌘+B, I and K as in the boxes.
        const key = event.key.toLowerCase();
        if (md && (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && ['b', 'i', 'k'].includes(key)) {
          event.preventDefault();
          const text = doc.getSelection().toString();
          const out = key === 'k' ? `[${text || 'link text'}](https://)` : text ? Markdown.wrapIn(text, key === 'b' ? '**' : '*') : key === 'b' ? '**bold text**' : '*italic text*';
          doc.execCommand('insertText', false, out);
        }
        if ((event.ctrlKey || event.metaKey) && event.key === 's') { event.preventDefault(); el.blur(); document.querySelector('button[form="bulk-edit"]')?.click(); }
      });
      el.addEventListener('blur', () => { editing = null; later(60); });
    });
    // Texts edited on the page aren't repeated in the cards. A box that has
    // been shown in a card stays there, though: typing into an empty text
    // puts it on the page, and the box mustn't vanish while it's in use.
    const onPage = new Set([...doc.querySelectorAll('[data-pe-field]')].map(el => el.dataset.peField));
    root.querySelectorAll('.pe-fields [form="bulk-edit"][name]').forEach(field => {
      const label = field.closest('label'); if (!label || field.closest('[data-items-field]')) return;
      label.hidden = onPage.has(field.name) && !shownInCard.has(field.name) && document.activeElement !== field;
      if (!label.hidden) shownInCard.add(field.name);
    });
    if (selected) select(selected, false);
  });
  function block(id) { return frame.contentDocument?.querySelector(`[data-pe-block="${CSS.escape(id)}"]`); }
  function select(id, scroll) {
    selected = id;
    const doc = frame.contentDocument;
    doc?.querySelectorAll('.pe-selected').forEach(el => el.classList.remove('pe-selected'));
    const el = block(id);
    el?.classList.add('pe-selected');
    if (scroll === true && el) el.scrollIntoView({block: 'center', behavior: 'smooth'});
    root.querySelectorAll('[data-pe-item]').forEach(li => li.classList.toggle('is-selected', li.dataset.peItem === id));
    // Its card opens in the bar, under the block's entry.
    root.querySelectorAll('[data-pe-fields]').forEach(card => {
      const mine = card.dataset.peFields === id;
      card.classList.toggle('is-open', mine);
      if (mine) { const li = root.querySelector(`[data-pe-item="${CSS.escape(id)}"]`); if (li && card.parentNode !== li) li.append(card); }
      else if (card.parentNode !== panels) panels.append(card);
    });
    if (scroll === 'card') root.querySelector('.pe-fields.is-open')?.scrollIntoView({block: 'nearest'});
  }
  // Clicking a block's entry selects it (and shows it on the page); again, closes its card.
  root.querySelectorAll('[data-pe-select]').forEach(button => button.addEventListener('click', () => select(selected === button.dataset.peSelect ? '' : button.dataset.peSelect, true)));
  root.addEventListener('click', event => { if (event.target.closest('[data-pe-close]')) select('', false); });
  // Settings changed in a card (or the page's own settings): redraw the page.
  for (const kind of ['input', 'change']) {
    document.addEventListener(kind, event => {
      const el = event.target;
      if (el.form !== bulk && el.getAttribute?.('form') !== 'bulk-edit') return;
      if (editing && frame.contentDocument?.activeElement) return;   // typing on the page: redraw on leaving the text
      later(kind === 'change' ? 60 : 500);
    });
  }
  // Blocks dragged (or moved) into a new order: number them again and redraw the page.
  root.querySelector('.pe-list')?.addEventListener('reordered', () => {
    root.querySelectorAll('.pe-list > [data-pe-item] .pe-item__n').forEach((n, i) => { n.textContent = i + 1; });
    refresh();
  });
  const opened = new URLSearchParams(location.search).get('open') || (location.hash.match(/^#block-(.+)/) || [])[1];
  if (opened) selected = opened;
  refresh();
})();

// A dismissable notice (the failed-request note): the × hides it for good in
// this browser, remembered by the request's id.
document.querySelectorAll('[data-dismiss]').forEach((note) => {
  const key = 'bf-dismissed-' + note.dataset.dismiss;
  let hidden = false;
  try { hidden = localStorage.getItem(key) === '1'; } catch (e) {}
  if (hidden) { note.remove(); return; }
  const button = note.querySelector('.notice-dismiss');
  if (!button) return;
  button.hidden = false;
  button.addEventListener('click', () => {
    try { localStorage.setItem(key, '1'); } catch (e) {}
    note.remove();
  });
});

// Analytics: a browser that signs in to the admin isn't counted on the public
// pages, unless the owner chose otherwise on the Analytics screen.
(() => {
  const KEY = 'bf-analytics-ignore', CHOSEN = 'bf-analytics-chosen';
  const read = (k) => { try { return localStorage.getItem(k) === '1'; } catch (e) { return false; } };
  const set = (on) => { try { on ? localStorage.setItem(KEY, '1') : localStorage.removeItem(KEY); } catch (e) {} };
  if (!read(CHOSEN)) set(true);
  const note = document.querySelector('[data-analytics-self]');
  if (!note) return;
  const button = note.querySelector('button');
  // A switch: on while this browser's visits are counted.
  const show = () => {
    note.hidden = false;
    button.classList.toggle('is-on', !read(KEY));
    button.setAttribute('aria-pressed', String(!read(KEY)));
  };
  button.addEventListener('click', () => { set(!read(KEY)); try { localStorage.setItem(CHOSEN, '1'); } catch (e) {} show(); });
  show();
})();