mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-18 09:06:53 +03:00
Migrate site from Bun to Astro (#130)
* 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>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
a312da5ec7
commit
b8f09c8142
@@ -0,0 +1,142 @@
|
||||
import { readySkills, skillFocusAreas } from "../data.js";
|
||||
import { renderSkillDemo, setupDemoTabs } from "../demo-renderer.js";
|
||||
import { setupDemoToggles } from "../demo-toggles.js";
|
||||
|
||||
export function initArtGallery() {
|
||||
// Initial setup if needed
|
||||
}
|
||||
|
||||
export function renderGallery(skills) {
|
||||
const container = document.querySelector(".skills-gallery");
|
||||
if (!container) return;
|
||||
|
||||
// Filter skills (hide impeccable as per original)
|
||||
const filteredSkills = skills.filter((s) => s.id !== "impeccable");
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="gallery-track">
|
||||
${filteredSkills.map((skill, index) => renderFrame(skill, index)).join("")}
|
||||
</div>
|
||||
<div class="gallery-map" role="tablist" aria-label="Skill gallery navigation">
|
||||
${filteredSkills.map((skill, index) => `<button class="gallery-dot ${index === 0 ? "active" : ""}" data-index="${index}" role="tab" aria-selected="${index === 0 ? "true" : "false"}" aria-label="View ${formatName(skill.id)} skill"></button>`).join("")}
|
||||
</div>
|
||||
`;
|
||||
|
||||
setupInteractions();
|
||||
setupDemoTabs();
|
||||
setupDemoToggles();
|
||||
}
|
||||
|
||||
function renderFrame(skill, index) {
|
||||
const isReady = readySkills.includes(skill.id);
|
||||
const focusAreas = skillFocusAreas[skill.id] || [];
|
||||
const displayName = formatName(skill.id);
|
||||
|
||||
return `
|
||||
<article class="gallery-frame ${index === 0 ? "active" : ""}" data-index="${index}" id="skill-${skill.id}">
|
||||
<div class="gallery-content">
|
||||
<div class="gallery-visual">
|
||||
${isReady ? renderSkillDemo(skill.id) : renderComingSoonVisual(skill.id)}
|
||||
</div>
|
||||
<div class="gallery-info">
|
||||
<div class="gallery-header">
|
||||
<h3 class="gallery-title">${displayName}</h3>
|
||||
<div class="gallery-meta">
|
||||
Skill · ${isReady ? "Available" : "Coming Soon"}
|
||||
</div>
|
||||
</div>
|
||||
<p class="gallery-desc">${skill.description}</p>
|
||||
|
||||
${
|
||||
focusAreas.length > 0
|
||||
? `
|
||||
<div class="gallery-tags">
|
||||
${focusAreas
|
||||
.slice(0, 4)
|
||||
.map(
|
||||
(area) => `
|
||||
<span class="gallery-tag">${area.area}</span>
|
||||
`,
|
||||
)
|
||||
.join("")}
|
||||
</div>
|
||||
`
|
||||
: ""
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderComingSoonVisual(id) {
|
||||
return `
|
||||
<div class="coming-soon-placeholder" style="text-align: center;">
|
||||
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" style="opacity: 0.3">
|
||||
<path d="M12 6v6l4 2M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"/>
|
||||
</svg>
|
||||
<p style="margin-top: 1rem; color: var(--color-ash); font-size: 0.875rem;">Coming Soon</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function formatName(id) {
|
||||
return id
|
||||
.split("-")
|
||||
.map((word) =>
|
||||
word === "ux" ? "UX" : word.charAt(0).toUpperCase() + word.slice(1),
|
||||
)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function setupInteractions() {
|
||||
const track = document.querySelector(".gallery-track");
|
||||
const frames = document.querySelectorAll(".gallery-frame");
|
||||
const dots = document.querySelectorAll(".gallery-dot");
|
||||
|
||||
if (!track) return;
|
||||
|
||||
// Intersection Observer for Active State
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
const index = entry.target.dataset.index;
|
||||
|
||||
// Update frames
|
||||
frames.forEach((f) => f.classList.remove("active"));
|
||||
entry.target.classList.add("active");
|
||||
|
||||
// Update dots
|
||||
dots.forEach((d) => {
|
||||
d.classList.remove("active");
|
||||
d.setAttribute("aria-selected", "false");
|
||||
});
|
||||
if (dots[index]) {
|
||||
dots[index].classList.add("active");
|
||||
dots[index].setAttribute("aria-selected", "true");
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
root: track,
|
||||
threshold: 0.6,
|
||||
},
|
||||
);
|
||||
|
||||
frames.forEach((frame) => observer.observe(frame));
|
||||
|
||||
// Dot navigation
|
||||
dots.forEach((dot, index) => {
|
||||
dot.addEventListener("click", () => {
|
||||
const frame = frames[index];
|
||||
if (frame) {
|
||||
frame.scrollIntoView({ behavior: "smooth", inline: "center" });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
export const foundationAnimations = {
|
||||
'Typography': `
|
||||
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" class="foundation-svg">
|
||||
<path d="M10 30L20 10L30 30" stroke="var(--color-mist)" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M10 30L20 10L30 30" stroke="var(--color-accent)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="anim-draw"/>
|
||||
<path d="M15 22H25" stroke="var(--color-accent)" stroke-width="1.5" stroke-linecap="round" class="anim-draw-delay"/>
|
||||
</svg>
|
||||
`,
|
||||
'Color & Contrast': `
|
||||
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" class="foundation-svg">
|
||||
<circle cx="16" cy="20" r="8" stroke="var(--color-ink)" stroke-width="1.5" class="anim-move-x"/>
|
||||
<circle cx="24" cy="20" r="8" stroke="var(--color-accent)" stroke-width="1.5" class="anim-move-x-opp"/>
|
||||
<path d="M20 14.5C21.5 16 22.5 18 22.5 20C22.5 22 21.5 24 20 25.5C18.5 24 17.5 22 17.5 20C17.5 18 18.5 16 20 14.5Z" fill="var(--color-accent)" class="anim-fade-in"/>
|
||||
</svg>
|
||||
`,
|
||||
'Spatial Design': `
|
||||
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" class="foundation-svg">
|
||||
<rect x="5" y="10" width="30" height="18.5" stroke="var(--color-mist)" stroke-width="1"/>
|
||||
<line x1="23.5" y1="10" x2="23.5" y2="28.5" stroke="var(--color-mist)" stroke-width="1"/>
|
||||
<line x1="23.5" y1="21.5" x2="35" y2="21.5" stroke="var(--color-mist)" stroke-width="1"/>
|
||||
<path d="M5 28.5C5 18.28 13.28 10 23.5 10C29.85 10 35 15.15 35 21.5C35 25.42 31.82 28.5 27.9 28.5" fill="none" stroke="var(--color-accent)" stroke-width="1.5" stroke-linecap="round" class="anim-draw"/>
|
||||
</svg>
|
||||
`,
|
||||
'Responsive': `
|
||||
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" class="foundation-svg">
|
||||
<rect x="6" y="8" width="28" height="24" rx="2" stroke="var(--color-ink)" stroke-width="1.5" class="anim-res-frame"/>
|
||||
<rect x="9" y="12" width="10" height="8" rx="1" fill="var(--color-accent)" class="anim-res-img"/>
|
||||
<rect x="22" y="12" width="10" height="2" rx="0.5" fill="var(--color-ink)" class="anim-res-title"/>
|
||||
<rect x="22" y="16.5" width="10" height="1.5" rx="0.5" fill="var(--color-ash)" class="anim-res-line-1"/>
|
||||
<rect x="22" y="20" width="8" height="1.5" rx="0.5" fill="var(--color-ash)" class="anim-res-line-2"/>
|
||||
</svg>
|
||||
`,
|
||||
'Interaction': `
|
||||
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" class="foundation-svg">
|
||||
<rect x="10" y="14" width="20" height="12" rx="6" stroke="var(--color-ink)" stroke-width="1.5"/>
|
||||
<circle cx="16" cy="20" r="4" fill="var(--color-mist)" class="anim-toggle-move"/>
|
||||
</svg>
|
||||
`,
|
||||
'Motion': `
|
||||
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" class="foundation-svg">
|
||||
<line x1="5" y1="32" x2="35" y2="32" stroke="var(--color-ink)" stroke-width="1.5"/>
|
||||
<circle cx="20" cy="15" r="5" fill="var(--color-accent)" class="anim-squash-ball"/>
|
||||
</svg>
|
||||
`,
|
||||
'UX Writing': `
|
||||
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" class="foundation-svg">
|
||||
<rect x="8" y="12" width="18" height="2" rx="1" fill="var(--color-ink)"/>
|
||||
<rect x="8" y="18" width="22" height="2" rx="1" fill="var(--color-ash)"/>
|
||||
<rect x="8" y="24" width="14" height="2" rx="1" fill="var(--color-accent)"/>
|
||||
<line x1="24" y1="23" x2="24" y2="27" stroke="var(--color-accent)" stroke-width="1.5" class="anim-blink"/>
|
||||
</svg>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { skillFocusAreas, dimensionGuidelineCounts } from '../data.js';
|
||||
import { foundationAnimations } from './foundation-animations.js';
|
||||
|
||||
export function initFoundationGrid() {
|
||||
const container = document.querySelector('.foundation-grid');
|
||||
if (!container) return;
|
||||
|
||||
const dimensions = skillFocusAreas['impeccable'];
|
||||
if (!dimensions) return;
|
||||
|
||||
container.innerHTML = dimensions.map((dim, i) => `
|
||||
<div class="foundation-column">
|
||||
<div class="foundation-card">
|
||||
<div class="foundation-card-viz">
|
||||
${foundationAnimations[dim.area] || ''}
|
||||
</div>
|
||||
<div class="foundation-card-header">
|
||||
<span class="foundation-card-label">${dim.area}</span>
|
||||
<span class="foundation-card-count">${dimensionGuidelineCounts[dim.area] || ''}</span>
|
||||
</div>
|
||||
<p class="foundation-card-detail">${dim.detail}</p>
|
||||
</div>
|
||||
<div class="foundation-plinth plinth-${i + 1}"></div>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
/**
|
||||
* Periodic Table of Commands
|
||||
* Clean grid visualization showing all commands organized by category
|
||||
* Hover tooltips show description and relationships inline.
|
||||
*/
|
||||
|
||||
import { commandCategories, commandRelationships, alphaCommands } from '../data.js';
|
||||
|
||||
const categoryColors = {
|
||||
create: { bg: 'var(--cat-create-bg)', border: 'var(--cat-create-border)', text: 'var(--cat-create-text)' },
|
||||
evaluate: { bg: 'var(--cat-evaluate-bg)', border: 'var(--cat-evaluate-border)', text: 'var(--cat-evaluate-text)' },
|
||||
refine: { bg: 'var(--cat-refine-bg)', border: 'var(--cat-refine-border)', text: 'var(--cat-refine-text)' },
|
||||
simplify: { bg: 'var(--cat-simplify-bg)', border: 'var(--cat-simplify-border)', text: 'var(--cat-simplify-text)' },
|
||||
harden: { bg: 'var(--cat-harden-bg)', border: 'var(--cat-harden-border)', text: 'var(--cat-harden-text)' },
|
||||
system: { bg: 'var(--cat-system-bg)', border: 'var(--cat-system-border)', text: 'var(--cat-system-text)' }
|
||||
};
|
||||
|
||||
const categoryLabels = {
|
||||
create: 'Create',
|
||||
evaluate: 'Evaluate',
|
||||
refine: 'Refine',
|
||||
simplify: 'Simplify',
|
||||
harden: 'Harden',
|
||||
system: 'System'
|
||||
};
|
||||
|
||||
const commandSymbols = {
|
||||
'impeccable': 'Im',
|
||||
'craft': 'Cf',
|
||||
'shape': 'Sh',
|
||||
'critique': 'Cr',
|
||||
'audit': 'Au',
|
||||
'typeset': 'Ty',
|
||||
'layout': 'La',
|
||||
'colorize': 'Co',
|
||||
'animate': 'An',
|
||||
'delight': 'De',
|
||||
'bolder': 'Bo',
|
||||
'quieter': 'Qu',
|
||||
'overdrive': 'Od',
|
||||
'distill': 'Di',
|
||||
'clarify': 'Cl',
|
||||
'adapt': 'Ad',
|
||||
'polish': 'Po',
|
||||
'optimize': 'Op',
|
||||
'harden': 'Ha',
|
||||
'onboard': 'On',
|
||||
'teach': 'Te',
|
||||
'document': 'Dc',
|
||||
'extract': 'Ex',
|
||||
'live': 'Li'
|
||||
};
|
||||
|
||||
const commandNumbers = {
|
||||
'impeccable': 1, 'craft': 2, 'shape': 3,
|
||||
'critique': 4, 'audit': 5,
|
||||
'typeset': 6, 'layout': 7, 'colorize': 8, 'animate': 9,
|
||||
'delight': 10, 'bolder': 11, 'quieter': 12, 'overdrive': 13,
|
||||
'distill': 14, 'clarify': 15, 'adapt': 16,
|
||||
'polish': 17, 'optimize': 18, 'harden': 19, 'onboard': 20,
|
||||
'teach': 21, 'document': 22, 'extract': 23, 'live': 24
|
||||
};
|
||||
|
||||
// After the v3.0 consolidation, all commands except the root "impeccable" are
|
||||
// sub-commands of /impeccable. The renderer handles the display label directly
|
||||
// (bare name for sub-commands, "/impeccable" for the root). This map is kept
|
||||
// as an extension point for any future per-command display overrides.
|
||||
const commandDisplay = {};
|
||||
|
||||
export class PeriodicTable {
|
||||
constructor(container) {
|
||||
this.container = container;
|
||||
this.activeTooltip = null;
|
||||
this.activeElement = null;
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.container.innerHTML = '';
|
||||
this.container.style.cssText = `
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 20px;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
`;
|
||||
|
||||
this.renderTable();
|
||||
}
|
||||
|
||||
renderTable() {
|
||||
const groups = {};
|
||||
Object.entries(commandCategories).forEach(([cmd, cat]) => {
|
||||
if (!groups[cat]) groups[cat] = [];
|
||||
groups[cat].push(cmd);
|
||||
});
|
||||
|
||||
const categoryOrder = ['create', 'evaluate', 'refine', 'simplify', 'harden', 'system'];
|
||||
|
||||
const grid = document.createElement('div');
|
||||
grid.style.cssText = `
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 16px;
|
||||
flex: 1;
|
||||
`;
|
||||
|
||||
categoryOrder.forEach(cat => {
|
||||
const commands = groups[cat];
|
||||
if (!commands) return;
|
||||
const group = this.createCategoryGroup(cat, commands);
|
||||
grid.appendChild(group);
|
||||
});
|
||||
|
||||
this.container.appendChild(grid);
|
||||
}
|
||||
|
||||
showTooltip(el, cmd) {
|
||||
this.hideTooltip();
|
||||
|
||||
const rel = commandRelationships[cmd] || {};
|
||||
const toArray = (val) => {
|
||||
if (!val) return [];
|
||||
if (Array.isArray(val)) return val;
|
||||
return [val];
|
||||
};
|
||||
|
||||
const pairs = toArray(rel.pairs);
|
||||
const leadsTo = toArray(rel.leadsTo);
|
||||
const combinesWith = toArray(rel.combinesWith);
|
||||
|
||||
// Build relationships line. Command names are shown bare (no slash)
|
||||
// because they're names, not invocations — the invocation is /impeccable <name>.
|
||||
let relParts = [];
|
||||
if (pairs.length > 0) relParts.push(`pairs with ${pairs.join(', ')}`);
|
||||
if (combinesWith.length > 0) relParts.push(`+ ${combinesWith.join(', ')}`);
|
||||
if (leadsTo.length > 0) relParts.push(`then ${leadsTo.join(', ')}`);
|
||||
|
||||
// Strip category prefix from flow for cleaner display
|
||||
const flow = (rel.flow || '').replace(/^[^:]+:\s*/, '');
|
||||
|
||||
const tooltip = document.createElement('div');
|
||||
tooltip.className = 'ptable-tooltip';
|
||||
tooltip.style.cssText = `
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
background: var(--color-paper);
|
||||
border: 1px solid var(--color-mist);
|
||||
border-radius: 6px;
|
||||
padding: 10px 14px;
|
||||
box-shadow: 0 8px 24px -4px rgba(0,0,0,0.12);
|
||||
pointer-events: none;
|
||||
max-width: 280px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s ease;
|
||||
`;
|
||||
|
||||
tooltip.innerHTML = `
|
||||
<div style="font-family: var(--font-body); font-size: 13px; color: var(--color-charcoal); line-height: 1.4; margin-bottom: ${relParts.length ? '6px' : '0'};">${flow}</div>
|
||||
${relParts.length ? `<div style="font-family: var(--font-mono); font-size: 11px; color: var(--color-ash); line-height: 1.4;">${relParts.join(' · ')}</div>` : ''}
|
||||
`;
|
||||
|
||||
this.container.appendChild(tooltip);
|
||||
|
||||
// Position relative to element
|
||||
const elRect = el.getBoundingClientRect();
|
||||
const containerRect = this.container.getBoundingClientRect();
|
||||
|
||||
const left = elRect.left - containerRect.left;
|
||||
const top = elRect.bottom - containerRect.top + 6;
|
||||
|
||||
tooltip.style.left = `${Math.min(left, containerRect.width - 290)}px`;
|
||||
tooltip.style.top = `${top}px`;
|
||||
|
||||
// Fade in
|
||||
requestAnimationFrame(() => { tooltip.style.opacity = '1'; });
|
||||
|
||||
this.activeTooltip = tooltip;
|
||||
}
|
||||
|
||||
hideTooltip() {
|
||||
if (this.activeTooltip) {
|
||||
this.activeTooltip.remove();
|
||||
this.activeTooltip = null;
|
||||
}
|
||||
}
|
||||
|
||||
createCategoryGroup(category, commands) {
|
||||
const colors = categoryColors[category];
|
||||
|
||||
const group = document.createElement('div');
|
||||
group.style.cssText = `display: flex; flex-direction: column; gap: 6px;`;
|
||||
|
||||
const label = document.createElement('div');
|
||||
label.style.cssText = `
|
||||
font-family: var(--font-body);
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: ${colors.text};
|
||||
padding-left: 2px;
|
||||
`;
|
||||
label.textContent = categoryLabels[category];
|
||||
group.appendChild(label);
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.style.cssText = `display: flex; flex-wrap: wrap; gap: 6px;`;
|
||||
|
||||
commands.forEach(cmd => {
|
||||
const element = this.createElement(cmd, category);
|
||||
row.appendChild(element);
|
||||
});
|
||||
|
||||
group.appendChild(row);
|
||||
return group;
|
||||
}
|
||||
|
||||
createElement(cmd, category) {
|
||||
const colors = categoryColors[category];
|
||||
const display = commandDisplay[cmd];
|
||||
|
||||
const el = document.createElement('button');
|
||||
el.type = 'button';
|
||||
// Build accessible label with the full invocation
|
||||
const invocation = cmd === 'impeccable'
|
||||
? '/impeccable'
|
||||
: cmd.startsWith('impeccable ')
|
||||
? `/${cmd}`
|
||||
: `/impeccable ${cmd}`;
|
||||
el.setAttribute('aria-label', `${invocation} command - ${categoryLabels[category]}`);
|
||||
el.style.cssText = `
|
||||
width: 56px;
|
||||
height: 64px;
|
||||
background: ${colors.bg};
|
||||
border: 1.5px solid ${colors.border};
|
||||
border-radius: 5px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
position: relative;
|
||||
font-family: inherit;
|
||||
padding: 0;
|
||||
`;
|
||||
|
||||
// Atomic number
|
||||
const number = document.createElement('div');
|
||||
number.style.cssText = `
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
left: 5px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 7px;
|
||||
color: ${colors.text};
|
||||
opacity: 0.5;
|
||||
`;
|
||||
number.textContent = commandNumbers[cmd];
|
||||
el.appendChild(number);
|
||||
|
||||
// Symbol
|
||||
const symbol = document.createElement('div');
|
||||
symbol.style.cssText = `
|
||||
font-family: var(--font-display);
|
||||
font-size: 20px;
|
||||
font-weight: 500;
|
||||
color: ${colors.text};
|
||||
line-height: 1;
|
||||
`;
|
||||
symbol.textContent = commandSymbols[cmd];
|
||||
el.appendChild(symbol);
|
||||
|
||||
// Command name. The root "impeccable" is shown with its slash as the
|
||||
// entry point. All other commands are sub-commands and show their
|
||||
// bare name (the invocation is /impeccable <name>).
|
||||
const name = document.createElement('div');
|
||||
name.style.cssText = `
|
||||
font-family: var(--font-mono);
|
||||
font-size: 8px;
|
||||
color: ${colors.text};
|
||||
opacity: 0.7;
|
||||
margin-top: 3px;
|
||||
text-align: center;
|
||||
max-width: 52px;
|
||||
line-height: 1.3;
|
||||
white-space: nowrap;
|
||||
`;
|
||||
if (cmd === 'impeccable') {
|
||||
name.textContent = '/impeccable';
|
||||
} else if (display) {
|
||||
name.textContent = display.label;
|
||||
} else {
|
||||
name.textContent = cmd;
|
||||
}
|
||||
el.appendChild(name);
|
||||
|
||||
// Alpha badge
|
||||
if (alphaCommands.includes(cmd)) {
|
||||
const badge = document.createElement('div');
|
||||
badge.style.cssText = `
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 3px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 5px;
|
||||
letter-spacing: 0.05em;
|
||||
color: ${colors.text};
|
||||
opacity: 0.45;
|
||||
text-transform: uppercase;
|
||||
`;
|
||||
badge.textContent = 'α';
|
||||
el.appendChild(badge);
|
||||
}
|
||||
|
||||
// Hover/focus: show tooltip
|
||||
const activate = () => {
|
||||
el.style.transform = 'translateY(-2px)';
|
||||
el.style.boxShadow = `0 4px 12px ${colors.border}40`;
|
||||
this.showTooltip(el, cmd);
|
||||
|
||||
if (this.activeElement && this.activeElement !== el) {
|
||||
this.activeElement.style.transform = 'translateY(0)';
|
||||
this.activeElement.style.boxShadow = 'none';
|
||||
}
|
||||
this.activeElement = el;
|
||||
};
|
||||
|
||||
const deactivate = () => {
|
||||
el.style.transform = 'translateY(0)';
|
||||
el.style.boxShadow = 'none';
|
||||
this.hideTooltip();
|
||||
};
|
||||
|
||||
el.addEventListener('mouseenter', activate);
|
||||
el.addEventListener('mouseleave', deactivate);
|
||||
el.addEventListener('focus', activate);
|
||||
el.addEventListener('blur', deactivate);
|
||||
|
||||
el.addEventListener('touchstart', (e) => {
|
||||
e.preventDefault();
|
||||
activate();
|
||||
}, { passive: false });
|
||||
|
||||
el.addEventListener('click', () => {
|
||||
activate();
|
||||
const scrollTarget = display ? display.scrollTo : cmd;
|
||||
|
||||
// Navigate the fisheye scroller to this command
|
||||
const fisheyeList = document.getElementById('fisheye-list');
|
||||
if (fisheyeList) {
|
||||
const items = [...fisheyeList.querySelectorAll('.fisheye-item')];
|
||||
const idx = items.findIndex(item => item.dataset.id === scrollTarget);
|
||||
if (idx >= 0 && fisheyeList._scrollToCommand) {
|
||||
// Scroll the commands section into view first
|
||||
const section = document.querySelector('.commands-subsection');
|
||||
if (section) section.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
fisheyeList._scrollToCommand(idx);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: scroll to the spread element
|
||||
const target = document.getElementById(`cmd-${scrollTarget}`);
|
||||
if (target) {
|
||||
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
});
|
||||
|
||||
return el;
|
||||
}
|
||||
}
|
||||
|
||||
export function initFrameworkViz() {
|
||||
const container = document.getElementById('framework-viz-container');
|
||||
if (container) {
|
||||
new PeriodicTable(container);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,667 @@
|
||||
import { renderCommandDemo, initCommandDemo } from "../demo-renderer.js";
|
||||
import { initSplitCompare } from "../effects/split-compare.js";
|
||||
import { commandProcessSteps, commandCategories, commandRelationships, alphaCommands } from "../data.js";
|
||||
|
||||
// Track current split instance and command for cleanup
|
||||
let currentSplitInstance = null;
|
||||
let currentCommandId = null;
|
||||
let sourceCache = {}; // Cache fetched source content
|
||||
|
||||
const MOBILE_BREAKPOINT = 900;
|
||||
|
||||
function isMobile() {
|
||||
return window.innerWidth <= MOBILE_BREAKPOINT;
|
||||
}
|
||||
|
||||
export function initGlassTerminal() {
|
||||
// Initial setup if needed
|
||||
}
|
||||
|
||||
export function renderTerminalLayout(commands) {
|
||||
const container = document.querySelector('.commands-gallery');
|
||||
if (!container) return;
|
||||
|
||||
if (isMobile()) {
|
||||
renderMobileLayout(container, commands);
|
||||
} else {
|
||||
renderDesktopLayout(container, commands);
|
||||
}
|
||||
|
||||
// Re-render on resize crossing breakpoint
|
||||
let wasMobile = isMobile();
|
||||
window.addEventListener('resize', () => {
|
||||
const nowMobile = isMobile();
|
||||
if (nowMobile !== wasMobile) {
|
||||
wasMobile = nowMobile;
|
||||
currentSplitInstance = null;
|
||||
currentCommandId = null;
|
||||
if (nowMobile) {
|
||||
renderMobileLayout(container, commands);
|
||||
} else {
|
||||
renderDesktopLayout(container, commands);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// DESKTOP LAYOUT - Magazine Spread
|
||||
// ============================================
|
||||
|
||||
let magazineState = {
|
||||
currentIndex: 0,
|
||||
commands: [],
|
||||
isTransitioning: false,
|
||||
keyboardBound: false,
|
||||
intersectionObserver: null
|
||||
};
|
||||
|
||||
const categoryOrder = ['diagnostic', 'quality', 'intensity', 'adaptation', 'enhancement', 'system'];
|
||||
const categoryLabels = {
|
||||
'create': 'Create',
|
||||
'evaluate': 'Evaluate',
|
||||
'refine': 'Refine',
|
||||
'simplify': 'Simplify',
|
||||
'harden': 'Harden',
|
||||
'system': 'System'
|
||||
};
|
||||
|
||||
function renderDesktopLayout(container, commands) {
|
||||
magazineState.commands = commands;
|
||||
|
||||
let startIndex = -1;
|
||||
|
||||
// Filter out deprecated shims. craft, teach, extract used to be filtered
|
||||
// too (when they were rendered as 'impeccable craft' etc.) but are now
|
||||
// first-class sub-commands that should appear in the gallery.
|
||||
const deprecated = new Set(['teach-impeccable', 'frontend-design', 'arrange', 'normalize', 'onboard', 'impeccable craft', 'impeccable teach', 'impeccable extract']);
|
||||
const filteredCommands = commands.filter(c => !deprecated.has(c.id));
|
||||
|
||||
const categoryOrder = ['create', 'evaluate', 'refine', 'simplify', 'harden', 'system'];
|
||||
const categoryLabelsShort = {
|
||||
'create': 'Create', 'evaluate': 'Evaluate', 'refine': 'Refine',
|
||||
'simplify': 'Simplify', 'harden': 'Harden', 'system': 'System'
|
||||
};
|
||||
// Preferred order within each category (unlisted commands append at end)
|
||||
const categoryCommandOrder = {
|
||||
'create': ['impeccable', 'craft', 'shape'],
|
||||
'evaluate': ['critique', 'audit'],
|
||||
'refine': ['typeset', 'layout', 'colorize', 'animate', 'delight', 'bolder', 'quieter', 'overdrive'],
|
||||
'simplify': ['distill', 'clarify', 'adapt'],
|
||||
'harden': ['polish', 'optimize', 'harden'],
|
||||
'system': ['teach', 'extract']
|
||||
};
|
||||
const grouped = {};
|
||||
filteredCommands.forEach(cmd => {
|
||||
const cat = commandCategories[cmd.id] || 'other';
|
||||
if (!grouped[cat]) grouped[cat] = [];
|
||||
grouped[cat].push(cmd);
|
||||
});
|
||||
// Sort each group by preferred order
|
||||
Object.entries(grouped).forEach(([cat, cmds]) => {
|
||||
const order = categoryCommandOrder[cat] || [];
|
||||
cmds.sort((a, b) => {
|
||||
const ai = order.indexOf(a.id);
|
||||
const bi = order.indexOf(b.id);
|
||||
return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi);
|
||||
});
|
||||
});
|
||||
const orderedCommands = [];
|
||||
const headerIndices = [];
|
||||
categoryOrder.forEach(cat => {
|
||||
if (!grouped[cat]) return;
|
||||
headerIndices.push({ index: orderedCommands.length, label: categoryLabelsShort[cat] || cat });
|
||||
orderedCommands.push(...grouped[cat]);
|
||||
});
|
||||
// Use ordered list for everything
|
||||
filteredCommands.length = 0;
|
||||
filteredCommands.push(...orderedCommands);
|
||||
magazineState.commands = filteredCommands;
|
||||
|
||||
// Determine starting index: URL hash takes priority, otherwise default to "clarify"
|
||||
const hash = window.location.hash;
|
||||
if (hash && hash.startsWith('#cmd-')) {
|
||||
const idx = filteredCommands.findIndex(c => c.id === hash.slice(5));
|
||||
if (idx >= 0) startIndex = idx;
|
||||
}
|
||||
if (startIndex < 0) {
|
||||
startIndex = Math.max(0, filteredCommands.findIndex(c => c.id === 'clarify'));
|
||||
}
|
||||
magazineState.currentIndex = startIndex;
|
||||
|
||||
// Build spreads HTML (after ordering so indices match fisheye)
|
||||
const spreadsHTML = filteredCommands.map((cmd, i) => renderSpread(cmd, i, i === startIndex)).join('');
|
||||
|
||||
const fisheyeHTML = filteredCommands.map((cmd, i) => {
|
||||
const cat = commandCategories[cmd.id] || 'other';
|
||||
const isAlpha = alphaCommands.includes(cmd.id);
|
||||
// The root skill is shown as "/impeccable", everything else is a sub-command
|
||||
// displayed without a slash (invocation is /impeccable <name>)
|
||||
const isRoot = cmd.id === 'impeccable';
|
||||
const label = isRoot
|
||||
? `<span class="fisheye-slash">/</span>impeccable`
|
||||
: cmd.id;
|
||||
return `<button class="fisheye-item${i === startIndex ? ' is-active' : ''}" data-index="${i}" data-id="${cmd.id}" data-cat="${cat}">${label}${isAlpha ? '<span class="fisheye-beta">ALPHA</span>' : ''}</button>`;
|
||||
}).join('');
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="magazine-container">
|
||||
<div class="fisheye-list" id="fisheye-list">
|
||||
<div class="fisheye-scroll">${fisheyeHTML}</div>
|
||||
</div>
|
||||
<div class="magazine-viewport">
|
||||
${spreadsHTML}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Init demo for active spread
|
||||
initSpreadDemo(startIndex);
|
||||
|
||||
// Set up interactions
|
||||
setupFisheyeList(filteredCommands, headerIndices);
|
||||
setupMagazineKeyboard(filteredCommands);
|
||||
setupMagazineIntersection(container);
|
||||
}
|
||||
|
||||
function renderSpread(cmd, index, isActive) {
|
||||
const cat = commandCategories[cmd.id] || 'other';
|
||||
const isAlpha = alphaCommands.includes(cmd.id);
|
||||
const relationship = commandRelationships[cmd.id];
|
||||
// Build relationship flow
|
||||
let flowHTML = '';
|
||||
if (relationship) {
|
||||
if (relationship.pairs) {
|
||||
flowHTML = `
|
||||
<div class="spread-flow">
|
||||
<span class="spread-flow-icon">↔</span>
|
||||
<span class="spread-flow-label">pairs with</span>
|
||||
<span class="spread-flow-cmd">/${relationship.pairs}</span>
|
||||
</div>`;
|
||||
} else if (relationship.leadsTo && relationship.leadsTo.length > 0) {
|
||||
flowHTML = `
|
||||
<div class="spread-flow">
|
||||
<span class="spread-flow-icon">→</span>
|
||||
<span class="spread-flow-label">leads to</span>
|
||||
${relationship.leadsTo.map(c => `<span class="spread-flow-cmd">/${c}</span>`).join(' ')}
|
||||
</div>`;
|
||||
} else if (relationship.combinesWith && relationship.combinesWith.length > 0) {
|
||||
flowHTML = `
|
||||
<div class="spread-flow">
|
||||
<span class="spread-flow-icon">+</span>
|
||||
<span class="spread-flow-label">combines with</span>
|
||||
${relationship.combinesWith.map(c => `<span class="spread-flow-cmd">/${c}</span>`).join(' ')}
|
||||
</div>`;
|
||||
}
|
||||
if (!flowHTML && relationship.flow) {
|
||||
flowHTML = `
|
||||
<div class="spread-flow">
|
||||
<span class="spread-flow-label">${relationship.flow}</span>
|
||||
</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// The root skill is rendered as /impeccable; sub-commands are rendered as
|
||||
// /impeccable on a smaller line above the command name, so the command name
|
||||
// stays the visual anchor at full display size.
|
||||
const isRoot = cmd.id === 'impeccable';
|
||||
const nameHTML = isRoot
|
||||
? `<span class="spread-slash">/</span>impeccable`
|
||||
: `<span class="spread-namespace"><span class="spread-slash">/</span>impeccable</span>${cmd.id}`;
|
||||
|
||||
return `
|
||||
<div class="magazine-spread${isActive ? ' active' : ''}" data-index="${index}" data-category="${cat}" data-id="${cmd.id}" id="cmd-${cmd.id}">
|
||||
<div class="spread-identity">
|
||||
<span class="spread-category-label">${categoryLabels[cat] || cat}</span>
|
||||
<h3 class="spread-command-name">${nameHTML}${isAlpha ? '<span class="beta-badge">ALPHA</span>' : ''}</h3>
|
||||
<p class="spread-description">${cmd.tagline || cmd.description}</p>
|
||||
${flowHTML}
|
||||
</div>
|
||||
<div class="spread-demo-area" data-demo-index="${index}">
|
||||
<!-- Demo rendered lazily -->
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function initSpreadDemo(index) {
|
||||
const cmd = magazineState.commands[index];
|
||||
if (!cmd) return;
|
||||
|
||||
const spread = document.querySelector(`.magazine-spread[data-index="${index}"]`);
|
||||
if (!spread) return;
|
||||
|
||||
const demoArea = spread.querySelector('.spread-demo-area');
|
||||
if (!demoArea) return;
|
||||
|
||||
// Cleanup previous split instance
|
||||
if (currentSplitInstance) {
|
||||
currentSplitInstance.destroy();
|
||||
currentSplitInstance = null;
|
||||
}
|
||||
|
||||
currentCommandId = cmd.id;
|
||||
|
||||
// Only render HTML once; re-init split compare every time
|
||||
if (demoArea.dataset.loaded !== 'true') {
|
||||
demoArea.innerHTML = renderCommandDemo(cmd.id);
|
||||
demoArea.dataset.loaded = 'true';
|
||||
}
|
||||
|
||||
const splitComparison = demoArea.querySelector('.demo-split-comparison');
|
||||
if (splitComparison) {
|
||||
currentSplitInstance = initSplitCompare(splitComparison, {
|
||||
defaultPosition: 50
|
||||
});
|
||||
}
|
||||
initCommandDemo(cmd.id, demoArea);
|
||||
}
|
||||
|
||||
function goToSpread(newIndex, commands) {
|
||||
if (newIndex < 0 || newIndex >= commands.length) return;
|
||||
if (newIndex === magazineState.currentIndex) return;
|
||||
|
||||
const oldIndex = magazineState.currentIndex;
|
||||
magazineState.currentIndex = newIndex;
|
||||
|
||||
const spreads = document.querySelectorAll('.magazine-spread');
|
||||
|
||||
// Destroy the old split instance before switching
|
||||
if (currentSplitInstance) {
|
||||
currentSplitInstance.destroy();
|
||||
currentSplitInstance = null;
|
||||
}
|
||||
|
||||
// Mark old as exiting
|
||||
spreads[oldIndex]?.classList.remove('active');
|
||||
spreads[oldIndex]?.classList.add('exiting');
|
||||
|
||||
// Mark new as active
|
||||
spreads[newIndex]?.classList.add('active');
|
||||
spreads[newIndex]?.classList.remove('exiting');
|
||||
|
||||
// No fisheye sync here -- fisheye drives goToSpread, not the other way around
|
||||
|
||||
// Update URL hash
|
||||
const cmd = commands[newIndex];
|
||||
if (cmd) {
|
||||
history.replaceState(null, '', `#cmd-${cmd.id}`);
|
||||
}
|
||||
|
||||
// Init demo for new spread (lazy)
|
||||
initSpreadDemo(newIndex);
|
||||
|
||||
// Clean exiting class after transition
|
||||
setTimeout(() => {
|
||||
spreads[oldIndex]?.classList.remove('exiting');
|
||||
}, 500);
|
||||
}
|
||||
|
||||
function setupFisheyeList(commands, headerIndices = []) {
|
||||
const list = document.getElementById('fisheye-list');
|
||||
const scroll = list?.querySelector('.fisheye-scroll');
|
||||
const items = list ? [...list.querySelectorAll('.fisheye-item')] : [];
|
||||
if (!list || !scroll || !items.length) return;
|
||||
|
||||
// Fixed item height (matches CSS). All math is index-based.
|
||||
// -- Fisheye with absolute positioning --
|
||||
// Each item is placed absolutely. Their Y positions are computed by
|
||||
// accumulating scaled heights, so small items cluster together
|
||||
// and the center item gets full space. Scroll position maps linearly
|
||||
// to a fractional "center index" which drives everything.
|
||||
|
||||
const BASE_H = 36; // height of the center (scale=1) item
|
||||
const MIN_SCALE = 0.35;
|
||||
const RADIUS = 5;
|
||||
const count = items.length;
|
||||
const listH = list.clientHeight;
|
||||
const centerY = listH / 2;
|
||||
let currentActive = -1;
|
||||
|
||||
// Total scroll range: one "step" per item
|
||||
const STEP = 30; // px of scroll per item advance
|
||||
const totalScroll = (count - 1) * STEP;
|
||||
|
||||
// Set scroll container height to accommodate the range + centering padding
|
||||
const spacer = document.createElement('div');
|
||||
spacer.style.height = `${totalScroll + listH}px`;
|
||||
scroll.appendChild(spacer);
|
||||
// Initial scroll to center first item
|
||||
scroll.scrollTop = 0;
|
||||
|
||||
// Map scrollTop to fractional center index
|
||||
const getCenterIndex = () => scroll.scrollTop / STEP;
|
||||
|
||||
// Compute eased scale for a given distance from center
|
||||
const getScale = (dist) => {
|
||||
const ratio = Math.max(0, 1 - dist / RADIUS);
|
||||
const eased = ratio * ratio * (3 - 2 * ratio); // smoothstep
|
||||
return MIN_SCALE + eased * (1 - MIN_SCALE);
|
||||
};
|
||||
|
||||
// Layout: position all items based on current center
|
||||
const layout = (center) => {
|
||||
// First, compute the Y position for each item by accumulating
|
||||
// scaled heights, centered around the center item
|
||||
const heights = items.map((_, i) => {
|
||||
const dist = Math.abs(i - center);
|
||||
return BASE_H * getScale(dist);
|
||||
});
|
||||
|
||||
// Find the Y offset so the fractional center position lands at centerY.
|
||||
// Interpolate between the integer positions for smooth scrolling.
|
||||
const floorIdx = Math.max(0, Math.min(count - 1, Math.floor(center)));
|
||||
const frac = center - floorIdx;
|
||||
|
||||
let yAtFloor = 0;
|
||||
for (let i = 0; i < floorIdx; i++) yAtFloor += heights[i];
|
||||
yAtFloor += heights[floorIdx] / 2;
|
||||
|
||||
// If between two items, blend toward the next
|
||||
let yAtCeil = yAtFloor;
|
||||
if (floorIdx < count - 1) {
|
||||
yAtCeil = yAtFloor + heights[floorIdx] / 2 + heights[floorIdx + 1] / 2;
|
||||
}
|
||||
const yAtCenter = yAtFloor + (yAtCeil - yAtFloor) * frac;
|
||||
const offset = centerY - yAtCenter + scroll.scrollTop;
|
||||
|
||||
// Position each item
|
||||
let y = offset;
|
||||
items.forEach((item, i) => {
|
||||
const h = heights[i];
|
||||
const scale = getScale(Math.abs(i - center));
|
||||
const opacity = 0.25 + (scale - MIN_SCALE) / (1 - MIN_SCALE) * 0.75;
|
||||
|
||||
item.style.top = `${y}px`;
|
||||
item.style.transform = `scale(${scale})`;
|
||||
item.style.opacity = opacity;
|
||||
y += h;
|
||||
});
|
||||
};
|
||||
|
||||
const activate = (idx) => {
|
||||
idx = Math.max(0, Math.min(count - 1, Math.round(idx)));
|
||||
if (idx === currentActive) return;
|
||||
currentActive = idx;
|
||||
items.forEach((it, i) => it.classList.toggle('is-active', i === idx));
|
||||
goToSpread(idx, commands);
|
||||
};
|
||||
|
||||
const scrollToIndex = (idx, behavior = 'smooth') => {
|
||||
idx = Math.max(0, Math.min(count - 1, idx));
|
||||
scroll.scrollTo({ top: idx * STEP, behavior });
|
||||
};
|
||||
|
||||
// Scroll handler
|
||||
let raf = null;
|
||||
scroll.addEventListener('scroll', () => {
|
||||
if (raf) cancelAnimationFrame(raf);
|
||||
raf = requestAnimationFrame(() => {
|
||||
const center = getCenterIndex();
|
||||
layout(center);
|
||||
activate(Math.round(center));
|
||||
});
|
||||
}, { passive: true });
|
||||
|
||||
|
||||
// Click to jump
|
||||
items.forEach((item, i) => {
|
||||
item.addEventListener('click', () => scrollToIndex(i));
|
||||
});
|
||||
|
||||
// Expose for keyboard/external nav
|
||||
list._scrollToCommand = (idx) => scrollToIndex(idx);
|
||||
|
||||
// Init
|
||||
const startIdx = magazineState.currentIndex;
|
||||
currentActive = -1;
|
||||
scroll.scrollTop = startIdx * STEP;
|
||||
layout(startIdx);
|
||||
activate(startIdx);
|
||||
}
|
||||
|
||||
function setupMagazineKeyboard(commands) {
|
||||
if (magazineState.keyboardBound) return;
|
||||
magazineState.keyboardBound = true;
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
// Only respond when magazine is visible (desktop)
|
||||
if (isMobile()) return;
|
||||
const magazineEl = document.querySelector('.magazine-container');
|
||||
if (!magazineEl) return;
|
||||
|
||||
// Check if magazine is somewhat in the viewport
|
||||
const rect = magazineEl.getBoundingClientRect();
|
||||
const inView = rect.top < window.innerHeight && rect.bottom > 0;
|
||||
if (!inView) return;
|
||||
|
||||
const fisheyeList = document.getElementById('fisheye-list');
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
fisheyeList?._scrollToCommand?.(magazineState.currentIndex + 1);
|
||||
} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
fisheyeList?._scrollToCommand?.(magazineState.currentIndex - 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setupMagazineIntersection(container) {
|
||||
// When the magazine section enters the viewport, ensure the active demo is rendered
|
||||
if (magazineState.intersectionObserver) {
|
||||
magazineState.intersectionObserver.disconnect();
|
||||
}
|
||||
|
||||
magazineState.intersectionObserver = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
initSpreadDemo(magazineState.currentIndex);
|
||||
}
|
||||
});
|
||||
}, { threshold: 0.1 });
|
||||
|
||||
const magazineEl = container.querySelector('.magazine-container');
|
||||
if (magazineEl) {
|
||||
magazineState.intersectionObserver.observe(magazineEl);
|
||||
}
|
||||
}
|
||||
|
||||
function truncateDescription(text, maxLen = 120) {
|
||||
if (text.length <= maxLen) return text;
|
||||
// Cut at last sentence boundary within limit, or last word boundary
|
||||
const truncated = text.slice(0, maxLen);
|
||||
const lastPeriod = truncated.lastIndexOf('.');
|
||||
if (lastPeriod > maxLen * 0.5) return truncated.slice(0, lastPeriod + 1);
|
||||
const lastSpace = truncated.lastIndexOf(' ');
|
||||
return truncated.slice(0, lastSpace) + '...';
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// MOBILE LAYOUT - Carousel + Sticky Demo
|
||||
// ============================================
|
||||
|
||||
function renderMobileLayout(container, commands) {
|
||||
// Build carousel pills
|
||||
// Carousel pills show bare command names for sub-commands, and /impeccable
|
||||
// for the root entry.
|
||||
const carouselHTML = commands.map((cmd, i) => `
|
||||
<button class="mobile-cmd-pill${i === 0 ? ' active' : ''}" data-id="${cmd.id}">
|
||||
${cmd.id === 'impeccable' ? '/impeccable' : cmd.id}
|
||||
</button>
|
||||
`).join('');
|
||||
|
||||
// Build command info cards (one per command, only active one shown)
|
||||
const infoCardsHTML = commands.map((cmd, i) => {
|
||||
const relationship = commandRelationships[cmd.id];
|
||||
let relationshipHTML = '';
|
||||
|
||||
// Relationships show bare command names (e.g., "pairs with quieter")
|
||||
// because the invocation is /impeccable <name>, not /<name>.
|
||||
if (relationship) {
|
||||
if (relationship.pairs) {
|
||||
relationshipHTML = `<div class="mobile-cmd-rel">↔ pairs with <code>${relationship.pairs}</code></div>`;
|
||||
} else if (relationship.leadsTo && relationship.leadsTo.length > 0) {
|
||||
relationshipHTML = `<div class="mobile-cmd-rel">→ leads to ${relationship.leadsTo.map(c => `<code>${c}</code>`).join(', ')}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
const cardName = cmd.id === 'impeccable'
|
||||
? '/impeccable'
|
||||
: `<span class="mobile-cmd-namespace">/impeccable</span> ${cmd.id}`;
|
||||
|
||||
return `
|
||||
<div class="mobile-cmd-info${i === 0 ? ' active' : ''}" data-id="${cmd.id}">
|
||||
<h3 class="mobile-cmd-name">${cardName}</h3>
|
||||
<p class="mobile-cmd-desc">${cmd.tagline || cmd.description}</p>
|
||||
${relationshipHTML}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="mobile-commands-layout">
|
||||
<div class="mobile-carousel-wrapper">
|
||||
<div class="mobile-carousel">
|
||||
${carouselHTML}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mobile-demo-area" id="mobile-demo-content">
|
||||
${renderCommandDemo(commands[0]?.id || 'audit')}
|
||||
</div>
|
||||
<div class="mobile-info-area">
|
||||
${infoCardsHTML}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
setupMobileInteractions(commands);
|
||||
}
|
||||
|
||||
function setupMobileInteractions(commands) {
|
||||
const pills = document.querySelectorAll('.mobile-cmd-pill');
|
||||
const demoArea = document.getElementById('mobile-demo-content');
|
||||
const infoCards = document.querySelectorAll('.mobile-cmd-info');
|
||||
|
||||
// Initialize first demo's split compare
|
||||
const initialSplit = demoArea.querySelector('.demo-split-comparison');
|
||||
if (initialSplit) {
|
||||
currentSplitInstance = initSplitCompare(initialSplit, {
|
||||
defaultPosition: 50,
|
||||
minPosition: 10,
|
||||
maxPosition: 90
|
||||
});
|
||||
}
|
||||
if (commands[0]) initCommandDemo(commands[0].id, demoArea);
|
||||
|
||||
// Pill click/tap handler
|
||||
pills.forEach(pill => {
|
||||
pill.addEventListener('click', () => {
|
||||
const cmdId = pill.dataset.id;
|
||||
const cmd = commands.find(c => c.id === cmdId);
|
||||
if (!cmd || currentCommandId === cmdId) return;
|
||||
|
||||
currentCommandId = cmdId;
|
||||
|
||||
// Update active pill
|
||||
pills.forEach(p => p.classList.remove('active'));
|
||||
pill.classList.add('active');
|
||||
|
||||
// Scroll pill into view horizontally
|
||||
pill.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
|
||||
|
||||
// Update info card
|
||||
infoCards.forEach(card => {
|
||||
card.classList.toggle('active', card.dataset.id === cmdId);
|
||||
});
|
||||
|
||||
// Cleanup previous split
|
||||
if (currentSplitInstance) {
|
||||
currentSplitInstance.destroy();
|
||||
currentSplitInstance = null;
|
||||
}
|
||||
|
||||
// Update demo
|
||||
demoArea.innerHTML = renderCommandDemo(cmdId);
|
||||
|
||||
// Init new split compare
|
||||
const splitComparison = demoArea.querySelector('.demo-split-comparison');
|
||||
if (splitComparison) {
|
||||
currentSplitInstance = initSplitCompare(splitComparison, {
|
||||
defaultPosition: 50
|
||||
});
|
||||
}
|
||||
initCommandDemo(cmdId, demoArea);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// STACKED WINDOWS - Tab Switching
|
||||
// ============================================
|
||||
|
||||
function setupStackTabs() {
|
||||
const tabs = document.querySelectorAll('.terminal-stack-tab');
|
||||
const demoWindow = document.querySelector('.terminal-window--demo');
|
||||
const sourceWindow = document.querySelector('.terminal-window--source');
|
||||
|
||||
tabs.forEach(tab => {
|
||||
tab.addEventListener('click', () => {
|
||||
const view = tab.dataset.view;
|
||||
|
||||
// Update tab states
|
||||
tabs.forEach(t => t.classList.remove('active'));
|
||||
tab.classList.add('active');
|
||||
|
||||
// Switch windows
|
||||
if (view === 'source') {
|
||||
demoWindow.classList.add('is-back');
|
||||
sourceWindow.classList.add('is-front');
|
||||
} else {
|
||||
demoWindow.classList.remove('is-back');
|
||||
sourceWindow.classList.remove('is-front');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchCommandSource(cmdId) {
|
||||
// Check cache first
|
||||
if (sourceCache[cmdId]) {
|
||||
return sourceCache[cmdId];
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/command-source/${cmdId}`);
|
||||
if (!response.ok) throw new Error('Failed to fetch source');
|
||||
const data = await response.json();
|
||||
sourceCache[cmdId] = data.content;
|
||||
return data.content;
|
||||
} catch (error) {
|
||||
console.error('Error fetching command source:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
async function updateSourceContent(cmdId) {
|
||||
const titleEl = document.getElementById('source-title');
|
||||
const contentEl = document.getElementById('source-content');
|
||||
|
||||
if (!titleEl || !contentEl) return;
|
||||
|
||||
titleEl.textContent = `${cmdId}.md`;
|
||||
contentEl.innerHTML = '<span class="source-loading">Loading...</span>';
|
||||
|
||||
const source = await fetchCommandSource(cmdId);
|
||||
if (source) {
|
||||
contentEl.textContent = source;
|
||||
} else {
|
||||
contentEl.innerHTML = '<span class="source-loading">Source not available</span>';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { initSplitCompare } from "../effects/split-compare.js";
|
||||
|
||||
export function initLensEffect() {
|
||||
const container = document.getElementById("lens-comparison");
|
||||
if (!container) return;
|
||||
|
||||
initSplitCompare(container, {
|
||||
defaultPosition: 50
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
// Interactive Live Mode demo loop. Matches the real picker flow:
|
||||
// - a persistent dark global bar stays at the bottom of the frame the whole time
|
||||
// - a light contextual bar floats above the picked element during a session,
|
||||
// morphing between configure → generating → cycling → accepted
|
||||
//
|
||||
// Plays only while the section is in view. Respects prefers-reduced-motion.
|
||||
|
||||
const PHASE = {
|
||||
HIDDEN: 'hidden',
|
||||
CONFIGURING: 'configuring',
|
||||
GENERATING: 'generating',
|
||||
CYCLING: 'cycling',
|
||||
ACCEPTED: 'accepted',
|
||||
};
|
||||
|
||||
const TIMELINE = [
|
||||
{ dt: 400, action: 'cursor-show' },
|
||||
{ dt: 400, action: 'cursor-to-target' },
|
||||
{ dt: 900, action: 'outline-show', caption: 'Hover to pick.' },
|
||||
{ dt: 500, action: 'cursor-click' },
|
||||
{ dt: 200, action: 'open-ctx', caption: 'Picked. Contextual bar appears.' },
|
||||
{ dt: 700, action: 'cursor-to-input' },
|
||||
{ dt: 300, action: 'type', text: 'more playful', caption: 'Type a refinement, or skip.' },
|
||||
{ dt: 1200, action: 'draw-stroke', caption: 'Annotate on the page, if you want.' },
|
||||
{ dt: 900, action: 'cursor-to-go' },
|
||||
{ dt: 300, action: 'click-go', caption: 'Generating three variants…' },
|
||||
{ dt: 1600, action: 'show-variant', n: 1, caption: 'Variant 1 of 3.' },
|
||||
{ dt: 1400, action: 'show-variant', n: 2, caption: 'Variant 2 of 3.' },
|
||||
{ dt: 1400, action: 'show-variant', n: 3, caption: 'Variant 3 of 3.' },
|
||||
{ dt: 900, action: 'cursor-to-accept' },
|
||||
{ dt: 300, action: 'click-accept', caption: 'Accepted. Written to source.' },
|
||||
{ dt: 1800, action: 'reset', caption: 'Hover to pick.' },
|
||||
];
|
||||
|
||||
export function initLiveDemo() {
|
||||
const root = document.getElementById('live-demo');
|
||||
if (!root) return;
|
||||
|
||||
const stage = root.querySelector('.live-demo-stage');
|
||||
const target = root.querySelector('[data-demo-target]');
|
||||
const outline = root.querySelector('[data-demo-outline]');
|
||||
const annotations = root.querySelector('[data-demo-annotations]');
|
||||
const cursor = root.querySelector('[data-demo-cursor]');
|
||||
const ctx = root.querySelector('[data-demo-ctx]');
|
||||
const inputText = root.querySelector('[data-demo-input-text]');
|
||||
const counter = root.querySelector('[data-demo-counter]');
|
||||
const captionLabel = root.querySelector('[data-demo-caption-label]');
|
||||
const variants = Array.from(root.querySelectorAll('.live-demo-variant'));
|
||||
|
||||
if (!stage || !target || !ctx) return;
|
||||
|
||||
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
// Position the outline around the target.
|
||||
const positionOutline = () => {
|
||||
const stageRect = stage.getBoundingClientRect();
|
||||
const targetRect = target.getBoundingClientRect();
|
||||
outline.style.left = (targetRect.left - stageRect.left - 4) + 'px';
|
||||
outline.style.top = (targetRect.top - stageRect.top - 4) + 'px';
|
||||
outline.style.width = (targetRect.width + 8) + 'px';
|
||||
outline.style.height = (targetRect.height + 8) + 'px';
|
||||
};
|
||||
|
||||
// Position the contextual bar below the target (or above if below would
|
||||
// collide with the global bar). Mirrors positionBar() in live-browser.js.
|
||||
const positionCtx = () => {
|
||||
const stageRect = stage.getBoundingClientRect();
|
||||
const targetRect = target.getBoundingClientRect();
|
||||
const ctxRect = ctx.getBoundingClientRect();
|
||||
const GAP = 10;
|
||||
const BAR_RESERVE = 60;
|
||||
const belowTop = targetRect.bottom - stageRect.top + GAP;
|
||||
const aboveTop = targetRect.top - stageRect.top - ctxRect.height - GAP;
|
||||
let top;
|
||||
if (belowTop + ctxRect.height + GAP <= stage.clientHeight - BAR_RESERVE) {
|
||||
top = belowTop;
|
||||
} else if (aboveTop >= GAP) {
|
||||
top = aboveTop;
|
||||
} else {
|
||||
top = stage.clientHeight - ctxRect.height - BAR_RESERVE;
|
||||
}
|
||||
ctx.style.top = top + 'px';
|
||||
};
|
||||
|
||||
const moveCursor = (selector, offsetX = 0, offsetY = 0) => {
|
||||
const stageRect = stage.getBoundingClientRect();
|
||||
const el = typeof selector === 'string' ? root.querySelector(selector) : selector;
|
||||
if (!el) return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const x = rect.left - stageRect.left + rect.width / 2 + offsetX;
|
||||
const y = rect.top - stageRect.top + rect.height / 2 + offsetY;
|
||||
cursor.style.transform = `translate(${x}px, ${y}px)`;
|
||||
};
|
||||
|
||||
const showVariant = (n) => {
|
||||
variants.forEach((v) => {
|
||||
const match = (n === 0 && v.dataset.variant === 'original') || v.dataset.variant === String(n);
|
||||
v.classList.toggle('is-active', match);
|
||||
});
|
||||
counter.textContent = n + ' / 3';
|
||||
requestAnimationFrame(() => {
|
||||
positionOutline();
|
||||
positionCtx();
|
||||
});
|
||||
};
|
||||
|
||||
const setCtxPhase = (phase) => {
|
||||
ctx.dataset.phase = phase;
|
||||
if (phase !== PHASE.HIDDEN) requestAnimationFrame(positionCtx);
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
setCtxPhase(PHASE.HIDDEN);
|
||||
cursor.classList.remove('is-visible', 'is-click');
|
||||
outline.classList.remove('is-visible');
|
||||
annotations.classList.remove('is-visible', 'is-comment-visible');
|
||||
inputText.textContent = '';
|
||||
showVariant(0);
|
||||
};
|
||||
|
||||
const setCaption = (text) => {
|
||||
if (text && captionLabel) captionLabel.textContent = text;
|
||||
};
|
||||
|
||||
const typeText = (text, duration) => new Promise((resolve) => {
|
||||
inputText.textContent = '';
|
||||
const per = Math.max(30, Math.floor(duration / text.length));
|
||||
let i = 0;
|
||||
const tick = () => {
|
||||
if (i >= text.length) return resolve();
|
||||
inputText.textContent += text[i++];
|
||||
setTimeout(tick, per);
|
||||
};
|
||||
tick();
|
||||
});
|
||||
|
||||
const step = async (s) => {
|
||||
switch (s.action) {
|
||||
case 'cursor-show':
|
||||
moveCursor(target, -120, 40);
|
||||
cursor.classList.add('is-visible');
|
||||
break;
|
||||
case 'cursor-to-target':
|
||||
moveCursor(target);
|
||||
break;
|
||||
case 'outline-show':
|
||||
positionOutline();
|
||||
outline.classList.add('is-visible');
|
||||
break;
|
||||
case 'cursor-click':
|
||||
cursor.classList.add('is-click');
|
||||
setTimeout(() => cursor.classList.remove('is-click'), 260);
|
||||
break;
|
||||
case 'open-ctx':
|
||||
setCtxPhase(PHASE.CONFIGURING);
|
||||
break;
|
||||
case 'cursor-to-input':
|
||||
moveCursor(root.querySelector('[data-demo-input]'));
|
||||
break;
|
||||
case 'type':
|
||||
await typeText(s.text, 700);
|
||||
break;
|
||||
case 'draw-stroke':
|
||||
annotations.classList.add('is-visible');
|
||||
setTimeout(() => annotations.classList.add('is-comment-visible'), 600);
|
||||
break;
|
||||
case 'cursor-to-go':
|
||||
moveCursor(root.querySelector('[data-demo-go]'));
|
||||
break;
|
||||
case 'click-go':
|
||||
cursor.classList.add('is-click');
|
||||
setTimeout(() => cursor.classList.remove('is-click'), 260);
|
||||
annotations.classList.remove('is-visible', 'is-comment-visible');
|
||||
setCtxPhase(PHASE.GENERATING);
|
||||
break;
|
||||
case 'show-variant':
|
||||
if (ctx.dataset.phase !== PHASE.CYCLING) setCtxPhase(PHASE.CYCLING);
|
||||
showVariant(s.n);
|
||||
break;
|
||||
case 'cursor-to-accept':
|
||||
moveCursor(root.querySelector('[data-demo-accept]'));
|
||||
break;
|
||||
case 'click-accept':
|
||||
cursor.classList.add('is-click');
|
||||
setTimeout(() => cursor.classList.remove('is-click'), 260);
|
||||
setCtxPhase(PHASE.ACCEPTED);
|
||||
outline.classList.remove('is-visible');
|
||||
break;
|
||||
case 'reset':
|
||||
reset();
|
||||
break;
|
||||
}
|
||||
setCaption(s.caption);
|
||||
};
|
||||
|
||||
let running = false;
|
||||
let cancelToken = 0;
|
||||
const sleep = (ms, token) => new Promise((resolve) => setTimeout(() => resolve(token === cancelToken), ms));
|
||||
|
||||
const run = async () => {
|
||||
if (running) return;
|
||||
running = true;
|
||||
const myToken = ++cancelToken;
|
||||
while (running && myToken === cancelToken) {
|
||||
reset();
|
||||
for (const s of TIMELINE) {
|
||||
const stillMe = await sleep(s.dt, myToken);
|
||||
if (!stillMe || !running) return;
|
||||
await step(s);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const stop = () => {
|
||||
running = false;
|
||||
cancelToken++;
|
||||
};
|
||||
|
||||
if (reduced) {
|
||||
// Freeze on a representative still: cycling, variant 3.
|
||||
showVariant(3);
|
||||
counter.textContent = '3 / 3';
|
||||
positionOutline();
|
||||
outline.classList.add('is-visible');
|
||||
setCtxPhase(PHASE.CYCLING);
|
||||
setCaption('Three variants. Pick the one you want.');
|
||||
return;
|
||||
}
|
||||
|
||||
const io = new IntersectionObserver((entries) => {
|
||||
entries.forEach((e) => {
|
||||
if (e.isIntersecting) run();
|
||||
else stop();
|
||||
});
|
||||
}, { threshold: 0.35 });
|
||||
io.observe(root);
|
||||
|
||||
window.addEventListener('resize', () => requestAnimationFrame(() => {
|
||||
positionOutline();
|
||||
positionCtx();
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Sticky Section Nav
|
||||
* Shows/hides based on scroll position and highlights current section.
|
||||
*/
|
||||
|
||||
export function initSectionNav() {
|
||||
const nav = document.getElementById('section-nav');
|
||||
if (!nav) return;
|
||||
|
||||
const items = nav.querySelectorAll('.section-nav-item');
|
||||
const sectionIds = Array.from(items).map(item => item.dataset.section);
|
||||
|
||||
// Show/hide nav based on scroll position
|
||||
const hero = document.getElementById('hero');
|
||||
const footer = document.querySelector('.site-footer');
|
||||
if (!hero) return;
|
||||
|
||||
let ticking = false;
|
||||
|
||||
// Returns the element's top position relative to the document,
|
||||
// which works even when the element is inside a positioned parent.
|
||||
function docTop(el) {
|
||||
return el.getBoundingClientRect().top + window.scrollY;
|
||||
}
|
||||
|
||||
function updateNav() {
|
||||
const scrollY = window.scrollY;
|
||||
const heroBottom = hero.offsetTop + hero.offsetHeight - 100;
|
||||
const footerTop = footer ? docTop(footer) : Infinity;
|
||||
const viewportBottom = scrollY + window.innerHeight;
|
||||
|
||||
// Show nav after hero, hide when footer is visible
|
||||
if (scrollY > heroBottom && viewportBottom < footerTop + 60) {
|
||||
nav.classList.add('is-visible');
|
||||
} else {
|
||||
nav.classList.remove('is-visible');
|
||||
}
|
||||
|
||||
// Find current section
|
||||
let currentSection = null;
|
||||
const viewportMiddle = scrollY + window.innerHeight * 0.4;
|
||||
|
||||
for (let i = sectionIds.length - 1; i >= 0; i--) {
|
||||
const section = document.getElementById(sectionIds[i]);
|
||||
if (section && docTop(section) <= viewportMiddle) {
|
||||
currentSection = sectionIds[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If the current section shares its top row with siblings (e.g. side-by-side
|
||||
// changelog + FAQ on desktop), treat all of them as active.
|
||||
const activeSections = new Set();
|
||||
if (currentSection) {
|
||||
const currentEl = document.getElementById(currentSection);
|
||||
const currentTop = currentEl ? docTop(currentEl) : 0;
|
||||
sectionIds.forEach(id => {
|
||||
const el = document.getElementById(id);
|
||||
if (el && Math.abs(docTop(el) - currentTop) < 4) {
|
||||
activeSections.add(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Update active state
|
||||
items.forEach(item => {
|
||||
if (activeSections.has(item.dataset.section)) {
|
||||
item.classList.add('is-active');
|
||||
} else {
|
||||
item.classList.remove('is-active');
|
||||
}
|
||||
});
|
||||
|
||||
ticking = false;
|
||||
}
|
||||
|
||||
window.addEventListener('scroll', () => {
|
||||
if (!ticking) {
|
||||
requestAnimationFrame(updateNav);
|
||||
ticking = true;
|
||||
}
|
||||
}, { passive: true });
|
||||
|
||||
// Initial check
|
||||
updateNav();
|
||||
}
|
||||
Reference in New Issue
Block a user