mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-12 06:06:37 +03:00
* feat(site): scaffold Astro migration, convert 3 pages Phase 1+2 of the Astro migration: - Astro v6.2.1 installed, srcDir: 'site', static output to build/ - Shared layout: Base.astro (head, fonts, meta, slots), Header.astro (star count in one place: 23k), Footer.astro - CSS moved from public/css/ to site/styles/ (9 files, @import chains resolve via Vite) - Three pages converted: privacy, cases/neo-mirai, live-mode (all return 200 on astro dev) Remaining: designing, slop, homepage, content collections (docs), JS migration, server/index.js deletion, build.js cleanup. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(site): migrate all 6 main pages to Astro Converts the remaining pages: - designing/index.html → site/pages/designing/index.astro (551 lines) - slop/index.html → site/pages/slop/index.astro (909 lines) - index.html → site/pages/index.astro (1278 lines, the homepage) Base.astro gains OG meta tag props, before-header/after-header slots (for grain overlay and section nav), and configurable mainId. Homepage uses link tags to public/css/ instead of frontmatter CSS imports to avoid esbuild choking on :has() in main.css. Curly braces inside <code> elements (CSS snippets in changelog) escaped with HTML entities to prevent Astro JSX expression parsing. All 6 pages return 200 on astro dev. Branch: feat/astro-migration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(site): content collections for docs and tutorials Replaces the 1532-line build-sub-pages.js generator with Astro v6 content collections: - 24 skill editorial files move to site/content/skills/ - 4 tutorial files move to site/content/tutorials/ - site/content.config.ts defines both collections with glob loaders - site/pages/docs/[...slug].astro reads skills collection + command metadata from source/skills/ at build time - site/pages/docs/index.astro renders the command grid grouped by category (create, evaluate, refine, simplify, harden, system) - site/pages/tutorials/ mirrors the pattern with ordered index - Doc.astro layout provides sidebar nav, breadcrumbs, and related- command chips from the COMMAND_RELATIONSHIPS data - Category/relationship data extracted to site/data/sub-pages-data.ts All 15 tested pages return 200: 6 main pages + 5 docs + 2 tutorials + 2 index pages. The old generator is not yet deleted (Task #6). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(site): move JS source from public/js/ to site/scripts/ Moves all 49 JS files (app.js + 48 in js/) into site/scripts/. Vite now processes them through its module bundler instead of serving them raw from public/. app.js import paths updated from ./js/X to ./X (the js/ nesting is gone since app.js now lives alongside the subdirectories). Homepage and live-mode page switch from <script is:inline src="/app.js"> to Vite-processed <script> imports, so tree-shaking, bundling, and minification happen automatically at build time. public/js/ still exists for now (cleanup in Task #6) and the generated/counts.js build output path needs updating there too. @paper-design/shaders added to npm dependencies (was missing). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(site): delete old Bun server, generator, and duplicated files Cleanup after the Astro migration: Deleted: - server/index.js (233 lines, replaced by `astro dev`) - scripts/build-sub-pages.js (1532 lines, replaced by content collections) - scripts/lib/render-page.js (247 lines, replaced by Base.astro layout) - content/site/partials/header.html (replaced by Header.astro component) - public/index.html, privacy.html, designing/, live-mode/, cases/ (replaced by .astro pages in site/pages/) - public/css/ (moved to site/styles/) - public/js/ old source files (moved to site/scripts/) - public/app.js (moved to site/scripts/app.js) Kept in public/: - antipattern-examples/ (standalone HTML demos, not Astro pages) - antipattern-images/, assets/, neo-mirai/ (static assets) - js/detect-antipatterns-browser.js (referenced by antipattern examples) - js/generated/counts.js (build output from scripts/build.js) - _data/api/ (generated API data, now written to public/ so Astro passes it through to build/) Updated: - astro.config.mjs: added redirects (skills->docs, cheatsheet->docs, gallery->slop, neon-mirai->neo-mirai, etc.) - package.json: dev->astro dev, build->build:skills+build:site, preview->astro preview - scripts/build.js: removed buildStaticSite(), generateSubPages(), static-asset copying. API data writes to public/_data/ instead of build/_data/. Site-header validator is a no-op (shared component). Em-dash validator scans site/components + site/layouts, not pages (pages contain content from other sources like detector descriptions). - .gitignore: removed public/slop/ entry Tests: 186/186 pass. Skills build: clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(site): fix redirect config for Astro compatibility Move the dynamic /skills/:id -> /docs/:id redirect to public/_redirects (Cloudflare Pages native format) since Astro's redirect config can't handle dynamic routes that don't match existing page patterns. Remove duplicate trailing-slash redirect entries that caused warnings. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(site): switch remaining pages from /css/ link tags to frontmatter imports Doc.astro, docs/index, tutorials/index, and tutorials/[slug] were still using <link href="/css/sub-pages.css"> which pointed at the deleted public/css/ directory. Switched to frontmatter CSS imports (import '../../styles/sub-pages.css') which Vite resolves from site/styles/. Homepage also switches from link tags to frontmatter imports for main.css and sub-pages.css — the esbuild error that originally forced the link-tag workaround was caused by unescaped curly braces in the HTML content (since fixed), not by the CSS itself. All pages verified visually in Chrome: homepage hero, foundation grid, docs index (card grid with categories), docs detail (sidebar + editorial content + visual mockups), designing (core loop diagram), privacy, tutorials. Header renders with 23k stars on every page. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(site): fix edge-to-edge sections, broken API paths, CSS links Three fixes: 1. Homepage sections sat on the viewport edge because Base.astro's <main> lacked the site-content class (provides max-width + padding). Added mainClass prop to Base.astro; homepage sets mainClass="site-content". 2. "Failed to load commands" because app.js fetched /api/commands which only existed in the old Bun server's routing. Updated to fetch from /_data/api/commands.json (the static JSON files that build:skills writes to public/_data/). 3. CSS reference fix (previous commit was incomplete): Doc.astro, docs/index, tutorials pages all used <link href="/css/sub-pages.css"> pointing at deleted public/css/. Switched to frontmatter imports. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(site): add sidebar to docs index page The docs index was using Base.astro directly without the skills-layout grid, so it rendered without a sidebar. Added the same sidebar structure from Doc.astro (category-grouped command list) and wrapped the content in the skills-layout grid. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(site): extract footer CSS to shared file, import in Base.astro Footer was unstyled on sub-pages because footer CSS lived only in main.css (loaded by the homepage) not in sub-pages.css. Extracted the 95 lines of footer rules into site/styles/footer.css and imported it in Base.astro so every page gets footer styles regardless of which page-specific CSS it loads. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(demos): move landing-demo into repo, add as slop specimens Moves ~/code/landing-demo/ into demos/landing-demo/ (without node_modules or the redundant .claude/.agents skill copies — the repo root's skill is found by walking up). PRODUCT.md, DESIGN.md, DESIGN.json, PROMPT.md, and SCRIPT.md stay in place so running Claude from demos/landing-demo/ picks up the project context. Also copies both pages as slop specimens to public/antipattern-examples/ with the detector script baked in: - new-slop-2026.html (Fraunces + warm cream editorial monoculture) - old-slop-2022.html (purple gradient + glassmorphism + neon glow) These can be linked from the slop page gallery alongside the existing 11 synthetic specimens. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(slop): replace single demo iframe with Then vs Now comparison The "See it" section (01) on the slop page now shows two side-by-side browser frames: 2022 slop (purple gradients, glassmorphism, neon glow) and 2026 slop (Fraunces, warm cream, editorial restraint). Both run the detector overlay live — hover either to see which rules fire. Replaces the single visual-mode-demo.html iframe. Responsive: stacks vertically on viewports below 900px. Caption: "Same engine, different decade, both flagged." Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(slop): switch to single-frame era toggle, center the section Replaces the side-by-side dual-iframe layout with a single large frame and a segmented 2022/2026 toggle. Clicking the toggle swaps which iframe is visible (both pre-loaded, instant switch). Browser chrome title updates to match the active era. Centers the lede text and toggle above the frame for visual cohesion with the full-width iframe below. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(slop): left-align See It section, toggle inline with lede Moves the era toggle to the right of the lede paragraph using a flex row (align-items: flex-end). Left-aligned text + right-docked toggle matches the rest of the page's flow instead of standing out as a centered island. Stacks vertically on narrow viewports. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(slop): left-align iframe, remove max-width and auto margin The visual-mode-preview had max-width: 1040px + margin: 0 auto which centered it within the column. Override both in the .slop-then-now context so the frame fills the full content width flush with the text above. Caption left-aligned to match. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(site): update star count to 24k (24,062) One file, one edit. The Astro migration working as intended. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(build): regenerate pnpm-lock.yaml for astro + shaders deps Cloudflare Pages uses pnpm with frozen-lockfile. The lockfile was stale after adding astro, @astrojs/cloudflare, and @paper-design/shaders via npm. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(build): resolve 3 bugbot review issues 1. Restore public/slop/ to .gitignore — prevents accidental legacy generator output from conflicting with the Astro page. 2. Move astro and @paper-design/shaders to devDependencies — these are site-build tools, not CLI runtime deps. Removes @astrojs/cloudflare entirely (unused; static output mode needs no adapter). 3. Fix Astro wiping build:skills output — CF config (_headers, _redirects, _routes.json) and API data now write to public/ so Astro copies them through. Dist ZIPs copy to build/_data/dist/ as a post-build step (after Astro finishes). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(build): merge duplicate devDependencies, use npx for astro CLI The previous commit created a second devDependencies key in package.json. JSON doesn't support duplicate keys — pnpm ignored the first block (with astro), so `astro build` wasn't found. Merged astro and @paper-design/shaders into the existing devDependencies block. Changed `astro build/dev/preview` to `npx astro build/dev/preview` so pnpm finds the local binary on Cloudflare Pages (which doesn't add node_modules/.bin to PATH by default). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(demos): remove private demo script and prompt from public repo SCRIPT.md contained a detailed conference talk script with personal delivery strategies, rehearsed Q&A answers, and venue details. PROMPT.md contained the origin brief for the demo page. Neither belongs in a public repo. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(build): gitignore generated public/ artifacts, consolidate redirects 1. Generated files written to public/ by build:skills (API data, CF config, browser detector, counts.js) are now gitignored. Prevents noisy diffs and merge conflicts from committed build artifacts. 2. Removed duplicate redirects from astro.config.mjs. All redirects now live in one place: the _redirects file generated by scripts/build.js (which Cloudflare Pages processes natively). Eliminates the dual-maintenance risk where the two sources could drift apart. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
415 lines
14 KiB
JavaScript
415 lines
14 KiB
JavaScript
import {
|
|
initGlassTerminal,
|
|
renderTerminalLayout,
|
|
} from "./components/glass-terminal.js";
|
|
import { initLensEffect } from "./components/lens.js";
|
|
import { initFrameworkViz } from "./components/framework-viz.js";
|
|
import { initScrollReveal } from "./utils/reveal.js";
|
|
import { initAnchorScroll, initHashTracking } from "./utils/scroll.js";
|
|
import { initSectionNav } from "./components/section-nav.js";
|
|
import { initFoundationGrid } from "./components/foundation-grid.js";
|
|
import { initLiveDemo } from "./components/live-demo.js";
|
|
|
|
// ============================================
|
|
// STATE
|
|
// ============================================
|
|
|
|
let allCommands = [];
|
|
|
|
// ============================================
|
|
// CONTENT LOADING
|
|
// ============================================
|
|
|
|
function escapeHtml(value) {
|
|
if (typeof value !== "string") return "";
|
|
return value
|
|
.replaceAll("&", "&")
|
|
.replaceAll("<", "<")
|
|
.replaceAll(">", ">")
|
|
.replaceAll('"', """)
|
|
.replaceAll("'", "'");
|
|
}
|
|
|
|
async function loadContent() {
|
|
try {
|
|
const [commandsRes, patternsRes] = await Promise.all([
|
|
fetch("/_data/api/commands.json"),
|
|
fetch("/_data/api/patterns.json"),
|
|
]);
|
|
|
|
// Check for HTTP errors
|
|
if (!commandsRes.ok) {
|
|
throw new Error(`Commands API failed: ${commandsRes.status}`);
|
|
}
|
|
if (!patternsRes.ok) {
|
|
throw new Error(`Patterns API failed: ${patternsRes.status}`);
|
|
}
|
|
|
|
allCommands = await commandsRes.json();
|
|
const patternsData = await patternsRes.json();
|
|
|
|
// Render commands (Glass Terminal)
|
|
renderTerminalLayout(allCommands);
|
|
|
|
// Initialize gallery card stack
|
|
initGalleryStack();
|
|
|
|
// Render patterns with tabbed navigation
|
|
renderPatternsWithTabs(patternsData.patterns, patternsData.antipatterns);
|
|
} catch (error) {
|
|
console.error("Failed to load content:", error);
|
|
showLoadError(error);
|
|
}
|
|
}
|
|
|
|
function showLoadError(error) {
|
|
// Show error in commands section
|
|
const commandsGallery = document.querySelector('.commands-gallery');
|
|
if (commandsGallery) {
|
|
commandsGallery.innerHTML = `
|
|
<div class="load-error" role="alert">
|
|
<div class="load-error-icon" aria-hidden="true">⚠</div>
|
|
<h3 class="load-error-title">Failed to load commands</h3>
|
|
<p class="load-error-text">There was a problem loading the content. Please check your connection and try again.</p>
|
|
<button class="btn btn-secondary load-error-retry" onclick="location.reload()">
|
|
Retry
|
|
</button>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
// Show error in patterns section
|
|
const patternsContainer = document.getElementById("patterns-categories");
|
|
if (patternsContainer) {
|
|
patternsContainer.innerHTML = `
|
|
<div class="load-error" role="alert">
|
|
<div class="load-error-icon" aria-hidden="true">⚠</div>
|
|
<h3 class="load-error-title">Failed to load patterns</h3>
|
|
<p class="load-error-text">There was a problem loading the content. Please check your connection and try again.</p>
|
|
<button class="btn btn-secondary load-error-retry" onclick="location.reload()">
|
|
Retry
|
|
</button>
|
|
</div>
|
|
`;
|
|
}
|
|
}
|
|
|
|
function initGalleryStack() {
|
|
const container = document.querySelector('.gallery-stack-container');
|
|
const stack = document.getElementById('gallery-stack');
|
|
if (!stack || !container) return;
|
|
|
|
const cards = stack.querySelectorAll('.gallery-stack-card');
|
|
const counter = container.querySelector('.gallery-stack-counter');
|
|
const total = cards.length;
|
|
let current = 0;
|
|
let lastScroll = 0;
|
|
|
|
function update() {
|
|
cards.forEach((card, i) => {
|
|
const offset = (i - current + total) % total;
|
|
card.dataset.offset = offset;
|
|
});
|
|
}
|
|
|
|
function next() { current = (current + 1) % total; update(); }
|
|
function prev() { current = (current - 1 + total) % total; update(); }
|
|
|
|
container.querySelector('.gallery-stack-prev').addEventListener('click', prev);
|
|
container.querySelector('.gallery-stack-next').addEventListener('click', next);
|
|
|
|
stack.addEventListener('wheel', (e) => {
|
|
e.preventDefault();
|
|
const now = Date.now();
|
|
if (now - lastScroll < 350) return;
|
|
lastScroll = now;
|
|
if (e.deltaY > 0) next(); else prev();
|
|
}, { passive: false });
|
|
|
|
update();
|
|
}
|
|
|
|
function renderPatternsWithTabs(patterns, antipatterns) {
|
|
const container = document.getElementById("patterns-categories");
|
|
if (!container || !patterns || !antipatterns) return;
|
|
|
|
const antipatternMap = {};
|
|
antipatterns.forEach(cat => { antipatternMap[cat.name] = cat.items; });
|
|
|
|
const tabsHTML = patterns.map((cat, i) =>
|
|
`<button class="patterns-tab${i === 0 ? ' is-active' : ''}" data-index="${i}">${escapeHtml(cat.name)}</button>`
|
|
).join('');
|
|
|
|
const panelsHTML = patterns.map((cat, i) => {
|
|
const antiItems = antipatternMap[cat.name] || [];
|
|
return `
|
|
<div class="patterns-content${i === 0 ? ' is-active' : ''}" data-index="${i}">
|
|
<div class="patterns-col patterns-col--dont">
|
|
<ul>${antiItems.map(item => `<li>${escapeHtml(item)}</li>`).join('')}</ul>
|
|
</div>
|
|
<div class="patterns-col patterns-col--do">
|
|
<ul>${cat.items.map(item => `<li>${escapeHtml(item)}</li>`).join('')}</ul>
|
|
</div>
|
|
</div>`;
|
|
}).join('');
|
|
|
|
container.innerHTML = `<div class="patterns-tabs-wrap"><div class="patterns-tabs" data-scroll="start">${tabsHTML}</div></div>${panelsHTML}`;
|
|
|
|
const tabsEl = container.querySelector('.patterns-tabs');
|
|
const tabsWrap = container.querySelector('.patterns-tabs-wrap');
|
|
|
|
container.addEventListener('click', (e) => {
|
|
const tab = e.target.closest('.patterns-tab');
|
|
if (!tab) return;
|
|
const index = tab.dataset.index;
|
|
container.querySelectorAll('.patterns-tab').forEach(t => t.classList.remove('is-active'));
|
|
container.querySelectorAll('.patterns-content').forEach(p => p.classList.remove('is-active'));
|
|
tab.classList.add('is-active');
|
|
container.querySelector(`.patterns-content[data-index="${index}"]`).classList.add('is-active');
|
|
// Center the clicked tab inside the tabs strip (not the page). Using
|
|
// scrollBy on the container keeps the page scroll untouched.
|
|
if (tabsEl) {
|
|
const tabRect = tab.getBoundingClientRect();
|
|
const stripRect = tabsEl.getBoundingClientRect();
|
|
const offset = (tabRect.left + tabRect.width / 2) - (stripRect.left + stripRect.width / 2);
|
|
tabsEl.scrollBy({ left: offset, behavior: 'smooth' });
|
|
}
|
|
});
|
|
|
|
// Track scroll position so the edge-fade mask only appears on sides where
|
|
// there's actually more content. At the start, no left fade; at the end,
|
|
// no right fade; if no overflow, no fade at all.
|
|
const updateScrollState = () => {
|
|
if (!tabsEl) return;
|
|
const { scrollLeft, scrollWidth, clientWidth } = tabsEl;
|
|
const max = scrollWidth - clientWidth;
|
|
let state;
|
|
if (max <= 1) state = 'none';
|
|
else if (scrollLeft <= 1) state = 'start';
|
|
else if (scrollLeft >= max - 1) state = 'end';
|
|
else state = 'middle';
|
|
tabsEl.dataset.scroll = state;
|
|
if (tabsWrap) tabsWrap.dataset.scroll = state;
|
|
};
|
|
tabsEl?.addEventListener('scroll', updateScrollState, { passive: true });
|
|
window.addEventListener('resize', updateScrollState);
|
|
updateScrollState();
|
|
}
|
|
|
|
// ============================================
|
|
// EVENT HANDLERS
|
|
// ============================================
|
|
|
|
// Handle bundle download clicks via event delegation.
|
|
// Each download button carries the full bundle name in data-bundle
|
|
// (currently just "universal") so the handler is just a redirect.
|
|
document.addEventListener("click", (e) => {
|
|
const bundleBtn = e.target.closest("[data-bundle]");
|
|
if (bundleBtn) {
|
|
const bundleName = bundleBtn.dataset.bundle;
|
|
window.location.href = `/api/download/bundle/${bundleName}`;
|
|
}
|
|
|
|
// Handle copy button clicks
|
|
const copyBtn = e.target.closest("[data-copy]");
|
|
if (copyBtn) {
|
|
const textToCopy = copyBtn.dataset.copy;
|
|
const onCopied = () => {
|
|
copyBtn.classList.add('copied');
|
|
setTimeout(() => copyBtn.classList.remove('copied'), 1500);
|
|
};
|
|
if (navigator.clipboard?.writeText) {
|
|
navigator.clipboard.writeText(textToCopy).then(onCopied).catch(() => {});
|
|
} else {
|
|
// Fallback for non-HTTPS or older browsers
|
|
const ta = Object.assign(document.createElement('textarea'), { value: textToCopy, style: 'position:fixed;left:-9999px' });
|
|
document.body.appendChild(ta);
|
|
ta.select();
|
|
try { document.execCommand('copy'); onCopied(); } catch {}
|
|
ta.remove();
|
|
}
|
|
}
|
|
});
|
|
|
|
|
|
// ============================================
|
|
// STARTUP
|
|
// ============================================
|
|
|
|
function init() {
|
|
initAnchorScroll();
|
|
initHashTracking();
|
|
initLensEffect();
|
|
initScrollReveal();
|
|
initGlassTerminal();
|
|
initFrameworkViz();
|
|
initFoundationGrid();
|
|
initSectionNav();
|
|
initWhyTabs();
|
|
initLanguageTabs();
|
|
initLiveDemo();
|
|
loadContent();
|
|
|
|
document.body.classList.add("loaded");
|
|
}
|
|
|
|
function initLanguageTabs() {
|
|
const toggle = document.querySelector('.language-view-toggle');
|
|
if (!toggle) return;
|
|
const tabs = Array.from(toggle.querySelectorAll('.language-view-tab'));
|
|
const panels = Array.from(document.querySelectorAll('.language-view[data-view-panel]'));
|
|
if (!tabs.length || !panels.length) return;
|
|
|
|
tabs.forEach((tab) => {
|
|
tab.addEventListener('click', () => {
|
|
const view = tab.dataset.view;
|
|
tabs.forEach((t) => {
|
|
const on = t === tab;
|
|
t.classList.toggle('is-active', on);
|
|
t.setAttribute('aria-selected', on ? 'true' : 'false');
|
|
});
|
|
panels.forEach((p) => {
|
|
const on = p.dataset.viewPanel === view;
|
|
p.classList.toggle('is-active', on);
|
|
if (on) p.removeAttribute('hidden');
|
|
else p.setAttribute('hidden', '');
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
function initWhyTabs() {
|
|
const container = document.querySelector('.why-layout');
|
|
if (!container) return;
|
|
const tabs = Array.from(container.querySelectorAll('.why-tab'));
|
|
const panels = Array.from(container.querySelectorAll('.why-panel'));
|
|
if (!tabs.length || !panels.length) return;
|
|
|
|
const CYCLE_MS = 7000;
|
|
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
let current = Math.max(tabs.findIndex((tab) => tab.classList.contains('is-active')), 0);
|
|
let timer = null;
|
|
let autoRotate = !reducedMotion;
|
|
let visible = false;
|
|
|
|
const tabStrip = container.querySelector('.why-tabs');
|
|
const getPanelForTab = (tab) => {
|
|
const panelId = tab?.getAttribute('aria-controls');
|
|
return panelId ? container.querySelector(`#${CSS.escape(panelId)}`) : null;
|
|
};
|
|
|
|
const centerActiveInStrip = (active) => {
|
|
// On mobile the tab list is a horizontal scroll strip. Keep the
|
|
// active pill visible without touching the page scroll. Using
|
|
// scrollTo with behavior:auto + direct scrollLeft assignment,
|
|
// because smooth-scroll on this container is disabled by the
|
|
// parent's mask-image compositing and silently no-ops.
|
|
if (!tabStrip || tabStrip.scrollWidth <= tabStrip.clientWidth + 1) return;
|
|
const tabRect = active.getBoundingClientRect();
|
|
const stripRect = tabStrip.getBoundingClientRect();
|
|
const offset = (tabRect.left + tabRect.width / 2) - (stripRect.left + stripRect.width / 2);
|
|
if (Math.abs(offset) < 2) return;
|
|
tabStrip.scrollLeft += offset;
|
|
};
|
|
|
|
const activate = (index, fromAuto = false) => {
|
|
const targetTab = tabs[index];
|
|
const targetPanel = getPanelForTab(targetTab);
|
|
if (!targetTab || !targetPanel) return;
|
|
current = index;
|
|
tabs.forEach((tab, i) => {
|
|
const on = i === index;
|
|
tab.classList.toggle('is-active', on);
|
|
tab.setAttribute('aria-selected', on ? 'true' : 'false');
|
|
// Reset cycling class, re-add on the new active tab so the
|
|
// progress indicator restarts cleanly.
|
|
tab.classList.remove('is-cycling');
|
|
});
|
|
panels.forEach((panel) => {
|
|
const on = panel === targetPanel;
|
|
panel.classList.toggle('is-active', on);
|
|
if (on) panel.removeAttribute('hidden');
|
|
else panel.setAttribute('hidden', '');
|
|
});
|
|
if (autoRotate && visible) {
|
|
// Force reflow so the animation restart is picked up.
|
|
void targetTab.offsetWidth;
|
|
targetTab.classList.add('is-cycling');
|
|
}
|
|
centerActiveInStrip(targetTab);
|
|
};
|
|
|
|
const scheduleNext = () => {
|
|
clearTimeout(timer);
|
|
if (!autoRotate || !visible) return;
|
|
timer = setTimeout(() => {
|
|
const next = (current + 1) % tabs.length;
|
|
activate(next, true);
|
|
scheduleNext();
|
|
}, CYCLE_MS);
|
|
};
|
|
|
|
const stopAuto = () => {
|
|
autoRotate = false;
|
|
clearTimeout(timer);
|
|
tabs.forEach((t) => t.classList.remove('is-cycling'));
|
|
};
|
|
|
|
tabs.forEach((tab, index) => {
|
|
tab.addEventListener('click', () => {
|
|
stopAuto();
|
|
activate(index);
|
|
});
|
|
tab.addEventListener('keydown', (e) => {
|
|
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
|
|
e.preventDefault();
|
|
stopAuto();
|
|
const dir = e.key === 'ArrowDown' ? 1 : -1;
|
|
const next = (index + dir + tabs.length) % tabs.length;
|
|
tabs[next].focus();
|
|
activate(next);
|
|
});
|
|
});
|
|
|
|
container.addEventListener('mouseenter', () => {
|
|
// Pause auto-rotation on hover. Resume only if still allowed and
|
|
// user hasn't interacted (stopAuto flips autoRotate off).
|
|
clearTimeout(timer);
|
|
tabs.forEach((t) => t.classList.remove('is-cycling'));
|
|
});
|
|
container.addEventListener('mouseleave', () => {
|
|
if (autoRotate && visible) {
|
|
// Re-apply cycling class to current tab and resume the timer.
|
|
const active = tabs[current];
|
|
void active.offsetWidth;
|
|
active.classList.add('is-cycling');
|
|
scheduleNext();
|
|
}
|
|
});
|
|
|
|
// Observe visibility so we only rotate while the user can see it.
|
|
const io = new IntersectionObserver((entries) => {
|
|
entries.forEach((e) => {
|
|
visible = e.isIntersecting;
|
|
if (visible) {
|
|
if (autoRotate) {
|
|
const active = tabs[current];
|
|
void active.offsetWidth;
|
|
active.classList.add('is-cycling');
|
|
scheduleNext();
|
|
}
|
|
} else {
|
|
clearTimeout(timer);
|
|
tabs.forEach((t) => t.classList.remove('is-cycling'));
|
|
}
|
|
});
|
|
}, { threshold: 0.35 });
|
|
io.observe(container);
|
|
}
|
|
|
|
if (document.readyState === "loading") {
|
|
document.addEventListener("DOMContentLoaded", init);
|
|
} else {
|
|
init();
|
|
}
|