${tone ? `${BADGE[tone]}` : ''}
On option ${String.fromCharCode(65 + k)}
“${inline(q.text || '', folder)}”
`;
}).join('');
return `
Round ${ri + 1}
${esc(r.title || '')}
${cards}
${quotes ? `
${quotes}
` : ''}
`;
}).join('');
return `${d.label ? `${esc(d.label)}` : ''}${rounds}${caption ? `${inline(caption, folder)}` : ''}`;
}
function journeyMap(d, folder, caption) {
const TRACK = 2000, BAND = 400, GAP = 56, IDEAS = 168, BOX = 96;
const k = TRACK / (d.width || 1540), X = v => Math.round(v * k);
const span = (rows, cls) => rows.map(([t, a, b]) => `
${inline(t, folder)}
`).join('');
const pts = d.points.map(([mood, x, y, t]) => ({ mood, x: X(x), y: Math.round(y / 100 * BAND), t }));
const moodCls = { '+': 'pos', '~': 'neu', '-': 'neg' }, gid = 'jm-grad-' + (journeyMap.n = (journeyMap.n || 0) + 1);
// Emotion curve, smoothed through the point centres
let curve = `M${pts[0].x} ${pts[0].y}`;
for (let i = 1; i < pts.length; i++) { const a = pts[i - 1], b = pts[i], mx = (a.x + b.x) / 2; curve += ` C${mx} ${a.y} ${mx} ${b.y} ${b.x} ${b.y}`; }
// Each idea sits directly under the point(s) it answers, so its connector(s) drop straight down
const ideas = (d.ideas || []).map(([, refs, t, wide]) => {
const qs = refs.map(r => pts[r - 1]).filter(Boolean), xs = qs.map(q => q.x);
const lo = Math.min(...xs), hi = Math.max(...xs);
return { qs, t, cx: (lo + hi) / 2, w: wide || Math.max(BOX, hi - lo + 40), neg: qs.some(q => q.mood === '-') };
});
const links = ideas.flatMap(id => id.qs.map(q => ``)).join('');
return `
ActionLocationGoals${FACE.happy}Pain / gain points${FACE.neutral}${FACE.sad}Ideas for improving
${span(d.phases, 'jm-phase')}
${span(d.actions, 'jm-action')}
${span(d.locations, 'jm-loc')}
${span(d.goals, 'jm-goal')}
${pts.map(q => `
${inline(q.t, folder)}
`).join('')}
${ideas.map(id => `
${inline(id.t, folder)}
`).join('')}
${caption ? `${esc(caption)}` : ''}
`;
}
/* Fit each journey map to the text column (same grid as the rest of the page)
with the map scaled down to fit. Below a minimum scale it scrolls instead. Clicking opens it full size. */
function fitJourneys() {
const vw = document.documentElement.clientWidth;
document.querySelectorAll('.jm-figure').forEach(fig => {
const frame = fig.querySelector('.jm-frame'), sizer = fig.querySelector('.jm-sizer'), jm = fig.querySelector('.jm');
const open = false;
const nw = jm.offsetWidth, nh = jm.offsetHeight;
const s = open ? 1 : Math.max(0.28, Math.min(1, frame.clientWidth / nw));
jm.style.transform = `scale(${s})`;
sizer.style.width = Math.ceil(nw * s) + 'px'; sizer.style.height = Math.ceil(nh * s) + 'px';
});
}
addEventListener('resize', () => requestAnimationFrame(fitJourneys));
document.fonts?.ready.then(fitJourneys);
// Enlarged view: a full-screen overlay (attached to ) with the map at full size, scrollable
function openJourney(fig) {
const ov = document.createElement('div');
ov.className = 'jm-overlay';
ov.setAttribute('role', 'dialog'); ov.setAttribute('aria-modal', 'true'); ov.setAttribute('aria-label', 'Journey map, enlarged');
ov.innerHTML = '';
const jm = fig.querySelector('.jm').cloneNode(true); jm.style.transform = '';
ov.querySelector('.jm-ov-frame').append(jm);
document.body.append(ov); document.body.style.overflow = 'hidden';
ov.querySelector('.jm-close').focus();
ov._from = fig;
}
function closeJourney() {
const ov = document.querySelector('.jm-overlay'); if (!ov) return;
ov.remove(); document.body.style.overflow = '';
ov._from?.querySelector('.jm-frame')?.focus();
}
document.addEventListener('click', e => {
if (document.querySelector('.jm-overlay')) { if (e.target.closest('.jm-close') || e.target.classList.contains('jm-overlay')) closeJourney(); return; }
const frame = e.target.closest('.jm-frame'); if (frame) openJourney(frame.closest('.jm-figure'));
});
document.addEventListener('keydown', e => {
if (document.querySelector('.jm-overlay')) { if (e.key === 'Escape') closeJourney(); return; }
if ((e.key === 'Enter' || e.key === ' ') && e.target.classList?.contains('jm-frame')) { e.preventDefault(); openJourney(e.target.closest('.jm-figure')); }
});
/* Icons for a list of tool names. "Name (detail)" looks up the icon by Name and shows the full text on hover. */
function toolIconList(tools) {
const icons = [];
for (const t of [].concat(tools || [])) {
const name = String(t).trim(), key = name.replace(/\s*\(.*\)\s*$/, '').toLowerCase();
const set = TOOL_ICONS[key] || [[`hsl(${[...key].reduce((h, c) => h + c.charCodeAt(0), 0) % 360} 45% 38%)`, '#fff',
esc(key.split(/\s+/).map(w => w[0]).join('').slice(0, 2).toUpperCase())]];
set.forEach(([bg, fg, glyph, label]) => icons.push({ bg, fg, glyph,
label: glyph === INTERNAL_ICON[2] ? `${name} (Capital One internal)` : (set.length > 1 ? (label || name) : name !== key && name.toLowerCase() !== key ? name : (label || name)) }));
}
return icons;
}
const toolSpans = icons => icons.map((ic, i) =>
`${ic.glyph}${esc(ic.label)}`).join('');
function toolTray(tools, hue) {
const icons = toolIconList(tools);
if (!icons.length) return '';
return `
${toolSpans(icons)}
`;
}
const attr = s => esc(s).replace(/"/g, '"');
const slug = s => s.toLowerCase().replace(/<[^>]+>|[*_`]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
function resolve(src, folder) {
return /^(https?:|\/|\.\.)/.test(src) ? src : `${folder}/${src}`;
}
function img(src, alt, folder, cls = '') {
// Videos (.mp4, .mov, .webm) play like a GIF: autoplaying, muted, looping.
// With "reduce motion" on (WCAG 2.2.2), they don't autoplay and show play controls instead.
if (/\.(mp4|mov|webm)$/i.test(src)) {
const still = matchMedia('(prefers-reduced-motion: reduce)').matches;
return ``;
}
// "name-light.png" pairs with "name-dark.png": each shows only in its own theme
const dark = src.replace(/-light(\.\w+)$/, '-dark$1');
if (dark !== src && !cls) return img(src, alt, folder, 'theme-light') + img(dark, alt, folder, 'theme-dark');
return ``;
}
/* Mock-data disclaimer under case study images. Set per case study with "mock_data: true" (default wording)
or "mock_data: Your own wording" in its frontmatter; viewProject sets MOCK_NOTE before rendering. */
let MOCK_NOTE = '';
const MOCK_DEFAULT = 'Images show mock data for illustration purposes only.';
const mockNote = () => MOCK_NOTE ? `${esc(MOCK_NOTE)}` : '';
function ph(el) {
const d = document.createElement('div');
d.className = 'ph';
const file = el.dataset.file || '';
d.innerHTML = `Image to add${esc(el.alt || el.getAttribute('aria-label') || '')}${esc(file)}`;
el.replaceWith(d);
}
function inline(s, folder) {
s = esc(s);
s = s.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, a, src) => img(src, a, folder));
s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1');
s = s.replace(/\*\*([^*]+)\*\*/g, '$1');
s = s.replace(/(^|[^*\w])\*([^*\s][^*]*?)\*(?!\*)/g, '$1$2');
s = s.replace(/`([^`]+)`/g, '$1');
s = s.replace(/==([^=\n]+)==/g, '$1');
s = s.replace(/\[(X+)\]/g, '[$1]');
return s;
}
const BLOCK_START = /^(#{1,6}\s|>|\||!\[|[-*]\s|\d+\.\s|---\s*$|:::)/;
const LIST_ITEM = /^([-*]|\d+\.)\s+(.*)$/;
function render(md, folder, headings) {
const L = md.replace(//g, '').split('\n');
const out = [];
let i = 0, m;
while (i < L.length) {
const l = L[i];
if (!l.trim()) { i++; continue; }
if ((m = l.match(/^(#{1,6})\s+(.*)$/))) {
const lv = m[1].length, id = slug(m[2]);
if (headings && lv === 2) headings.push({ id, text: m[2].replace(/[*`]/g, '') });
// "## Phase 1: Title" shows "Phase 1" as a small all-caps eyebrow above the title
const ph = lv === 2 && m[2].match(/^(Phase\s+\d+):\s*(.+)$/i);
out.push(ph
? `
${esc(ph[1])}${inline(ph[2], folder)}
`
: `${inline(m[2], folder)}`);
i++; continue;
}
if (/^---\s*$/.test(l)) { out.push(''); i++; continue; }
if (/^:::\s*space\s*$/.test(l)) { out.push(''); i++; continue; } // "::: space" adds extra room between blocks
if (/^:::\s*tight\s*$/.test(l)) { // "::: tight" … ":::" renders its paragraph and list with no extra spacing between them
const inner = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) inner.push(L[i++]);
i++;
out.push(`
${render(inner.join('\n'), folder, headings)}
`);
continue;
}
if (/^:::\s*stats\s*$/.test(l)) {
const stats = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const mm = L[i].match(LIST_ITEM);
if (mm) { const [value, label = ''] = mm[2].split(' :: '); stats.push({ value, label }); }
i++;
}
i++;
out.push(`
`);
continue;
}
// "::: avatars" block: each line " text" becomes a circular image beside its paragraph
if (/^:::\s*avatars\s*$/.test(l)) {
const rows = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const mm = L[i].match(/^!\[([^\]]*)\]\(([^)]+)\)\s*(.*)$/);
if (mm) rows.push(`
${img(mm[2], mm[1], folder)}
${inline(mm[3], folder)}
`);
i++;
}
i++;
out.push(`
${rows.join('')}
`);
continue;
}
// "::: columns" block: each item "Eyebrow ::  text" becomes a column (image, eyebrow, text)
// "::: columns real" skips the mock-data disclaimer; "::: columns wide" makes the images fill their column
// "::: columns row" keeps every item on one row (images fill their column) until phone widths
if ((m = l.match(/^:::\s*columns((?:\s+(?:real|wide|row))*)\s*$/))) {
const flags = m[1] || '', cols = [], note = /real/.test(flags) ? '' : mockNote();
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const mm = L[i].match(LIST_ITEM);
const c = mm && mm[2].match(/^(?:(.+?)\s+::\s+)?(?:!\[([^\]]*)\]\(([^)]+)\)\s*)?(.*)$/);
if (c) cols.push(`
`);
continue;
}
// "::: media" block: each line " text" becomes a row with the image left and the text right
// "::: media real" skips the mock-data disclaimer (for real, public screenshots)
// "::: media wide" gives the image half the row instead of capping it at 250px (flags combine: "::: media wide real")
if ((m = l.match(/^:::\s*media((?:\s+(?:real|wide))*)\s*$/))) {
const rows = [], note = /\breal\b/.test(m[1]) ? '' : mockNote(), wide = /\bwide\b/.test(m[1]);
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const mm = L[i].match(/^!\[([^\]]*)\]\(([^)]+)\)\s*(.*)$/);
if (mm) rows.push(`
${img(mm[2], mm[1], folder)}${note}
${inline(mm[3], folder)}
`);
i++;
}
i++;
out.push(`
${rows.join('')}
`);
continue;
}
// "::: compare #from #to" block: each line "- Label :: " becomes a labeled image, side by side
// on a gradient from the first colour to the second (no colours: no panel)
if ((m = l.match(/^:::\s*compare\s*(#[0-9a-f]{3,8})?\s*(#[0-9a-f]{3,8})?\s*(real)?\s*$/i))) { // "real" at the end skips the mock-data note
const sides = [], note = m[3] ? '' : mockNote();
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const mm = L[i].match(/^[-*]\s+(?:(.+?)\s*::\s*)?!\[([^\]]*)\]\(([^)]+)\)/);
if (mm) sides.push(`
`);
continue;
}
// "::: shift to:" block: each line "quote" (or " quote" for a small image above it) becomes a column,
// with the word after "shift" (default "to:") between the columns
if ((m = l.match(/^:::\s*shift\s*(.*)$/))) {
const sides = []; let lead = '';
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const ld = L[i].match(/^Lead:\s*(.+)$/); // "Lead: text" shows a small intro line at the top of the box
if (ld) { lead = `${inline(ld[1], folder)}`; i++; continue; }
const mm = L[i].match(/^(?:!\[([^\]]*)\]\(([^)]+)\)\s*)?(.+)$/);
if (mm) sides.push(`
`);
}
continue;
}
if (/^>/.test(l)) {
const q = [];
while (i < L.length && /^>/.test(L[i])) q.push(L[i++].replace(/^>\s?/, ''));
out.push(quote(q, folder)); continue;
}
if (/^\|/.test(l)) {
const t = [];
while (i < L.length && /^\|/.test(L[i])) t.push(L[i++]);
out.push(table(t, folder)); continue;
}
// Two or more image lines in a row (no blank line between) sit side by side
const IMG_LINE = /^!\[([^\]]*)\]\(([^)]+)\)(?:\{([\w\s-]+)\})?\s*$/;
if (IMG_LINE.test(l) && IMG_LINE.test(L[i + 1] || '')) {
const figs = [];
while (i < L.length && (m = L[i].match(IMG_LINE))) { figs.push(`${img(m[2], m[1], folder)}${/\breal\b/.test(m[3] || "") ? "" : mockNote()}${esc(m[1])}`); i++; }
// A "Caption: ..." line right after the images becomes one caption under the whole row
const cap = (L[i] || '').match(/^Caption:\s*(.+)$/i);
if (cap) i++;
const tag = cap ? 'figure' : 'div';
out.push(`<${tag} class="fig-row${figs.some(f => /class="[^"]*\bflush\b/.test(f)) ? ' flush' : ''}" style="--n:${figs.length}">${figs.join('')}${cap ? `${inline(cap[1], folder)}` : ''}${tag}>`);
continue;
}
if ((m = l.match(/^!\[([^\]]*)\]\(([^)]+)\)(?:\{([\w\s-]+)\})?\s*$/))) {
const cls = m[3] ? ` class="${attr(m[3].trim())}"` : '';
const pan = /\bpan\b/.test(m[3] || "");
const inner = pan ? `${img(m[2], m[1], folder)}` : img(m[2], m[1], folder);
// A "Note: …" line right under the image replaces the mock-data note with its own small italic text
const own = (L[i + 1] || '').match(/^Note:\s*(.+)$/);
const note = own ? `${inline(own[1], folder)}` : /\breal\b/.test(m[3] || "") ? "" : mockNote();
out.push(`${inner}${note}${esc(m[1])}${pan ? " Scroll to explore → · click to open full size" : ""}`);
i += own ? 2 : 1; continue;
}
if (LIST_ITEM.test(l)) {
const ordered = /^\d/.test(l);
const items = [];
let cur = null;
while (i < L.length) {
const x = L[i], mm = x.match(LIST_ITEM);
if (mm && /^\d/.test(x) === ordered) { cur = [mm[2]]; items.push(cur); i++; continue; }
if (!x.trim()) {
let j = i + 1;
while (j < L.length && !L[j].trim()) j++;
const nxt = L[j] || '';
if (/^\s{2,}\S/.test(nxt) || (LIST_ITEM.test(nxt) && /^\d/.test(nxt) === ordered)) { cur.push(''); i++; continue; }
break;
}
if (/^\s{2,}\S/.test(x)) { cur.push(x.replace(/^\s{2,4}/, '')); i++; continue; }
break;
}
const tag = ordered ? 'ol' : 'ul';
out.push(`<${tag}>` + items.map(it => {
const content = it.join('\n').trim();
if (!content.includes('\n')) {
const parts = content.split(' | ');
return parts.length === 2
? `
`;
}).join('') + `${tag}>`);
continue;
}
const p = [];
while (i < L.length && L[i].trim() && (!p.length || !BLOCK_START.test(L[i]))) p.push(L[i++].trim());
const text = p.join(' ');
out.push(`
${inline(text, folder)}
`);
}
return out.join('\n');
}
function quote(lines, folder) {
lines = lines.filter(x => x.trim());
let cite = '';
if (lines.length > 1 && !/^["“]/.test(lines[lines.length - 1].trim())) cite = lines.pop();
let text = lines.join(' ').trim();
/* The callout draws its own opening mark, so drop the typed wrapping quotes. */
if (/^["“]/.test(text) && /["”]$/.test(text)) text = text.slice(1, -1);
/* " Name" in the attribution line shows a round photo beside it. */
const av = cite.match(/^!\[([^\]]*)\]\(([^)]+)\)\s*(.*)$/);
if (av) return `
`;
}
/* ---------- Router ---------- */
let observer;
function route() {
const h = location.hash.replace(/^#/, '') || '/';
const app = document.getElementById('app');
let key = 'work';
if (h.startsWith('/work/')) { app.innerHTML = viewProject(h.slice(6)); }
else if (h === '/info') { app.innerHTML = viewInfo(); key = 'info'; }
else if (h.startsWith('/play/')) { app.innerHTML = viewProject(h.slice(6)); key = 'play'; }
else if (h === '/play' && play) { app.innerHTML = viewPlay(); key = 'play'; }
else { app.innerHTML = viewHome(); }
document.querySelectorAll('[data-nav]').forEach(a => a.classList.toggle('on', a.dataset.nav === key));
const t = app.querySelector('h1');
document.title = ((h.startsWith('/work/') || h.startsWith('/play/')) && t ? t.textContent + ' — ' : '') + 'Deni Lewis — UX Designer';
window.scrollTo(0, 0);
keepLastWords(app);
fitJourneys();
setupToc();
setupTrays();
}
/* Orphan guard: glue each text block's last two words with a non-breaking space,
so a single word never wraps onto a line by itself. Only short pairs are glued, so narrow columns
don't end up pushing a long unbreakable pair down and stranding the word before it. */
function keepLastWords(root) {
root.querySelectorAll('h1, h2, h3, h4, p, li, blockquote, figcaption, td, dd').forEach(el => {
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
let last = null;
for (let n; (n = walker.nextNode());) if (n.textContent.trim()) last = n;
if (!last) return;
last.textContent = last.textContent.replace(/(\S+)[ \t\n]+(\S+)\s*$/, (m, a, b) => a.length + b.length <= 15 ? `${a} ${b}` : m);
});
}
/* Single-column layout: open each card's tools tray while it's in the middle of the screen (touch has no hover) */
let trayObserver;
function setupTrays() {
if (trayObserver) trayObserver.disconnect();
trayObserver = new IntersectionObserver(entries => entries.forEach(en =>
en.target.closest('.project').classList.toggle('in-view', en.isIntersecting)), { rootMargin: '-30% 0px -30% 0px' });
document.querySelectorAll('.project .thumb-wrap').forEach(el => trayObserver.observe(el));
}
// Contents button appears once the case study body reaches the screen; tapping outside closes its menu
function showDock() {
const dock = document.querySelector('.toc-dock'), body = document.querySelector('.cs-body');
if (!dock || !body) return;
const on = body.getBoundingClientRect().top < innerHeight * .75;
dock.classList.toggle('show', on);
// Current section: the last heading that has scrolled above 40% of the screen
const links = [...dock.querySelectorAll('.toc-panel a')];
let current = null;
links.forEach(a => { const h = document.getElementById(a.dataset.target); if (h && h.getBoundingClientRect().top < innerHeight * .4) current = a; });
links.forEach(a => a.classList.toggle('on', a === current));
dock.querySelector('.toc-cur').textContent = current ? current.textContent : '';
if (!on && dock.classList.contains('open')) { dock.classList.remove('open'); dock.querySelector('.toc-btn').setAttribute('aria-expanded', 'false'); }
}
addEventListener('scroll', showDock, { passive: true });
document.addEventListener('click', e => {
const dock = document.querySelector('.toc-dock.open');
if (dock && !dock.contains(e.target)) { dock.classList.remove('open'); dock.querySelector('.toc-btn').setAttribute('aria-expanded', 'false'); }
});
function setupToc() {
if (observer) observer.disconnect();
const dock = document.querySelector('.toc-dock');
const links = [...document.querySelectorAll('.toc-panel a')];
if (!dock || !links.length) return;
const btn = dock.querySelector('.toc-btn');
const setOpen = open => { dock.classList.toggle('open', open); btn.setAttribute('aria-expanded', String(open)); };
btn.addEventListener('click', () => setOpen(!dock.classList.contains('open')));
dock.addEventListener('keydown', e => { if (e.key === 'Escape') { setOpen(false); btn.focus(); } });
links.forEach(a => a.addEventListener('click', e => {
e.preventDefault();
setOpen(false);
document.getElementById(a.dataset.target)?.scrollIntoView({ behavior: 'smooth' });
}));
showDock();
}
/* Light / dark toggle. Remembers the choice; otherwise follows the system setting. */
const themeBtn = document.getElementById('theme');
function applyTheme(t, save) {
document.documentElement.dataset.theme = t;
themeBtn.setAttribute('aria-label', t === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
if (save) try { localStorage.setItem('theme', t); } catch (e) {}
}
applyTheme(document.documentElement.dataset.theme);
themeBtn.addEventListener('click', () => applyTheme(document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark', true));
// Small-screen "Menu" dropdown for the page links
const menuBtn = document.getElementById('menu-btn'), navLinks = document.getElementById('nav-links');
function setMenu(open) { navLinks.classList.toggle('open', open); menuBtn.setAttribute('aria-expanded', open); }
menuBtn.addEventListener('click', () => setMenu(!navLinks.classList.contains('open')));
navLinks.addEventListener('click', e => { if (e.target.closest('a')) setMenu(false); });
document.addEventListener('click', e => { if (!e.target.closest('nav')) setMenu(false); });
document.addEventListener('keydown', e => { if (e.key === 'Escape' && navLinks.classList.contains('open')) { setMenu(false); menuBtn.focus(); } });
window.addEventListener('hashchange', () => setMenu(false));
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
let saved = null;
try { saved = localStorage.getItem('theme'); } catch (err) {}
if (!saved) applyTheme(e.matches ? 'dark' : 'light');
});
/* Segment explorer: pick a segment in the list to show it in the detail panel.
On phones the panel is hidden and the list behaves as an accordion. */
function panelHTML(lob, nameHTML, descHTML, i, n) {
const pad = x => String(x).padStart(2, '0');
return `
${esc(lob)}
${nameHTML}
${descHTML}
${pad(i + 1)} / ${pad(n)}
`;
}
function selectSeg(ex, btn, fromList) {
const item = btn.closest('.ex-item');
const mobile = matchMedia('(max-width: 700px)').matches;
const collapse = mobile && fromList && item.classList.contains('on');
ex.querySelectorAll('.ex-item').forEach(it => {
const on = it === item && !collapse;
it.classList.toggle('on', on);
it.querySelector('.seg[data-i]')?.setAttribute('aria-expanded', on);
});
const panel = ex.querySelector('.ex-panel');
if (panel && !collapse) panel.style.setProperty("--h", btn.dataset.h);
if (panel && !collapse) panel.innerHTML = panelHTML(btn.dataset.lob, btn.querySelector('span').innerHTML, item.querySelector('.seg-desc').innerHTML, +btn.dataset.i, +ex.dataset.total);
}
document.addEventListener('click', e => {
const ex = e.target.closest('.explorer');
if (!ex) return;
const btn = e.target.closest('.seg[data-i]');
if (btn) return selectSeg(ex, btn, true);
const step = e.target.closest('.ex-nav button');
if (step) {
const n = +ex.dataset.total;
const cur = +(ex.querySelector('.ex-item.on .seg')?.dataset.i || 0);
selectSeg(ex, ex.querySelector(`.seg[data-i="${(cur + +step.dataset.step + n) % n}"]`), false);
}
});
document.addEventListener('keydown', e => {
const btn = e.target.closest?.('.seg[data-i]');
if (!btn || !['ArrowDown', 'ArrowUp', 'ArrowRight', 'ArrowLeft'].includes(e.key)) return;
e.preventDefault();
const ex = btn.closest('.explorer'), n = +ex.dataset.total;
const next = ex.querySelector(`.seg[data-i="${(+btn.dataset.i + (e.key === 'ArrowDown' || e.key === 'ArrowRight' ? 1 : -1) + n) % n}"]`);
next.focus();
selectSeg(ex, next, false);
});
window.addEventListener('hashchange', route);
document.addEventListener('submit', async e => {
if (e.target.id !== 'gate') return;
e.preventDefault();
const input = document.getElementById('gate-pw'), err = document.getElementById('gate-err');
err.hidden = true;
if (await unlockAll(input.value)) route();
else { err.hidden = false; input.select(); }
});
footer();
route();
// Already unlocked earlier in this session? Decrypt quietly and re-render.
(async () => {
let pw = null; try { pw = sessionStorage.getItem('pw'); } catch (e) {}
if (pw && Object.values(docs).some(d => d.locked) && await unlockAll(pw)) {
const y = scrollY; route(); scrollTo(0, y);
}
})();