Robert Birming

Bear Blog tag and meta manager

Bear has a brand new API, and of course I wanted to take it for a spin. My first idea was a backup tool, but I soon felt it would be a bit complex for others to use. I wanted something useful and fairly easy for the everyday Bear blogger.

Then I looked at my own blog. Over 800 posts and pages, most of them missing tags and meta descriptions. The idea was born: a tag and meta manager.

The tag and meta manager in the Bear dashboard, listing posts with editable tags, image and description fields.

It's a dashboard plugin that lists all of your posts and pages, along with tags, meta description, and meta image. You can see right away what's missing, fix it, save it and move on. Easy peasy!

The Show menu in the tag and meta manager: 596 of 811 posts and pages missing a description, 807 missing tags and 654 missing an image.

What it does

Nothing changes on your blog until you press save, and only the posts you've edited are sent.

Getting started

The API is available on upgraded blogs.

  1. Go to Settings → API and generate a key.
  2. Copy the plugin below and add it like any other dashboard plugin.
  3. Click Manager in the dashboard nav and paste your key.

Your key is saved in your own browser and only ever sent to Bear. There's a Forget key button if you're on a shared computer.

The first load takes a little while on a big blog, since Bear's API allows 60 requests a minute. After that, the list opens right away and updates itself in the background.

The plugin

<script>
/*
  Plugin name: Tag & meta manager
  Version: 1.0
  Description: Edit tags, meta descriptions and meta images for all your posts and pages in one place, using the Bear API. Find what's missing, rename, merge or delete tags across your whole blog.
  Author: Robert Birming
  Source: https://robertbirming.com/bear-blog-tag-meta-manager-plugin/
*/
(() => {
  const parts = location.pathname.split('/').filter(Boolean);
  const sub = parts[0];
  if (!sub || parts[1] !== 'dashboard' || document.getElementById('tmm-dialog')) return;

  const API = `/${sub}/api/v1/`;
  const KEY_STORE = `tmm-key:${sub}`;
  const CACHE_STORE = `tmm-cache:${sub}`;
  const RATE_STORE = `tmm-rate:${sub}`;
  const DESC_MAX = 160;
  const CACHE_VERSION = 1;
  const REFRESH_AFTER = 5 * 60 * 1000; // refresh in the background if the saved copy is older than 5 minutes

  const ls = {
    get(k) { try { return localStorage.getItem(k); } catch { return null; } },
    set(k, v) { try { localStorage.setItem(k, v); } catch {} },
    del(k) { try { localStorage.removeItem(k); } catch {} }
  };

  let key = ls.get(KEY_STORE) || '';
  let posts = [];
  let byUid = new Map();
  const edits = new Map();
  let cacheAt = 0;
  let shown = false;
  let loading = false;
  let saving = false;
  let selectedTag = null;

  /* ---------- Nav link ---------- */
  const navAnchor =
    document.querySelector('a[href$="/dashboard/pages/"]') ||
    document.querySelector('a[href*="/dashboard/posts"]');
  if (!navAnchor) return;

  const link = document.createElement('a');
  link.href = '#';
  link.textContent = 'Manager';
  if (navAnchor.parentElement.tagName === 'LI') {
    const li = document.createElement('li');
    li.append(link);
    navAnchor.parentElement.after(li);
  } else {
    navAnchor.after(document.createTextNode(' '), link);
  }

  /* ---------- Styles ---------- */
  const style = document.createElement('style');
  style.textContent = `
#tmm-dialog{--b:color-mix(in srgb,var(--tmm-fg) 18%,transparent);background:var(--tmm-bg);color:var(--tmm-fg);border:1px solid var(--b);border-radius:8px;padding:0;width:min(1100px,calc(100vw - 2rem));height:calc(100dvh - 4rem);max-height:none;font:inherit;box-sizing:border-box}
#tmm-dialog[open]{display:flex;flex-direction:column}
#tmm-dialog::backdrop{background:rgb(0 0 0 / .5)}
#tmm-dialog [hidden]{display:none!important}
#tmm-dialog input,#tmm-dialog textarea,#tmm-dialog select,#tmm-dialog button{font:inherit;font-size:.9rem;color:inherit;background:transparent;border:1px solid var(--b);border-radius:4px;padding:.35rem .5rem;box-sizing:border-box}
#tmm-dialog input,#tmm-dialog textarea{font-weight:400}
#tmm-dialog ::placeholder{color:inherit;opacity:.45}
#tmm-dialog select{background:var(--tmm-bg)}
#tmm-dialog button{cursor:pointer}
#tmm-dialog button:disabled{opacity:.5;cursor:default}
.tmm-head{display:flex;gap:.75rem;align-items:center;padding:.75rem 1rem;border-bottom:1px solid var(--b)}
.tmm-status{flex:1;opacity:.75;font-size:.85em}
.tmm-keyform,.tmm-main{padding:0 1rem 1rem;overflow:auto;flex:1}
.tmm-keyform{padding-top:1rem}
.tmm-keyform input{width:min(100%,24rem);margin-right:.5rem}
.tmm-bar{display:flex;flex-wrap:wrap;gap:.5rem;position:sticky;top:0;background:var(--tmm-bg);padding:.75rem 0;z-index:1;border-bottom:1px solid var(--b)}
.tmm-search{flex:1 1 12rem}
#tmm-dialog .tmm-save:not(:disabled){background:var(--tmm-accent);color:var(--tmm-bg);border-color:var(--tmm-accent)}
.tmm-tags-panel{margin-top:.75rem}
.tmm-tags-panel summary{cursor:pointer}
.tmm-taglist{display:flex;flex-wrap:wrap;gap:.35rem;margin:.5rem 0;max-height:12rem;overflow:auto}
#tmm-dialog .tmm-taglist button{padding:.1rem .55rem;border-radius:99px;font-size:.85rem}
#tmm-dialog .tmm-taglist button.is-dupe{border-style:dashed;border-color:#d9822b}
#tmm-dialog .tmm-taglist button[aria-pressed="true"]{background:var(--tmm-accent);color:var(--tmm-bg);border-color:var(--tmm-accent)}
.tmm-taglist small{opacity:.6}
.tmm-tagactions{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin:.25rem 0 .5rem;font-size:.9em}
.tmm-count{font-size:.85em;opacity:.7;margin:.75rem 0 0}
.tmm-errors{color:#d9534f;font-size:.85em}
.tmm-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) minmax(0,1.6fr);gap:.75rem;padding:.75rem 0;border-bottom:1px solid var(--b);align-items:start}
.tmm-row.is-edited{box-shadow:inset 3px 0 var(--tmm-accent);padding-left:.75rem}
.tmm-title a{color:var(--tmm-accent);text-decoration:none;font-weight:600;overflow-wrap:anywhere}
.tmm-title small{display:block;opacity:.65;font-size:.8em;margin-top:.2rem}
.tmm-title small a{font-weight:400;color:inherit;text-decoration:underline}
.tmm-col{display:flex;flex-direction:column;gap:.5rem;min-width:0}
.tmm-field{display:flex;flex-direction:column;gap:.2rem;min-width:0}
.tmm-field > span{font-size:.75em;opacity:.65;display:flex;justify-content:space-between;gap:.5rem}
.tmm-field em{font-style:normal}
.tmm-field em.is-long{color:#d9822b}
.tmm-field a{color:var(--tmm-accent)}
.tmm-field > span.tmm-imghead{justify-content:flex-start}
.tmm-imglink{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;opacity:1}
.tmm-imglink a{text-decoration:none}
.tmm-field input,.tmm-field textarea{width:100%}
.tmm-field textarea{resize:vertical;min-height:5.6em}
#tmm-dialog .tmm-field input.is-invalid{border-color:#d9534f}
.tmm-foot{display:flex;gap:.5rem;justify-content:flex-end;padding-top:1rem}
@media (max-width:700px){
  #tmm-dialog{width:100vw;max-width:100vw;height:100dvh;border-radius:0;margin:0;border:0}
  .tmm-row{grid-template-columns:1fr}
  .tmm-field textarea{min-height:3.2em}
}`;
  document.head.append(style);

  /* ---------- Dialog ---------- */
  const dlg = document.createElement('dialog');
  dlg.id = 'tmm-dialog';
  dlg.innerHTML = `
<div class="tmm-head">
  <strong>Tag &amp; meta manager</strong>
  <span class="tmm-status" aria-live="polite"></span>
  <button type="button" data-act="reload" hidden>Refresh</button>
  <button type="button" data-act="close" aria-label="Close">✕</button>
</div>
<form class="tmm-keyform" hidden>
  <p class="tmm-keymsg"></p>
  <p>Paste your API key from <b>Settings → API</b>. It's saved in this browser only and only ever sent to Bear.</p>
  <input type="password" name="key" placeholder="API key" autocomplete="off" required>
  <button type="submit">Save key</button>
</form>
<div class="tmm-main" hidden>
  <div class="tmm-bar">
    <input type="search" class="tmm-search" placeholder="Search titles" aria-label="Search titles">
    <select class="tmm-type" aria-label="Type">
      <option value="">Posts &amp; pages</option>
      <option value="post">Posts</option>
      <option value="page">Pages</option>
    </select>
    <select class="tmm-show" aria-label="Show"></select>
    <button type="button" class="tmm-save" data-act="save" disabled>Save changes</button>
  </div>
  <details class="tmm-tags-panel">
    <summary>Tags</summary>
    <div class="tmm-taglist"></div>
    <div class="tmm-tagactions" hidden>
      <span>Selected: <b class="tmm-seltag"></b></span>
      <button type="button" data-act="tag-rename">Rename or merge</button>
      <button type="button" data-act="tag-delete">Delete</button>
      <button type="button" data-act="tag-clear">Clear</button>
    </div>
  </details>
  <ul class="tmm-errors" hidden></ul>
  <p class="tmm-count"></p>
  <div class="tmm-list"></div>
  <div class="tmm-foot">
    <button type="button" data-act="forget">Forget key</button>
  </div>
</div>`;
  document.body.append(dlg);

  const $ = s => dlg.querySelector(s);
  const statusEl = $('.tmm-status');
  const refreshBtn = $('[data-act="reload"]');
  const keyForm = $('.tmm-keyform');
  const main = $('.tmm-main');
  const list = $('.tmm-list');
  const search = $('.tmm-search');
  const typeSel = $('.tmm-type');
  const showSel = $('.tmm-show');
  const saveBtn = $('.tmm-save');
  const tagList = $('.tmm-taglist');
  const tagActions = $('.tmm-tagactions');
  const errorsEl = $('.tmm-errors');

  /* ---------- Helpers ---------- */
  const sleep = ms => new Promise(r => setTimeout(r, ms));
  const esc = s => String(s ?? '').replace(/[&<>"']/g, c =>
    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  const setStatus = t => { statusEl.textContent = t; };
  const parseTags = s => [...new Set(String(s).split(',').map(t => t.trim()).filter(Boolean))];
  const fmtDate = d => d ? new Date(d).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : '';
  const isUrl = s => !s || /^https?:\/\/\S+$/i.test(s);
  const newer = (a, b) => a && b && new Date(a) > new Date(b);

  function ago(t) {
    const m = Math.round((Date.now() - t) / 60000);
    if (m < 1) return 'just now';
    if (m < 60) return `${m} min ago`;
    const h = Math.round(m / 60);
    return h < 24 ? `${h} h ago` : `${Math.round(h / 24)} days ago`;
  }
  const idleStatus = () => { if (!loading && !saving) setStatus(`${posts.length} posts and pages · updated ${ago(cacheAt)}`); };

  const cur = (p, f) => {
    const e = edits.get(p.uid);
    if (e && f in e) return e[f];
    return p[f] ?? (f === 'tags' ? [] : '');
  };

  function setEdit(uid, f, v) {
    const p = byUid.get(uid);
    if (!p) return;
    const same = f === 'tags'
      ? (p.tags || []).join('\u0000') === v.join('\u0000')
      : (p[f] || '') === v;
    const e = edits.get(uid) || {};
    if (same) delete e[f]; else e[f] = v;
    if (Object.keys(e).length) edits.set(uid, e); else edits.delete(uid);
  }

  /* ---------- Saved copy ---------- */
  function readCache() {
    try {
      const c = JSON.parse(ls.get(CACHE_STORE));
      const ok = c && c.v === CACHE_VERSION && Array.isArray(c.posts) &&
        c.posts.every(p => p && typeof p.uid === 'string');
      return ok ? c : null;
    } catch { return null; }
  }
  function writeCache() {
    cacheAt = cacheAt || Date.now();
    ls.set(CACHE_STORE, JSON.stringify({ v: CACHE_VERSION, at: cacheAt, posts }));
  }

  /* ---------- API (rate limited, remembered across dashboard pages) ---------- */
  let stamps = (() => { try { return JSON.parse(ls.get(RATE_STORE)) || []; } catch { return []; } })();

  async function api(path, opts = {}) {
    for (let attempt = 0; attempt < 6; attempt++) {
      for (;;) {
        const now = Date.now();
        stamps = stamps.filter(t => now - t < 60000);
        if (stamps.length < 55) break;
        const wait = 60000 - (now - stamps[0]) + 250;
        setStatus(`Pausing for Bear's rate limit… ${Math.ceil(wait / 1000)}s`);
        await sleep(wait);
      }
      stamps.push(Date.now());
      ls.set(RATE_STORE, JSON.stringify(stamps));

      const headers = { Authorization: `Bearer ${key}` };
      if (opts.body) headers['Content-Type'] = 'application/json';
      const res = await fetch(API + path, { ...opts, headers });

      if (res.status === 429) {
        const s = parseInt(res.headers.get('Retry-After'), 10) || 10;
        setStatus(`Bear asked us to slow down… waiting ${s}s`);
        await sleep(s * 1000);
        continue;
      }
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        const err = new Error(data.error || `HTTP ${res.status}`);
        err.status = res.status;
        throw err;
      }
      return data;
    }
    throw new Error('Too many retries');
  }

  function handleAuthError(err) {
    if (err.status === 401 || err.status === 403) {
      ls.del(KEY_STORE);
      key = '';
      showKeyForm(err.status === 401
        ? "That key didn't work. Check it and try again."
        : 'The API needs an upgraded blog.');
      return true;
    }
    return false;
  }

  /* ---------- Loading ---------- */
  async function load() {
    if (loading) return;
    loading = true;
    refreshBtn.disabled = true;
    const quiet = shown;
    setStatus(quiet ? 'Updating in the background…' : 'Loading…');
    try {
      const all = [];
      let page = 1;
      while (page) {
        const d = await api(`post/?page=${page}`);
        all.push(...(d.posts || []));
        if (!quiet) setStatus(`Loading… ${all.length} of ${d.count ?? '?'}`);
        const n = d.next_page;
        if (n == null) page = null;
        else if (typeof n === 'number') page = n;
        else {
          const parsed = Number(new URL(String(n), location.origin).searchParams.get('page') || n);
          page = Number.isFinite(parsed) && parsed > page ? parsed : page + 1;
        }
      }
      applyFresh(all.map(({ content, ...p }) => p));
      cacheAt = Date.now();
      writeCache();
      loading = false;
      idleStatus();
    } catch (err) {
      loading = false;
      if (!handleAuthError(err)) setStatus(`Couldn't load: ${err.message}`);
    } finally {
      loading = false;
      refreshBtn.disabled = false;
    }
  }

  function applyFresh(all) {
    const old = byUid;
    // Keep our own copy if it's newer (saved while this refresh was running)
    posts = all.map(p => {
      const o = old.get(p.uid);
      return o && newer(o.last_modified, p.last_modified) ? o : p;
    });
    byUid = new Map(posts.map(p => [p.uid, p]));

    // Drop edits for deleted posts, and edits that now match what's on Bear
    for (const [uid, e] of [...edits]) {
      if (!byUid.has(uid)) { edits.delete(uid); continue; }
      for (const f of Object.keys(e)) setEdit(uid, f, e[f]);
    }

    if (!shown) { showMain(); return; }

    const focusRow = document.activeElement?.closest?.('.tmm-row');
    const changedSet = posts.length !== old.size || posts.some(p => !old.has(p.uid));
    if (changedSet && !focusRow) { refresh(); return; }

    // Update only rows that changed on Bear, and never one you're editing
    for (const row of list.querySelectorAll('.tmm-row')) {
      const uid = row.dataset.uid;
      const p = byUid.get(uid);
      const o = old.get(uid);
      if (!p || row === focusRow || edits.has(uid)) continue;
      if (o && o.last_modified === p.last_modified) continue;
      row.outerHTML = rowHTML(p);
    }
    renderShowOptions();
    renderTags();
    renderCount();
    updateSave();
  }

  function showMain() {
    shown = true;
    keyForm.hidden = true;
    main.hidden = false;
    refreshBtn.hidden = false;
    refresh();
  }

  /* ---------- Rendering ---------- */
  // Type, search and tag: the counts in the "Show" menu follow these
  function baseFiltered() {
    const q = search.value.trim().toLowerCase();
    const type = typeSel.value;
    return posts.filter(p => {
      if (type === 'post' && p.is_page) return false;
      if (type === 'page' && !p.is_page) return false;
      if (q && !(p.title || '').toLowerCase().includes(q)) return false;
      if (selectedTag && !cur(p, 'tags').includes(selectedTag)) return false;
      return true;
    });
  }

  function filtered() {
    const show = showSel.value;
    return baseFiltered().filter(p => {
      if (show === 'nodesc' && cur(p, 'meta_description').trim()) return false;
      if (show === 'notags' && cur(p, 'tags').length) return false;
      if (show === 'noimg' && cur(p, 'meta_image').trim()) return false;
      if (show === 'edited' && !edits.has(p.uid)) return false;
      return true;
    });
  }

  function imgLink(img) {
    if (!img || !isUrl(img)) return '';
    let name = img.split(/[?#]/)[0].split('/').filter(Boolean).pop() || img;
    try { name = decodeURIComponent(name); } catch {}
    return `<a href="${esc(img)}" target="_blank" rel="noopener" title="${esc(img)}">${esc(name)} ↗</a>`;
  }

  function rowHTML(p) {
    const d = cur(p, 'meta_description');
    const img = cur(p, 'meta_image');
    const bits = [];
    if (p.is_page) bits.push('Page');
    if (!p.publish) bits.push('Draft');
    else if (p.published_date && new Date(p.published_date) > Date.now()) bits.push('Scheduled');
    const date = fmtDate(p.published_date);
    if (date) bits.unshift(date);
    return `
<div class="tmm-row${edits.has(p.uid) ? ' is-edited' : ''}" data-uid="${esc(p.uid)}">
  <div class="tmm-title">
    <a href="${esc(p.url)}" target="_blank" rel="noopener">${esc(p.title) || '(untitled)'}</a>
    <small>${esc(bits.join(' · '))}${bits.length ? ' · ' : ''}<a href="/${esc(sub)}/dashboard/posts/${esc(p.uid)}/">Edit</a></small>
  </div>
  <div class="tmm-col">
    <label class="tmm-field"><span>Tags</span>
      <input data-f="tags" value="${esc(cur(p, 'tags').join(', '))}" placeholder="No tags">
    </label>
    <label class="tmm-field"><span class="tmm-imghead">Image <span class="tmm-imglink">${imgLink(img)}</span></span>
      <input data-f="meta_image" type="url" value="${esc(img)}" placeholder="Blog default image"${isUrl(img) ? '' : ' class="is-invalid"'}>
    </label>
  </div>
  <label class="tmm-field"><span>Description <em class="${d.length > DESC_MAX ? 'is-long' : ''}">${d.length}</em></span>
    <textarea data-f="meta_description" rows="3" placeholder="No description">${esc(d)}</textarea>
  </label>
</div>`;
  }

  function renderShowOptions() {
    const keep = showSel.value;
    const base = baseFiltered();
    const n = fn => base.filter(fn).length;
    const opts = [
      ['', `Everything (${base.length})`],
      ['nodesc', `Missing description (${n(p => !cur(p, 'meta_description').trim())})`],
      ['notags', `Missing tags (${n(p => !cur(p, 'tags').length)})`],
      ['noimg', `Missing image (${n(p => !cur(p, 'meta_image').trim())})`],
      ['edited', `Unsaved edits (${n(p => edits.has(p.uid))})`]
    ];
    showSel.innerHTML = opts.map(([v, t]) => `<option value="${v}">${esc(t)}</option>`).join('');
    showSel.value = keep;
  }

  function renderTags() {
    const counts = new Map();
    for (const p of posts) for (const t of cur(p, 'tags')) counts.set(t, (counts.get(t) || 0) + 1);
    if (selectedTag && !counts.has(selectedTag)) selectedTag = null;
    const sorted = [...counts].sort((a, b) => a[0].localeCompare(b[0], undefined, { sensitivity: 'base' }) || a[0].localeCompare(b[0]));
    // Spot tags that only differ by case, like "Photo" and "photo"
    const lower = new Map();
    for (const [t] of sorted) lower.set(t.toLowerCase(), [...(lower.get(t.toLowerCase()) || []), t]);
    const dupes = sorted.filter(([t]) => lower.get(t.toLowerCase()).length > 1).length;
    $('.tmm-tags-panel summary').textContent = `Tags (${sorted.length})` +
      (dupes ? ` · ${dupes} differ only by case` : '');
    tagList.innerHTML = sorted.map(([t, c]) => {
      const twins = lower.get(t.toLowerCase()).filter(x => x !== t);
      const hint = twins.length ? ` title="Also used as ${esc(twins.join(', '))}. Rename one to merge them."` : '';
      return `<button type="button" data-tag="${esc(t)}" aria-pressed="${t === selectedTag}" aria-label="${esc(t)}, ${c} ${c === 1 ? 'post' : 'posts'}"${twins.length ? ' class="is-dupe"' : ''}${hint}>${esc(t)} <small>${c}</small></button>`;
    }).join('') || '<small>No tags yet.</small>';
    tagActions.hidden = !selectedTag;
    $('.tmm-seltag').textContent = selectedTag || '';
  }

  let lastShown = 0;
  function renderList() {
    const rows = filtered();
    lastShown = rows.length;
    list.innerHTML = rows.map(rowHTML).join('');
    renderCount();
  }
  function renderCount() {
    $('.tmm-count').textContent = `Showing ${lastShown} of ${posts.length}` +
      (selectedTag ? ` · tagged "${selectedTag}"` : '');
  }

  function updateSave() {
    saveBtn.disabled = saving || !edits.size;
    saveBtn.textContent = edits.size ? `Save changes (${edits.size})` : 'Save changes';
  }

  function refresh() {
    renderShowOptions();
    renderTags();
    renderList();
    updateSave();
  }

  /* ---------- Key form ---------- */
  function showKeyForm(msg = '') {
    main.hidden = true;
    refreshBtn.hidden = true;
    keyForm.hidden = false;
    shown = false;
    $('.tmm-keymsg').textContent = msg;
    $('.tmm-keymsg').hidden = !msg;
    keyForm.key.value = '';
    keyForm.key.focus();
    setStatus('');
  }

  keyForm.addEventListener('submit', e => {
    e.preventDefault();
    key = keyForm.key.value.trim();
    if (!key) return;
    ls.set(KEY_STORE, key);
    keyForm.hidden = true;
    load();
  });

  /* ---------- Editing ---------- */
  list.addEventListener('input', e => {
    const f = e.target.dataset.f;
    if (!f) return;
    const row = e.target.closest('.tmm-row');
    const uid = row.dataset.uid;
    const v = e.target.value;
    if (f === 'tags') {
      setEdit(uid, 'tags', parseTags(v));
    } else if (f === 'meta_image') {
      setEdit(uid, f, v.trim());
      e.target.classList.toggle('is-invalid', !isUrl(v.trim()));
      row.querySelector('.tmm-imglink').innerHTML = imgLink(v.trim());
    } else {
      setEdit(uid, f, v);
      const len = row.querySelector('em');
      len.textContent = v.length;
      len.classList.toggle('is-long', v.length > DESC_MAX);
    }
    row.classList.toggle('is-edited', edits.has(uid));
    updateSave();
  });

  list.addEventListener('change', () => {
    renderShowOptions();
    renderTags();
  });

  /* ---------- Tags panel ---------- */
  tagList.addEventListener('click', e => {
    const b = e.target.closest('button[data-tag]');
    if (!b) return;
    selectedTag = selectedTag === b.dataset.tag ? null : b.dataset.tag;
    renderTags();
    renderShowOptions();
    renderList();
  });

  const withTag = t => posts.filter(p => cur(p, 'tags').includes(t));

  function renameTag() {
    const from = selectedTag;
    const input = prompt(`Rename "${from}" to:\n(Use an existing tag to merge them. One tag only, no commas.)`, from);
    if (input == null) return;
    const to = input.trim();
    if (to.includes(',')) { setStatus("Tags can't contain commas. Nothing changed."); return; }
    if (!to || to === from) return;
    const hit = withTag(from);
    for (const p of hit) {
      setEdit(p.uid, 'tags', [...new Set(cur(p, 'tags').map(t => t === from ? to : t))]);
    }
    selectedTag = to;
    refresh();
    setStatus(`Changed on ${hit.length} posts. Remember to save.`);
  }

  function deleteTag() {
    const t = selectedTag;
    const hit = withTag(t);
    if (!confirm(`Remove "${t}" from ${hit.length} posts?`)) return;
    for (const p of hit) setEdit(p.uid, 'tags', cur(p, 'tags').filter(x => x !== t));
    selectedTag = null;
    refresh();
    setStatus(`Removed from ${hit.length} posts. Remember to save.`);
  }

  /* ---------- Saving ---------- */
  async function save() {
    if (saving || !edits.size) return;
    const bad = [...edits].filter(([, e]) => 'meta_image' in e && !isUrl(e.meta_image));
    if (bad.length) {
      setStatus(`Fix ${bad.length} image ${bad.length === 1 ? 'link' : 'links'} first (they need to start with https://)`);
      showSel.value = 'edited';
      renderList();
      return;
    }
    saving = true;
    list.inert = true;
    updateSave();
    errorsEl.hidden = true;
    const jobs = [...edits];
    const errors = [];
    let i = 0;
    try {
      for (const [uid, e] of jobs) {
        setStatus(`Saving ${++i} of ${jobs.length}…`);
        try {
          const res = await api(`post/${encodeURIComponent(uid)}/`, {
            method: 'PATCH',
            body: JSON.stringify(e)
          });
          const p = byUid.get(uid);
          // Keep the saved copy small: never store post content
          const { content, ...fresh } = res && res.uid === uid ? res : {};
          Object.assign(p, e, fresh);
          edits.delete(uid);
        } catch (err) {
          if (handleAuthError(err)) break;
          errors.push(`${byUid.get(uid)?.title || uid}: ${err.message}`);
        }
      }
    } finally {
      saving = false;
      list.inert = false;
      writeCache();
    }
    if (main.hidden) return;
    refresh();
    if (errors.length) {
      setStatus(`Saved ${jobs.length - errors.length}, ${errors.length} failed`);
      errorsEl.innerHTML = errors.map(m => `<li>${esc(m)}</li>`).join('');
      errorsEl.hidden = false;
    } else {
      setStatus(`Saved ${jobs.length} ✓`);
    }
  }

  /* ---------- Buttons ---------- */
  dlg.addEventListener('click', e => {
    const act = e.target.closest('[data-act]')?.dataset.act;
    if (!act) return;
    if (act === 'close' && okToClose()) dlg.close();
    if (act === 'save') save();
    if (act === 'reload') load();
    if (act === 'tag-rename') renameTag();
    if (act === 'tag-delete') deleteTag();
    if (act === 'tag-clear') { selectedTag = null; renderTags(); renderShowOptions(); renderList(); }
    if (act === 'forget') {
      if (!confirm('Forget the API key and saved post list in this browser?')) return;
      ls.del(KEY_STORE);
      ls.del(CACHE_STORE);
      key = '';
      posts = [];
      byUid = new Map();
      edits.clear();
      cacheAt = 0;
      showKeyForm('Key forgotten.');
    }
  });

  const refilter = () => { renderShowOptions(); renderList(); };
  function okToClose() {
    return !edits.size || saving ||
      confirm(`You have ${edits.size} unsaved ${edits.size === 1 ? 'change' : 'changes'}. Close anyway?\n(They're kept until you leave this page.)`);
  }
  dlg.addEventListener('cancel', e => { if (!okToClose()) e.preventDefault(); });
  dlg.addEventListener('keydown', e => {
    if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
      e.preventDefault();
      save();
    }
  });

  search.addEventListener('input', refilter);
  typeSel.addEventListener('change', refilter);
  showSel.addEventListener('change', renderList);

  window.addEventListener('beforeunload', e => {
    if (edits.size) { e.preventDefault(); e.returnValue = ''; }
  });

  /* ---------- Open ---------- */
  function applyColors() {
    const transparent = c => !c || c === 'transparent' || /rgba\(.*,\s*0\)$/.test(c);
    let bg = getComputedStyle(document.body).backgroundColor;
    if (transparent(bg)) bg = getComputedStyle(document.documentElement).backgroundColor;
    if (transparent(bg)) bg = '#fff';
    dlg.style.setProperty('--tmm-bg', bg);
    dlg.style.setProperty('--tmm-fg', getComputedStyle(document.body).color);
    dlg.style.setProperty('--tmm-accent', getComputedStyle(navAnchor).color);
  }

  link.addEventListener('click', e => {
    e.preventDefault();
    applyColors();
    dlg.showModal();
    if (!key) { showKeyForm(); return; }
    if (!shown) {
      const c = readCache();
      if (c) {
        posts = c.posts;
        byUid = new Map(posts.map(p => [p.uid, p]));
        cacheAt = c.at || 0;
        showMain();
      }
    }
    if (!shown || Date.now() - cacheAt > REFRESH_AFTER) load();
    else idleStatus();
  });
})();
</script>

What's next?

I've been thinking about a Create image button. One click and it makes a meta image from the post title, uploads it and fills it in, just like my Meta image plugin.

Would you use that? Let me know.

Happy tidying!

#bear #plugins