// House app shell: top bar, sidebar nav (a drawer on phones), theme toggle,
// "/" to find a view, client-side routing and a home grid, all built from one
// list of views. Copy into the project (e.g. static/js/shell.js) unchanged and
// call startShell() from the project's own main.js. Expects the markup in
// index.html (ids: view, nav-list, nav-filter, topbar-title, theme-btn,
// menu-btn, scrim, sidebar).
//
// A view: {
// id, name, path, // path '/x' owns /x and everything under /x/
// category, icon, // sidebar group; 1-3 character monogram ('{ }', 'M↓', '⎘')
// description, // home card text and nav search
// load: () => import('./views/x.js'), // module exports mount(root, ctx)
// badge?: () => number, // count on the nav item; dispatch 'app:badges' on window when it changes
// }
// mount(root, ctx) may return a cleanup function. ctx = {
// rest, // path after the view's own, e.g. "abc123" for /paste/abc123
// query, // URLSearchParams of the current URL
// navigate, // navigate('/x/abc'): client-side navigation
// setTitle, // setTitle('abc123'): extra text in the top bar and tab title
// }
// A view with path '/' replaces the home grid.
import { el, store } from './ui.js';
const $ = (id) => document.getElementById(id);
let cfg, cleanup = null, routeSeq = 0;
/**
* startShell({
* name: 'tools', // shown in the tab title
* views: [...],
* categories: ['Text', 'Data'], // sidebar order; unknown ones go last, alphabetically
* home: { title, intro }, // the home page heading and one-line description
* sidebar: true, // false: top bar only (single-screen apps)
* passthrough: ['/api/', '/static/'], // same-origin links the router must leave alone
* })
*/
export function startShell(options) {
cfg = { categories: [], sidebar: true, passthrough: ['/api/', '/static/'], home: {}, ...options };
setupTheme();
if (cfg.sidebar) setupNav();
else document.querySelector('.shell')?.classList.add('bare');
setupLinks();
route();
}
// ---------- theme: auto → light → dark, remembered per browser ----------
const THEMES = ['auto', 'light', 'dark'];
const svg = (d) => ``;
const THEME_ICON = {
auto: svg(''),
light: svg(''),
dark: svg(''),
};
function setupTheme() {
const btn = $('theme-btn');
let theme = store.get('theme', 'auto');
const apply = (t) => {
if (t === 'auto') delete document.documentElement.dataset.theme;
else document.documentElement.dataset.theme = t;
if (btn) {
btn.innerHTML = THEME_ICON[t];
btn.title = `Theme: ${t}`;
}
};
apply(theme);
btn?.addEventListener('click', () => {
theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
store.set('theme', theme);
apply(theme);
});
}
// ---------- navigation ----------
function grouped(views) {
const groups = new Map();
for (const v of views) {
const c = v.category || 'Other';
if (!groups.has(c)) groups.set(c, []);
groups.get(c).push(v);
}
const rank = (c) => (cfg.categories.includes(c) ? cfg.categories.indexOf(c) : 999);
return [...groups].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b));
}
function matches(v, q) {
q = q.trim().toLowerCase();
return !q || `${v.name} ${v.description || ''} ${v.category || ''}`.toLowerCase().includes(q);
}
const listed = () => cfg.views.filter((v) => v.path !== '/');
function renderNav() {
const q = $('nav-filter').value;
const homeView = cfg.views.find((v) => v.path === '/');
$('nav-list').replaceChildren(
el('a.nav-item', { href: '/', dataset: { path: '/' } },
el('span.nav-icon', {}, homeView?.icon || '⌂'), el('span.nav-label', {}, homeView?.name || 'Home')),
...grouped(listed().filter((v) => matches(v, q))).map(([cat, views]) =>
el('div.nav-group', {},
el('div.nav-heading', {}, cat),
views.map((v) => el('a.nav-item', { href: v.path, dataset: { path: v.path, view: v.id } },
el('span.nav-icon', {}, v.icon), el('span.nav-label', {}, v.name), v.badge ? el('span.badge', { hidden: true }) : null)),
),
),
);
markActive();
updateBadges();
}
function updateBadges() {
if (!cfg.sidebar) return;
let total = 0;
for (const v of cfg.views) {
if (!v.badge) continue;
let n = 0;
try { n = v.badge() || 0; } catch {}
total += n;
const b = $('nav-list').querySelector(`.nav-item[data-view="${v.id}"] .badge`);
if (b) {
b.hidden = !n;
b.textContent = n > 99 ? '99+' : String(n);
b.title = `${n} new`;
}
}
$('menu-btn')?.classList.toggle('has-badge', total > 0);
}
function markActive() {
if (!cfg.sidebar) return;
const view = findView(location.pathname);
for (const a of $('nav-list').querySelectorAll('.nav-item')) {
const on = view ? a.dataset.path === view.path : a.dataset.path === '/';
a.classList.toggle('active', on);
if (on) a.setAttribute('aria-current', 'page');
else a.removeAttribute('aria-current');
}
}
function setDrawer(open) {
document.body.classList.toggle('drawer-open', open);
$('menu-btn')?.setAttribute('aria-expanded', String(open));
}
function setupNav() {
const filter = $('nav-filter');
filter.addEventListener('input', renderNav);
filter.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const first = listed().find((v) => matches(v, filter.value));
if (first) {
filter.value = '';
renderNav();
setDrawer(false);
navigate(first.path);
}
} else if (e.key === 'Escape') {
filter.value = '';
renderNav();
filter.blur();
setDrawer(false);
}
});
document.addEventListener('keydown', (e) => {
const a = document.activeElement;
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(a?.tagName) || a?.isContentEditable;
if (e.key === '/' && !typing && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
setDrawer(true);
filter.focus();
}
});
$('menu-btn')?.addEventListener('click', () => setDrawer(!document.body.classList.contains('drawer-open')));
$('scrim')?.addEventListener('click', () => setDrawer(false));
window.addEventListener('app:badges', updateBadges);
window.addEventListener('storage', (e) => { if (!e.key || e.key.startsWith(store.prefix)) updateBadges(); }); // other tabs
setInterval(updateBadges, 60000);
renderNav();
}
// ---------- routing ----------
function findView(pathname) {
return cfg.views.find((v) => (v.path === '/' ? pathname === '/' : pathname === v.path || pathname.startsWith(`${v.path}/`)));
}
export function navigate(path, { replace = false } = {}) {
if (path === location.pathname + location.search) return;
history[replace ? 'replaceState' : 'pushState']({}, '', path);
route();
}
function setupLinks() {
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 || cfg.passthrough.some((p) => url.pathname.startsWith(p))) return;
if (url.pathname === location.pathname && url.search === location.search && url.hash) return; // in-page anchor
e.preventDefault();
setDrawer(false);
navigate(url.pathname + url.search);
});
window.addEventListener('popstate', route);
}
function setTitle(view, extra) {
const isHome = !view || view.path === '/';
const t = $('topbar-title');
if (t) t.textContent = isHome ? '' : [view.name, extra].filter(Boolean).join(' · ');
document.title = isHome ? cfg.name : `${[extra, view.name].filter(Boolean).join(' · ')} — ${cfg.name}`;
}
async function route() {
const seq = ++routeSeq;
if (cleanup) {
try { cleanup(); } catch (err) { console.error(err); }
cleanup = null;
}
markActive();
const root = $('view');
const view = findView(location.pathname);
document.body.dataset.view = view ? view.id : 'home';
if (!view) {
if (location.pathname !== '/') history.replaceState({}, '', '/');
setTitle(null);
renderHome(root);
return;
}
setTitle(view);
root.replaceChildren(el('div.loading', {}, 'Loading…'));
try {
const mod = await view.load();
if (seq !== routeSeq) return; // navigated away while loading
root.replaceChildren();
const ctx = {
rest: view.path === '/' ? '' : location.pathname.slice(view.path.length).replace(/^\//, ''),
query: new URLSearchParams(location.search),
navigate,
setTitle: (extra) => setTitle(view, extra),
};
cleanup = (await mod.mount(root, ctx)) || null;
} catch (err) {
console.error(err);
if (seq === routeSeq) root.replaceChildren(el('div.empty', {}, `Couldn't load ${view.name}: ${err.message}`));
}
}
function renderHome(root) {
const filter = el('input.page-filter', { type: 'search', placeholder: 'Find…', 'aria-label': 'Filter' });
const grid = el('div.card-grid');
const draw = () =>
grid.replaceChildren(
...listed().filter((v) => matches(v, filter.value)).map((v) =>
el('a.card-link', { href: v.path },
el('div.card-link-icon', { 'aria-hidden': 'true' }, v.icon),
el('div', {}, el('div.card-link-name', {}, v.name), el('div.card-link-desc', {}, v.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();
root.replaceChildren(
el('div.page', {},
el('h1', {}, cfg.home.title || cfg.name),
cfg.home.intro ? el('p.muted', {}, cfg.home.intro) : null,
listed().length > 6 ? filter : null,
grid,
),
);
}