`));
if ((p.pain || []).includes(j + 1)) cells.push(`
${bars(3, n)}
`);
}
cells.push(`
${''.repeat(p.tools || 0)}
`);
c += steps;
});
const pains = phases.reduce((t, p) => t + (p.pain || []).length, 0);
const summary = `${d.title ? d.title + ' journey map' : 'Journey map'}, as a wireframe: ${phases.length} phases and ${cols} steps, each step with its own ${rows.join(', ').toLowerCase()}, tools, and ${pains} flagged pain points. Phases: ` +
phases.map(p => p.meta ? `${p.name} (${p.meta})` : p.name).join('; ') + '.';
const totals = (d.totals || []).map(([num, label]) => `${esc(String(num))}${esc(label)}`).join('');
return `${d.note ? `${inline(d.note, folder)}` : ''}
${cells.join('')}
` +
`${totals ? `
${totals}
` : ''}` +
`${d.caption ? `${inline(d.caption, folder)}` : ''}`;
}
/* "::: compare slider": before/after drag-to-reveal. The before image is the base; the after image sits on top, clipped at the
handle, so dragging right reveals the after. A full-size range input does the dragging, so it also works with a keyboard (arrow keys) and screen readers. */
function baSlider([before, after], folder, note, flush) {
const label = (s, fallback) => esc(s.label || fallback);
return `
${img(after.src, after.alt, folder)}
${img(before.src, before.alt, folder)}
${label(before, 'Before')}
${note}`;
}
document.addEventListener('input', e => {
if (e.target.classList?.contains('ba-range')) {
const s = e.target.closest('.ba-slider'), lab = s.querySelector('.ba-label');
s.style.setProperty('--pos', e.target.value + '%');
lab.textContent = +e.target.value >= 50 ? lab.dataset.before : lab.dataset.after; // names whichever side fills most of the frame
}
});
/* "::: phasebars" table. JSON: rows ({ name, days, to (optional upper end of a range), time (label), tools, people }),
optional "highlight": [first, last] rows in blue, "headers" (four column names), "bars": false (numbers only) and "caption". Bars share one scale. */
function phaseBars(d, folder) {
const rows = d.rows || [], hl = d.highlight || [];
const max = Math.max(...rows.map(r => r.to || r.days || 0)) || 1;
const [h1, h2, h3, h4] = d.headers || ['Step', 'Time', 'Tools', 'People'];
const body = rows.map((r, n) => {
const on = n + 1 >= hl[0] && n + 1 <= hl[1];
const w = (r.days || 0) / max * 100, ext = r.to ? (r.to - r.days) / max * 100 : 0;
return `
${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'));
});
// Photo carousel: clicking, tapping, or pressing Enter/Space on it pauses and resumes the scrolling (moving content needs a pause control, WCAG 2.2.2)
document.addEventListener('click', e => { e.target.closest('figure.carousel')?.classList.toggle('paused'); });
document.addEventListener('keydown', e => {
const car = e.target.classList?.contains('carousel') && e.target;
if (car && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); car.classList.toggle('paused'); }
});
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) {
// Internal Capital One tools are left out of the tray (they still appear in the case study's Tools list)
const icons = toolIconList(tools).filter(ic => ic.glyph !== INTERNAL_ICON[2] && !/internal/i.test(ic.label));
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]');
s = s.replace(/<br\s*\/?>/g, ' '); // a typed forces a line break
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+(.*)$/))) {
// "## Phase 1: Title" or "## Eyebrow :: Title" shows the first part as a small all-caps eyebrow above the title
const lv = m[1].length;
const ph = lv === 2 && m[2].match(/^(Phase\s+\d+):\s*(.+)$/i);
const id = slug(ph ? ph[2] : m[2]);
const sub = (lv === 2 || lv === 3) && !ph && m[2].match(/^(.+?)\s+::\s+(.+)$/); // "## / ### Title :: Smaller text" adds a small line under the heading
if (headings && lv === 2) headings.push({ id: sub ? slug(sub[1]) : id, text: (ph ? ph[2] : sub ? sub[1] : m[2]).replace(/[*`]/g, '') });
out.push(ph
? `
${esc(ph[1])}${inline(ph[2], folder)}
`
: sub ? `${inline(sub[1], folder)}${inline(sub[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*quotes\s*$/.test(l)) { // "::: quotes" … ":::" shows its quotes side by side (stacked on phones)
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;
}
if ((m = l.match(/^:::\s*steps((?:\s+(?:journey|rows|plain))*)\s*$/))) {
const steps = [];
let hl = null; // "Highlight: 1-2 :: label" line: those steps light up in blue on scroll, with the label pointing at them
let dots = []; // "Colors: #hex, #hex, …" line: one colour per step number pill, in order (the rest of each step stays neutral)
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const h = L[i].match(/^Highlight:\s*(\d+)\s*-\s*(\d+)\s*::\s*(.+)$/);
if (h) { hl = { from: +h[1], to: +h[2], label: h[3] }; i++; continue; }
const cl = L[i].match(/^Colors:\s*(.+)$/);
if (cl) { dots = cl[1].split(/\s*,\s*/).filter(c => /^#[0-9a-fA-F]{3,8}$/.test(c)); i++; continue; }
const mm = L[i].match(LIST_ITEM);
if (mm) {
const t = mm[2].match(/^\*\*(.+?):?\*\*:?\s*(.*)$/);
const desc = t ? t[2] : '';
steps.push({ title: t ? t[1] : mm[2], desc: desc.charAt(0).toUpperCase() + desc.slice(1) });
}
i++;
}
i++;
const HUES = [228, 200, 168, 132, 48, 22, 345, 280];
// "::: steps journey": the journey map's section colours, in order (blue, purple, yellow, teal, orange, black/neutral, green, periwinkle)
const JOURNEY = [[214, 1], [275, 1], [46, 1], [165, 1], [20, 1], [0, 0], [128, 1], [242, 1]];
const pal = /plain/.test(m[1]) ? [[0, 0]] : /journey/.test(m[1]) ? JOURNEY : HUES.map(h => [h, 1]); // "plain": every step in the neutral grey
const lit = n => hl && n + 1 >= hl.from && n + 1 <= hl.to;
const list = `${steps.map((s, n) => `
${n + 1}${inline(s.title, folder)}
${s.desc ? `
${inline(s.desc, folder)}
` : ''}
${hl && n + 1 === hl.to ? `
${inline(hl.label, folder)}
` : ''}`).join('')}`;
out.push(hl ? `
${list}
` : list);
continue;
}
// "::: layers Top label @ 22% | Bottom label @ 74%" … ":::" with two "- Heading :: " lines:
// two images side by side under centered subheaders, with a column of labels on the left, each centered at
// its % of the image height (e.g. naming the top and bottom halves of both images). On phones the images stack
// and each gets its own label column.
if ((m = l.match(/^:::\s*layers\s+(.+?)\s*@\s*([\d.]+)%\s*\|\s*(.+?)\s*@\s*([\d.]+)%\s*$/))) {
const sides = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const mm = L[i].match(/^[-*]\s+(?:(.+?)\s*::\s*)?!\[([^\]]*)\]\(([^)]+)\)/);
if (mm) sides.push(mm);
i++;
}
i++;
const tags = dup => `
`).join('')}`);
continue;
}
// "::: pairs Left label | Right label" … ":::": each line holds a before and after image (" ").
// Desktop: every "before" in the left group and every "after" in the right group, one label over each group.
// Phones: a 2-column grid, one before/after pair per row, labels on top.
if ((m = l.match(/^:::\s*pairs\s+(.+?)\s*\|\s*(.+?)\s*$/))) {
const rows = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const ims = [...L[i].matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)];
if (ims.length === 2) rows.push(ims);
i++;
}
i++;
const n = rows.length, cell = (im, side, r) => `
${img(im[2], im[1], folder)}
`;
out.push(`${esc(m[1])}${esc(m[2])}${rows.map((r, k) => cell(r[0], 0, k) + cell(r[1], 1, k)).join('')}`);
continue;
}
// "::: band" ... "::: /band": wraps anything (images, stats, other blocks) in a full-width tinted band,
// the same overlay as the top of each page, to break up long stretches of a case study
if ((m = l.match(/^:::\s*band(\s+tight)?(?:\s+(#[0-9a-f]{6}))?\s*$/i))) { // "::: band tight": less padding inside and less room above/below; "::: band #EDEBEB": a solid color (no grain) matched to the images inside
const inner = [];
i++;
while (i < L.length && !/^:::\s*\/band\s*$/.test(L[i])) inner.push(L[i++]);
i++;
out.push(`
${render(inner.join('\n'), folder, headings)}
`);
continue;
}
// "::: collage" block: each line is a row of one or more images (no captions or notes); images in a row share one height
if (/^:::\s*collage\s*$/.test(l)) {
const rows = [];
i++;
for (; i < L.length && !/^:::\s*$/.test(L[i]); i++) {
const pics = [...L[i].matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)];
if (pics.length) rows.push(`
${pics.map(p => `
${img(p[2], p[1], folder).replace('`).join('')}
`);
}
i++;
out.push(`
${rows.join('')}
`);
continue;
}
// "::: carousel" block: one image per line, shown as a slow, endlessly scrolling strip across the full page width
if (/^:::\s*carousel\s*$/.test(l)) {
const pics = [];
i++;
for (; i < L.length && !/^:::\s*$/.test(L[i]); i++) {
const m = L[i].match(/^!\[([^\]]*)\]\(([^)]+)\)/);
if (m) pics.push({ alt: m[1], src: m[2] });
}
i++;
const imgs = (hidden) => pics.map(p => ``).join('');
out.push(`
${imgs(false)}
${imgs(true)}
`);
continue;
}
// "::: phasebars" block: JSON for a table of steps with a time bar per step, plus tool and people counts
if (/^:::\s*phasebars\s*$/.test(l)) {
const json = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) json.push(L[i++]);
i++;
try { out.push(phaseBars(JSON.parse(json.join('\n')), folder)); }
catch (e) { out.push(`
Phasebars block has invalid JSON: ${esc(e.message)}
`); }
continue;
}
// "::: lanes" block: JSON for a wireframe-style swimlane map (one lane per team across the phases, with shared steps spanning lanes)
if (/^:::\s*lanes\s*$/.test(l)) {
const json = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) json.push(L[i++]);
i++;
try { out.push(lanesMap(JSON.parse(json.join('\n')), folder)); }
catch (e) { out.push(`
Lanes block has invalid JSON: ${esc(e.message)}
`); }
continue;
}
// "::: journeymap" block: JSON for one team's wireframe journey map (phase bands, a column per step, detail rows)
if (/^:::\s*journeymap\s*$/.test(l)) {
const json = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) json.push(L[i++]);
i++;
try { out.push(stepMap(JSON.parse(json.join("\n")), folder)); }
catch (e) { out.push(`
Journey map block has invalid JSON: ${esc(e.message)}
`); }
continue;
}
// "::: persona" block: JSON for a persona card (avatar, facts, bio, quote, goals, challenges)
if (/^:::\s*persona\s*$/.test(l)) {
const json = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) json.push(L[i++]);
i++;
try {
const p = JSON.parse(json.join('\n'));
const ul = items => `
${(items || []).map(x => `
${inline(x, folder)}
`).join('')}
`;
out.push(`
${img(p.avatar || '', p.name || '', folder)}
${esc(p.name || '')}
${(p.facts || []).map(([a, b]) => `
${esc(a)}: ${esc(b)}
`).join('')}
${p.bio ? `
${inline(p.bio, folder)}
` : ''}
${p.quote ? `
${inline(p.quote, folder)}
` : ''}
${p.goals ? `
Goals${ul(p.goals)}
` : ''}
${p.challenges ? `
Challenges${ul(p.challenges)}
` : ''}
`);
} catch (e) { out.push(`
Persona data couldn't be read: ${esc(e.message)}
`); }
continue;
}
// "::: pickfu Caption" block: JSON data for PickFu test rounds (see pickfuRounds())
if ((m = l.match(/^:::\s*pickfu\s*(.*)$/))) {
const cap = m[1].trim(), json = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) json.push(L[i++]);
i++;
try { out.push(pickfuRounds(JSON.parse(json.join('\n')), folder, cap)); }
catch (e) { out.push(`
PickFu data couldn't be read: ${esc(e.message)}
`); }
continue;
}
// "::: journey Caption" block: JSON data for a coded journey map (see journeyMap())
if ((m = l.match(/^:::\s*journey\s*(.*)$/))) {
const cap = m[1].trim(), json = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) json.push(L[i++]);
i++;
try { out.push(journeyMap(JSON.parse(json.join('\n')), folder, cap)); }
catch (e) { out.push(`
Journey map data couldn't be read: ${esc(e.message)}
`); }
continue;
}
// "::: apps" block: a bullet list of tool names shown as app icons (name on hover)
if (/^:::\s*apps\s*$/.test(l)) {
const names = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) { const mm = L[i].match(LIST_ITEM); if (mm) names.push(mm[2]); i++; }
i++;
const icons = toolIconList(names);
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
// "::: columns boxed" puts the columns in a tinted box (same style as the "::: shift" box)
// "::: columns center" centers each column's image, eyebrow, and text
if ((m = l.match(/^:::\s*columns((?:\s+(?:real|wide|row|boxed|center|avatars))*)\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}
${mm[3].split(/\s*\|\|\s*/).map(t => `
${inline(t, folder)}
`).join('')}
`); // " || " in the text starts a new paragraph
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|flush|slider|heads|spaced|row|breakpoints|center|narrow))*)\s*$/i))) { // "real" skips the mock-data note; "flush" removes the gap between the images; "heads" turns the labels into centered subheaders; "slider" shows two images as a drag-to-reveal before/after
const sides = [], flags = m[3] || '', note = /real/i.test(flags) ? '' : mockNote();
const raw = [];
i++;
while (i < L.length && !/^:::\s*$/.test(L[i])) {
const mm = L[i].match(/^[-*]\s+(?:(.+?)\s*::\s*)?!\[([^\]]*)\]\(([^)]+)\)(?:\{([^}]*)\})?(?:\s+(.+))?/); // optional {outline} after the image, then optional text shown small under it
if (mm) raw.push({ label: mm[1], alt: mm[2], src: mm[3] });
if (mm) sides.push(`
`);
i++;
}
i++;
if (/breakpoints/i.test(flags) && sides.length > 2) sides.splice(2, 0, ''); // phones: first two on one line, the rest on the next
if (/slider/i.test(flags) && raw.length === 2) { out.push(baSlider(raw, folder, note, /flush/i.test(flags))); continue; }
out.push(`
${sides.join('')}
${note}`); // one mock-data note under the whole row
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*$/;
// A "Label: …" line right above a single image shows as a small all-caps header over it (picked up below)
if (/^Label:\s*\S/.test(l) && IMG_LINE.test(L[i + 1] || '')) { i++; continue; }
if ((m = l.match(/^Label:\s*(.+)$/))) { out.push(`
${inline(m[1], folder)}
`); i++; continue; } // a "Label:" line anywhere else: the same small all-caps label, over text or a block
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*$/))) {
// A "#hex" flag fills the full column behind the image with that color (e.g. a {narrow} GIF's own backdrop color)
const matte = (m[3] || '').match(/#[0-9a-f]{3,8}\b/i);
if (matte) m[3] = m[3].replace(matte[0], 'matte');
const cls = m[3] ? ` class="${attr(m[3].trim())}"${matte ? ` style="--matte:${matte[0]}"` : ''}` : '';
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();
const lab = (L[i - 1] || '').match(/^Label:\s*(.+)$/);
out.push(`${lab ? `${inline(lab[1], folder)}` : ''}${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(' ');
// A paragraph starting "Note:" shows as small italic text (same style as the mock-data note under images)
const small = text.match(/^Note:\s*(.+)$/);
if (small) { out.push(`
${inline(small[1], folder)}
`); continue; }
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);
/* "{blue}" at the end of the attribution line tints that quote with the case study's highlight blue. */
const tint = cite.match(/\s*\{blue\}\s*$/);
if (tint) cite = cite.slice(0, tint.index);
const bq = `
`;
/* " Name" in the attribution line shows a round photo beside it. */
const av = cite.match(/^!\[([^\]]*)\]\(([^)]+)\)\s*(.*)$/);
if (av) return `${bq}
`).join('')}`;
}
function viewProject(folder) {
const isPlay = /^play-/.test(folder), pool = isPlay ? playCases : projects;
const base = isPlay ? '#/play/' : '#/work/', back = ''; // no back links on case study or Play pages; the header nav covers it
const p = pool.find(x => x.folder === folder);
if (!p) return isPlay ? viewPlay() : viewHome();
const d = p.data;
if (p.locked) return `
${back}
${moreWork}`;
}
function viewInfo() {
const d = about.data;
const sections = about.body.split(/^## /m).slice(1).map(s => {
const nl = s.indexOf('\n');
return { title: s.slice(0, nl).trim(), body: s.slice(nl + 1) };
});
const short = sections.find(s => /short bio/i.test(s.title));
const rest = sections.filter(s => s !== short);
const lead = short ? inline(short.body.trim()) : '';
return `
${lead}
${rest.map((s, k) => {
const hide = /\{nolabel\}/.test(s.title), half = /\{half\}/.test(s.title); // "## Title {nolabel}": the label is read by screen readers but not shown
const title = s.title.replace(/\s*\{(nolabel|half)\}/g, '');
const html = `
`;
// "## Title {half}": two {half} sections in a row sit side by side as two columns
const prevHalf = k > 0 && /\{half\}/.test(rest[k - 1].title), nextHalf = /\{half\}/.test((rest[k + 1] || {}).title || '');
return !half ? html : !prevHalf ? `
${html}` + (nextHalf ? '' : '
') : html + '
';
}).join('')}`;
}
// Experience list: put the company's logo circle (same as the homepage cards) in front of each "**Company** · role" line
function withLogos(html) {
// Grouped list: a company with its roles nested underneath gets the logo beside the company name
html = html.replace(/
([^<]+)<\/strong>([^<]*)<\/p>\s*
/g, // text after the bold name, like "(Contract)", stays beside it
(m, name, note) => `
${clientBadge(name)}${name}${rest}`);
}
/* Play page (_pages/play.md): intro paragraph, then one project row per "## " section (same layout as the homepage).
Lines like "tags: …", "image: …", "badge: …", "link: …" right under a heading set that row's details. */
// Curly arrow after linked Play titles: a short tail, one loop, then an arrowhead pointing right
const LOOP_ARROW = '';
function viewPlay() {
const body = play.body.replace(//g, '');
const [introMd, ...parts] = body.split(/^## /m);
const items = parts.map(s => {
const lines = s.split('\n'), title = lines.shift().trim(), meta = {};
while (lines.length && (/^\s*$/.test(lines[0]) || /^(tags?|image|badge|link):/i.test(lines[0]))) {
const m = lines.shift().match(/^(\w+):\s*(.*)$/); if (m) meta[m[1].toLowerCase().replace(/^tag$/, 'tags')] = m[2].trim();
}
return { title, meta, desc: lines.join(' ').replace(/\s+/g, ' ').trim() };
});
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 === '/about' || h === '/info') { app.innerHTML = viewInfo(); key = 'about'; } // old /info links still work
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 — Senior Product Designer';
window.scrollTo(0, 0);
keepLastWords(app);
fitJourneys();
setupToc();
setupTrays();
startVideos(app);
}
/* GIF-style videos: the page is built with innerHTML, and some phones (iOS especially) won't honor the
autoplay/muted attributes on elements made that way, so mute and start each one from script. If the phone
still refuses (Low Power Mode, data saver), show play controls instead of leaving a frozen first frame. */
function startVideos(root) {
root.querySelectorAll('video[autoplay]').forEach(v => {
v.muted = true; v.defaultMuted = true; v.playsInline = true;
const p = v.play();
if (p) p.catch(() => { v.controls = true; });
});
}
/* 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);
});
}
/* Highlighted steps ("Highlight:" line): light them up once they're well into the screen */
function lightSteps() {
document.querySelectorAll('.steps-hl:not(.lit)').forEach(box => {
const first = box.querySelector('.step.hl');
if (first && first.getBoundingClientRect().top < innerHeight * .7) box.classList.add('lit');
});
}
addEventListener('scroll', lightSteps, { passive: true });
/* 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);
if (!DARK_MODE) themeBtn.hidden = true;
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 && DARK_MODE) 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); // plain numbers, no leading zero
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);
}
})();