// App shell: navigation, routing, theme. Tools themselves live in js/tools/*.js.
//
// A tool module exports mount(el, ctx) and may return a cleanup function.
// ctx = {
// rest, // path after the tool's own path, e.g. "abc123" for /paste/abc123
// query, // URLSearchParams of the current URL
// navigate, // navigate('/paste/abc') — client-side navigation
// setTitle, // setTitle('abc123') — extra text in the top bar and tab title
// }
import { TOOLS, CATEGORY_ORDER } from './registry.js';
import { el, store } from './ui.js';
const view = document.getElementById('view');
const navList = document.getElementById('nav-list');
const navFilter = document.getElementById('nav-filter');
const titleEl = document.getElementById('topbar-title');
let cleanup = null;
let routeSeq = 0;
// ---------- theme ----------
const THEMES = ['auto', 'light', 'dark'];
const svg = (d) => ``;
const THEME_ICON = {
auto: svg(''),
light: svg(''),
dark: svg(''),
};
const themeBtn = document.getElementById('theme-btn');
function applyTheme(t) {
if (t === 'auto') delete document.documentElement.dataset.theme;
else document.documentElement.dataset.theme = t;
themeBtn.innerHTML = THEME_ICON[t];
themeBtn.title = `Theme: ${t}`;
}
let theme = store.get('theme', 'auto');
applyTheme(theme);
themeBtn.addEventListener('click', () => {
theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
store.set('theme', theme);
applyTheme(theme);
});
// ---------- navigation ----------
function grouped(tools) {
const groups = new Map();
for (const t of tools) {
if (!groups.has(t.category)) groups.set(t.category, []);
groups.get(t.category).push(t);
}
const rank = (c) => (CATEGORY_ORDER.includes(c) ? CATEGORY_ORDER.indexOf(c) : 999);
return [...groups].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b));
}
function matches(t, q) {
q = q.trim().toLowerCase();
return !q || `${t.name} ${t.description} ${t.category}`.toLowerCase().includes(q);
}
function renderNav() {
const q = navFilter.value;
navList.replaceChildren(
el('a.nav-item.nav-home', { href: '/', dataset: { path: '/' } }, el('span.nav-icon', {}, '⌂'), 'All tools'),
...grouped(TOOLS.filter((t) => matches(t, q))).map(([cat, tools]) =>
el('div.nav-group', {},
el('div.nav-heading', {}, cat),
tools.map((t) => el('a.nav-item', { href: t.path, dataset: { path: t.path, tool: t.id } },
el('span.nav-icon', {}, t.icon), el('span.nav-label', {}, t.name), t.badge ? el('span.badge', { hidden: true }) : null)),
),
),
);
markActive();
updateBadges();
}
// Counts on nav items (e.g. unread shared pastes), plus a dot on the mobile menu button.
function updateBadges() {
let total = 0;
for (const t of TOOLS) {
if (!t.badge) continue;
let n = 0;
try { n = t.badge() || 0; } catch {}
total += n;
const b = navList.querySelector(`.nav-item[data-tool="${t.id}"] .badge`);
if (b) {
b.hidden = !n;
b.textContent = n > 99 ? '99+' : String(n);
b.title = `${n} new`;
}
}
menuBtn.classList.toggle('has-badge', total > 0);
}
window.addEventListener('tools:badges', updateBadges);
window.addEventListener('storage', (e) => { if (!e.key || e.key.startsWith('tools:')) updateBadges(); }); // other tabs
setInterval(updateBadges, 60000); // expiry
function markActive() {
const tool = findTool(location.pathname);
for (const a of navList.querySelectorAll('.nav-item')) {
const on = tool ? a.dataset.path === tool.path : a.dataset.path === '/';
a.classList.toggle('active', on);
if (on) a.setAttribute('aria-current', 'page');
else a.removeAttribute('aria-current');
}
}
navFilter.addEventListener('input', renderNav);
navFilter.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const first = TOOLS.find((t) => matches(t, navFilter.value));
if (first) {
navFilter.value = '';
renderNav();
navigate(first.path);
}
} else if (e.key === 'Escape') {
navFilter.value = '';
renderNav();
navFilter.blur();
}
});
document.addEventListener('keydown', (e) => {
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName) || document.activeElement?.isContentEditable;
if (e.key === '/' && !typing) {
e.preventDefault();
setDrawer(true);
navFilter.focus();
}
});
// Mobile drawer
const menuBtn = document.getElementById('menu-btn');
function setDrawer(open) {
document.body.classList.toggle('drawer-open', open);
menuBtn.setAttribute('aria-expanded', String(open));
}
menuBtn.addEventListener('click', () => setDrawer(!document.body.classList.contains('drawer-open')));
document.getElementById('scrim').addEventListener('click', () => setDrawer(false));
// ---------- routing ----------
function findTool(pathname) {
return TOOLS.find((t) => pathname === t.path || pathname.startsWith(`${t.path}/`));
}
export function navigate(path, { replace = false } = {}) {
if (path === location.pathname + location.search) return;
history[replace ? 'replaceState' : 'pushState']({}, '', path);
route();
}
document.addEventListener('click', (e) => {
const a = e.target.closest('a[href]');
if (!a || a.target || a.hasAttribute('download') || e.defaultPrevented) return;
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const url = new URL(a.href, location.href);
if (url.origin !== location.origin || url.pathname.startsWith('/raw/') || url.pathname.startsWith('/api/')) return;
e.preventDefault();
setDrawer(false);
navigate(url.pathname + url.search);
});
window.addEventListener('popstate', route);
function setTitle(tool, extra) {
titleEl.textContent = tool ? [tool.name, extra].filter(Boolean).join(' · ') : '';
document.title = tool ? `${[extra, tool.name].filter(Boolean).join(' · ')} — tools` : 'tools';
}
async function route() {
const seq = ++routeSeq;
if (cleanup) {
try { cleanup(); } catch (err) { console.error(err); }
cleanup = null;
}
markActive();
const tool = findTool(location.pathname);
document.body.dataset.tool = tool ? tool.id : 'home';
if (!tool) {
if (location.pathname !== '/') history.replaceState({}, '', '/');
setTitle(null);
renderHome();
return;
}
setTitle(tool);
view.replaceChildren(el('div.loading', {}, 'Loading…'));
try {
const mod = await tool.load();
if (seq !== routeSeq) return; // navigated away while loading
view.replaceChildren();
const ctx = {
rest: location.pathname.slice(tool.path.length).replace(/^\//, ''),
query: new URLSearchParams(location.search),
navigate,
setTitle: (extra) => setTitle(tool, extra),
};
cleanup = (await mod.mount(view, ctx)) || null;
} catch (err) {
console.error(err);
if (seq === routeSeq) view.replaceChildren(el('div.empty', {}, `Couldn't load ${tool.name}: ${err.message}`));
}
}
function renderHome() {
const filter = el('input.home-filter', { type: 'search', placeholder: 'Find a tool…', 'aria-label': 'Find a tool' });
const grid = el('div.card-grid');
const draw = () =>
grid.replaceChildren(
...TOOLS.filter((t) => matches(t, filter.value)).map((t) =>
el('a.tool-card', { href: t.path },
el('div.tool-card-icon', {}, t.icon),
el('div', {}, el('div.tool-card-name', {}, t.name), el('div.tool-card-desc', {}, t.description)),
),
),
);
filter.addEventListener('input', draw);
filter.addEventListener('keydown', (e) => {
const first = e.key === 'Enter' && grid.querySelector('a');
if (first) navigate(new URL(first.href).pathname);
});
draw();
view.replaceChildren(
el('div.home', {},
el('h1', {}, 'Tools'),
el('p.muted', {}, 'Small utilities that run in your browser. Only pastes are stored on the server, and only for 24 hours.'),
filter,
grid,
),
);
}
renderNav();
route();