Files
pbakaus_impeccable/site/scripts/components/glass-terminal.js
T
c8e973b324 Site polish: de-warm the palette, refine chrome, clean up /designing (#176)
* fix(home): command-wheel contrast, slop copy, line-length

Address P1/P2/P3 findings from /impeccable critique of the homepage:

- Command wheel (The Language): off-center command names floored at
  ~1.43:1 contrast were illegible (WCAG 1.4.3 fail) and hid most of the
  23-command vocabulary. Raise the fisheye opacity floor 0.25 -> 0.62,
  MIN_SCALE 0.35 -> 0.52, and lift the base color from --ks-text-muted to
  --ks-text. Off-center now measures >=4.59:1; full list stays scannable
  while gold + size + weight still carry focus.
- Slop section copy: rewrite all 7 discipline cards off the uniform
  "No X. No Y. No Z." triad into varied cadence with positives, and lead
  the section with what Impeccable does instead of the "Skills can't..."
  negation pivot. Drops the en-dash joiners too.
- Line length: cap .downloads-rebuild-note (was unbounded, ~102ch) and
  tighten the homepage .section-lead 68ch -> 62ch (rendered ~86 actual
  chars/line).

The diagonal plinth ramp on the slop grid is intentionally kept per
design preference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(home): de-warm and brighten the text ramp

Warmth now lives only in the gold accents and surfaces, not the type.
Body, headings, and the secondary tiers read crisp on lacquer instead of
mushing into the warm floor:

- --ks-champagne 84% .035 82 -> 91% .006 90 (headings/strong, now neutral;
  token name kept for compatibility)
- --ks-text 81% .03 82 -> 88% .008 90 (body)
- --ks-text-muted / -faint / -mute-deep lifted and de-warmed to match

DESIGN.md frontmatter + prose synced to the new values.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(home): outlined testimonials + cleaner hero boundary

Testimonials:
- Flatten the double container: drop the t-plinth shelf wrapper (markup +
  CSS); the marquee sits directly in the section and carries its inset.
- Outlined cards: no fill, 1px solid neutral border (oklch .64 0 0 / .22),
  no dead drop-shadow. Removes the mushy gray-on-gray blend and the stacked
  dotted-divider + gold-hairline chrome.
- Section has no background of its own (rides the body lacquer gradient) and
  no top padding, so cards sit right under the hero divider.

Hero:
- Drop the bottom fade and the top nav scrim; the kintsugi art runs at full
  strength. A 1px neutral border-bottom (matching the card border) marks the
  testimonials boundary instead of a wash.
- "How it works" is the kit ghost link (white), not an outlined button.

Foundation/slop cards: lift the surface 9% -> 15% so they read as raised
specimen cards instead of vanishing into the ground.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(live): quieter, more refined picker chrome

Gold is reserved for the brand mark and the active control instead of
ringing every container. Applied to the homepage demo, /live-mode, and the
real injected picker (skill/scripts/live-browser.js, rebuilt into the
harness dirs):

- Container: neutral 1px hairline + tight neutral shadow (was a 1.5px gold
  border + gold halo ring); radius 10px -> 8px.
- Active toggle: crisp graphite pill with gold text (was a murky kinpaku-dim
  wash).
- Internal control borders (action pill / input / count): neutral hairline
  (was a warm gold rule); configure-row controls share one 30px baseline.
- Pick outline: crisp 1.5px line, no soft gold glow ring; tighter radius.
- Demo browser chrome: small uniform neutral dots, neutral URL pill, slimmer
  bar; frame edge neutral hairline + tighter shadow that registers on dark.

DESIGN.md "Live Mode Picker" spec + "Picker Is Brand Rule" updated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(design): neutral default hairline (--ks-rule)

The default border/divider token was a warm gold hairline, used ~200x as
the site-wide default border — so every small label, pill, counter, card,
and divider carried warmth. Redefine it neutral so borders read clean;
gold stays where it signals.

- --ks-rule oklch(58% 0.065 82 / 0.32) -> oklch(78% 0 0 / 0.16)
- --ks-rule-strong (active/focus/brand borders) unchanged, still gold
- GitHub star pill: explicit near-white border (oklch 92% 0 0 / 0.18)
- DESIGN.md hairline mirror + prose synced

Verified across home, /design-system, and /docs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(home): testimonials separator + visible star-pill border

- Move the dotted accent to the bottom of the testimonials (neutral dots)
  as a deliberate separator into the slop section; drop the oversized
  bottom padding to 1em so cards sit near the separator.
- Star-counter pill: solid oklch(80% 0 0) border. The previous near-white
  at 0.32 alpha rendered as faded mid-gray on the near-black pill; a solid
  light border reads as the intended white hairline.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(design): neutralize body text (--ks-text)

Drop the last bit of warm chroma from the body text token; it still read
slightly warm at 0.008 chroma.

--ks-text oklch(88% 0.008 90) -> oklch(88% 0 0)  (pure neutral)

DESIGN.md mirror + prose synced.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(design): neutral text everywhere

Zero the residual warm chroma across the rest of the text ramp so no text
tier carries warmth (warmth lives only in gold accents + surfaces).

- --ks-champagne 91% .006 90 -> 91% 0 0
- --ks-text-muted 72% .01 90  -> 72% 0 0
- --ks-text-faint 62% .008 90 -> 62% 0 0
- --ks-text-mute-deep 52% .008 90 -> 52% 0 0

(--ks-text was already neutralized.) DESIGN.md mirror + prose synced.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(home): crisp, neutral Desloppification section

- Foundation card background: oklch(15% .004 95) -> oklch(15% 0 0) (neutral
  graphite) so cards read crisp, not warm.
- Plinth hatch: kinpaku gold -> neutral (oklch 80% 0 0 / .07) on a neutral
  base; the gold hatch was washing the section champagne.
- Remove the plinth bottom mask-fade so the pedestals end on a clean edge.

Gold stays only on the card icons as the accent.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(home): drop the homepage warm-token overrides

The homepage redefined --ks-rule, --ks-rule-strong, and --ks-muted to warm
values locally (an old "busier surfaces" tweak), so homepage borders and
secondary text stayed champagne even after the global de-warm. That's why
the Desloppification cards still read warm.

- Remove the --ks-rule / --ks-rule-strong overrides; inherit the global
  tokens (neutral default border, gold strong/active border).
- Alias --ks-muted to the global --ks-text-muted (no divergent value);
  legacy code still reads the --ks-muted name.

Result: all homepage borders + secondary text are neutral; gold stays on
accents (icons, mark, CTAs, active/focus).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(design): canonical code tokens (inline + block)

Code styling was all over the place: homepage inline code was gold-on-gold,
the slop CLI was a one-off gold-on-raised-lacquer, downloads used a separate
--card-cmd-* set, docs used yet another. Add one shared token set and point
the canonical surfaces at it.

New :root tokens:
- --ks-code-fg / --ks-code-bg / --ks-code-radius      (inline: neutral chip)
- --ks-code-block-fg / -bg / -border / -radius        (block/CLI: lacquer terminal)
- --ks-code-cmd                                        (code that's a command link)

Migrated: homepage inline code (was gold -> neutral chip), slop-teaser-cli
(the "weird color" -> neutral terminal), downloads-cmd, and the docs inline +
fenced-block rules (now the token source of truth; block text also neutralized).

Remaining pages (designing, changelog/faq, detector, case studies) swept next.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(design): sweep remaining pages onto code tokens

Point the rest of the site's code rules at the shared code tokens so inline
code and blocks are consistent everywhere:

- Inline code (designing, changelog, faq): gold -> neutral chip
  (--ks-code-fg / --ks-code-bg).
- Detector rule pills + table cells: code text -> --ks-code-fg.
- Neon-mirai case-study code block -> --ks-code-block-* tokens.

Command tags (the gold /command pills: spread-flow-cmd, docs-flow-cmd,
designing-phase-cmd, why-ci-cmd, etc.) are intentionally left as their own
interactive category, not generic code.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(home): polish "The Language" section

- Command tags (/polish, /adapt): gold command text on a neutral code chip
  (--ks-code-cmd / --ks-code-bg), dropping the muddy gold-tint border.
- Commands panel kept as the solid oklch(0.17 0 0) panel (no border).
- Demo preview cleaned up to a single framed split: strip the grid ::before,
  the gold-grid/radial-glow container background, and the inner drop-shadow;
  before-half inherits the panel, after-half is near-black, with one thin
  neutral border on the demo itself (caption sits outside it).
- Periodic table: crisp flat neutral graphite tiles. Removed the JS-inlined
  category bg (var(--cat-*-bg)) + 1.5px colored border + hover drop-shadow,
  the gold-leaf ::before texture, the ::after accent line, the inset box-shadow,
  and the gold hover glow. Now a 1px neutral border, white symbols, readable
  neutral names, and a clean neutral-border hover with no shadow.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(design): roomier inline-code padding

Inline code chips were tight top/bottom (the homepage one was only 0.05em).
Add a --ks-code-pad token (0.3em 0.5em) and point every inline-code rule at
it so the chips have consistent breathing room.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(home): drop non-steering commands from the command palette

impeccable, init, extract, document, and live are setup/management commands,
not steering verbs. Filter them out of the palette (fisheye + mobile carousel)
via a shared PALETTE_EXCLUDED set. They stay in the periodic table, which is
rendered separately by framework-viz.js.

Palette: 23 -> 18 commands.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(designing): flatten the pre-ship nested box

The pre-ship cards were a box-in-box: a legacy .designing-polish-grid panel
(cream bg + L/R/B border + padding, from docs-visuals.css) wrapping cards that
already have their own border + fill. Override the grid to a plain transparent
layout so the three cards are the only surface.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(designing): remove step counter + flatten design-debt boxes

- Drop the cryptic "03 · 04" pre-ship step counter (.designing-polish-band-meta)
  and tighten the band to a single bottom hairline.
- Design-debt: flatten the box-in-box (bento plinth > tile > stage). The
  .designing-maintain-stage no longer adds its own border + fill; the demo
  sits directly in the bento tile.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(designing): neutralize code/terminal/panel surfaces

The terminal block, surface-cmd chips, command pills, live-frame, and other
dark panels used a slightly-warm dark fill (oklch 1X% 0.006 95). Drop the warm
chroma so they read neutral like the rest of the de-warmed site; the page
ground + deep surfaces stay lacquer-warm.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(designing): neutralize inline code + live-mock picker chrome

- Inline code: the phase-sub and avoid-title code were still gold; point them
  at --ks-code-fg so all inline code reads neutral (gold stays only on command
  *links*).
- docs-viz-live mock: bring the duplicated picker chrome in line with the
  refactored neutral treatment — neutral 1px container borders (no gold halo),
  neutral active "Pick" pill (was the kinpaku-dim wash), crisp pick outline
  (no glow), tighter radii.
- CTAs (SEND ME ONE, Accept): pale-cream kinpaku-pale -> solid kinpaku gold.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(designing): flatten lanes + avoid sections

- Brand/Product lane mock cards: drop the inner border+fill box; the mock sits
  directly in the bento tile, separated by a top hairline (no plinth>tile>mock
  nesting).
- "What to avoid" list: flatten the boxed list cards into a clean divided list
  (hairline separators, no per-item border/fill).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(designing): clean up the Brand/Product lanes

- Drop the bento plinth (0.17 fill + 8px gutter that drew the weird gutter
  "borders") and the tile fill; the two lanes sit on the page split by a single
  center hairline.
- Brand mock title used the pinstripe display face at 1.6rem (reads broken at
  that size, the "champagne text"); switch it to the clean body face so it
  matches the product mock title.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(site): update GitHub star count to 31k

31,188 stars as of now; header pill + aria-label were stale at 30k.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add Neo Kinpaku light mode across the site.

Wire theme persistence and a header toggle, then layer light-mode overrides for docs viz contrast, command demos, live-mode pathway cards, and the designing/home surfaces.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(designing): replace em dashes flagged by prose validator

Brand/Product lane copy used em dashes ("the deliverable —", "the task —");
swap for colons per STYLE.md so the Cloudflare build's validateProse passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(designing): address Cursor bugbot nits

- Fold the duplicate .designing-avoid { gap: 0 } override into the original
  rule (the gap: 18px was dead code).
- Drop the leftover el.style.boxShadow = 'none' in the periodic-tile deactivate
  handler — activate no longer sets a box-shadow, so this only left a dead
  inline none that could suppress a future CSS shadow.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 03:50:23 -07:00

677 lines
25 KiB
JavaScript

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;
// Setup / management commands that aren't "steering" verbs. They're kept off
// the command palette (fisheye + mobile carousel) but still appear in the
// periodic table (rendered separately by framework-viz.js).
const PALETTE_EXCLUDED = new Set(['impeccable', 'init', 'extract', 'document', 'live']);
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) && !PALETTE_EXCLUDED.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': ['init', '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 command palette lists command names, not raw invocations.
const label = 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">&#8596;</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">&#8594;</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
? '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,
skewAngle: 0
});
}
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.52; // off-center items stay legibly sized, not microscopic
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));
// Floor at 0.62 so off-center command names stay readable (WCAG): the
// full vocabulary is the point of this view. Focus still reads clearly
// via scale + the gold/weight active state, not by crushing legibility.
const opacity = 0.62 + (scale - MIN_SCALE) / (1 - MIN_SCALE) * 0.38;
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) {
// Keep setup/management commands off the palette (they stay in the periodic
// table); match the desktop fisheye filter.
commands = commands.filter(c => !PALETTE_EXCLUDED.has(c.id));
// 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,
skewAngle: 0,
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,
skewAngle: 0
});
}
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>';
}
}