mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-11 21:57:14 +03:00
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
630e586b01 | ||
|
|
39bec7c08c | ||
|
|
e3d488e123 | ||
|
|
668263843f | ||
|
|
94b315ef63 | ||
|
|
28875097b0 | ||
|
|
65bbd6cb5f | ||
|
|
17fe31baa9 | ||
|
|
427128e073 | ||
|
|
70a9246401 | ||
|
|
8548003cc1 | ||
|
|
579006cda5 | ||
|
|
ceb0ef8f67 | ||
|
|
25e6c820aa | ||
|
|
6e96f62803 | ||
|
|
74f16d6310 | ||
|
|
d26ccac1be | ||
|
|
4310352423 | ||
|
|
89ffd73d4b | ||
|
|
4fa02bf573 | ||
|
|
7baf77a457 | ||
|
|
c3e18fe664 | ||
|
|
c8de59d81e | ||
|
|
d29a690797 | ||
|
|
d340f075e8 | ||
|
|
7de610c620 | ||
|
|
25353448e2 | ||
|
|
346ce25952 | ||
|
|
f5e82162c1 | ||
|
|
6816558d7a |
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
$impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run $impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -12,12 +12,12 @@
|
||||
{
|
||||
"name": "impeccable",
|
||||
"description": "Design fluency for frontend development. 1 skill with 23 commands (/impeccable polish, /impeccable audit, /impeccable critique, etc.) and curated anti-pattern detection.",
|
||||
"version": "3.0.0",
|
||||
"version": "3.0.2",
|
||||
"author": {
|
||||
"name": "Paul Bakaus",
|
||||
"email": "paul@paulbakaus.com"
|
||||
},
|
||||
"source": "./",
|
||||
"source": "./plugin",
|
||||
"category": "design",
|
||||
"homepage": "https://impeccable.style",
|
||||
"tags": ["design", "frontend", "ui", "ux", "skills", "commands"]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "impeccable",
|
||||
"description": "Design fluency for frontend development. 1 skill with 23 commands (/impeccable polish, /impeccable audit, /impeccable critique, etc.) and curated anti-pattern detection.",
|
||||
"version": "3.0.0",
|
||||
"version": "3.0.2",
|
||||
"author": {
|
||||
"name": "Paul Bakaus",
|
||||
"email": "paul@paulbakaus.com"
|
||||
},
|
||||
"homepage": "https://impeccable.style",
|
||||
"repository": "https://github.com/pbakaus/impeccable",
|
||||
"skills": "./.claude/skills"
|
||||
"skills": "./.claude/skills/"
|
||||
}
|
||||
|
||||
@@ -1,257 +0,0 @@
|
||||
---
|
||||
name: anti-patterns
|
||||
description: Use when adding, modifying, or debugging an anti-pattern detection rule in this repo. Walks through the TDD recipe, the rule schema, all five plug-in points, jsdom constraints, and the post-implementation checklist. Trigger this for any work touching src/detect-antipatterns.mjs, tests/fixtures/antipatterns/, or extension/detector/.
|
||||
tools: Read, Edit, Write, Glob, Grep, Bash, mcp__claude-in-chrome__navigate, mcp__claude-in-chrome__javascript_tool, mcp__claude-in-chrome__tabs_context_mcp, mcp__claude-in-chrome__tabs_create_mcp
|
||||
---
|
||||
|
||||
# Anti-Pattern Engine Maintenance
|
||||
|
||||
This agent handles every step of adding or modifying an anti-pattern detection rule in the impeccable repo. The rule engine is wired into many places — tests, browser bundle, extension detector, extension panel JSON, homepage count, and the skill content — and missing a step causes silent drift between them.
|
||||
|
||||
## The five things that need to stay in sync
|
||||
|
||||
When you add a rule, all of these update or get regenerated:
|
||||
|
||||
| Where | What | How it stays in sync |
|
||||
|---|---|---|
|
||||
| `src/detect-antipatterns.mjs` `ANTIPATTERNS` | Rule metadata (id, category, name, description, skillSection, skillGuideline) and the detection logic (`checkXxx`) | **Hand-edited.** Source of truth. |
|
||||
| `src/detect-antipatterns-browser.js` | Browser-bundled engine for the public site overlay | Generated by `bun run build:browser` |
|
||||
| `extension/detector/detect.js` | Browser-bundled engine for the Chrome extension | Generated by `bun run build:extension` |
|
||||
| `extension/detector/antipatterns.json` | Rule list (id, name, category, description) for the extension's devtools panel — drives rule toggles UI | Generated by `bun run build:extension` |
|
||||
| `public/js/generated/counts.js` | `DETECTION_COUNT` integer for homepage display | Generated by `bun run build` |
|
||||
| `source/skills/impeccable/SKILL.md` and `reference/*.md` | Design guidance that a human or LLM reads. Can reference anti-patterns in its own voice. | **Hand-edited**, alongside the rule. Drift is a code-review concern, not a programmatic one. |
|
||||
|
||||
The CLI (`bin/cli.js`) imports `ANTIPATTERNS` directly from `src/detect-antipatterns.mjs` — no separate sync needed.
|
||||
|
||||
## Rule schema
|
||||
|
||||
Each entry in the `ANTIPATTERNS` array (around src/detect-antipatterns.mjs:77) looks like this:
|
||||
|
||||
```js
|
||||
{
|
||||
id: 'icon-tile-stack', // kebab-case, unique, stable
|
||||
category: 'slop', // 'slop' or 'quality' (see below)
|
||||
name: 'Icon tile stacked above heading', // human-readable, used in extension UI
|
||||
description: // 1–2 sentences. Used in CLI output, extension tooltips, web overlay labels
|
||||
'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
|
||||
skillSection: 'Typography', // OPTIONAL. The logical skill section this rule maps to; used for /docs/impeccable deep-links.
|
||||
skillGuideline: 'large icons with rounded corners above every heading', // OPTIONAL. Canonical short phrasing for the rule; used in CLI output and as a linkable fragment.
|
||||
}
|
||||
```
|
||||
|
||||
### Categories
|
||||
|
||||
- **`slop`** = "AI tells". Patterns that scream *AI generated this*. Things like purple gradients, gradient text, dark glow accents, thick side borders, icon-tile-stacks. Flagging these is about taste and freshness, not correctness.
|
||||
- **`quality`** = real design or accessibility issues regardless of who wrote the code. WCAG contrast, line length, padding, line height, justified text, skipped headings, etc.
|
||||
|
||||
If you're not sure, ask: *"would a human designer who's careful and tasteful still ship this?"* If no, it's `quality`. If they would (because it works fine, it just looks templated), it's `slop`.
|
||||
|
||||
### `skillSection` values
|
||||
|
||||
The value is used by `scripts/build-sub-pages.js` to build deep links into the impeccable docs page. Use one of the logical sections the skill groups rules under (e.g. `Typography`, `Color`, `Layout`, `Motion`, `Visual Details`). If the section you pick matches an `### Heading` somewhere in the skill body, the deep link will land precisely; otherwise it falls back to the section's top. Omit entirely for rules that don't have a natural home in the skill.
|
||||
|
||||
### `skillGuideline` phrasing
|
||||
|
||||
Canonical short phrasing for the rule (3–6 words). Used as the CLI output label when `npx impeccable detect` reports a violation, and as human-readable text in the extension's devtools panel. The skill's prose may or may not echo this phrasing verbatim — the skill is the design-guidance document, not a rule manifest.
|
||||
|
||||
Examples: `'AI color palette'`, `'large icons with rounded corners above every heading'`, `'WCAG AA contrast'`.
|
||||
|
||||
Omit if the rule doesn't need a short label (rare — only niche a11y-only rules).
|
||||
|
||||
## The TDD recipe (always do it in this order)
|
||||
|
||||
This order is non-negotiable. Fixture and failing test before implementation. The full suite must run between the rule going in and you committing.
|
||||
|
||||
### 1. Write the fixture (two-column convention)
|
||||
|
||||
A single HTML file at `tests/fixtures/antipatterns/{rule-id}.html` with two columns: left = should-flag, right = should-pass. Each test case carries a unique heading text so the test can match snippets back to expectations.
|
||||
|
||||
Convention skeleton:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 32px; max-width: 960px; margin: 0 auto; padding: 24px; }
|
||||
.col h2 { font-size: 14px; text-transform: uppercase; }
|
||||
/* ... per-case styles with EXPLICIT pixel dimensions (jsdom can't lay out) ... */
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="grid">
|
||||
<div class="col" data-col="flag">
|
||||
<h2>Should flag</h2>
|
||||
<!-- 4–6 cases that should be flagged, each with a unique <h3> text -->
|
||||
</div>
|
||||
<div class="col" data-col="pass">
|
||||
<h2>Should pass</h2>
|
||||
<!-- 5–8 cases that should NOT be flagged: cover every false-positive shape you can think of -->
|
||||
</div>
|
||||
</div>
|
||||
<script src="/js/detect-antipatterns-browser.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
The script tag at the bottom is critical — it lets you load the fixture in the browser via `http://localhost:3000/fixtures/antipatterns/{rule-id}.html` (served by `server/index.js:62` route for `/fixtures/*`).
|
||||
|
||||
**Should-pass cases must cover the false-positive shapes you can think of in advance.** A good fixture has 5+ pass cases. The icon-tile-stack fixture covers: round avatar, wide thumbnail, side-by-side, no-icon, too-tiny, too-huge.
|
||||
|
||||
### 2. Write the failing test
|
||||
|
||||
Add to `tests/detect-antipatterns-fixtures.test.mjs` in its own `describe` block. Use the snippet-substring matching pattern — the test parses heading text out of each finding's snippet and asserts membership against expected lists:
|
||||
|
||||
```js
|
||||
describe('detectHtml — {rule-id}', () => {
|
||||
const SHOULD_FLAG = ['Heading One', 'Heading Two', /* ... */];
|
||||
const SHOULD_PASS = ['Pass Heading One', /* ... */];
|
||||
|
||||
it('{rule-id}: flags only the should-flag column', async () => {
|
||||
const f = await detectHtml(path.join(FIXTURES, '{rule-id}.html'));
|
||||
const flagged = new Set();
|
||||
for (const r of f) {
|
||||
if (r.antipattern !== '{rule-id}') continue;
|
||||
const m = (r.snippet || '').match(/"([^"]+)"/);
|
||||
if (m) flagged.add(m[1]);
|
||||
}
|
||||
for (const text of SHOULD_FLAG) {
|
||||
assert.ok(flagged.has(text), `expected "${text}" to be flagged`);
|
||||
}
|
||||
for (const text of SHOULD_PASS) {
|
||||
assert.ok(!flagged.has(text), `"${text}" should NOT be flagged`);
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
For this to work, the rule's snippet **must include the heading text in quotes**. See "Snippet conventions" below.
|
||||
|
||||
Run `node --test tests/detect-antipatterns-fixtures.test.mjs` and **watch it fail**. If it doesn't fail, your test is wrong.
|
||||
|
||||
### 3. Add the rule definition
|
||||
|
||||
Add a new entry to the `ANTIPATTERNS` array in `src/detect-antipatterns.mjs`. Place it in the right category section (slop or quality). Fill in all fields including `skillSection` and `skillGuideline`.
|
||||
|
||||
### 4. Implement the pure check function
|
||||
|
||||
Add a `checkXxx(opts)` function alongside the others (`checkColors`, `checkBorders`, `checkMotion`, `checkGlow`, `checkIconTile`, etc.). The pure function takes a plain options object — no DOM access — and returns an array of `{ id, snippet }`. This makes it testable and reusable across the browser/Node adapters.
|
||||
|
||||
Example shape (see `checkIconTile` in src/detect-antipatterns.mjs for a real one):
|
||||
|
||||
```js
|
||||
function checkXxx(opts) {
|
||||
const { tag, /* whatever fields the rule needs */ } = opts;
|
||||
if (SAFE_TAGS.has(tag)) return [];
|
||||
// ... your detection logic ...
|
||||
if (matches) {
|
||||
return [{ id: 'rule-id', snippet: `... "${headingText}"` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Add the two adapters
|
||||
|
||||
Two adapters wrap the pure function with environment-specific input gathering:
|
||||
|
||||
- **`checkElementXxxDOM(el)`** — for the browser. Uses `getComputedStyle(el)` and `el.getBoundingClientRect()`.
|
||||
- **`checkElementXxx(el, tag, window)`** — for jsdom (Node). Uses `window.getComputedStyle(el)` and **must read explicit pixel dimensions from `parseFloat(style.width)`** instead of bounding rects, because **jsdom does not lay out** — `getBoundingClientRect()` returns 0×0 for everything.
|
||||
|
||||
If your rule needs vertical positioning info (e.g. "icon must be above heading"), that check is browser-only — gate it behind `if (headingTop && siblingBottom)` so the Node path skips it. The structural checks alone (sizes, sibling identity, classes) are enough for the fixture.
|
||||
|
||||
### 6. Wire into both element-iteration loops
|
||||
|
||||
Two loops iterate every element on the page. You need to add your DOM-adapter call to **both**:
|
||||
|
||||
- **Browser loop** at src/detect-antipatterns.mjs:1837 (`for (const el of document.querySelectorAll('*'))` with the `findings` spread). Add a line like:
|
||||
```js
|
||||
...checkElementXxxDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
```
|
||||
- **Node (jsdom) loop** at src/detect-antipatterns.mjs:2058 (in `detectHtml`). Add a block like:
|
||||
```js
|
||||
for (const f of checkElementXxx(el, tag, window)) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
```
|
||||
|
||||
Forgetting one of these is the most common mistake — the test passes but the live page doesn't show anything (or vice versa).
|
||||
|
||||
### 7. Decide whether the skill needs an update
|
||||
|
||||
If the rule introduces a new design concept not already covered by the impeccable skill, update `source/skills/impeccable/SKILL.md` (or the appropriate register file in `reference/editorial.md` / `reference/product.md`) to teach the concept. The skill is a design-guidance document — it doesn't need to echo every rule verbatim, and one skill line can cover multiple engine rules. Only add prose if there's a real gap in the guidance.
|
||||
|
||||
### 8. Run the build (regenerates everything)
|
||||
|
||||
```bash
|
||||
bun run build && bun run build:browser && bun run build:extension
|
||||
```
|
||||
|
||||
This regenerates:
|
||||
- `src/detect-antipatterns-browser.js` (public-site detector)
|
||||
- `extension/detector/detect.js` (extension detector)
|
||||
- `extension/detector/antipatterns.json` (extension rule list, includes description)
|
||||
- `public/js/generated/counts.js` (DETECTION_COUNT)
|
||||
|
||||
### 9. Run the test suite
|
||||
|
||||
```bash
|
||||
bun run test
|
||||
```
|
||||
|
||||
166 unit tests + N fixture tests, including your new one. All should be green.
|
||||
|
||||
### 10. Verify on a live page in the browser
|
||||
|
||||
Don't skip this. The jsdom path uses `parseFloat(style.width)` and the browser path uses `getBoundingClientRect()` — they can disagree. The fixture test catches one path; manual browser verification catches the other.
|
||||
|
||||
```
|
||||
http://localhost:3000/fixtures/antipatterns/{rule-id}.html
|
||||
http://localhost:3000/antipattern-examples/{your-example}.html (if relevant)
|
||||
http://localhost:3000/ (no false positives on real pages)
|
||||
```
|
||||
|
||||
Use the chrome MCP tools (`mcp__claude-in-chrome__navigate` + `mcp__claude-in-chrome__javascript_tool`) to inject `window.impeccableScan()` and read `.impeccable-overlay` / `.impeccable-label` from the DOM to verify. Don't try to screenshot — the overlays are decorative; read them programmatically.
|
||||
|
||||
## Snippet conventions
|
||||
|
||||
The fixture-test convention extracts the heading text from a finding's snippet using regex `/"([^"]+)"/` — so **wrap the identifying heading text in straight double quotes** in your snippet. Examples:
|
||||
|
||||
- `'80x80px icon tile above h3 "Lightning Fast"'`
|
||||
- `'4.5:1 (need 4.5:1) — text #808080 on #3b82f6'` ← uses element identifiers instead, since this rule isn't anchored to a heading
|
||||
|
||||
If your rule isn't naturally anchored to a heading, pick another stable identifier (a class name, the parent element's text, etc.) and document the test pattern in the test itself.
|
||||
|
||||
## jsdom constraints (the most common gotcha)
|
||||
|
||||
- **No layout.** `getBoundingClientRect()` returns `0×0` always. Read `parseFloat(style.width)` and `parseFloat(style.height)` instead — jsdom does honor explicit pixel widths in `<style>` and inline styles.
|
||||
- **`background:` shorthand isn't decomposed.** `style.backgroundColor` and `style.backgroundImage` may be empty even when `style="background: ..."` is set. The existing `resolveBackground()` and `resolveGradientStops()` helpers (src/detect-antipatterns.mjs:631 and src/detect-antipatterns.mjs:670) handle this — use them.
|
||||
- **Computed colors are normalized in real browsers, not in jsdom.** A browser returns `rgb(59, 130, 246)`; jsdom may return the original hex. The `parseGradientColors()` helper handles both.
|
||||
- **No SAFE_TAGS skipping for parent walks.** When walking ancestors, you don't get the `SAFE_TAGS` filter the main loop applies — be explicit.
|
||||
|
||||
## Where to find concrete example rules to learn from
|
||||
|
||||
- Simplest border check: **`side-tab`** — `checkBorders()` at src/detect-antipatterns.mjs:312
|
||||
- Color/contrast with gradient handling: **`low-contrast`** — `checkColors()` at src/detect-antipatterns.mjs:339
|
||||
- Element-relationship check (siblings): **`icon-tile-stack`** — `checkIconTile()` at src/detect-antipatterns.mjs:425
|
||||
- Page-level / cross-element: **`flat-type-hierarchy`** — `checkPageTypography()` at src/detect-antipatterns.mjs:1080
|
||||
- Motion/animation: **`bounce-easing`** — `checkMotion()` at src/detect-antipatterns.mjs:425
|
||||
|
||||
## Pre-commit checklist
|
||||
|
||||
Before you commit a new rule:
|
||||
|
||||
- [ ] Test passes: `bun run test` is green
|
||||
- [ ] Build passes: `bun run build && bun run build:browser && bun run build:extension` is green
|
||||
- [ ] Live verification: rule fires on a real page and produces zero false positives on the homepage `http://localhost:3000/`
|
||||
- [ ] Both element loops were updated (browser DOM at line ~1846 + Node jsdom at line ~2058)
|
||||
- [ ] Snippet format matches the test's extraction regex
|
||||
- [ ] Fixture covers ≥4 should-flag and ≥5 should-pass cases
|
||||
- [ ] Skill reviewed: if the rule introduces a new design concept, the relevant skill file teaches it
|
||||
- [ ] Commit only the relevant files — `git status` will show many unrelated stale skill builds; do not stage them
|
||||
|
||||
## Things that have bitten previous sessions
|
||||
|
||||
- **Forgot to run `bun run build:extension`** — extension JSON went stale, missing the new rule. Symptom: extension panel doesn't show toggle for new rule. Fix: always run all three build commands.
|
||||
- **Forgot to update both loops** — test passed in jsdom but live browser was silent (or vice versa). Fix: grep for an existing rule's adapter call and copy its placement.
|
||||
- **Wrote the fixture without explicit pixel dimensions** — jsdom returned 0×0 and the rule never matched. Fix: always set `width: Npx; height: Npx` in CSS for fixture elements, or use inline style attributes.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
---
|
||||
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
---
|
||||
|
||||
Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
---
|
||||
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
allowed-tools:
|
||||
- Bash(npx impeccable *)
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.0
|
||||
version: 3.0.2
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
@@ -4,17 +4,17 @@ Perform a meticulous final pass to catch all the small details that separate goo
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Before polishing, understand the system you are polishing toward:
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: color tokens, spacing scale, typography styles, component API.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established?
|
||||
3. **Identify drift**: Where does the target feature deviate from the system? Hard-coded values that should be tokens, custom components that duplicate shared ones, spacing that doesn't match the scale.
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish should align the feature with it. If none exists, polish against the conventions visible in the codebase.
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals:
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
@@ -22,13 +22,18 @@ Understand the current state and goals:
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Identify polish areas**:
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
@@ -50,6 +55,16 @@ Work through these dimensions methodically:
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
@@ -158,6 +173,8 @@ Every interactive element needs all states:
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
@@ -183,12 +200,15 @@ Go through systematically:
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
|
||||
@@ -149,13 +149,16 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
const replacement = [];
|
||||
|
||||
if (cssContent) {
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">');
|
||||
// JSX targets need the CSS body wrapped in a template literal so that the
|
||||
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
||||
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
||||
// Re-indent CSS content to match
|
||||
for (const cssLine of cssContent) {
|
||||
replacement.push(indent + cssLine.trimStart());
|
||||
}
|
||||
replacement.push(indent + '</style>');
|
||||
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
||||
if (paramValues && Object.keys(paramValues).length > 0) {
|
||||
// Preserve the user's knob positions for the carbonize-cleanup agent
|
||||
// to bake into the final CSS when it collapses scoped rules.
|
||||
@@ -169,8 +172,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
||||
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
||||
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
||||
// it moves the CSS to a proper stylesheet.
|
||||
//
|
||||
// Style attribute syntax has to follow the host file's flavor — JSX files
|
||||
// need the object form, otherwise React 19 throws "Failed to set indexed
|
||||
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
||||
if (cssContent) {
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" style="display: contents">');
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
||||
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
||||
replacement.push(...restored);
|
||||
replacement.push(indent + '</div>');
|
||||
} else {
|
||||
@@ -344,7 +353,11 @@ function extractCss(lines, block, id) {
|
||||
}
|
||||
|
||||
if (inStyle) {
|
||||
if (line.trimStart().startsWith('</style>')) break;
|
||||
// Detect </style> anywhere on the line — JSX template-literal closes
|
||||
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
||||
// template-literal punctuation as CSS content.
|
||||
const closeIdx = line.indexOf('</style>');
|
||||
if (closeIdx !== -1) break;
|
||||
content.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,45 @@
|
||||
|
||||
function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
|
||||
|
||||
// Modal-aware chrome: keep our floating UI clickable inside Radix /
|
||||
// Headless UI / vaul portals.
|
||||
//
|
||||
// Two host-page behaviors break us when the picked element lives inside a
|
||||
// modal dialog:
|
||||
//
|
||||
// 1. Modal scroll-lock disables outside pointer events. Radix's
|
||||
// `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
|
||||
// while a modal is open and only restores `auto` on the layer. Our
|
||||
// chrome inherits `none` from <body> and becomes unclickable.
|
||||
// 2. The dialog's outside-interaction handler (Radix's
|
||||
// `usePointerDownOutside`) listens at document level and dismisses
|
||||
// the dialog whenever a `pointerdown` lands outside the layer node.
|
||||
// Our chrome is a sibling of <body>, so Radix classifies our clicks
|
||||
// as outside and tears the dialog down mid-task.
|
||||
//
|
||||
// We can't reliably re-parent our chrome into the dialog subtree (z-index
|
||||
// stacking, scroll containers, theming all become host-page concerns), so
|
||||
// we defang both behaviors at our root:
|
||||
//
|
||||
// - `pointer-events: auto !important` overrides the inherited `none`.
|
||||
// - Stop `pointerdown` / `mousedown` propagation so the document-level
|
||||
// dismiss listener never fires for our clicks.
|
||||
// - Stop `focusin` propagation so any focus shifts inside our chrome
|
||||
// don't read as "focus moved outside the dialog" to focus traps.
|
||||
//
|
||||
// Click events still bubble normally — only the early pointer/focus
|
||||
// signals that drive outside-interaction detection are silenced.
|
||||
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
|
||||
if (!rootEl) return;
|
||||
if (setPointerEvents) {
|
||||
rootEl.style.setProperty('pointer-events', 'auto', 'important');
|
||||
}
|
||||
const stop = (e) => e.stopPropagation();
|
||||
rootEl.addEventListener('pointerdown', stop);
|
||||
rootEl.addEventListener('mousedown', stop);
|
||||
rootEl.addEventListener('focusin', stop);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Highlight overlay
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -336,6 +375,11 @@
|
||||
annotOverlayEl.addEventListener('pointerup', onAnnotUp);
|
||||
annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
|
||||
document.body.appendChild(annotOverlayEl);
|
||||
// Modal-host friendliness: pointer-events is already 'auto' on this
|
||||
// overlay; we only need to silence the host's outside-interaction
|
||||
// listeners. Don't override pointer-events here (the overlay toggles
|
||||
// visibility via display:none, which is fine).
|
||||
defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
|
||||
}
|
||||
|
||||
function updateClearChip() {
|
||||
@@ -811,6 +855,7 @@
|
||||
maxWidth: '520px', minWidth: '320px',
|
||||
});
|
||||
document.body.appendChild(barEl);
|
||||
defangOutsideHandlers(barEl);
|
||||
}
|
||||
|
||||
function positionBar() {
|
||||
@@ -905,7 +950,12 @@
|
||||
pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
|
||||
row.appendChild(pill);
|
||||
|
||||
// Freeform input
|
||||
// Freeform input. Focus state shows an accent-colored border only —
|
||||
// an earlier version tinted the background with `BP.accentSoft`, which
|
||||
// composited against the dark bar surface to a murky purple where the
|
||||
// browser's default placeholder gray was unreadable. Placeholder color
|
||||
// is set explicitly via a one-shot stylesheet keyed off this input's id
|
||||
// so it picks up the bar's `textDim` token in both themes.
|
||||
const input = document.createElement('input');
|
||||
input.id = PREFIX + '-input';
|
||||
input.type = 'text';
|
||||
@@ -916,15 +966,20 @@
|
||||
border: '1px solid transparent', background: 'transparent',
|
||||
fontFamily: FONT, fontSize: '12px', color: BP.text,
|
||||
outline: 'none',
|
||||
transition: 'border-color 0.15s ease, background 0.15s ease',
|
||||
transition: 'border-color 0.15s ease',
|
||||
});
|
||||
if (!document.getElementById(PREFIX + '-input-style')) {
|
||||
const s = document.createElement('style');
|
||||
s.id = PREFIX + '-input-style';
|
||||
s.textContent =
|
||||
'#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
input.addEventListener('focus', () => {
|
||||
input.style.borderColor = BP.hairline;
|
||||
input.style.background = BP.accentSoft;
|
||||
input.style.borderColor = BP.accent;
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
input.style.borderColor = 'transparent';
|
||||
input.style.background = 'transparent';
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
|
||||
@@ -1320,6 +1375,7 @@
|
||||
|
||||
pickerEl.appendChild(grid);
|
||||
document.body.appendChild(pickerEl);
|
||||
defangOutsideHandlers(pickerEl);
|
||||
|
||||
// Cache the palette on the picker so toggleActionPicker's state refresh
|
||||
// uses the same theme-aware colors when it repaints chips.
|
||||
@@ -1433,6 +1489,10 @@
|
||||
|
||||
paramsPanelEl.appendChild(paramsPanelBody);
|
||||
document.body.appendChild(paramsPanelEl);
|
||||
// Don't override pointer-events: the panel toggles between 'none' (closed,
|
||||
// click-through) and 'auto' (open) on its own. Just silence the host's
|
||||
// outside-interaction listeners while the panel is open.
|
||||
defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
|
||||
paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
|
||||
}
|
||||
|
||||
@@ -2011,7 +2071,16 @@
|
||||
for (const m of mutations) {
|
||||
if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
|
||||
if (n.nodeType !== 1) continue;
|
||||
// Direct hit: the added node itself is the wrapper or a variant.
|
||||
if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
|
||||
dominated = true; break;
|
||||
}
|
||||
// Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
|
||||
// a whole subtree where the wrapper is a descendant of the added
|
||||
// node. Without this check, the observer ignores those mutations
|
||||
// and the session stays in GENERATING forever.
|
||||
if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
|
||||
dominated = true; break;
|
||||
}
|
||||
}
|
||||
@@ -2126,17 +2195,20 @@
|
||||
}
|
||||
break;
|
||||
}
|
||||
// HMR didn't propagate in time. Give it a 2s grace window, then
|
||||
// reload the page. resumeSession counts variants off the rendered
|
||||
// DOM on load and transitions straight to CYCLING — reload is the
|
||||
// one universal recovery path: HTML, JSX/TSX, Vue, Svelte, static
|
||||
// servers, anything. We used to try DOMParser on the raw source,
|
||||
// but JSX expressions aren't valid HTML and the parse fails.
|
||||
// Variants are in source but not in the DOM yet. Common when the
|
||||
// picked element lived inside conditional render (closed modal,
|
||||
// hidden tab, a route the user navigated away from). The variant
|
||||
// MutationObserver stays armed and auto-transitions to CYCLING
|
||||
// the moment the wrapper actually mounts. Nudge the user toward
|
||||
// that path with a toast — better than the prior force-reload
|
||||
// which reset framework state and left the session stuck.
|
||||
setTimeout(() => {
|
||||
if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
|
||||
if (state !== 'GENERATING') return;
|
||||
saveSession();
|
||||
window.location.reload();
|
||||
showToast(
|
||||
"Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
|
||||
15000,
|
||||
);
|
||||
}, 2000);
|
||||
break;
|
||||
case 'error':
|
||||
@@ -2236,6 +2308,60 @@
|
||||
showBar('configure');
|
||||
startScrollTracking();
|
||||
maybePrefetchPage();
|
||||
maybeWarnConditionalAncestor(selectedElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface a brief, non-blocking heads-up when the picked element lives
|
||||
* inside a container whose visibility is gated by ephemeral state — modals,
|
||||
* collapsible panels, popovers, off-screen tab panels. If HMR remounts the
|
||||
* parent during generation (Vite Fast Refresh, SvelteKit page reload), the
|
||||
* variants land in source but stay invisible until the user re-opens the
|
||||
* container. Telling the user upfront is much friendlier than the silent
|
||||
* timeout-then-toast that they'd otherwise hit.
|
||||
*
|
||||
* Heuristic, intentionally narrow — only fires for unambiguous cases so
|
||||
* we don't cry wolf on every nested element.
|
||||
*/
|
||||
function maybeWarnConditionalAncestor(el) {
|
||||
let node = el?.parentElement;
|
||||
let depth = 0;
|
||||
while (node && depth < 12) {
|
||||
// 1. Active dialog / modal
|
||||
if (node.getAttribute && node.getAttribute('role') === 'dialog'
|
||||
&& node.getAttribute('aria-modal') === 'true') {
|
||||
showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 2. Common Radix / shadcn / headless-ui open-state attribute
|
||||
if (node.dataset && node.dataset.state === 'open') {
|
||||
showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
|
||||
return;
|
||||
}
|
||||
// 3. Tab panel — only meaningful when the page also shows ANOTHER
|
||||
// tab as selected. A single tabpanel with no tablist is just a static
|
||||
// section in disguise and isn't conditional.
|
||||
if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
|
||||
const list = document.querySelector('[role="tablist"]');
|
||||
if (list) {
|
||||
const tabs = list.querySelectorAll('[role="tab"]');
|
||||
if (tabs.length > 1) {
|
||||
showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Collapsible: aria-expanded sibling. Look for the trigger button.
|
||||
if (node.id) {
|
||||
const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
|
||||
if (trigger) {
|
||||
showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
|
||||
// Fire a lightweight prefetch event the first time the user selects an
|
||||
@@ -2694,7 +2820,13 @@ void main() {
|
||||
const img = document.createElement('img');
|
||||
img.src = URL.createObjectURL(blob);
|
||||
img.id = PREFIX + '-shader';
|
||||
Object.assign(img.style, canvas.style, { outline: '2px dashed ' + C.brand, outlineOffset: '-2px' });
|
||||
// Copy positioning via cssText. Object.assign across CSSStyleDeclaration
|
||||
// throws in modern Chromium because the source's indexed properties
|
||||
// (style[0], [1], ...) are read-only and the engine forbids writing
|
||||
// them on the destination.
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.style.outline = '2px dashed ' + C.brand;
|
||||
img.style.outlineOffset = '-2px';
|
||||
document.body.appendChild(img);
|
||||
shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
|
||||
return;
|
||||
@@ -2942,8 +3074,16 @@ void main() {
|
||||
|
||||
function showToast(message, duration) {
|
||||
if (toastEl) toastEl.remove();
|
||||
// Stack the toast above the global bar (which sits at bottom:14px) so
|
||||
// the two never overlap. Read the bar's actual rect — its height varies
|
||||
// with hover-expanded labels — and fall back to a sensible default
|
||||
// when the bar isn't mounted yet.
|
||||
const barRect = globalBarEl?.getBoundingClientRect();
|
||||
const barTopFromBottom = barRect && barRect.height > 0
|
||||
? Math.max(16, window.innerHeight - barRect.top + 12)
|
||||
: 16;
|
||||
toastEl = el('div', {
|
||||
position: 'fixed', bottom: '16px', left: '50%',
|
||||
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
|
||||
transform: 'translateX(-50%) translateY(8px)',
|
||||
background: C.ink, color: C.white,
|
||||
fontFamily: FONT, fontSize: '12px',
|
||||
@@ -3066,13 +3206,33 @@ void main() {
|
||||
// page bg. Used for screenshots and theme QA.
|
||||
const override = localStorage.getItem('impeccable-dev-theme');
|
||||
if (override === 'light' || override === 'dark') return override;
|
||||
const bg = getComputedStyle(document.body).backgroundColor
|
||||
|| getComputedStyle(document.documentElement).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (!m) return 'light';
|
||||
const [, r, g, b] = m;
|
||||
|
||||
// Walk body → html, taking the first opaque background. The browser's
|
||||
// default body / html background is `rgba(0, 0, 0, 0)`, which a naive
|
||||
// regex would read as black and mislabel a perfectly white page as
|
||||
// dark. Honoring alpha avoids that — and falling through to <html>
|
||||
// catches the common pattern of a bg only on <html> (or only on body).
|
||||
function readOpaque(el) {
|
||||
if (!el) return null;
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
|
||||
if (!m) return null;
|
||||
const alpha = m[4] == null ? 1 : parseFloat(m[4]);
|
||||
if (alpha < 0.5) return null; // transparent / nearly transparent → skip
|
||||
return [+m[1], +m[2], +m[3]];
|
||||
}
|
||||
|
||||
const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
|
||||
// Both transparent → fall back to the browser's effective canvas color.
|
||||
// White is the universal default; only one in a thousand sites swaps it
|
||||
// via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
|
||||
// us catch that case.
|
||||
if (!rgb) {
|
||||
return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
const [r, g, b] = rgb;
|
||||
// Perceptual luminance (Rec. 709)
|
||||
const L = (0.2126 * +r + 0.7152 * +g + 0.0722 * +b) / 255;
|
||||
const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
||||
return L > 0.55 ? 'light' : 'dark';
|
||||
} catch { return 'light'; }
|
||||
}
|
||||
@@ -3275,15 +3435,24 @@ void main() {
|
||||
});
|
||||
inner.appendChild(divider);
|
||||
|
||||
// Exit (subtle × on the right) — SVG for baseline-free centering
|
||||
// Exit × on the right — intentionally subtle (textDim at rest, text on
|
||||
// hover) so it sits behind the active toggles in visual hierarchy.
|
||||
//
|
||||
// Explicit padding + box-sizing here is load-bearing: a host page like
|
||||
// `button { padding: 0.5rem 1rem; }` (very common in resets) would
|
||||
// otherwise inflate this 24x24 button into 56x40 and push the SVG out
|
||||
// of the visible bar — the X stays invisible even though the styles in
|
||||
// DevTools look fine. Every other chrome button sets padding inline;
|
||||
// this one needed it too.
|
||||
const exitBtn = el('button', {
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: '26px', height: '26px', borderRadius: '6px',
|
||||
padding: '0', boxSizing: 'border-box',
|
||||
width: '24px', height: '24px', borderRadius: '6px',
|
||||
border: 'none', background: 'transparent',
|
||||
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
|
||||
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
|
||||
});
|
||||
exitBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><line x1="2.5" y1="2.5" x2="9.5" y2="9.5"/><line x1="9.5" y1="2.5" x2="2.5" y2="9.5"/></svg>';
|
||||
exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
|
||||
exitBtn.title = 'Exit live mode';
|
||||
exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
|
||||
exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
|
||||
@@ -3301,6 +3470,7 @@ void main() {
|
||||
});
|
||||
|
||||
document.body.appendChild(globalBarEl);
|
||||
defangOutsideHandlers(globalBarEl);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
globalBarEl.style.opacity = '1';
|
||||
@@ -3513,6 +3683,11 @@ void main() {
|
||||
designShadow.appendChild(root);
|
||||
|
||||
document.body.appendChild(designHost);
|
||||
// The host is pointer-events: none; the panel inside the shadow DOM
|
||||
// manages its own auto/none. Events bubble through the shadow boundary,
|
||||
// so attaching here silences host-page outside-interaction handlers
|
||||
// without touching the host's click-through behavior.
|
||||
defangOutsideHandlers(designHost, { setPointerEvents: false });
|
||||
|
||||
loadDesignPrefs();
|
||||
renderDesignChrome();
|
||||
@@ -4577,6 +4752,18 @@ void main() {
|
||||
// Check for an active session to resume (variant wrapper already in DOM after HMR)
|
||||
if (!resumeSession()) {
|
||||
console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
|
||||
// SvelteKit (and any framework that hydrates after HTML parse) may add
|
||||
// the variant wrapper AFTER init runs. Watch for it and retry resume
|
||||
// once it appears. Disconnect on first hit.
|
||||
const scout = new MutationObserver(() => {
|
||||
const wrapper = document.querySelector('[data-impeccable-variants]');
|
||||
if (!wrapper) return;
|
||||
scout.disconnect();
|
||||
if (resumeSession()) {
|
||||
console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
|
||||
}
|
||||
});
|
||||
scout.observe(document.body, { childList: true, subtree: true });
|
||||
} else {
|
||||
console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,15 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const updated = removeTag(content, config.commentSyntax);
|
||||
const detagged = removeTag(content, config.commentSyntax);
|
||||
const updated = revertCspMeta(detagged);
|
||||
if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, removed: true };
|
||||
return {
|
||||
file: relFile,
|
||||
removed: detagged !== content,
|
||||
cspReverted: updated !== detagged,
|
||||
};
|
||||
});
|
||||
console.log(JSON.stringify({ ok: true, results }));
|
||||
return;
|
||||
@@ -109,11 +114,18 @@ Output (JSON):
|
||||
const absFile = path.resolve(process.cwd(), relFile);
|
||||
if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
|
||||
const content = fs.readFileSync(absFile, 'utf-8');
|
||||
const withoutOld = removeTag(content, config.commentSyntax);
|
||||
const updated = insertTag(withoutOld, config, port);
|
||||
if (updated === withoutOld) return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
|
||||
const withTag = insertTag(withoutOld, config, port);
|
||||
if (withTag === withoutOld) {
|
||||
return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
|
||||
}
|
||||
const updated = patchCspMeta(withTag, port);
|
||||
fs.writeFileSync(absFile, updated, 'utf-8');
|
||||
return { file: relFile, inserted: true };
|
||||
return {
|
||||
file: relFile,
|
||||
inserted: true,
|
||||
cspPatched: updated !== withTag,
|
||||
};
|
||||
});
|
||||
const anyInserted = results.some((r) => r.inserted);
|
||||
console.log(JSON.stringify({ ok: anyInserted, port, results }));
|
||||
@@ -296,6 +308,121 @@ function removeTag(content, _syntax) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content-Security-Policy meta-tag patcher
|
||||
//
|
||||
// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
|
||||
// the cross-origin load of /live.js (and the SSE/POST connection back to
|
||||
// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
|
||||
//
|
||||
// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
|
||||
// and stash the original `content` value in a `data-impeccable-csp-original`
|
||||
// attribute (base64) so revert is exact.
|
||||
//
|
||||
// On remove: detect the marker attribute, decode it, restore the original
|
||||
// content value verbatim, drop the marker.
|
||||
//
|
||||
// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
|
||||
// shared helpers) is NOT patched here — those need framework-specific config
|
||||
// edits and are handled via the existing detect-csp.mjs reference output.
|
||||
// Only the in-source meta-tag form gets the auto-patch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
|
||||
|
||||
function findCspMetaTags(content) {
|
||||
const out = [];
|
||||
const tagRe = /<meta\s+([^>]*?)\/?>/gis;
|
||||
let m;
|
||||
while ((m = tagRe.exec(content)) !== null) {
|
||||
const attrs = m[1];
|
||||
if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
|
||||
out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getAttr(attrs, name) {
|
||||
const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
|
||||
const m = attrs.match(re);
|
||||
return m ? { quote: m[1], value: m[2], full: m[0] } : null;
|
||||
}
|
||||
|
||||
function appendOriginToDirective(csp, directive, origin) {
|
||||
const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
|
||||
const m = csp.match(re);
|
||||
if (m) {
|
||||
const tokens = m[4].trim().split(/\s+/);
|
||||
if (tokens.includes(origin)) return csp;
|
||||
return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
|
||||
}
|
||||
// Directive missing — add it. Use 'self' + origin so we don't inadvertently
|
||||
// narrow the policy compared to the default-src fallback (most users with
|
||||
// an explicit CSP have 'self' there).
|
||||
return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
|
||||
}
|
||||
|
||||
export function patchCspMeta(content, port) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
const origin = `http://localhost:${port}`;
|
||||
|
||||
// Walk last-to-first so prior splices don't invalidate later indices.
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const attrs = tag.attrs;
|
||||
if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
|
||||
const contentAttr = getAttr(attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
const original = contentAttr.value;
|
||||
let patched = original;
|
||||
patched = appendOriginToDirective(patched, 'script-src', origin);
|
||||
patched = appendOriginToDirective(patched, 'connect-src', origin);
|
||||
// The shader overlay during 'generating' creates a screenshot via
|
||||
// URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
|
||||
// those. Add `blob:` so the overlay doesn't throw a CSP violation.
|
||||
patched = appendOriginToDirective(patched, 'img-src', 'blob:');
|
||||
if (patched === original) continue;
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
|
||||
const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
|
||||
const newAttrs = attrs.replace(contentAttr.full, newContentAttr) + ' ' + marker;
|
||||
const newTag = tag.full.replace(attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function revertCspMeta(content) {
|
||||
const tags = findCspMetaTags(content);
|
||||
if (tags.length === 0) return content;
|
||||
|
||||
let result = content;
|
||||
for (let i = tags.length - 1; i >= 0; i--) {
|
||||
const tag = tags[i];
|
||||
const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
|
||||
if (!origAttr) continue;
|
||||
const contentAttr = getAttr(tag.attrs, 'content');
|
||||
if (!contentAttr) continue;
|
||||
|
||||
let originalValue;
|
||||
try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
|
||||
catch { continue; }
|
||||
|
||||
const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
|
||||
let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
|
||||
// Drop the marker attribute and any single space immediately preceding it.
|
||||
newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
|
||||
const newTag = tag.full.replace(tag.attrs, newAttrs);
|
||||
|
||||
result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auto-execute
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,3 +433,4 @@ if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs
|
||||
}
|
||||
|
||||
export { insertTag, removeTag, validateConfig, buildTagBlock };
|
||||
// patchCspMeta + revertCspMeta are exported above where they're defined.
|
||||
|
||||
@@ -15,6 +15,7 @@ If you load the Impeccable skill from `.agents/skills/impeccable/SKILL.md` (or a
|
||||
- `bun run rebuild` - clean and rebuild everything from scratch.
|
||||
- `bun test tests/build.test.js` - run a focused Bun test.
|
||||
- `bun run test` - run the full Bun + Node test suite.
|
||||
- `bun run test:live-e2e` - opt-in live-mode E2E against framework fixtures (~2 min; needs `npx playwright install chromium` once).
|
||||
- `bun run build:browser` / `bun run build:extension` - rebuild browser-specific bundles.
|
||||
|
||||
Run `bun run build` after changing anything in `source/`, transformer code, or user-facing counts.
|
||||
@@ -27,6 +28,25 @@ Use ESM, semicolons, and the existing two-space indentation style in JS, HTML, a
|
||||
|
||||
Tests use Bun’s test runner plus Node’s built-in `--test`. Name tests `*.test.js` or `*.test.mjs` and place new fixtures near the behavior they cover, usually under `tests/fixtures/`. Prefer targeted test runs while iterating, then finish with `bun run test`. If you change generated outputs or provider transforms, verify both source parsing and at least one affected provider path in `dist/`.
|
||||
|
||||
For changes to `source/skills/impeccable/scripts/live-*.{mjs,js}`, also run `bun run test:live-e2e` (kept out of the default suite because it does real `npm install` per fixture and boots framework dev servers). Scope to one fixture with `IMPECCABLE_E2E_ONLY=<fixture-name>` while iterating; pass `IMPECCABLE_E2E_DEBUG=1` for page-DOM and dev-server-log dumps on failure. Schema and authoring guide for new fixtures live in `tests/framework-fixtures/README.md`.
|
||||
|
||||
Set `IMPECCABLE_E2E_AGENT=llm` to swap the deterministic fake agent for a Claude-backed one (`tests/live-e2e/agents/llm-agent.mjs`, default Haiku 4.5, override via `IMPECCABLE_E2E_LLM_MODEL`). Requires `ANTHROPIC_API_KEY`; tests skip cleanly when it's unset. This path hits the API — use it for verification, not CI.
|
||||
|
||||
## Anti-pattern detection rules
|
||||
|
||||
`src/detect-antipatterns.mjs` is the source of truth for the rule engine. It feeds the CLI, the site overlay (`src/detect-antipatterns-browser.js`, regenerated by `bun run build:browser`), the Chrome extension (`extension/detector/`, regenerated by `bun run build:extension`), and the homepage `DETECTION_COUNT` in `public/js/generated/counts.js` (regenerated by `bun run build`). After any rule change run all three builds plus `bun run test` so nothing drifts.
|
||||
|
||||
TDD order is non-negotiable:
|
||||
|
||||
1. Add a fixture at `tests/fixtures/antipatterns/{rule-id}.html` with two columns (should-flag / should-pass), each case identified by a unique heading. ≥4 flag cases and ≥5 false-positive shapes. **Use explicit pixel dimensions in CSS** — jsdom does no layout.
|
||||
2. Add a failing test in `tests/detect-antipatterns-fixtures.test.mjs` using the snippet-substring pattern (regex `/"([^"]+)"/` against `SHOULD_FLAG` / `SHOULD_PASS` lists).
|
||||
3. Add the rule entry to the `ANTIPATTERNS` array (`id`, `category` = `slop` or `quality`, `name`, `description`, optional `skillSection` / `skillGuideline`).
|
||||
4. Implement a pure `checkXxx(opts)` returning `[{ id, snippet }]` — no DOM access inside.
|
||||
5. Add two adapters that wrap the pure check: `checkElementXxxDOM(el)` for the browser (`getComputedStyle` + `getBoundingClientRect`) and `checkElementXxx(el, tag, window)` for jsdom (`parseFloat(style.width)` instead of layout). Wire **both** adapters into **both** element loops in `src/detect-antipatterns.mjs` (browser loop ~line 1837, jsdom loop in `detectHtml` ~line 2058). Forgetting one is the most common mistake.
|
||||
6. Verify on a live page at `http://localhost:3000/fixtures/antipatterns/{rule-id}.html` and on the homepage. The two adapter paths can disagree.
|
||||
|
||||
Conventions: wrap the identifying heading text in straight double quotes inside snippets so the fixture test can extract it. jsdom-specific helpers `resolveBackground()`, `resolveGradientStops()`, and `parseGradientColors()` exist because `background:` shorthand isn't decomposed and computed colors aren't normalized in jsdom — use them. Reference rules to copy from: `side-tab` (border), `low-contrast` (color+gradient), `icon-tile-stack` (sibling relationship), `flat-type-hierarchy` (page-level).
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
|
||||
Recent history favors short, imperative subjects such as `Fix: ...`, `Add ...`, `Improve ...`, or `Bump ...`. Keep commits focused and explain the user-facing impact when it is not obvious. PRs should summarize what changed, list validation performed, and call out regenerated artifacts like `dist/` or `build/`. Include screenshots for visible `public/` changes and mention affected providers when transform behavior changes.
|
||||
|
||||
@@ -104,13 +104,34 @@ Local state files inside harness directories (e.g. `.claude/scheduled_tasks.lock
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
bun run test # Run all tests
|
||||
bun run test # Default suite: unit + static framework fixtures
|
||||
bun run test:live-e2e # Opt-in: full-cycle live-mode E2E across framework fixtures
|
||||
```
|
||||
|
||||
Unit tests (build orchestration, detector logic) run via `bun test`. Fixture tests (jsdom-based HTML detection) run via `node --test` because bun is too slow with jsdom. The `test` script handles this split automatically.
|
||||
|
||||
**Important:** `tests/build.test.js` uses `spyOn(transformers, 'transformCursor')` with the named exports from `scripts/lib/transformers/index.js`. Those named exports (`transformCursor`, `transformClaudeCode`, etc.) are kept specifically for test spying, even though `build.js` itself uses `createTransformer + PROVIDERS` directly. **Do not delete them as "dead code"** — I made that mistake once and broke 8 tests.
|
||||
|
||||
### Live-mode E2E
|
||||
|
||||
`tests/live-e2e.test.mjs` drives the entire user flow (handshake → pick → Go → cycle → accept → carbonize cleanup) against every fixture in `tests/framework-fixtures/` that declares a `runtime` block. Each fixture installs real deps, boots its framework dev server (Vite, Next, SvelteKit, Astro, Nuxt static), and runs Playwright Chromium against a deterministic fake agent that produces realistic variants in the exact format `reference/live.md` describes.
|
||||
|
||||
```bash
|
||||
bun run test:live-e2e # full suite, ~2 min, 19 fixtures
|
||||
IMPECCABLE_E2E_ONLY=vite8-react-modal bun run test:live-e2e # scope to one fixture
|
||||
IMPECCABLE_E2E_DEBUG=1 bun run test:live-e2e # dump page DOM + dev-server tail on failure
|
||||
```
|
||||
|
||||
**One-time setup**: `npx playwright install chromium` (the suite uses a specific Chromium build keyed to the bundled Playwright version).
|
||||
|
||||
**Kept out of the default `bun run test`** because (a) it does real `npm install` per fixture, (b) it boots framework dev servers, (c) wall time is ~2 minutes, and (d) it requires Playwright's browser cache. Run it locally before shipping changes to anything in `source/skills/impeccable/scripts/live-*.{mjs,js}`.
|
||||
|
||||
The agent is pluggable via a one-method interface in `tests/live-e2e/agent.mjs`: `generateVariants(event, context) → { scopedCss, variants[] }`. The default fake agent emits canned variants that exercise all three param kinds (`range`, `steps`, `toggle`). The orchestrator (wrap, write, accept, carbonize) is agent-agnostic.
|
||||
|
||||
**LLM agent (opt-in)**: set `IMPECCABLE_E2E_AGENT=llm` to swap the fake agent for `tests/live-e2e/agents/llm-agent.mjs`, which calls Claude (default Haiku 4.5) via `@anthropic-ai/sdk`. Requires `ANTHROPIC_API_KEY` in env; the test runner skips with a clear message when it's unset. Override the model with `IMPECCABLE_E2E_LLM_MODEL=claude-sonnet-4-6` if Haiku produces unreliable JSON. Caching is on — live.md is the cacheable prefix, and after the first call subsequent fixtures pay only the cache-read rate. Pass rate on a typical sweep is 18/19; the modal fixture's intrinsic state-loss flake is amplified by LLM latency and may need a re-run. **This path hits the API and costs money** — keep it out of CI unless you really want it there.
|
||||
|
||||
Adding a new fixture is a matter of cloning a directory under `tests/framework-fixtures/`, swapping the source files, and writing a `fixture.json`. See `tests/framework-fixtures/README.md` for the full schema.
|
||||
|
||||
## CLI
|
||||
|
||||
The CLI lives in this repo under `bin/` and `src/`. Published to npm as `impeccable`.
|
||||
@@ -194,6 +215,42 @@ The tagline is used by UI surfaces (magazine spread, docs cards) that need a sho
|
||||
|
||||
Every command should have an editorial file eventually, but the build does not require one: commands without editorials fall back to the frontmatter description.
|
||||
|
||||
## Adding or modifying anti-pattern detection rules
|
||||
|
||||
`src/detect-antipatterns.mjs` is the source of truth for the rule engine. It powers the CLI, the public-site overlay, the Chrome extension, and the homepage rule count. Five places stay in sync:
|
||||
|
||||
| Where | How it stays in sync |
|
||||
|---|---|
|
||||
| `src/detect-antipatterns.mjs` (`ANTIPATTERNS` array + `checkXxx` logic) | Hand-edited |
|
||||
| `src/detect-antipatterns-browser.js` | `bun run build:browser` |
|
||||
| `extension/detector/detect.js` + `extension/detector/antipatterns.json` | `bun run build:extension` |
|
||||
| `public/js/generated/counts.js` (`DETECTION_COUNT`) | `bun run build` |
|
||||
| `source/skills/impeccable/SKILL.md` and `reference/*.md` | Hand-edited if the rule introduces new design guidance |
|
||||
|
||||
Always run all three builds and the test suite after a rule change:
|
||||
|
||||
```bash
|
||||
bun run build && bun run build:browser && bun run build:extension && bun run test
|
||||
```
|
||||
|
||||
### TDD order (non-negotiable)
|
||||
|
||||
1. **Fixture** at `tests/fixtures/antipatterns/{rule-id}.html` with two columns (should-flag / should-pass), each case identified by a unique heading. Cover ≥4 flag cases and ≥5 false-positive shapes. Use **explicit pixel dimensions in CSS** because jsdom does no layout.
|
||||
2. **Failing test** in `tests/detect-antipatterns-fixtures.test.mjs` using the snippet-substring pattern (regex `/"([^"]+)"/` against `SHOULD_FLAG` / `SHOULD_PASS` lists). Run it and watch it fail before implementing.
|
||||
3. **Rule entry** in the `ANTIPATTERNS` array: `id`, `category` (`slop` for AI tells, `quality` for real design or a11y issues), `name`, `description`, optional `skillSection` and `skillGuideline`.
|
||||
4. **Pure check function** `checkXxx(opts)` returning `[{ id, snippet }]`. No DOM access in the pure function.
|
||||
5. **Two adapters**: `checkElementXxxDOM(el)` for the browser (`getComputedStyle` + `getBoundingClientRect`) and `checkElementXxx(el, tag, window)` for jsdom (`parseFloat(style.width)` instead of layout). Wire **both** into **both** element loops in `src/detect-antipatterns.mjs` — the browser loop (~line 1837) and the jsdom loop in `detectHtml` (~line 2058). Forgetting one is the most common mistake; symptom is "test passes, live page silent" or vice versa.
|
||||
6. **Verify on a live page**: `http://localhost:3000/fixtures/antipatterns/{rule-id}.html` and the homepage (no false positives). The two adapter paths can disagree, so manual browser checks catch what the fixture test can't.
|
||||
|
||||
### Conventions and jsdom gotchas
|
||||
|
||||
- **Snippet format**: wrap the identifying heading text in straight double quotes (e.g. `'icon tile above h3 "Lightning Fast"'`) so the fixture test can extract it. For rules not anchored to a heading, pick another stable identifier.
|
||||
- **jsdom doesn't lay out**: `getBoundingClientRect()` returns 0×0. Read `parseFloat(style.width)` and `parseFloat(style.height)` from explicit CSS instead.
|
||||
- **`background:` shorthand isn't decomposed in jsdom**: use the existing `resolveBackground()` and `resolveGradientStops()` helpers (~line 631 / 670).
|
||||
- **Computed colors aren't normalized in jsdom**: `parseGradientColors()` handles both hex and rgb forms.
|
||||
|
||||
Reference rules to copy from: `side-tab` (border, ~line 312), `low-contrast` (color + gradient, ~line 339), `icon-tile-stack` (sibling relationship, ~line 425), `flat-type-hierarchy` (page-level, ~line 1080).
|
||||
|
||||
## Evals Framework (separate private repo)
|
||||
|
||||
The eval framework lives in a separate private repo at `~/code/impeccable-evals/`. It measures whether the `/impeccable` skill improves or harms AI-generated frontend design by running the same brief through a model with and without the skill loaded.
|
||||
|
||||
@@ -5,31 +5,32 @@
|
||||
"": {
|
||||
"name": "vibe-design-plugins",
|
||||
"dependencies": {
|
||||
"jsdom": "^29.0.0",
|
||||
"marked": "^16.1.0",
|
||||
"jsdom": "29.0.0",
|
||||
"marked": "^16.4.2",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ai-sdk/anthropic": "^3.0.69",
|
||||
"@ai-sdk/anthropic": "^3.0.71",
|
||||
"@ai-sdk/openai": "^3.0.53",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.110",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.119",
|
||||
"@anthropic-ai/sdk": "^0.91.1",
|
||||
"@google/genai": "^1.50.1",
|
||||
"ai": "^6.0.162",
|
||||
"ai": "^6.0.168",
|
||||
"archiver": "^7.0.1",
|
||||
"modern-screenshot": "^4.7.0",
|
||||
"motion": "^12.38.0",
|
||||
"playwright": "^1.58.2",
|
||||
"wrangler": "^4.75.0",
|
||||
"playwright": "^1.59.1",
|
||||
"wrangler": "^4.85.0",
|
||||
"zod": "^4.3.6",
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"puppeteer": "^24.39.1",
|
||||
"puppeteer": "^24.42.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.69", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-LshR7X3pFugY0o41G2VKTmg1XoGpSl7uoYWfzk6zjVZLhCfeFiwgpOga+eTV4XY1VVpZwKVqRnkDbIL7K2eH5g=="],
|
||||
"@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.71", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-bUWOzrzR0gJKJO/PLGMR4uH2dqEgqGhrsCV+sSpk4KtOEnUQlfjZI/F7BFlqSvVpFbjdgYRRLysAeEZpJ6S1lg=="],
|
||||
|
||||
"@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.99", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23", "@vercel/oidc": "3.1.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-8/UuzFY8p+T8j4XP/9m841pUb5bhnFt8cecSnJpd2zhBttNZ6GbfjZTmsqnvM/RwJOvzIsdFULZrU+E9QFREsQ=="],
|
||||
"@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.104", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ZKX5n74io8VIRlhIMSLWVlvT3sXC8Z7cZ9GHuWBWZDVi96+62AIsWuLGvMfcBA1STYuSoDrp6rIziZmvrTq0TA=="],
|
||||
|
||||
"@ai-sdk/openai": ["@ai-sdk/openai@3.0.53", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Wld+Rbc05KaUn08uBt06eEuwcgalcIFtIl32Yp+GxuZXUQwOb6YeAuq+C6da4ch6BurFoqEaLemJVwjBb7x+PQ=="],
|
||||
|
||||
@@ -37,13 +38,31 @@
|
||||
|
||||
"@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.23", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-z8GlDaCmRSDlqkMF2f4/RFgWxdarvIbyuk+m6WXT1LYgsnGiXRJGTD2Z1+SDl3LqtFuRtGX1aghYvQLoHL/9pg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.2.110", "", { "dependencies": { "@anthropic-ai/sdk": "^0.81.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-pS7QlPcJwQU8a87F8qChKlmnjddt3smUi6X7WvSluD0kzt72jphCe30QmKKXPJnjW3SVHu12cu6SLzfYQrWwHg=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.2.119", "", { "dependencies": { "@anthropic-ai/sdk": "^0.81.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.2.119", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.2.119", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.2.119", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.2.119", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.2.119", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.2.119", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.2.119", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.2.119" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-6AvthpsaOTlkn514brSGOcCSLHDXODnU+ExN1O3CJCjxr5RBcmzR057C9EIM0G7IchnXsRfMZgRO1QKsjTXdbA=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.81.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-D4K5PvEV6wPiRtVlVsJHIUhHAmOZ6IT/I9rKlTf84gR7GyyAurPJK7z9BOf/AZqC5d1DhYQGJNKRmV+q8dGhgw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.2.119", "", { "os": "darwin", "cpu": "arm64" }, "sha512-kxnG37SZqUata2Jcp/YQ0n9Y7o/sinE/8LdG4ltM1gePh+z+0Mfa4vBUUTEBMBFth9PTovKoesIuVuyFpvO/Cw=="],
|
||||
|
||||
"@asamuzakjp/css-color": ["@asamuzakjp/css-color@5.0.1", "", { "dependencies": { "@csstools/css-calc": "^3.1.1", "@csstools/css-color-parser": "^4.0.2", "@csstools/css-parser-algorithms": "^4.0.0", "@csstools/css-tokenizer": "^4.0.0", "lru-cache": "^11.2.6" } }, "sha512-2SZFvqMyvboVV1d15lMf7XiI3m7SDqXUuKaTymJYLN6dSGadqp+fVojqJlVoMlbZnlTmu3S0TLwLTJpvBMO1Aw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.2.119", "", { "os": "darwin", "cpu": "x64" }, "sha512-9Aj8g3ELsmZuOFg17TCkikeg/Wt2ucVT8hOOPQUatzLd7BKhydrHLA0RP42nBpWECO1B/n/mPdQ4iS/LS3s2Fg=="],
|
||||
|
||||
"@asamuzakjp/dom-selector": ["@asamuzakjp/dom-selector@7.0.3", "", { "dependencies": { "@asamuzakjp/nwsapi": "^2.3.9", "bidi-js": "^1.0.3", "css-tree": "^3.2.1", "is-potential-custom-element-name": "^1.0.1", "lru-cache": "^11.2.7" } }, "sha512-Q6mU0Z6bfj6YvnX2k9n0JxiIwrCFN59x/nWmYQnAqP000ruX/yV+5bp/GRcF5T8ncvfwJQ7fgfP74DlpKExILA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.2.119", "", { "os": "linux", "cpu": "arm64" }, "sha512-v3o464XkiYehp/OKidQQirxdVb+aGSvdJvHF2zH9p33W8M/NC21zwwh4dhwDnKsyrtBIgkt2CcMwzIl30r0OtA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.2.119", "", { "os": "linux", "cpu": "arm64" }, "sha512-IPGWgtz+gGnD7fxKAvSf913EUT/lYBTBE8EZ7lh3+x5ZP2859LWLmrCm053Lf3nMWo/CWikZsVPwkDVwpz6tIQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.2.119", "", { "os": "linux", "cpu": "x64" }, "sha512-9ePt4ZN+hsqDw4AgS4KtcWIGKfL9Oq28kwkrTER/QAcSrVKxiLonp81cCLzg7Ok/IUJu4Cfd71GZbFv/WE54zw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.2.119", "", { "os": "linux", "cpu": "x64" }, "sha512-QYxFNAe4FFridPkKhGlNcNBJ0TaIygWYyvfI9g4kX0i+RVbresUWuZVkWY06ioJ0fXoixFJ+HNQBMB7dLrIp8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.2.119", "", { "os": "win32", "cpu": "arm64" }, "sha512-p/TjcKQvkCYtXGPlR+mdyNwqCmvRcQL34Wtq0yUZ+iqmI/eyCe59IJ3AZrE0EZoqmiAevEYzatPIt9sncC9uxw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.2.119", "", { "os": "win32", "cpu": "x64" }, "sha512-k98Ju0wtktm6FhqTE/cXlVr6K4kGqBolVjEGzeKkW6ZILc7124euwNapAvkQCwMAavAxS/ZnO3jdKMtHtwTVTA=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.91.1", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw=="],
|
||||
|
||||
"@asamuzakjp/css-color": ["@asamuzakjp/css-color@5.1.11", "", { "dependencies": { "@asamuzakjp/generational-cache": "^1.0.1", "@csstools/css-calc": "^3.2.0", "@csstools/css-color-parser": "^4.1.0", "@csstools/css-parser-algorithms": "^4.0.0", "@csstools/css-tokenizer": "^4.0.0" } }, "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg=="],
|
||||
|
||||
"@asamuzakjp/dom-selector": ["@asamuzakjp/dom-selector@7.1.1", "", { "dependencies": { "@asamuzakjp/generational-cache": "^1.0.1", "@asamuzakjp/nwsapi": "^2.3.9", "bidi-js": "^1.0.3", "css-tree": "^3.2.1", "is-potential-custom-element-name": "^1.0.1" } }, "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ=="],
|
||||
|
||||
"@asamuzakjp/generational-cache": ["@asamuzakjp/generational-cache@1.0.1", "", {}, "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg=="],
|
||||
|
||||
"@asamuzakjp/nwsapi": ["@asamuzakjp/nwsapi@2.3.9", "", {}, "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q=="],
|
||||
|
||||
@@ -57,29 +76,29 @@
|
||||
|
||||
"@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.4.2", "", {}, "sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ=="],
|
||||
|
||||
"@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.15.0", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": "1.20260301.1 || ~1.20260302.1 || ~1.20260303.1 || ~1.20260304.1 || >1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-EGYmJaGZKWl+X8tXxcnx4v2bOZSjQeNI5dWFeXivgX9+YCT69AkzHHwlNbVpqtEUTbew8eQurpyOpeN8fg00nw=="],
|
||||
"@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.1", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw=="],
|
||||
|
||||
"@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260317.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-8hjh3sPMwY8M/zedq3/sXoA2Q4BedlGufn3KOOleIG+5a4ReQKLlUah140D7J6zlKmYZAFMJ4tWC7hCuI/s79g=="],
|
||||
"@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260424.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-yFR1XaJbSDLg/qbwtrYaU2xwFXatIPKR5nrMQCN1q/m6+Qe/j6r+kCnFEvOJjMZOm9iCKsE6Qly5clgl4u32qw=="],
|
||||
|
||||
"@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260317.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-M/MnNyvO5HMgoIdr3QHjdCj2T1ki9gt0vIUnxYxBu9ISXS/jgtMl6chUVPJ7zHYBn9MyYr8ByeN6frjYxj0MGg=="],
|
||||
"@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260424.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LqWKcE7x/9KyC2iQvKPeb20hKST3dYXDZlYTvFymgR1DfLS0OFOCzVGTloVNd7WqvK4SkdzBYfxo7QMIAeBK0w=="],
|
||||
|
||||
"@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260317.1", "", { "os": "linux", "cpu": "x64" }, "sha512-1ltuEjkRcS3fsVF7CxsKlWiRmzq2ZqMfqDN0qUOgbUwkpXsLVJsXmoblaLf5OP00ELlcgF0QsN0p2xPEua4Uug=="],
|
||||
"@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260424.1", "", { "os": "linux", "cpu": "x64" }, "sha512-YlEBFbAYZHe/ylzl8WEYQEU/jr+0XMqXaST2oBk5oVjksdb1NGuJaggluCdZAzuJJ8UqdTmyhY5u/qrasbiFWA=="],
|
||||
|
||||
"@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260317.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-3QrNnPF1xlaNwkHpasvRvAMidOvQs2NhXQmALJrEfpIJ/IDL2la8g499yXp3eqhG3hVMCB07XVY149GTs42Xtw=="],
|
||||
"@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260424.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-qJ0X0m6cL8fWDUPDg8K4IxYZXNJI6XbeOihqjnqKbAClrjdPDn8VUSd+z2XiCQ5NylMtMrpa/skC9UfaR6mh8g=="],
|
||||
|
||||
"@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260317.1", "", { "os": "win32", "cpu": "x64" }, "sha512-MfZTz+7LfuIpMGTa3RLXHX8Z/pnycZLItn94WRdHr8LPVet+C5/1Nzei399w/jr3+kzT4pDKk26JF/tlI5elpQ=="],
|
||||
"@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260424.1", "", { "os": "win32", "cpu": "x64" }, "sha512-tZ7Z9qmYNAP6z1/+8r/zKbk8F8DZmpmwNzMeN+zkde2Wnhfr3FBqOkJXT/5zmli8HPoWrIXxSiyqcNDMy8V2Zg=="],
|
||||
|
||||
"@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],
|
||||
|
||||
"@csstools/color-helpers": ["@csstools/color-helpers@6.0.2", "", {}, "sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q=="],
|
||||
|
||||
"@csstools/css-calc": ["@csstools/css-calc@3.1.1", "", { "peerDependencies": { "@csstools/css-parser-algorithms": "^4.0.0", "@csstools/css-tokenizer": "^4.0.0" } }, "sha512-HJ26Z/vmsZQqs/o3a6bgKslXGFAungXGbinULZO3eMsOyNJHeBBZfup5FiZInOghgoM4Hwnmw+OgbJCNg1wwUQ=="],
|
||||
"@csstools/css-calc": ["@csstools/css-calc@3.2.0", "", { "peerDependencies": { "@csstools/css-parser-algorithms": "^4.0.0", "@csstools/css-tokenizer": "^4.0.0" } }, "sha512-bR9e6o2BDB12jzN/gIbjHa5wLJ4UjD1CB9pM7ehlc0ddk6EBz+yYS1EV2MF55/HUxrHcB/hehAyt5vhsA3hx7w=="],
|
||||
|
||||
"@csstools/css-color-parser": ["@csstools/css-color-parser@4.0.2", "", { "dependencies": { "@csstools/color-helpers": "^6.0.2", "@csstools/css-calc": "^3.1.1" }, "peerDependencies": { "@csstools/css-parser-algorithms": "^4.0.0", "@csstools/css-tokenizer": "^4.0.0" } }, "sha512-0GEfbBLmTFf0dJlpsNU7zwxRIH0/BGEMuXLTCvFYxuL1tNhqzTbtnFICyJLTNK4a+RechKP75e7w42ClXSnJQw=="],
|
||||
"@csstools/css-color-parser": ["@csstools/css-color-parser@4.1.0", "", { "dependencies": { "@csstools/color-helpers": "^6.0.2", "@csstools/css-calc": "^3.2.0" }, "peerDependencies": { "@csstools/css-parser-algorithms": "^4.0.0", "@csstools/css-tokenizer": "^4.0.0" } }, "sha512-U0KhLYmy2GVj6q4T3WaAe6NPuFYCPQoE3b0dRGxejWDgcPp8TP7S5rVdM5ZrFaqu4N67X8YaPBw14dQSYx3IyQ=="],
|
||||
|
||||
"@csstools/css-parser-algorithms": ["@csstools/css-parser-algorithms@4.0.0", "", { "peerDependencies": { "@csstools/css-tokenizer": "^4.0.0" } }, "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w=="],
|
||||
|
||||
"@csstools/css-syntax-patches-for-csstree": ["@csstools/css-syntax-patches-for-csstree@1.1.1", "", { "peerDependencies": { "css-tree": "^3.2.1" }, "optionalPeers": ["css-tree"] }, "sha512-BvqN0AMWNAnLk9G8jnUT77D+mUbY/H2b3uDTvg2isJkHaOufUE2R3AOwxWo7VBQKT1lOdwdvorddo2B/lk64+w=="],
|
||||
"@csstools/css-syntax-patches-for-csstree": ["@csstools/css-syntax-patches-for-csstree@1.1.3", "", { "peerDependencies": { "css-tree": "^3.2.1" }, "optionalPeers": ["css-tree"] }, "sha512-SH60bMfrRCJF3morcdk57WklujF4Jr/EsQUzqkarfHXEFcAR1gg7fS/chAE922Sehgzc1/+Tz5H3Ypa1HiEKrg=="],
|
||||
|
||||
"@csstools/css-tokenizer": ["@csstools/css-tokenizer@4.0.0", "", {}, "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA=="],
|
||||
|
||||
@@ -249,7 +268,7 @@
|
||||
|
||||
"@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
|
||||
|
||||
"@vercel/oidc": ["@vercel/oidc@3.1.0", "", {}, "sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w=="],
|
||||
"@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],
|
||||
|
||||
"abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],
|
||||
|
||||
@@ -257,7 +276,7 @@
|
||||
|
||||
"agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
|
||||
|
||||
"ai": ["ai@6.0.162", "", { "dependencies": { "@ai-sdk/gateway": "3.0.99", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-1PSvNEK1PEbpUXahnFrcey6l7DJXMVWmg0ibQ8h8oMSe9V1Vx5d+R3xNu0hzBtwqfxYj21ddZo+EUYVs6GOEyA=="],
|
||||
"ai": ["ai@6.0.168", "", { "dependencies": { "@ai-sdk/gateway": "3.0.104", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-2HqCJuO+1V2aV7vfYs5LFEUfxbkGX+5oa54q/gCCTL7KLTdbxcCu5D7TdLA5kwsrs3Szgjah9q6D9tpjHM3hUQ=="],
|
||||
|
||||
"ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
|
||||
|
||||
@@ -367,7 +386,7 @@
|
||||
|
||||
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
|
||||
|
||||
"devtools-protocol": ["devtools-protocol@0.0.1581282", "", {}, "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ=="],
|
||||
"devtools-protocol": ["devtools-protocol@0.0.1595872", "", {}, "sha512-kRfgp8vWVjBu/fbYCiVFiOqsCk3CrMKEo3WbgGT2NXK2dG7vawWPBljixajVgGK9II8rDO9G0oD0zLt3I1daRg=="],
|
||||
|
||||
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
@@ -383,7 +402,7 @@
|
||||
|
||||
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
|
||||
|
||||
"entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
|
||||
"entities": ["entities@8.0.0", "", {}, "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA=="],
|
||||
|
||||
"env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
|
||||
|
||||
@@ -557,7 +576,7 @@
|
||||
|
||||
"long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
|
||||
|
||||
"lru-cache": ["lru-cache@11.2.7", "", {}, "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA=="],
|
||||
"lru-cache": ["lru-cache@11.3.5", "", {}, "sha512-NxVFwLAnrd9i7KUBxC4DrUhmgjzOs+1Qm50D3oF1/oL+r1NpZ4gA7xvG0/zJ8evR7zIKn4vLf7qTNduWFtCrRw=="],
|
||||
|
||||
"marked": ["marked@16.4.2", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA=="],
|
||||
|
||||
@@ -573,7 +592,7 @@
|
||||
|
||||
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
|
||||
|
||||
"miniflare": ["miniflare@4.20260317.0", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "^0.34.5", "undici": "7.24.4", "workerd": "1.20260317.1", "ws": "8.18.0", "youch": "4.1.0-beta.10" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-xuwk5Kjv+shi5iUBAdCrRl9IaWSGnTU8WuTQzsUS2GlSDIMCJuu8DiF/d9ExjMXYiQG5ml+k9SVKnMj8cRkq0w=="],
|
||||
"miniflare": ["miniflare@4.20260424.0", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "^0.34.5", "undici": "7.24.8", "workerd": "1.20260424.1", "ws": "8.18.0", "youch": "4.1.0-beta.10" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-B6MKBBd5TJ19daUc3Ae9rWctn1nDA/VCXykXfCsp9fTxyfGxnZY27tJs1caxgE9MWEMMKGbGHouqVtgKbKGxmw=="],
|
||||
|
||||
"minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
|
||||
|
||||
@@ -621,7 +640,7 @@
|
||||
|
||||
"parse-json": ["parse-json@5.2.0", "", { "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg=="],
|
||||
|
||||
"parse5": ["parse5@8.0.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA=="],
|
||||
"parse5": ["parse5@8.0.1", "", { "dependencies": { "entities": "^8.0.0" } }, "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw=="],
|
||||
|
||||
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
|
||||
|
||||
@@ -639,9 +658,9 @@
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"playwright": ["playwright@1.58.2", "", { "dependencies": { "playwright-core": "1.58.2" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A=="],
|
||||
"playwright": ["playwright@1.59.1", "", { "dependencies": { "playwright-core": "1.59.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw=="],
|
||||
|
||||
"playwright-core": ["playwright-core@1.58.2", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg=="],
|
||||
"playwright-core": ["playwright-core@1.59.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg=="],
|
||||
|
||||
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
|
||||
|
||||
@@ -661,9 +680,9 @@
|
||||
|
||||
"punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
|
||||
|
||||
"puppeteer": ["puppeteer@24.39.1", "", { "dependencies": { "@puppeteer/browsers": "2.13.0", "chromium-bidi": "14.0.0", "cosmiconfig": "^9.0.0", "devtools-protocol": "0.0.1581282", "puppeteer-core": "24.39.1", "typed-query-selector": "^2.12.1" }, "bin": { "puppeteer": "lib/cjs/puppeteer/node/cli.js" } }, "sha512-68Zc9QpcVvfxp2C+3UL88TyUogEAn5tSylXidbEuEXvhiqK1+v65zeBU5ubinAgEHMGr3dcSYqvYrGtdzsPI3w=="],
|
||||
"puppeteer": ["puppeteer@24.42.0", "", { "dependencies": { "@puppeteer/browsers": "2.13.0", "chromium-bidi": "14.0.0", "cosmiconfig": "^9.0.0", "devtools-protocol": "0.0.1595872", "puppeteer-core": "24.42.0", "typed-query-selector": "^2.12.1" }, "bin": { "puppeteer": "lib/cjs/puppeteer/node/cli.js" } }, "sha512-94MoPfFp2eY3eYIMdINkez4IOP5TMHntlZbVx06fHlQTtiQiYgaY0L2Zzfod8PVUkPqP7m3Qlre2v8YS8cudPA=="],
|
||||
|
||||
"puppeteer-core": ["puppeteer-core@24.39.1", "", { "dependencies": { "@puppeteer/browsers": "2.13.0", "chromium-bidi": "14.0.0", "debug": "^4.4.3", "devtools-protocol": "0.0.1581282", "typed-query-selector": "^2.12.1", "webdriver-bidi-protocol": "0.4.1", "ws": "^8.19.0" } }, "sha512-AMqQIKoEhPS6CilDzw0Gd1brLri3emkC+1N2J6ZCCuY1Cglo56M63S0jOeBZDQlemOiRd686MYVMl9ELJBzN3A=="],
|
||||
"puppeteer-core": ["puppeteer-core@24.42.0", "", { "dependencies": { "@puppeteer/browsers": "2.13.0", "chromium-bidi": "14.0.0", "debug": "^4.4.3", "devtools-protocol": "0.0.1595872", "typed-query-selector": "^2.12.1", "webdriver-bidi-protocol": "0.4.1", "ws": "^8.19.0" } }, "sha512-T4zXokk/izH01fYPhyyev1A4piWiOKrYq7CUFpdoYQxmOnXoV6YjUabmfIjCYkNspSoAXIxRid3Tw+Vg0fthYg=="],
|
||||
|
||||
"qs": ["qs@6.15.1", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg=="],
|
||||
|
||||
@@ -769,7 +788,7 @@
|
||||
|
||||
"typed-query-selector": ["typed-query-selector@2.12.1", "", {}, "sha512-uzR+FzI8qrUEIu96oaeBJmd9E7CFEiQ3goA5qCVgc4s5llSubcfGHq9yUstZx/k4s9dXHVKsE35YWoFyvEqEHA=="],
|
||||
|
||||
"undici": ["undici@7.24.4", "", {}, "sha512-BM/JzwwaRXxrLdElV2Uo6cTLEjhSb3WXboncJamZ15NgUURmvlXvxa6xkwIOILIjPNo9i8ku136ZvWV0Uly8+w=="],
|
||||
"undici": ["undici@7.25.0", "", {}, "sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ=="],
|
||||
|
||||
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
|
||||
|
||||
@@ -795,9 +814,9 @@
|
||||
|
||||
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"workerd": ["workerd@1.20260317.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260317.1", "@cloudflare/workerd-darwin-arm64": "1.20260317.1", "@cloudflare/workerd-linux-64": "1.20260317.1", "@cloudflare/workerd-linux-arm64": "1.20260317.1", "@cloudflare/workerd-windows-64": "1.20260317.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-ZuEq1OdrJBS+NV+L5HMYPCzVn49a2O60slQiiLpG44jqtlOo+S167fWC76kEXteXLLLydeuRrluRel7WdOUa4g=="],
|
||||
"workerd": ["workerd@1.20260424.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260424.1", "@cloudflare/workerd-darwin-arm64": "1.20260424.1", "@cloudflare/workerd-linux-64": "1.20260424.1", "@cloudflare/workerd-linux-arm64": "1.20260424.1", "@cloudflare/workerd-windows-64": "1.20260424.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-oKsB0Xo/mfkYMdSACoS06XZg09VUK4rXwHfF/1t3P++sMbwzf4UHQvMO57+zxpEB2nVrY/ZkW0bYFGq4GdAFSQ=="],
|
||||
|
||||
"wrangler": ["wrangler@4.75.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.2", "@cloudflare/unenv-preset": "2.15.0", "blake3-wasm": "2.1.5", "esbuild": "0.27.3", "miniflare": "4.20260317.0", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260317.1" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260317.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-Efk1tcnm4eduBYpH1sSjMYydXMnIFPns/qABI3+fsbDrUk5GksNYX8nYGVP4sFygvGPO7kJc36YJKB5ooA7JAg=="],
|
||||
"wrangler": ["wrangler@4.85.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.2", "@cloudflare/unenv-preset": "2.16.1", "blake3-wasm": "2.1.5", "esbuild": "0.27.3", "miniflare": "4.20260424.0", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260424.1" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260424.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-93cwt2RPb1qdcmEgPzH7ybiLN4BIKoWpscIX6SywjHrQOeIZrQk2haoc3XMLKtQTmzapxza9OuDD+kMHpsuuhg=="],
|
||||
|
||||
"wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
|
||||
|
||||
@@ -829,6 +848,8 @@
|
||||
|
||||
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk/@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.81.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-D4K5PvEV6wPiRtVlVsJHIUhHAmOZ6IT/I9rKlTf84gR7GyyAurPJK7z9BOf/AZqC5d1DhYQGJNKRmV+q8dGhgw=="],
|
||||
|
||||
"@isaacs/cliui/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],
|
||||
|
||||
"@isaacs/cliui/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],
|
||||
@@ -843,6 +864,8 @@
|
||||
|
||||
"lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
|
||||
|
||||
"miniflare/undici": ["undici@7.24.8", "", {}, "sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ=="],
|
||||
|
||||
"miniflare/ws": ["ws@8.18.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="],
|
||||
|
||||
"path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
|
||||
|
||||
+11
-9
@@ -49,30 +49,32 @@
|
||||
"dev": "bun run server/index.js",
|
||||
"preview": "bun run build && wrangler pages dev",
|
||||
"deploy": "bun run build && wrangler pages deploy build/",
|
||||
"test": "bun test tests/build.test.js tests/detect-antipatterns.test.js && node --test tests/detect-antipatterns-fixtures.test.mjs && node --test tests/detect-antipatterns-browser.test.mjs && node --test tests/cleanup-deprecated.test.mjs && node --test tests/live-wrap.test.mjs && node --test tests/live-accept.test.mjs && node --test tests/live-inject.test.mjs && node --test tests/live-server.test.mjs && node --test tests/framework-fixtures.test.mjs",
|
||||
"test": "bun test tests/build.test.js tests/detect-antipatterns.test.js tests/windows-path-fix.test.js && node --test tests/detect-antipatterns-fixtures.test.mjs && node --test tests/detect-antipatterns-browser.test.mjs && node --test tests/cleanup-deprecated.test.mjs && node --test tests/live-wrap.test.mjs && node --test tests/live-accept.test.mjs && node --test tests/live-inject.test.mjs && node --test tests/live-server.test.mjs && node --test tests/framework-fixtures.test.mjs",
|
||||
"test:live-e2e": "node --test --test-timeout=600000 tests/live-e2e.test.mjs",
|
||||
"prepack": "cp README.md README.repo.md && cp README.npm.md README.md",
|
||||
"postpack": "cp README.repo.md README.md && rm README.repo.md",
|
||||
"screenshot": "bun run scripts/screenshot-antipatterns.js",
|
||||
"og-image": "bun run scripts/generate-og-image.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"jsdom": "^29.0.0",
|
||||
"marked": "^16.1.0"
|
||||
"jsdom": "29.0.0",
|
||||
"marked": "^16.4.2"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"puppeteer": "^24.39.1"
|
||||
"puppeteer": "^24.42.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ai-sdk/anthropic": "^3.0.69",
|
||||
"@ai-sdk/anthropic": "^3.0.71",
|
||||
"@ai-sdk/openai": "^3.0.53",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.110",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.119",
|
||||
"@anthropic-ai/sdk": "^0.91.1",
|
||||
"@google/genai": "^1.50.1",
|
||||
"ai": "^6.0.162",
|
||||
"ai": "^6.0.168",
|
||||
"archiver": "^7.0.1",
|
||||
"modern-screenshot": "^4.7.0",
|
||||
"motion": "^12.38.0",
|
||||
"playwright": "^1.58.2",
|
||||
"wrangler": "^4.75.0",
|
||||
"playwright": "^1.59.1",
|
||||
"wrangler": "^4.85.0",
|
||||
"zod": "^4.3.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "impeccable",
|
||||
"description": "Design fluency for frontend development. 1 skill with 23 commands (/impeccable polish, /impeccable audit, /impeccable critique, etc.) and curated anti-pattern detection.",
|
||||
"version": "3.0.2",
|
||||
"author": {
|
||||
"name": "Paul Bakaus",
|
||||
"email": "paul@paulbakaus.com"
|
||||
},
|
||||
"homepage": "https://impeccable.style",
|
||||
"repository": "https://github.com/pbakaus/impeccable",
|
||||
"skills": "./skills/"
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
---
|
||||
name: impeccable
|
||||
description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
|
||||
version: 3.0.2
|
||||
user-invocable: true
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
|
||||
license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
|
||||
allowed-tools:
|
||||
- Bash(npx impeccable *)
|
||||
---
|
||||
|
||||
Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
|
||||
|
||||
## Setup (non-optional)
|
||||
|
||||
Two steps before any design work. Both are required. Skipping either produces generic output that ignores the project.
|
||||
|
||||
### 1. Context gathering
|
||||
|
||||
Two files at the project root, case-insensitive:
|
||||
|
||||
- **PRODUCT.md** — required. Users, brand, tone, anti-references, strategic principles.
|
||||
- **DESIGN.md** — optional, strongly recommended. Colors, typography, elevation, components.
|
||||
|
||||
Load both in one call:
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/load-context.mjs
|
||||
```
|
||||
|
||||
Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`.
|
||||
|
||||
If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
|
||||
|
||||
`/impeccable live` already warms context via `live.mjs` — if you've run `live.mjs`, don't also run `load-context.mjs` this session.
|
||||
|
||||
If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context.
|
||||
|
||||
If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
|
||||
|
||||
### 2. Register
|
||||
|
||||
Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio — design IS the product) or **product** (app UI, admin, dashboard, tool — design SERVES the product).
|
||||
|
||||
Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
|
||||
|
||||
If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
|
||||
|
||||
Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
|
||||
|
||||
## Shared design laws
|
||||
|
||||
Apply to every design, both registers. Match implementation complexity to the aesthetic vision — maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. Claude is capable of extraordinary work — don't hold back.
|
||||
|
||||
### Color
|
||||
|
||||
- Use OKLCH. Reduce chroma as lightness approaches 0 or 100 — high chroma at extremes looks garish.
|
||||
- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
|
||||
- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
|
||||
- **Restrained** — tinted neutrals + one accent ≤10%. Product default; brand minimalism.
|
||||
- **Committed** — one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
|
||||
- **Full palette** — 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
|
||||
- **Drenched** — the surface IS the color. Brand heroes, campaign pages.
|
||||
- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
|
||||
|
||||
### Theme
|
||||
|
||||
Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
|
||||
|
||||
Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough — add detail until it does.
|
||||
|
||||
"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
|
||||
|
||||
### Typography
|
||||
|
||||
- Cap body line length at 65–75ch.
|
||||
- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
|
||||
|
||||
### Layout
|
||||
|
||||
- Vary spacing for rhythm. Same padding everywhere is monotony.
|
||||
- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
|
||||
- Don't wrap everything in a container. Most things don't need one.
|
||||
|
||||
### Motion
|
||||
|
||||
- Don't animate CSS layout properties.
|
||||
- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
|
||||
|
||||
### Absolute bans
|
||||
|
||||
Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
|
||||
|
||||
- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
|
||||
- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
|
||||
- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
|
||||
- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
|
||||
- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
|
||||
- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
|
||||
|
||||
### Copy
|
||||
|
||||
- Every word earns its place. No restated headings, no intros that repeat the title.
|
||||
- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
|
||||
|
||||
### The AI slop test
|
||||
|
||||
If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
|
||||
|
||||
**Category-reflex check.** If someone could guess the theme and palette from the category name alone — "observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black" — it's the training-data reflex. Rework the scene sentence and color strategy until the answer is no longer obvious from the domain.
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Category | Description | Reference |
|
||||
|---|---|---|---|
|
||||
| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
|
||||
| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
|
||||
| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
|
||||
| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
|
||||
| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
|
||||
| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
|
||||
| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
|
||||
| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
|
||||
| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
|
||||
| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
|
||||
| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
|
||||
| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
|
||||
| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
|
||||
| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
|
||||
| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
|
||||
| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
|
||||
| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
|
||||
| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
|
||||
| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
|
||||
| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
|
||||
| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
|
||||
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
|
||||
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
|
||||
|
||||
Plus two management commands — `pin <command>` and `unpin <command>`, detailed below.
|
||||
|
||||
### Routing rules
|
||||
|
||||
1. **No argument** — render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
|
||||
2. **First word matches a command** — load its reference file and follow its instructions. Everything after the command name is the target.
|
||||
3. **First word doesn't match** — general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
|
||||
|
||||
Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
|
||||
|
||||
## Pin / Unpin
|
||||
|
||||
**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
|
||||
```
|
||||
|
||||
Valid `<command>` is any command from the table above. Report the script's result concisely — confirm the new shortcut on success, relay stderr verbatim on error.
|
||||
@@ -0,0 +1,190 @@
|
||||
> **Additional context needed**: target platforms/devices and usage contexts.
|
||||
|
||||
Adapt existing designs to work effectively across different contexts - different screen sizes, devices, platforms, or use cases.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Assess Adaptation Challenge
|
||||
|
||||
Understand what needs adaptation and why:
|
||||
|
||||
1. **Identify the source context**:
|
||||
- What was it designed for originally? (Desktop web? Mobile app?)
|
||||
- What assumptions were made? (Large screen? Mouse input? Fast connection?)
|
||||
- What works well in current context?
|
||||
|
||||
2. **Understand target context**:
|
||||
- **Device**: Mobile, tablet, desktop, TV, watch, print?
|
||||
- **Input method**: Touch, mouse, keyboard, voice, gamepad?
|
||||
- **Screen constraints**: Size, resolution, orientation?
|
||||
- **Connection**: Fast wifi, slow 3G, offline?
|
||||
- **Usage context**: On-the-go vs desk, quick glance vs focused reading?
|
||||
- **User expectations**: What do users expect on this platform?
|
||||
|
||||
3. **Identify adaptation challenges**:
|
||||
- What won't fit? (Content, navigation, features)
|
||||
- What won't work? (Hover states on touch, tiny touch targets)
|
||||
- What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
|
||||
|
||||
**CRITICAL**: Adaptation is not just scaling - it's rethinking the experience for the new context.
|
||||
|
||||
## Plan Adaptation Strategy
|
||||
|
||||
Create context-appropriate strategy:
|
||||
|
||||
### Mobile Adaptation (Desktop → Mobile)
|
||||
|
||||
**Layout Strategy**:
|
||||
- Single column instead of multi-column
|
||||
- Vertical stacking instead of side-by-side
|
||||
- Full-width components instead of fixed widths
|
||||
- Bottom navigation instead of top/side navigation
|
||||
|
||||
**Interaction Strategy**:
|
||||
- Touch targets 44x44px minimum (not hover-dependent)
|
||||
- Swipe gestures where appropriate (lists, carousels)
|
||||
- Bottom sheets instead of dropdowns
|
||||
- Thumbs-first design (controls within thumb reach)
|
||||
- Larger tap areas with more spacing
|
||||
|
||||
**Content Strategy**:
|
||||
- Progressive disclosure (don't show everything at once)
|
||||
- Prioritize primary content (secondary content in tabs/accordions)
|
||||
- Shorter text (more concise)
|
||||
- Larger text (16px minimum)
|
||||
|
||||
**Navigation Strategy**:
|
||||
- Hamburger menu or bottom navigation
|
||||
- Reduce navigation complexity
|
||||
- Sticky headers for context
|
||||
- Back button in navigation flow
|
||||
|
||||
### Tablet Adaptation (Hybrid Approach)
|
||||
|
||||
**Layout Strategy**:
|
||||
- Two-column layouts (not single or three-column)
|
||||
- Side panels for secondary content
|
||||
- Master-detail views (list + detail)
|
||||
- Adaptive based on orientation (portrait vs landscape)
|
||||
|
||||
**Interaction Strategy**:
|
||||
- Support both touch and pointer
|
||||
- Touch targets 44x44px but allow denser layouts than phone
|
||||
- Side navigation drawers
|
||||
- Multi-column forms where appropriate
|
||||
|
||||
### Desktop Adaptation (Mobile → Desktop)
|
||||
|
||||
**Layout Strategy**:
|
||||
- Multi-column layouts (use horizontal space)
|
||||
- Side navigation always visible
|
||||
- Multiple information panels simultaneously
|
||||
- Fixed widths with max-width constraints (don't stretch to 4K)
|
||||
|
||||
**Interaction Strategy**:
|
||||
- Hover states for additional information
|
||||
- Keyboard shortcuts
|
||||
- Right-click context menus
|
||||
- Drag and drop where helpful
|
||||
- Multi-select with Shift/Cmd
|
||||
|
||||
**Content Strategy**:
|
||||
- Show more information upfront (less progressive disclosure)
|
||||
- Data tables with many columns
|
||||
- Richer visualizations
|
||||
- More detailed descriptions
|
||||
|
||||
### Print Adaptation (Screen → Print)
|
||||
|
||||
**Layout Strategy**:
|
||||
- Page breaks at logical points
|
||||
- Remove navigation, footer, interactive elements
|
||||
- Black and white (or limited color)
|
||||
- Proper margins for binding
|
||||
|
||||
**Content Strategy**:
|
||||
- Expand shortened content (show full URLs, hidden sections)
|
||||
- Add page numbers, headers, footers
|
||||
- Include metadata (print date, page title)
|
||||
- Convert charts to print-friendly versions
|
||||
|
||||
### Email Adaptation (Web → Email)
|
||||
|
||||
**Layout Strategy**:
|
||||
- Narrow width (600px max)
|
||||
- Single column only
|
||||
- Inline CSS (no external stylesheets)
|
||||
- Table-based layouts (for email client compatibility)
|
||||
|
||||
**Interaction Strategy**:
|
||||
- Large, obvious CTAs (buttons not text links)
|
||||
- No hover states (not reliable)
|
||||
- Deep links to web app for complex interactions
|
||||
|
||||
## Implement Adaptations
|
||||
|
||||
Apply changes systematically:
|
||||
|
||||
### Responsive Breakpoints
|
||||
|
||||
Choose appropriate breakpoints:
|
||||
- Mobile: 320px-767px
|
||||
- Tablet: 768px-1023px
|
||||
- Desktop: 1024px+
|
||||
- Or content-driven breakpoints (where design breaks)
|
||||
|
||||
### Layout Adaptation Techniques
|
||||
|
||||
- **CSS Grid/Flexbox**: Reflow layouts automatically
|
||||
- **Container Queries**: Adapt based on container, not viewport
|
||||
- **`clamp()`**: Fluid sizing between min and max
|
||||
- **Media queries**: Different styles for different contexts
|
||||
- **Display properties**: Show/hide elements per context
|
||||
|
||||
### Touch Adaptation
|
||||
|
||||
- Increase touch target sizes (44x44px minimum)
|
||||
- Add more spacing between interactive elements
|
||||
- Remove hover-dependent interactions
|
||||
- Add touch feedback (ripples, highlights)
|
||||
- Consider thumb zones (easier to reach bottom than top)
|
||||
|
||||
### Content Adaptation
|
||||
|
||||
- Use `display: none` sparingly (still downloads)
|
||||
- Progressive enhancement (core content first, enhancements on larger screens)
|
||||
- Lazy loading for off-screen content
|
||||
- Responsive images (`srcset`, `picture` element)
|
||||
|
||||
### Navigation Adaptation
|
||||
|
||||
- Transform complex nav to hamburger/drawer on mobile
|
||||
- Bottom nav bar for mobile apps
|
||||
- Persistent side navigation on desktop
|
||||
- Breadcrumbs on smaller screens for context
|
||||
|
||||
**IMPORTANT**: Test on real devices, not just browser DevTools. Device emulation is helpful but not perfect.
|
||||
|
||||
**NEVER**:
|
||||
- Hide core functionality on mobile (if it matters, make it work)
|
||||
- Assume desktop = powerful device (consider accessibility, older machines)
|
||||
- Use different information architecture across contexts (confusing)
|
||||
- Break user expectations for platform (mobile users expect mobile patterns)
|
||||
- Forget landscape orientation on mobile/tablet
|
||||
- Use generic breakpoints blindly (use content-driven breakpoints)
|
||||
- Ignore touch on desktop (many desktop devices have touch)
|
||||
|
||||
## Verify Adaptations
|
||||
|
||||
Test thoroughly across contexts:
|
||||
|
||||
- **Real devices**: Test on actual phones, tablets, desktops
|
||||
- **Different orientations**: Portrait and landscape
|
||||
- **Different browsers**: Safari, Chrome, Firefox, Edge
|
||||
- **Different OS**: iOS, Android, Windows, macOS
|
||||
- **Different input methods**: Touch, mouse, keyboard
|
||||
- **Edge cases**: Very small screens (320px), very large screens (4K)
|
||||
- **Slow connections**: Test on throttled network
|
||||
|
||||
Remember: You're a cross-platform design expert. Make experiences that feel native to each context while maintaining brand and functionality consistency. Adapt intentionally, test thoroughly.
|
||||
@@ -0,0 +1,173 @@
|
||||
> **Additional context needed**: performance constraints.
|
||||
|
||||
Analyze a feature and strategically add animations and micro-interactions that enhance understanding, provide feedback, and create delight.
|
||||
|
||||
---
|
||||
|
||||
## Register
|
||||
|
||||
Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
|
||||
|
||||
Product: 150–250 ms on most transitions. Motion conveys state — feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
|
||||
|
||||
---
|
||||
|
||||
## Assess Animation Opportunities
|
||||
|
||||
Analyze where motion would improve the experience:
|
||||
|
||||
1. **Identify static areas**:
|
||||
- **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
|
||||
- **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
|
||||
- **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
|
||||
- **Lack of delight**: Functional but joyless interactions
|
||||
- **Missed guidance**: Opportunities to direct attention or explain behavior
|
||||
|
||||
2. **Understand the context**:
|
||||
- What's the personality? (Playful vs serious, energetic vs calm)
|
||||
- What's the performance budget? (Mobile-first? Complex page?)
|
||||
- Who's the audience? (Motion-sensitive users? Power users who want speed?)
|
||||
- What matters most? (One hero animation vs many micro-interactions?)
|
||||
|
||||
If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
|
||||
|
||||
**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
|
||||
|
||||
## Plan Animation Strategy
|
||||
|
||||
Create a purposeful animation plan:
|
||||
|
||||
- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
|
||||
- **Feedback layer**: Which interactions need acknowledgment?
|
||||
- **Transition layer**: Which state changes need smoothing?
|
||||
- **Delight layer**: Where can we surprise and delight?
|
||||
|
||||
**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
|
||||
|
||||
## Implement Animations
|
||||
|
||||
Add motion systematically across these categories:
|
||||
|
||||
### Entrance Animations
|
||||
- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
|
||||
- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
|
||||
- **Content reveals**: Scroll-triggered animations using intersection observer
|
||||
- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
|
||||
|
||||
### Micro-interactions
|
||||
- **Button feedback**:
|
||||
- Hover: Subtle scale (1.02-1.05), color shift, shadow increase
|
||||
- Click: Quick scale down then up (0.95 → 1), ripple effect
|
||||
- Loading: Spinner or pulse state
|
||||
- **Form interactions**:
|
||||
- Input focus: Border color transition, slight scale or glow
|
||||
- Validation: Shake on error, check mark on success, smooth color transitions
|
||||
- **Toggle switches**: Smooth slide + color transition (200-300ms)
|
||||
- **Checkboxes/radio**: Check mark animation, ripple effect
|
||||
- **Like/favorite**: Scale + rotation, particle effects, color transition
|
||||
|
||||
### State Transitions
|
||||
- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
|
||||
- **Expand/collapse**: Height transition with overflow handling, icon rotation
|
||||
- **Loading states**: Skeleton screen fades, spinner animations, progress bars
|
||||
- **Success/error**: Color transitions, icon animations, gentle scale pulse
|
||||
- **Enable/disable**: Opacity transitions, cursor changes
|
||||
|
||||
### Navigation & Flow
|
||||
- **Page transitions**: Crossfade between routes, shared element transitions
|
||||
- **Tab switching**: Slide indicator, content fade/slide
|
||||
- **Carousel/slider**: Smooth transforms, snap points, momentum
|
||||
- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
|
||||
|
||||
### Feedback & Guidance
|
||||
- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
|
||||
- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
|
||||
- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
|
||||
- **Focus flow**: Highlight path through form or workflow
|
||||
|
||||
### Delight Moments
|
||||
- **Empty states**: Subtle floating animations on illustrations
|
||||
- **Completed actions**: Confetti, check mark flourish, success celebrations
|
||||
- **Easter eggs**: Hidden interactions for discovery
|
||||
- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
|
||||
|
||||
## Technical Implementation
|
||||
|
||||
Use appropriate techniques for each animation:
|
||||
|
||||
### Timing & Easing
|
||||
|
||||
**Durations by purpose:**
|
||||
- **100-150ms**: Instant feedback (button press, toggle)
|
||||
- **200-300ms**: State changes (hover, menu open)
|
||||
- **300-500ms**: Layout changes (accordion, modal)
|
||||
- **500-800ms**: Entrance animations (page load)
|
||||
|
||||
**Easing curves (use these, not CSS defaults):**
|
||||
```css
|
||||
/* Recommended - natural deceleration */
|
||||
--ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth, refined */
|
||||
--ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
|
||||
--ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
|
||||
|
||||
/* AVOID - feel dated and tacky */
|
||||
/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
|
||||
/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
|
||||
```
|
||||
|
||||
**Exit animations are faster than entrances.** Use ~75% of enter duration.
|
||||
|
||||
### CSS Animations
|
||||
```css
|
||||
/* Prefer for simple, declarative animations */
|
||||
- transitions for state changes
|
||||
- @keyframes for complex sequences
|
||||
- transform + opacity only (GPU-accelerated)
|
||||
```
|
||||
|
||||
### JavaScript Animation
|
||||
```javascript
|
||||
/* Use for complex, interactive animations */
|
||||
- Web Animations API for programmatic control
|
||||
- Framer Motion for React
|
||||
- GSAP for complex sequences
|
||||
```
|
||||
|
||||
### Performance
|
||||
- **GPU acceleration**: Use `transform` and `opacity`, avoid layout properties
|
||||
- **will-change**: Add sparingly for known expensive animations
|
||||
- **Reduce paint**: Minimize repaints, use `contain` where appropriate
|
||||
- **Monitor FPS**: Ensure 60fps on target devices
|
||||
|
||||
### Accessibility
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**NEVER**:
|
||||
- Use bounce or elastic easing curves—they feel dated and draw attention to the animation itself
|
||||
- Animate layout properties (width, height, top, left)—use transform instead
|
||||
- Use durations over 500ms for feedback—it feels laggy
|
||||
- Animate without purpose—every animation needs a reason
|
||||
- Ignore `prefers-reduced-motion`—this is an accessibility violation
|
||||
- Animate everything—animation fatigue makes interfaces feel exhausting
|
||||
- Block interaction during animations unless intentional
|
||||
|
||||
## Verify Quality
|
||||
|
||||
Test animations thoroughly:
|
||||
|
||||
- **Smooth at 60fps**: No jank on target devices
|
||||
- **Feels natural**: Easing curves feel organic, not robotic
|
||||
- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
|
||||
- **Reduced motion works**: Animations disabled or simplified appropriately
|
||||
- **Doesn't block**: Users can interact during/after animations
|
||||
- **Adds value**: Makes interface clearer or more delightful
|
||||
|
||||
Remember: Motion should enhance understanding and provide feedback, not just add decoration. Animate with purpose, respect performance constraints, and always consider accessibility. Great animation is invisible - it just makes everything feel right.
|
||||
@@ -0,0 +1,134 @@
|
||||
Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues — document them for other commands to address.
|
||||
|
||||
This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
|
||||
|
||||
## Diagnostic Scan
|
||||
|
||||
Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
|
||||
|
||||
### 1. Accessibility (A11y)
|
||||
|
||||
**Check for**:
|
||||
- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
|
||||
- **Missing ARIA**: Interactive elements without proper roles, labels, or states
|
||||
- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
|
||||
- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
|
||||
- **Alt text**: Missing or poor image descriptions
|
||||
- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
|
||||
|
||||
**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
|
||||
|
||||
### 2. Performance
|
||||
|
||||
**Check for**:
|
||||
- **Layout thrashing**: Reading/writing layout properties in loops
|
||||
- **Expensive animations**: Animating layout properties (width, height, top, left) instead of transform/opacity
|
||||
- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
|
||||
- **Bundle size**: Unnecessary imports, unused dependencies
|
||||
- **Render performance**: Unnecessary re-renders, missing memoization
|
||||
|
||||
**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
|
||||
|
||||
### 3. Theming
|
||||
|
||||
**Check for**:
|
||||
- **Hard-coded colors**: Colors not using design tokens
|
||||
- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
|
||||
- **Inconsistent tokens**: Using wrong tokens, mixing token types
|
||||
- **Theme switching issues**: Values that don't update on theme change
|
||||
|
||||
**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
|
||||
|
||||
### 4. Responsive Design
|
||||
|
||||
**Check for**:
|
||||
- **Fixed widths**: Hard-coded widths that break on mobile
|
||||
- **Touch targets**: Interactive elements < 44x44px
|
||||
- **Horizontal scroll**: Content overflow on narrow viewports
|
||||
- **Text scaling**: Layouts that break when text size increases
|
||||
- **Missing breakpoints**: No mobile/tablet variants
|
||||
|
||||
**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
|
||||
|
||||
### 5. Anti-Patterns (CRITICAL)
|
||||
|
||||
Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
|
||||
|
||||
**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
|
||||
|
||||
## Generate Report
|
||||
|
||||
### Audit Health Score
|
||||
|
||||
| # | Dimension | Score | Key Finding |
|
||||
|---|-----------|-------|-------------|
|
||||
| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
|
||||
| 2 | Performance | ? | |
|
||||
| 3 | Responsive Design | ? | |
|
||||
| 4 | Theming | ? | |
|
||||
| 5 | Anti-Patterns | ? | |
|
||||
| **Total** | | **??/20** | **[Rating band]** |
|
||||
|
||||
**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
|
||||
|
||||
### Anti-Patterns Verdict
|
||||
**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
|
||||
|
||||
### Executive Summary
|
||||
- Audit Health Score: **??/20** ([rating band])
|
||||
- Total issues found (count by severity: P0/P1/P2/P3)
|
||||
- Top 3-5 critical issues
|
||||
- Recommended next steps
|
||||
|
||||
### Detailed Findings by Severity
|
||||
|
||||
Tag every issue with **P0-P3 severity**:
|
||||
- **P0 Blocking**: Prevents task completion — fix immediately
|
||||
- **P1 Major**: Significant difficulty or WCAG AA violation — fix before release
|
||||
- **P2 Minor**: Annoyance, workaround exists — fix in next pass
|
||||
- **P3 Polish**: Nice-to-fix, no real user impact — fix if time permits
|
||||
|
||||
For each issue, document:
|
||||
- **[P?] Issue name**
|
||||
- **Location**: Component, file, line
|
||||
- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
|
||||
- **Impact**: How it affects users
|
||||
- **WCAG/Standard**: Which standard it violates (if applicable)
|
||||
- **Recommendation**: How to fix it
|
||||
- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
|
||||
|
||||
### Patterns & Systemic Issues
|
||||
|
||||
Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
|
||||
- "Hard-coded colors appear in 15+ components, should use design tokens"
|
||||
- "Touch targets consistently too small (<44px) throughout mobile experience"
|
||||
|
||||
### Positive Findings
|
||||
|
||||
Note what's working well — good practices to maintain and replicate.
|
||||
|
||||
## Recommended Actions
|
||||
|
||||
List recommended commands in priority order (P0 first, then P1, then P2):
|
||||
|
||||
1. **[P?] `/command-name`** — Brief description (specific context from audit findings)
|
||||
2. **[P?] `/command-name`** — Brief description (specific context)
|
||||
|
||||
**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
|
||||
|
||||
After presenting the summary, tell the user:
|
||||
|
||||
> You can ask me to run these one at a time, all at once, or in any order you prefer.
|
||||
>
|
||||
> Re-run `/impeccable audit` after fixes to see your score improve.
|
||||
|
||||
**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
|
||||
|
||||
**NEVER**:
|
||||
- Report issues without explaining impact (why does this matter?)
|
||||
- Provide generic recommendations (be specific and actionable)
|
||||
- Skip positive findings (celebrate what works)
|
||||
- Forget to prioritize (everything can't be P0)
|
||||
- Report false positives without verification
|
||||
|
||||
Remember: You're a technical quality auditor. Document systematically, prioritize ruthlessly, cite specific code locations, and provide clear paths to improvement.
|
||||
@@ -0,0 +1,113 @@
|
||||
Increase visual impact and personality in designs that are too safe, generic, or visually underwhelming, creating more engaging and memorable experiences.
|
||||
|
||||
---
|
||||
|
||||
## Register
|
||||
|
||||
Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
|
||||
|
||||
Product: "bolder" rarely means theatrics — those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
|
||||
|
||||
---
|
||||
|
||||
## Assess Current State
|
||||
|
||||
Analyze what makes the design feel too safe or boring:
|
||||
|
||||
1. **Identify weakness sources**:
|
||||
- **Generic choices**: System fonts, basic colors, standard layouts
|
||||
- **Timid scale**: Everything is medium-sized with no drama
|
||||
- **Low contrast**: Everything has similar visual weight
|
||||
- **Static**: No motion, no energy, no life
|
||||
- **Predictable**: Standard patterns with no surprises
|
||||
- **Flat hierarchy**: Nothing stands out or commands attention
|
||||
|
||||
2. **Understand the context**:
|
||||
- What's the brand personality? (How far can we push?)
|
||||
- What's the purpose? (Marketing can be bolder than financial dashboards)
|
||||
- Who's the audience? (What will resonate?)
|
||||
- What are the constraints? (Brand guidelines, accessibility, performance)
|
||||
|
||||
If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
|
||||
|
||||
**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
|
||||
|
||||
**WARNING - AI SLOP TRAP**: When making things "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the OPPOSITE of bold. They're generic. Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
|
||||
|
||||
## Plan Amplification
|
||||
|
||||
Create a strategy to increase impact while maintaining coherence:
|
||||
|
||||
- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
|
||||
- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
|
||||
- **Risk budget**: How experimental can we be? Push boundaries within constraints.
|
||||
- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
|
||||
|
||||
**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
|
||||
|
||||
## Amplify the Design
|
||||
|
||||
Systematically increase impact across these dimensions:
|
||||
|
||||
### Typography Amplification
|
||||
- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
|
||||
- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
|
||||
- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
|
||||
- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
|
||||
|
||||
### Color Intensification
|
||||
- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
|
||||
- **Bold palette**: Introduce unexpected color combinations—avoid the purple-blue gradient AI slop
|
||||
- **Dominant color strategy**: Let one bold color own 60% of the design
|
||||
- **Sharp accents**: High-contrast accent colors that pop
|
||||
- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
|
||||
- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
|
||||
|
||||
### Spatial Drama
|
||||
- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
|
||||
- **Break the grid**: Let hero elements escape containers and cross boundaries
|
||||
- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
|
||||
- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
|
||||
- **Overlap**: Layer elements intentionally for depth
|
||||
|
||||
### Visual Effects
|
||||
- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
|
||||
- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
|
||||
- **Texture & depth**: Grain, halftone, duotone, layered elements—NOT glassmorphism (it's overused AI slop)
|
||||
- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
|
||||
- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
|
||||
|
||||
### Motion & Animation
|
||||
- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
|
||||
- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
|
||||
- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
|
||||
- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic—they cheapen the effect)
|
||||
|
||||
### Composition Boldness
|
||||
- **Hero moments**: Create clear focal points with dramatic treatment
|
||||
- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
|
||||
- **Full-bleed elements**: Use full viewport width/height for impact
|
||||
- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
|
||||
|
||||
**NEVER**:
|
||||
- Add effects randomly without purpose (chaos ≠ bold)
|
||||
- Sacrifice readability for aesthetics (body text must be readable)
|
||||
- Make everything bold (then nothing is bold - need contrast)
|
||||
- Ignore accessibility (bold design must still meet WCAG standards)
|
||||
- Overwhelm with motion (animation fatigue is real)
|
||||
- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
|
||||
|
||||
## Verify Quality
|
||||
|
||||
Ensure amplification maintains usability and coherence:
|
||||
|
||||
- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
|
||||
- **Still functional**: Can users accomplish tasks without distraction?
|
||||
- **Coherent**: Does everything feel intentional and unified?
|
||||
- **Memorable**: Will users remember this experience?
|
||||
- **Performant**: Do all these effects run smoothly?
|
||||
- **Accessible**: Does it still meet accessibility standards?
|
||||
|
||||
**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
|
||||
|
||||
Remember: Bold design is confident design. It takes risks, makes statements, and creates memorable experiences. But bold without strategy is just loud. Be intentional, be dramatic, be unforgettable.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Brand register
|
||||
|
||||
When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself — a visitor's impression is the thing being made.
|
||||
|
||||
The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance — *communicate, not transact* — and diverge wildly in aesthetic. Don't collapse them into a single look.
|
||||
|
||||
## The brand slop test
|
||||
|
||||
If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness — a visitor should ask "how was this made?", not "which AI made this?"
|
||||
|
||||
Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
|
||||
|
||||
**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
|
||||
|
||||
## Typography
|
||||
|
||||
### Font selection procedure
|
||||
|
||||
Every project. Never skip.
|
||||
|
||||
1. Read the brief. Write three concrete brand-voice words — not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
|
||||
2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them — they are training-data defaults and they create monoculture.
|
||||
3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object* — a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
|
||||
4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
|
||||
|
||||
### Reflex-reject list
|
||||
|
||||
Training-data defaults. Ban list — look further:
|
||||
|
||||
Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
|
||||
|
||||
### Pairing and voice
|
||||
|
||||
Distinctive + refined is the goal — the specific shape depends on the brand:
|
||||
|
||||
- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
|
||||
- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
|
||||
- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
|
||||
- **Creative studios / agencies**: rule-breaking welcome — mono-only, or display-only, or custom-drawn type as voice.
|
||||
|
||||
Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
|
||||
|
||||
Vary across projects. If the last brief was a serif-display landing page, this one isn't.
|
||||
|
||||
### Scale
|
||||
|
||||
Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
|
||||
|
||||
Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
|
||||
|
||||
## Color
|
||||
|
||||
Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess — it's voice. A beige-and-muted-slate landing page ignores the register.
|
||||
|
||||
- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
|
||||
- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
|
||||
- When the strategy is Committed or Drenched, the color is load-bearing. Don't hedge with neutrals around the edges — commit.
|
||||
- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
|
||||
|
||||
## Layout
|
||||
|
||||
- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
|
||||
- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm — generous separations, tight groupings.
|
||||
- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed" — the failure mode is splitting the difference into a generic centered stack.
|
||||
- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
|
||||
- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` — breakpoint-free responsiveness.
|
||||
|
||||
## Imagery
|
||||
|
||||
Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
|
||||
|
||||
**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse.
|
||||
|
||||
- **For greenfield work without local assets, use stock imagery** — Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. Pick real Unsplash photo IDs you're confident exist (`photo-1559339352-11d035aa65de`, `photo-1590490360182-c33d57733427`, etc.); if unsure, pick fewer photos but don't substitute colored `<div>` placeholders.
|
||||
- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
|
||||
- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
|
||||
- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
|
||||
|
||||
Tech / dev-tool brands are the exception where zero imagery can be correct — a developer landing page often carries its voice through typography, code samples, diagrams. Know which kind of brand you're working on.
|
||||
|
||||
## Motion
|
||||
|
||||
- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions — when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
|
||||
- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
|
||||
|
||||
## Brand bans (on top of the shared absolute bans)
|
||||
|
||||
- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
|
||||
- Large rounded-corner icons above every heading. Screams template.
|
||||
- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
|
||||
- All-caps body copy. Reserve caps for short labels and headings.
|
||||
- Timid palettes and average layouts. Safe = invisible.
|
||||
- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
|
||||
- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
|
||||
|
||||
## Brand permissions
|
||||
|
||||
Brand can afford things product can't. Take them.
|
||||
|
||||
- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
|
||||
- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
|
||||
- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
|
||||
- Unexpected color strategies. Palette IS voice — a calm brand and a restless brand should not share palette mechanics.
|
||||
- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
|
||||
@@ -0,0 +1,174 @@
|
||||
> **Additional context needed**: audience technical level and users' mental state in context.
|
||||
|
||||
Identify and improve unclear, confusing, or poorly written interface text to make the product easier to understand and use.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Assess Current Copy
|
||||
|
||||
Identify what makes the text unclear or ineffective:
|
||||
|
||||
1. **Find clarity problems**:
|
||||
- **Jargon**: Technical terms users won't understand
|
||||
- **Ambiguity**: Multiple interpretations possible
|
||||
- **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
|
||||
- **Length**: Too wordy or too terse
|
||||
- **Assumptions**: Assuming user knowledge they don't have
|
||||
- **Missing context**: Users don't know what to do or why
|
||||
- **Tone mismatch**: Too formal, too casual, or inappropriate for situation
|
||||
|
||||
2. **Understand the context**:
|
||||
- Who's the audience? (Technical? General? First-time users?)
|
||||
- What's the user's mental state? (Stressed during error? Confident during success?)
|
||||
- What's the action? (What do we want users to do?)
|
||||
- What's the constraint? (Character limits? Space limitations?)
|
||||
|
||||
**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
|
||||
|
||||
## Plan Copy Improvements
|
||||
|
||||
Create a strategy for clearer communication:
|
||||
|
||||
- **Primary message**: What's the ONE thing users need to know?
|
||||
- **Action needed**: What should users do next (if anything)?
|
||||
- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
|
||||
- **Constraints**: Length limits, brand voice, localization considerations
|
||||
|
||||
**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
|
||||
|
||||
## Improve Copy Systematically
|
||||
|
||||
Refine text across these common areas:
|
||||
|
||||
### Error Messages
|
||||
**Bad**: "Error 403: Forbidden"
|
||||
**Good**: "You don't have permission to view this page. Contact your admin for access."
|
||||
|
||||
**Bad**: "Invalid input"
|
||||
**Good**: "Email addresses need an @ symbol. Try: name@example.com"
|
||||
|
||||
**Principles**:
|
||||
- Explain what went wrong in plain language
|
||||
- Suggest how to fix it
|
||||
- Don't blame the user
|
||||
- Include examples when helpful
|
||||
- Link to help/support if applicable
|
||||
|
||||
### Form Labels & Instructions
|
||||
**Bad**: "DOB (MM/DD/YYYY)"
|
||||
**Good**: "Date of birth" (with placeholder showing format)
|
||||
|
||||
**Bad**: "Enter value here"
|
||||
**Good**: "Your email address" or "Company name"
|
||||
|
||||
**Principles**:
|
||||
- Use clear, specific labels (not generic placeholders)
|
||||
- Show format expectations with examples
|
||||
- Explain why you're asking (when not obvious)
|
||||
- Put instructions before the field, not after
|
||||
- Keep required field indicators clear
|
||||
|
||||
### Button & CTA Text
|
||||
**Bad**: "Click here" | "Submit" | "OK"
|
||||
**Good**: "Create account" | "Save changes" | "Got it, thanks"
|
||||
|
||||
**Principles**:
|
||||
- Describe the action specifically
|
||||
- Use active voice (verb + noun)
|
||||
- Match user's mental model
|
||||
- Be specific ("Save" is better than "OK")
|
||||
|
||||
### Help Text & Tooltips
|
||||
**Bad**: "This is the username field"
|
||||
**Good**: "Choose a username. You can change this later in Settings."
|
||||
|
||||
**Principles**:
|
||||
- Add value (don't just repeat the label)
|
||||
- Answer the implicit question ("What is this?" or "Why do you need this?")
|
||||
- Keep it brief but complete
|
||||
- Link to detailed docs if needed
|
||||
|
||||
### Empty States
|
||||
**Bad**: "No items"
|
||||
**Good**: "No projects yet. Create your first project to get started."
|
||||
|
||||
**Principles**:
|
||||
- Explain why it's empty (if not obvious)
|
||||
- Show next action clearly
|
||||
- Make it welcoming, not dead-end
|
||||
|
||||
### Success Messages
|
||||
**Bad**: "Success"
|
||||
**Good**: "Settings saved! Your changes will take effect immediately."
|
||||
|
||||
**Principles**:
|
||||
- Confirm what happened
|
||||
- Explain what happens next (if relevant)
|
||||
- Be brief but complete
|
||||
- Match the user's emotional moment (celebrate big wins)
|
||||
|
||||
### Loading States
|
||||
**Bad**: "Loading..." (for 30+ seconds)
|
||||
**Good**: "Analyzing your data... this usually takes 30-60 seconds"
|
||||
|
||||
**Principles**:
|
||||
- Set expectations (how long?)
|
||||
- Explain what's happening (when it's not obvious)
|
||||
- Show progress when possible
|
||||
- Offer escape hatch if appropriate ("Cancel")
|
||||
|
||||
### Confirmation Dialogs
|
||||
**Bad**: "Are you sure?"
|
||||
**Good**: "Delete 'Project Alpha'? This can't be undone."
|
||||
|
||||
**Principles**:
|
||||
- State the specific action
|
||||
- Explain consequences (especially for destructive actions)
|
||||
- Use clear button labels ("Delete project" not "Yes")
|
||||
- Don't overuse confirmations (only for risky actions)
|
||||
|
||||
### Navigation & Wayfinding
|
||||
**Bad**: Generic labels like "Items" | "Things" | "Stuff"
|
||||
**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
|
||||
|
||||
**Principles**:
|
||||
- Be specific and descriptive
|
||||
- Use language users understand (not internal jargon)
|
||||
- Make hierarchy clear
|
||||
- Consider information scent (breadcrumbs, current location)
|
||||
|
||||
## Apply Clarity Principles
|
||||
|
||||
Every piece of copy should follow these rules:
|
||||
|
||||
1. **Be specific**: "Enter email" not "Enter value"
|
||||
2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
|
||||
3. **Be active**: "Save changes" not "Changes will be saved"
|
||||
4. **Be human**: "Oops, something went wrong" not "System error encountered"
|
||||
5. **Be helpful**: Tell users what to do, not just what happened
|
||||
6. **Be consistent**: Use same terms throughout (don't vary for variety)
|
||||
|
||||
**NEVER**:
|
||||
- Use jargon without explanation
|
||||
- Blame users ("You made an error" → "This field is required")
|
||||
- Be vague ("Something went wrong" without explanation)
|
||||
- Use passive voice unnecessarily
|
||||
- Write overly long explanations (be concise)
|
||||
- Use humor for errors (be empathetic instead)
|
||||
- Assume technical knowledge
|
||||
- Vary terminology (pick one term and stick with it)
|
||||
- Repeat information (headers restating intros, redundant explanations)
|
||||
- Use placeholders as the only labels (they disappear when users type)
|
||||
|
||||
## Verify Improvements
|
||||
|
||||
Test that copy improvements work:
|
||||
|
||||
- **Comprehension**: Can users understand without context?
|
||||
- **Actionability**: Do users know what to do next?
|
||||
- **Brevity**: Is it as short as possible while remaining clear?
|
||||
- **Consistency**: Does it match terminology elsewhere?
|
||||
- **Tone**: Is it appropriate for the situation?
|
||||
|
||||
Remember: You're a clarity expert with excellent communication skills. Write like you're explaining to a smart friend who's unfamiliar with the product. Be clear, be helpful, be human.
|
||||
@@ -0,0 +1,106 @@
|
||||
# Cognitive Load Assessment
|
||||
|
||||
Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
|
||||
|
||||
---
|
||||
|
||||
## Three Types of Cognitive Load
|
||||
|
||||
### Intrinsic Load — The Task Itself
|
||||
Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
|
||||
|
||||
**Manage it by**:
|
||||
- Breaking complex tasks into discrete steps
|
||||
- Providing scaffolding (templates, defaults, examples)
|
||||
- Progressive disclosure — show what's needed now, hide the rest
|
||||
- Grouping related decisions together
|
||||
|
||||
### Extraneous Load — Bad Design
|
||||
Mental effort caused by poor design choices. **Eliminate this ruthlessly** — it's pure waste.
|
||||
|
||||
**Common sources**:
|
||||
- Confusing navigation that requires mental mapping
|
||||
- Unclear labels that force users to guess meaning
|
||||
- Visual clutter competing for attention
|
||||
- Inconsistent patterns that prevent learning
|
||||
- Unnecessary steps between user intent and result
|
||||
|
||||
### Germane Load — Learning Effort
|
||||
Mental effort spent building understanding. This is *good* cognitive load — it leads to mastery.
|
||||
|
||||
**Support it by**:
|
||||
- Progressive disclosure that reveals complexity gradually
|
||||
- Consistent patterns that reward learning
|
||||
- Feedback that confirms correct understanding
|
||||
- Onboarding that teaches through action, not walls of text
|
||||
|
||||
---
|
||||
|
||||
## Cognitive Load Checklist
|
||||
|
||||
Evaluate the interface against these 8 items:
|
||||
|
||||
- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
|
||||
- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
|
||||
- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
|
||||
- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
|
||||
- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
|
||||
- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
|
||||
- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
|
||||
- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
|
||||
|
||||
**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
|
||||
|
||||
---
|
||||
|
||||
## The Working Memory Rule
|
||||
|
||||
**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
|
||||
|
||||
At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
|
||||
- **≤4 items**: Within working memory limits — manageable
|
||||
- **5–7 items**: Pushing the boundary — consider grouping or progressive disclosure
|
||||
- **8+ items**: Overloaded — users will skip, misclick, or abandon
|
||||
|
||||
**Practical applications**:
|
||||
- Navigation menus: ≤5 top-level items (group the rest under clear categories)
|
||||
- Form sections: ≤4 fields visible per group before a visual break
|
||||
- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
|
||||
- Dashboard widgets: ≤4 key metrics visible without scrolling
|
||||
- Pricing tiers: ≤3 options (more causes analysis paralysis)
|
||||
|
||||
---
|
||||
|
||||
## Common Cognitive Load Violations
|
||||
|
||||
### 1. The Wall of Options
|
||||
**Problem**: Presenting 10+ choices at once with no hierarchy.
|
||||
**Fix**: Group into categories, highlight recommended, use progressive disclosure.
|
||||
|
||||
### 2. The Memory Bridge
|
||||
**Problem**: User must remember info from step 1 to complete step 3.
|
||||
**Fix**: Keep relevant context visible, or repeat it where it's needed.
|
||||
|
||||
### 3. The Hidden Navigation
|
||||
**Problem**: User must build a mental map of where things are.
|
||||
**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
|
||||
|
||||
### 4. The Jargon Barrier
|
||||
**Problem**: Technical or domain language forces translation effort.
|
||||
**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
|
||||
|
||||
### 5. The Visual Noise Floor
|
||||
**Problem**: Every element has the same visual weight — nothing stands out.
|
||||
**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
|
||||
|
||||
### 6. The Inconsistent Pattern
|
||||
**Problem**: Similar actions work differently in different places.
|
||||
**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
|
||||
|
||||
### 7. The Multi-Task Demand
|
||||
**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
|
||||
**Fix**: Sequence the steps. Let the user do one thing at a time.
|
||||
|
||||
### 8. The Context Switch
|
||||
**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
|
||||
**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
|
||||
@@ -0,0 +1,105 @@
|
||||
# Color & Contrast
|
||||
|
||||
## Color Spaces: Use OKLCH
|
||||
|
||||
**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal—unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
|
||||
|
||||
The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness — but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
|
||||
|
||||
The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex — those are the dominant AI-design defaults, not the right answer for any specific brand.
|
||||
|
||||
## Building Functional Palettes
|
||||
|
||||
### Tinted Neutrals
|
||||
|
||||
**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
|
||||
|
||||
The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
|
||||
|
||||
**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
|
||||
|
||||
### Palette Structure
|
||||
|
||||
A complete system needs:
|
||||
|
||||
| Role | Purpose | Example |
|
||||
|------|---------|---------|
|
||||
| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
|
||||
| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
|
||||
| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
|
||||
| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
|
||||
|
||||
**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
|
||||
|
||||
### The 60-30-10 Rule (Applied Correctly)
|
||||
|
||||
This rule is about **visual weight**, not pixel count:
|
||||
|
||||
- **60%**: Neutral backgrounds, white space, base surfaces
|
||||
- **30%**: Secondary colors—text, borders, inactive states
|
||||
- **10%**: Accent—CTAs, highlights, focus states
|
||||
|
||||
The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
|
||||
|
||||
## Contrast & Accessibility
|
||||
|
||||
### WCAG Requirements
|
||||
|
||||
| Content Type | AA Minimum | AAA Target |
|
||||
|--------------|------------|------------|
|
||||
| Body text | 4.5:1 | 7:1 |
|
||||
| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
|
||||
| UI components, icons | 3:1 | 4.5:1 |
|
||||
| Non-essential decorations | None | None |
|
||||
|
||||
**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
|
||||
|
||||
### Dangerous Color Combinations
|
||||
|
||||
These commonly fail contrast or cause readability issues:
|
||||
|
||||
- Light gray text on white (the #1 accessibility fail)
|
||||
- **Gray text on any colored background**—gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
|
||||
- Red text on green background (or vice versa)—8% of men can't distinguish these
|
||||
- Blue text on red background (vibrates visually)
|
||||
- Yellow text on white (almost always fails)
|
||||
- Thin light text on images (unpredictable contrast)
|
||||
|
||||
### Never Use Pure Gray or Pure Black
|
||||
|
||||
Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature—real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
|
||||
|
||||
### Testing
|
||||
|
||||
Don't trust your eyes. Use tools:
|
||||
|
||||
- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
|
||||
- Browser DevTools → Rendering → Emulate vision deficiencies
|
||||
- [Polypane](https://polypane.app/) for real-time testing
|
||||
|
||||
## Theming: Light & Dark Mode
|
||||
|
||||
### Dark Mode Is Not Inverted Light Mode
|
||||
|
||||
You can't just swap colors. Dark mode requires different design decisions:
|
||||
|
||||
| Light Mode | Dark Mode |
|
||||
|------------|-----------|
|
||||
| Shadows for depth | Lighter surfaces for depth (no shadows) |
|
||||
| Dark text on light | Light text on dark (reduce font weight) |
|
||||
| Vibrant accents | Desaturate accents slightly |
|
||||
| White backgrounds | Never pure black—use dark gray (oklch 12-18%) |
|
||||
|
||||
In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project — do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
|
||||
|
||||
### Token Hierarchy
|
||||
|
||||
Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer—primitives stay the same.
|
||||
|
||||
## Alpha Is A Design Smell
|
||||
|
||||
Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
|
||||
@@ -0,0 +1,154 @@
|
||||
> **Additional context needed**: existing brand colors.
|
||||
|
||||
Strategically introduce color to designs that are too monochromatic, gray, or lacking in visual warmth and personality.
|
||||
|
||||
---
|
||||
|
||||
## Register
|
||||
|
||||
Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule — that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
|
||||
|
||||
Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators — not decoration. Every color has a consistent meaning across every screen.
|
||||
|
||||
---
|
||||
|
||||
## Assess Color Opportunity
|
||||
|
||||
Analyze the current state and identify opportunities:
|
||||
|
||||
1. **Understand current state**:
|
||||
- **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
|
||||
- **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
|
||||
- **Context**: What's appropriate for this domain and audience?
|
||||
- **Brand**: Are there existing brand colors we should use?
|
||||
|
||||
2. **Identify where color adds value**:
|
||||
- **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
|
||||
- **Hierarchy**: Drawing attention to important elements
|
||||
- **Categorization**: Different sections, types, or states
|
||||
- **Emotional tone**: Warmth, energy, trust, creativity
|
||||
- **Wayfinding**: Helping users navigate and understand structure
|
||||
- **Delight**: Moments of visual interest and personality
|
||||
|
||||
If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
|
||||
|
||||
**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
|
||||
|
||||
## Plan Color Strategy
|
||||
|
||||
Create a purposeful color introduction plan:
|
||||
|
||||
- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
|
||||
- **Dominant color**: Which color owns 60% of colored elements?
|
||||
- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
|
||||
- **Application strategy**: Where does each color appear and why?
|
||||
|
||||
**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
|
||||
|
||||
## Introduce Color Strategically
|
||||
|
||||
Add color systematically across these dimensions:
|
||||
|
||||
### Semantic Color
|
||||
- **State indicators**:
|
||||
- Success: Green tones (emerald, forest, mint)
|
||||
- Error: Red/pink tones (rose, crimson, coral)
|
||||
- Warning: Orange/amber tones
|
||||
- Info: Blue tones (sky, ocean, indigo)
|
||||
- Neutral: Gray/slate for inactive states
|
||||
|
||||
- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
|
||||
- **Progress indicators**: Colored bars, rings, or charts showing completion or health
|
||||
|
||||
### Accent Color Application
|
||||
- **Primary actions**: Color the most important buttons/CTAs
|
||||
- **Links**: Add color to clickable text (maintain accessibility)
|
||||
- **Icons**: Colorize key icons for recognition and personality
|
||||
- **Headers/titles**: Add color to section headers or key labels
|
||||
- **Hover states**: Introduce color on interaction
|
||||
|
||||
### Background & Surfaces
|
||||
- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
|
||||
- **Colored sections**: Use subtle background colors to separate areas
|
||||
- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
|
||||
- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
|
||||
|
||||
**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
|
||||
|
||||
### Data Visualization
|
||||
- **Charts & graphs**: Use color to encode categories or values
|
||||
- **Heatmaps**: Color intensity shows density or importance
|
||||
- **Comparison**: Color coding for different datasets or timeframes
|
||||
|
||||
### Borders & Accents
|
||||
- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes — see the absolute ban on `border-left/right > 1px`)
|
||||
- **Underlines**: Color underlines for emphasis or active states
|
||||
- **Dividers**: Subtle colored dividers instead of gray lines
|
||||
- **Focus rings**: Colored focus indicators matching brand
|
||||
- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
|
||||
|
||||
**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix — not a side stripe.
|
||||
|
||||
### Typography Color
|
||||
- **Colored headings**: Use brand colors for section headings (maintain contrast)
|
||||
- **Highlight text**: Color for emphasis or categories
|
||||
- **Labels & tags**: Small colored labels for metadata or categories
|
||||
|
||||
### Decorative Elements
|
||||
- **Illustrations**: Add colored illustrations or icons
|
||||
- **Shapes**: Geometric shapes in brand colors as background elements
|
||||
- **Gradients**: Colorful gradient overlays or mesh backgrounds
|
||||
- **Blobs/organic shapes**: Soft colored shapes for visual interest
|
||||
|
||||
## Balance & Refinement
|
||||
|
||||
Ensure color addition improves rather than overwhelms:
|
||||
|
||||
### Maintain Hierarchy
|
||||
- **Dominant color** (60%): Primary brand color or most used accent
|
||||
- **Secondary color** (30%): Supporting color for variety
|
||||
- **Accent color** (10%): High contrast for key moments
|
||||
- **Neutrals** (remaining): Gray/black/white for structure
|
||||
|
||||
### Accessibility
|
||||
- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
|
||||
- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
|
||||
- **Test for color blindness**: Verify red/green combinations work for all users
|
||||
|
||||
### Cohesion
|
||||
- **Consistent palette**: Use colors from defined palette, not arbitrary choices
|
||||
- **Systematic application**: Same color meanings throughout (green always = success)
|
||||
- **Temperature consistency**: Warm palette stays warm, cool stays cool
|
||||
|
||||
**NEVER**:
|
||||
- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
|
||||
- Apply color randomly without semantic meaning
|
||||
- Put gray text on colored backgrounds—it looks washed out; use a darker shade of the background color or transparency instead
|
||||
- Use pure gray for neutrals—add subtle color tint (warm or cool) for sophistication
|
||||
- Use pure black (`#000`) or pure white (`#fff`) for large areas
|
||||
- Violate WCAG contrast requirements
|
||||
- Use color as the only indicator (accessibility issue)
|
||||
- Make everything colorful (defeats the purpose)
|
||||
- Default to purple-blue gradients (AI slop aesthetic)
|
||||
|
||||
## Verify Color Addition
|
||||
|
||||
Test that colorization improves the experience:
|
||||
|
||||
- **Better hierarchy**: Does color guide attention appropriately?
|
||||
- **Clearer meaning**: Does color help users understand states/categories?
|
||||
- **More engaging**: Does the interface feel warmer and more inviting?
|
||||
- **Still accessible**: Do all color combinations meet WCAG standards?
|
||||
- **Not overwhelming**: Is color balanced and purposeful?
|
||||
|
||||
Remember: Color is emotional and powerful. Use it to create warmth, guide attention, communicate meaning, and express personality. But restraint and strategy matter more than saturation and variety. Be colorful, but be intentional.
|
||||
|
||||
## Live-mode signature params
|
||||
|
||||
When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)` — typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
|
||||
|
||||
```json
|
||||
{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
|
||||
```
|
||||
|
||||
Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
|
||||
@@ -0,0 +1,138 @@
|
||||
# Craft Flow
|
||||
|
||||
Build a feature with impeccable UX and UI quality through a structured process: shape the design, load the right references, then build and iterate visually until the result is delightful.
|
||||
|
||||
## Real Example: Neo Mirai
|
||||
|
||||
Neo Mirai is the full craft loop in public. A retro-futurist AI design conference started with generated brand and hi-fi reference images, then shipped as a responsive static site in `public/neo-mirai`.
|
||||
|
||||
Repro command:
|
||||
|
||||
```bash
|
||||
/impeccable craft retro-futurist AI design conference website
|
||||
```
|
||||
|
||||
The important detail is the artifact chain: brand toolkit, north-star mock, semantic implementation, regenerated assets, browser iteration, responsive fixes. The mock was not treated as a screenshot to trace. It was used as direction for a real page.
|
||||
|
||||
## Step 1: Shape the Design
|
||||
|
||||
Run /impeccable shape, passing along whatever feature description the user provided.
|
||||
|
||||
Wait for the design brief to be fully confirmed before proceeding. The brief is your blueprint, and every implementation decision should trace back to it.
|
||||
|
||||
If the user has already run /impeccable shape and has a confirmed design brief, skip this step and use the existing brief.
|
||||
|
||||
## Step 2: Load References
|
||||
|
||||
Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
|
||||
|
||||
- [spatial-design.md](spatial-design.md) for layout and spacing
|
||||
- [typography.md](typography.md) for type hierarchy
|
||||
|
||||
Then add references based on the brief's needs:
|
||||
- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
|
||||
- Animation or transitions? Consult [motion-design.md](motion-design.md)
|
||||
- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
|
||||
- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
|
||||
- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
|
||||
|
||||
## Step 3: North Star Mock (Capability-Gated)
|
||||
|
||||
Before implementation, generate a small set of high-fidelity visual comps when all of these are true:
|
||||
|
||||
- The work is **net-new** or visually open-ended enough that composition exploration will improve the build.
|
||||
- The brief's scope is **mid-fi, high-fi, or production-ready**.
|
||||
- The current harness has **built-in image generation capability** (for example, Codex with a native image tool). Do **not** ask the user to set up external APIs, shell scripts, or one-off tooling just to do this.
|
||||
|
||||
When those conditions are met, this step is the default for **both brand and product work**.
|
||||
|
||||
### Purpose
|
||||
|
||||
Use the mock step to find a stronger visual lane than code-first generation would reliably discover on its own. The brief remains authoritative on user, purpose, content, constraints, states, and anti-goals. The mock clarifies composition, hierarchy, density, typography, and visual tone.
|
||||
|
||||
### What to generate
|
||||
|
||||
Generate **1 to 3** high-fidelity north-star comps based on the confirmed brief.
|
||||
|
||||
- For brand work, push visual identity, composition, and mood aggressively.
|
||||
- For product work, still push hierarchy, topology, density, and tone, but keep the comps grounded in realistic product structure and states.
|
||||
|
||||
The comps must be genuinely different in primary visual direction, not just color variants.
|
||||
|
||||
### After generation
|
||||
|
||||
Choose a direction with the user, or if the user delegated the decision, pick the strongest one and explain why.
|
||||
|
||||
Before moving to implementation, summarize:
|
||||
|
||||
- What to carry into code
|
||||
- What **not** to literalize from the mock
|
||||
|
||||
Treat the mock as a **north star**, not a screenshot to trace. Do **not** let it override the confirmed brief.
|
||||
|
||||
## Step 4: Asset Extraction (Optional)
|
||||
|
||||
If the chosen direction includes image-native visual ingredients that would materially improve the implementation, generate them as separate assets before building.
|
||||
|
||||
Good candidates:
|
||||
|
||||
- stickers
|
||||
- badges
|
||||
- seals
|
||||
- tickets
|
||||
- graphic labels
|
||||
- textures
|
||||
- abstract objects
|
||||
- decorative marks
|
||||
- non-semantic scene elements
|
||||
|
||||
Do **not** export assets for core UI text, navigation, body copy, or any structure that should stay semantic and editable in code.
|
||||
|
||||
Usually **1 to 5** extracted assets is enough. If the design can be built cleanly in HTML/CSS/SVG, prefer that over raster assets.
|
||||
|
||||
## Step 5: Build
|
||||
|
||||
Implement the feature following the design brief. Work in this order:
|
||||
|
||||
1. **Structure first**: HTML/semantic structure for the primary state. No styling yet.
|
||||
2. **Layout and spacing**: Establish the spatial rhythm and visual hierarchy.
|
||||
3. **Typography and color**: Apply the type scale and color system.
|
||||
4. **Interactive states**: Hover, focus, active, disabled.
|
||||
5. **Edge case states**: Empty, loading, error, overflow, first-run.
|
||||
6. **Motion**: Purposeful transitions and animations (if appropriate).
|
||||
7. **Responsive**: Adapt for different viewports. Don't just shrink; redesign for the context.
|
||||
|
||||
### During Build
|
||||
- Test with real (or realistic) data at every step, not placeholder text
|
||||
- Check each state as you build it, not all at the end
|
||||
- If you discover a design question, stop and ask rather than guessing
|
||||
- Every visual choice should trace back to something in the design brief or the chosen north-star direction
|
||||
- Keep text semantic, layout real, and interactions accessible. Do not turn the mock into a pile of rasterized UI
|
||||
- If assets were extracted, use them intentionally. They support the build; they do not replace interface structure
|
||||
|
||||
## Step 6: Visual Iteration
|
||||
|
||||
**This step is critical.** Do not stop after the first implementation pass.
|
||||
|
||||
Open the result in a browser window. If browser automation tools are available, use them to navigate to the page and visually inspect the result. If not, ask the user to open it and provide feedback.
|
||||
|
||||
Iterate through these checks visually:
|
||||
|
||||
1. **Does it match the brief?** Compare the live result against every section of the design brief. Fix discrepancies.
|
||||
2. **Does it pass the AI slop test?** If someone saw this and said "AI made this," would they believe it immediately? If yes, it needs more design intention.
|
||||
3. **Check against impeccable's DON'T guidelines.** Fix any anti-pattern violations.
|
||||
4. **Check every state.** Navigate through empty, error, loading, and edge case states. Each one should feel intentional, not like an afterthought.
|
||||
5. **Check responsive.** Resize the viewport. Does it adapt well or just shrink?
|
||||
6. **Check the details.** Spacing consistency, type hierarchy clarity, color contrast, interactive feedback, motion timing.
|
||||
|
||||
After each round of fixes, visually verify again. **Repeat until you would be proud to show this to the user.** The bar is not "it works"; the bar is "this delights."
|
||||
|
||||
## Step 7: Present
|
||||
|
||||
Present the result to the user:
|
||||
- Show the feature in its primary state
|
||||
- Walk through the key states (empty, error, responsive)
|
||||
- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock
|
||||
- Ask: "What's working? What isn't?"
|
||||
|
||||
Iterate based on feedback. Good design is rarely right on the first pass.
|
||||
@@ -0,0 +1,213 @@
|
||||
> **Additional context needed**: what the interface is trying to accomplish.
|
||||
|
||||
### Gather Assessments
|
||||
|
||||
Launch two independent assessments. **Neither may see the other's output** — this isolation is what makes the combined score honest. Running both in one head silently anchors them to each other; do not shortcut it for cost, speed, or context-size reasons.
|
||||
|
||||
Delegate each assessment to a separate sub-agent (Claude Code's `Agent` tool, Codex's subagent spawning, etc.). Each returns structured findings as text. Do NOT output findings to the user yet.
|
||||
|
||||
Fall back to sequential in-head work only if the environment genuinely cannot spawn sub-agents.
|
||||
|
||||
**Tab isolation**: When browser automation is available, each assessment MUST create its own new tab. Never reuse an existing tab, even if one is already open at the correct URL. This prevents the two assessments from interfering with each other's page state.
|
||||
|
||||
#### Assessment A: LLM Design Review
|
||||
|
||||
Read the relevant source files (HTML, CSS, JS/TS) and, if browser automation is available, visually inspect the live page. **Create a new tab** for this; do not reuse existing tabs. After navigation, label the tab by setting the document title:
|
||||
```javascript
|
||||
document.title = '[LLM] ' + document.title;
|
||||
```
|
||||
Think like a design director. Evaluate:
|
||||
|
||||
**AI Slop Detection (CRITICAL)**: Does this look like every other AI-generated interface? Review against ALL **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Check for AI color palette, gradient text, dark glows, glassmorphism, hero metric layouts, identical card grids, generic fonts, and all other tells. **The test**: If someone said "AI made this," would you believe them immediately?
|
||||
|
||||
**Holistic Design Review**: visual hierarchy (eye flow, primary action clarity), information architecture (structure, grouping, cognitive load), emotional resonance (does it match brand and audience?), discoverability (are interactive elements obvious?), composition (balance, whitespace, rhythm), typography (hierarchy, readability, font choices), color (purposeful use, cohesion, accessibility), states & edge cases (empty, loading, error, success), microcopy (clarity, tone, helpfulness).
|
||||
|
||||
**Cognitive Load** (consult [cognitive-load](cognitive-load.md)):
|
||||
- Run the 8-item cognitive load checklist. Report failure count: 0-1 = low (good), 2-3 = moderate, 4+ = critical.
|
||||
- Count visible options at each decision point. If >4, flag it.
|
||||
- Check for progressive disclosure: is complexity revealed only when needed?
|
||||
|
||||
**Emotional Journey**:
|
||||
- What emotion does this interface evoke? Is that intentional?
|
||||
- **Peak-end rule**: Is the most intense moment positive? Does the experience end well?
|
||||
- **Emotional valleys**: Check for anxiety spikes at high-stakes moments (payment, delete, commit). Are there design interventions (progress indicators, reassurance copy, undo options)?
|
||||
|
||||
**Nielsen's Heuristics** (consult [heuristics-scoring](heuristics-scoring.md)):
|
||||
Score each of the 10 heuristics 0-4. This scoring will be presented in the report.
|
||||
|
||||
Return structured findings covering: AI slop verdict, heuristic scores, cognitive load assessment, what's working (2-3 items), priority issues (3-5 with what/why/fix), minor observations, and provocative questions.
|
||||
|
||||
#### Assessment B: Automated Detection
|
||||
|
||||
Run the bundled deterministic detector, which flags 25 specific patterns (AI slop tells + general design quality).
|
||||
|
||||
**CLI scan**:
|
||||
```bash
|
||||
npx impeccable --json [--fast] [target]
|
||||
```
|
||||
|
||||
- Pass HTML/JSX/TSX/Vue/Svelte files or directories as `[target]` (anything with markup). Do not pass CSS-only files.
|
||||
- For URLs, skip the CLI scan (it requires Puppeteer). Use browser visualization instead.
|
||||
- For large directories (200+ scannable files), use `--fast` (regex-only, skips jsdom)
|
||||
- For 500+ files, narrow scope or ask the user
|
||||
- Exit code 0 = clean, 2 = findings
|
||||
|
||||
**Browser visualization** — **required** when browser automation tools are available AND the target is a viewable page. The `[Human]` overlay tab is the user-facing deliverable; the critique is incomplete without it. Skip only if the target is not a viewable page (CSS-only file, non-browser target).
|
||||
|
||||
The overlay is a **visual aid for the user**. It highlights issues directly in their browser. Do NOT scroll through the page to screenshot overlays. Instead, read the console output to get the results programmatically.
|
||||
|
||||
1. **Start the live detection server**:
|
||||
```bash
|
||||
npx impeccable live &
|
||||
```
|
||||
Note the port printed to stdout (auto-assigned). Use `--port=PORT` to fix it.
|
||||
2. **Create a new tab** and navigate to the page (use dev server URL for local files, or direct URL). Do not reuse existing tabs.
|
||||
3. **Label the tab** via `javascript_tool` so the user can distinguish it:
|
||||
```javascript
|
||||
document.title = '[Human] ' + document.title;
|
||||
```
|
||||
4. **Scroll to top** to ensure the page is scrolled to the very top before injection
|
||||
5. **Inject** via `javascript_tool` (replace PORT with the port from step 1):
|
||||
```javascript
|
||||
const s = document.createElement('script'); s.src = 'http://localhost:PORT/detect.js'; document.head.appendChild(s);
|
||||
```
|
||||
6. Wait 2-3 seconds for the detector to render overlays
|
||||
7. **Read results from console** using `read_console_messages` with pattern `impeccable`. The detector logs all findings with the `[impeccable]` prefix. Do NOT scroll through the page to take screenshots of the overlays.
|
||||
8. **Cleanup**: Stop the live server when done:
|
||||
```bash
|
||||
npx impeccable live stop
|
||||
```
|
||||
|
||||
For multi-view targets, inject on 3-5 representative pages. If injection fails, continue with CLI results only.
|
||||
|
||||
Return: CLI findings (JSON), browser console findings (if applicable), and any false positives noted.
|
||||
|
||||
### Generate Combined Critique Report
|
||||
|
||||
Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
|
||||
|
||||
Structure your feedback as a design director would:
|
||||
|
||||
#### Design Health Score
|
||||
> *Consult [heuristics-scoring](heuristics-scoring.md)*
|
||||
|
||||
Present the Nielsen's 10 heuristics scores as a table:
|
||||
|
||||
| # | Heuristic | Score | Key Issue |
|
||||
|---|-----------|-------|-----------|
|
||||
| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
|
||||
| 2 | Match System / Real World | ? | |
|
||||
| 3 | User Control and Freedom | ? | |
|
||||
| 4 | Consistency and Standards | ? | |
|
||||
| 5 | Error Prevention | ? | |
|
||||
| 6 | Recognition Rather Than Recall | ? | |
|
||||
| 7 | Flexibility and Efficiency | ? | |
|
||||
| 8 | Aesthetic and Minimalist Design | ? | |
|
||||
| 9 | Error Recovery | ? | |
|
||||
| 10 | Help and Documentation | ? | |
|
||||
| **Total** | | **??/40** | **[Rating band]** |
|
||||
|
||||
Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
|
||||
|
||||
#### Anti-Patterns Verdict
|
||||
|
||||
**Start here.** Does this look AI-generated?
|
||||
|
||||
**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
|
||||
|
||||
**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
|
||||
|
||||
**Visual overlays** (if browser was used): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported.
|
||||
|
||||
#### Overall Impression
|
||||
A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
|
||||
|
||||
#### What's Working
|
||||
Highlight 2-3 things done well. Be specific about why they work.
|
||||
|
||||
#### Priority Issues
|
||||
The 3-5 most impactful design problems, ordered by importance.
|
||||
|
||||
For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
|
||||
- **[P?] What**: Name the problem clearly
|
||||
- **Why it matters**: How this hurts users or undermines goals
|
||||
- **Fix**: What to do about it (be concrete)
|
||||
- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
|
||||
|
||||
#### Persona Red Flags
|
||||
> *Consult [personas](personas.md)*
|
||||
|
||||
Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `CLAUDE.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
|
||||
|
||||
For each selected persona, walk through the primary user action and list specific red flags found:
|
||||
|
||||
**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
|
||||
|
||||
**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
|
||||
|
||||
Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
|
||||
|
||||
#### Minor Observations
|
||||
Quick notes on smaller issues worth addressing.
|
||||
|
||||
#### Questions to Consider
|
||||
Provocative questions that might unlock better solutions:
|
||||
- "What if the primary action were more prominent?"
|
||||
- "Does this need to feel this complex?"
|
||||
- "What would a confident version of this look like?"
|
||||
|
||||
**Remember**:
|
||||
- Be direct. Vague feedback wastes everyone's time.
|
||||
- Be specific. "The submit button," not "some elements."
|
||||
- Say what's wrong AND why it matters to users.
|
||||
- Give concrete suggestions, not just "consider exploring..."
|
||||
- Prioritize ruthlessly. If everything is important, nothing is.
|
||||
- Don't soften criticism. Developers need honest feedback to ship great design.
|
||||
|
||||
### Ask the User
|
||||
|
||||
**After presenting findings**, use targeted questions based on what was actually found. STOP and call the AskUserQuestion tool to clarify. These answers will shape the action plan.
|
||||
|
||||
Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
|
||||
|
||||
1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
|
||||
|
||||
2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
|
||||
|
||||
3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
|
||||
|
||||
4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
|
||||
|
||||
**Rules for questions**:
|
||||
- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
|
||||
- Keep it to 2-4 questions maximum. Respect the user's time.
|
||||
- Offer concrete options, not open-ended prompts.
|
||||
- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
|
||||
|
||||
### Recommended Actions
|
||||
|
||||
**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
|
||||
|
||||
#### Action Summary
|
||||
|
||||
List recommended commands in priority order, based on the user's answers:
|
||||
|
||||
1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
|
||||
2. **`/command-name`**: Brief description (specific context)
|
||||
...
|
||||
|
||||
**Rules for recommendations**:
|
||||
- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
|
||||
- Order by the user's stated priorities first, then by impact
|
||||
- Each item's description should carry enough context that the command knows what to focus on
|
||||
- Map each Priority Issue to the appropriate command
|
||||
- Skip commands that would address zero issues
|
||||
- If the user chose a limited scope, only include items within that scope
|
||||
- If the user marked areas as off-limits, exclude commands that would touch those areas
|
||||
- End with `/impeccable polish` as the final step if any fixes were recommended
|
||||
|
||||
After presenting the summary, tell the user:
|
||||
|
||||
> You can ask me to run these one at a time, all at once, or in any order you prefer.
|
||||
>
|
||||
> Re-run `/impeccable critique` after fixes to see your score improve.
|
||||
@@ -0,0 +1,302 @@
|
||||
> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
|
||||
|
||||
Identify opportunities to add moments of joy, personality, and unexpected polish that transform functional interfaces into delightful experiences.
|
||||
|
||||
---
|
||||
|
||||
## Register
|
||||
|
||||
Brand: delight can be distributed — copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
|
||||
|
||||
Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
|
||||
|
||||
---
|
||||
|
||||
## Assess Delight Opportunities
|
||||
|
||||
Identify where delight would enhance (not distract from) the experience:
|
||||
|
||||
1. **Find natural delight moments**:
|
||||
- **Success states**: Completed actions (save, send, publish)
|
||||
- **Empty states**: First-time experiences, onboarding
|
||||
- **Loading states**: Waiting periods that could be entertaining
|
||||
- **Achievements**: Milestones, streaks, completions
|
||||
- **Interactions**: Hover states, clicks, drags
|
||||
- **Errors**: Softening frustrating moments
|
||||
- **Easter eggs**: Hidden discoveries for curious users
|
||||
|
||||
2. **Understand the context**:
|
||||
- What's the brand personality? (Playful? Professional? Quirky? Elegant?)
|
||||
- Who's the audience? (Tech-savvy? Creative? Corporate?)
|
||||
- What's the emotional context? (Accomplishment? Exploration? Frustration?)
|
||||
- What's appropriate? (Banking app ≠ gaming app)
|
||||
|
||||
3. **Define delight strategy**:
|
||||
- **Subtle sophistication**: Refined micro-interactions (luxury brands)
|
||||
- **Playful personality**: Whimsical illustrations and copy (consumer apps)
|
||||
- **Helpful surprises**: Anticipating needs before users ask (productivity tools)
|
||||
- **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
|
||||
|
||||
If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
|
||||
|
||||
**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
|
||||
|
||||
## Delight Principles
|
||||
|
||||
Follow these guidelines:
|
||||
|
||||
### Delight Amplifies, Never Blocks
|
||||
- Delight moments should be quick (< 1 second)
|
||||
- Never delay core functionality for delight
|
||||
- Make delight skippable or subtle
|
||||
- Respect user's time and task focus
|
||||
|
||||
### Surprise and Discovery
|
||||
- Hide delightful details for users to discover
|
||||
- Reward exploration and curiosity
|
||||
- Don't announce every delight moment
|
||||
- Let users share discoveries with others
|
||||
|
||||
### Appropriate to Context
|
||||
- Match delight to emotional moment (celebrate success, empathize with errors)
|
||||
- Respect the user's state (don't be playful during critical errors)
|
||||
- Match brand personality and audience expectations
|
||||
- Cultural sensitivity (what's delightful varies by culture)
|
||||
|
||||
### Compound Over Time
|
||||
- Delight should remain fresh with repeated use
|
||||
- Vary responses (not same animation every time)
|
||||
- Reveal deeper layers with continued use
|
||||
- Build anticipation through patterns
|
||||
|
||||
## Delight Techniques
|
||||
|
||||
Add personality and joy through these methods:
|
||||
|
||||
### Micro-interactions & Animation
|
||||
|
||||
**Button delight**:
|
||||
```css
|
||||
/* Satisfying button press */
|
||||
.button {
|
||||
transition: transform 0.1s, box-shadow 0.1s;
|
||||
}
|
||||
.button:active {
|
||||
transform: translateY(2px);
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
|
||||
}
|
||||
|
||||
/* Ripple effect on click */
|
||||
/* Smooth lift on hover */
|
||||
.button:hover {
|
||||
transform: translateY(-2px);
|
||||
transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
|
||||
}
|
||||
```
|
||||
|
||||
**Loading delight**:
|
||||
- Playful loading animations (not just spinners)
|
||||
- Personality in loading messages (write product-specific ones, not generic AI filler)
|
||||
- Progress indication with encouraging messages
|
||||
- Skeleton screens with subtle animations
|
||||
|
||||
**Success animations**:
|
||||
- Checkmark draw animation
|
||||
- Confetti burst for major achievements
|
||||
- Gentle scale + fade for confirmation
|
||||
- Satisfying sound effects (subtle)
|
||||
|
||||
**Hover surprises**:
|
||||
- Icons that animate on hover
|
||||
- Color shifts or glow effects
|
||||
- Tooltip reveals with personality
|
||||
- Cursor changes (custom cursors for branded experiences)
|
||||
|
||||
### Personality in Copy
|
||||
|
||||
**Playful error messages**:
|
||||
```
|
||||
"Error 404"
|
||||
"This page is playing hide and seek. (And winning)"
|
||||
|
||||
"Connection failed"
|
||||
"Looks like the internet took a coffee break. Want to retry?"
|
||||
```
|
||||
|
||||
**Encouraging empty states**:
|
||||
```
|
||||
"No projects"
|
||||
"Your canvas awaits. Create something amazing."
|
||||
|
||||
"No messages"
|
||||
"Inbox zero! You're crushing it today."
|
||||
```
|
||||
|
||||
**Playful labels & tooltips**:
|
||||
```
|
||||
"Delete"
|
||||
"Send to void" (for playful brand)
|
||||
|
||||
"Help"
|
||||
"Rescue me" (tooltip)
|
||||
```
|
||||
|
||||
**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
|
||||
|
||||
### Illustrations & Visual Personality
|
||||
|
||||
**Custom illustrations**:
|
||||
- Empty state illustrations (not stock icons)
|
||||
- Error state illustrations (friendly monsters, quirky characters)
|
||||
- Loading state illustrations (animated characters)
|
||||
- Success state illustrations (celebrations)
|
||||
|
||||
**Icon personality**:
|
||||
- Custom icon set matching brand personality
|
||||
- Animated icons (subtle motion on hover/click)
|
||||
- Illustrative icons (more detailed than generic)
|
||||
- Consistent style across all icons
|
||||
|
||||
**Background effects**:
|
||||
- Subtle particle effects
|
||||
- Gradient mesh backgrounds
|
||||
- Geometric patterns
|
||||
- Parallax depth
|
||||
- Time-of-day themes (morning vs night)
|
||||
|
||||
### Satisfying Interactions
|
||||
|
||||
**Drag and drop delight**:
|
||||
- Lift effect on drag (shadow, scale)
|
||||
- Snap animation when dropped
|
||||
- Satisfying placement sound
|
||||
- Undo toast ("Dropped in wrong place? [Undo]")
|
||||
|
||||
**Toggle switches**:
|
||||
- Smooth slide with spring physics
|
||||
- Color transition
|
||||
- Haptic feedback on mobile
|
||||
- Optional sound effect
|
||||
|
||||
**Progress & achievements**:
|
||||
- Streak counters with celebratory milestones
|
||||
- Progress bars that "celebrate" at 100%
|
||||
- Badge unlocks with animation
|
||||
- Playful stats ("You're on fire! 5 days in a row")
|
||||
|
||||
**Form interactions**:
|
||||
- Input fields that animate on focus
|
||||
- Checkboxes with a satisfying scale pulse when checked
|
||||
- Success state that celebrates valid input
|
||||
- Auto-grow textareas
|
||||
|
||||
### Sound Design
|
||||
|
||||
**Subtle audio cues** (when appropriate):
|
||||
- Notification sounds (distinctive but not annoying)
|
||||
- Success sounds (satisfying "ding")
|
||||
- Error sounds (empathetic, not harsh)
|
||||
- Typing sounds for chat/messaging
|
||||
- Ambient background audio (very subtle)
|
||||
|
||||
**IMPORTANT**:
|
||||
- Respect system sound settings
|
||||
- Provide mute option
|
||||
- Keep volumes quiet (subtle cues, not alarms)
|
||||
- Don't play on every interaction (sound fatigue is real)
|
||||
|
||||
### Easter Eggs & Hidden Delights
|
||||
|
||||
**Discovery rewards**:
|
||||
- Konami code unlocks special theme
|
||||
- Hidden keyboard shortcuts (Cmd+K for special features)
|
||||
- Hover reveals on logos or illustrations
|
||||
- Alt text jokes on images (for screen reader users too!)
|
||||
- Console messages for developers ("Like what you see? We're hiring!")
|
||||
|
||||
**Seasonal touches**:
|
||||
- Holiday themes (subtle, tasteful)
|
||||
- Seasonal color shifts
|
||||
- Weather-based variations
|
||||
- Time-based changes (dark at night, light during day)
|
||||
|
||||
**Contextual personality**:
|
||||
- Different messages based on time of day
|
||||
- Responses to specific user actions
|
||||
- Randomized variations (not same every time)
|
||||
- Progressive reveals with continued use
|
||||
|
||||
### Loading & Waiting States
|
||||
|
||||
**Make waiting engaging**:
|
||||
- Interesting loading messages that rotate
|
||||
- Progress bars with personality
|
||||
- Mini-games during long loads
|
||||
- Fun facts or tips while waiting
|
||||
- Countdown with encouraging messages
|
||||
|
||||
```
|
||||
Loading messages — write ones specific to your product, not generic AI filler:
|
||||
- "Crunching your latest numbers..."
|
||||
- "Syncing with your team's changes..."
|
||||
- "Preparing your dashboard..."
|
||||
- "Checking for updates since yesterday..."
|
||||
```
|
||||
|
||||
**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy — instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
|
||||
|
||||
### Celebration Moments
|
||||
|
||||
**Success celebrations**:
|
||||
- Confetti for major milestones
|
||||
- Animated checkmarks for completions
|
||||
- Progress bar celebrations at 100%
|
||||
- "Achievement unlocked" style notifications
|
||||
- Personalized messages ("You published your 10th article!")
|
||||
|
||||
**Milestone recognition**:
|
||||
- First-time actions get special treatment
|
||||
- Streak tracking and celebration
|
||||
- Progress toward goals
|
||||
- Anniversary celebrations
|
||||
|
||||
## Implementation Patterns
|
||||
|
||||
**Animation libraries**:
|
||||
- Framer Motion (React)
|
||||
- GSAP (universal)
|
||||
- Lottie (After Effects animations)
|
||||
- Canvas confetti (party effects)
|
||||
|
||||
**Sound libraries**:
|
||||
- Howler.js (audio management)
|
||||
- Use-sound (React hook)
|
||||
|
||||
**Physics libraries**:
|
||||
- React Spring (spring physics)
|
||||
- Popmotion (animation primitives)
|
||||
|
||||
**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
|
||||
|
||||
**NEVER**:
|
||||
- Delay core functionality for delight
|
||||
- Force users through delightful moments (make skippable)
|
||||
- Use delight to hide poor UX
|
||||
- Overdo it (less is more)
|
||||
- Ignore accessibility (animate responsibly, provide alternatives)
|
||||
- Make every interaction delightful (special moments should be special)
|
||||
- Sacrifice performance for delight
|
||||
- Be inappropriate for context (read the room)
|
||||
|
||||
## Verify Delight Quality
|
||||
|
||||
Test that delight actually delights:
|
||||
|
||||
- **User reactions**: Do users smile? Share screenshots?
|
||||
- **Doesn't annoy**: Still pleasant after 100th time?
|
||||
- **Doesn't block**: Can users opt out or skip?
|
||||
- **Performant**: No jank, no slowdown
|
||||
- **Appropriate**: Matches brand and context
|
||||
- **Accessible**: Works with reduced motion, screen readers
|
||||
|
||||
Remember: Delight is the difference between a tool and an experience. Add personality, surprise users positively, and create moments worth sharing. But always respect usability - delight should enhance, never obstruct.
|
||||
@@ -0,0 +1,111 @@
|
||||
Remove unnecessary complexity from designs, revealing the essential elements and creating clarity through ruthless simplification.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Assess Current State
|
||||
|
||||
Analyze what makes the design feel complex or cluttered:
|
||||
|
||||
1. **Identify complexity sources**:
|
||||
- **Too many elements**: Competing buttons, redundant information, visual clutter
|
||||
- **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
|
||||
- **Information overload**: Everything visible at once, no progressive disclosure
|
||||
- **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
|
||||
- **Confusing hierarchy**: Unclear what matters most
|
||||
- **Feature creep**: Too many options, actions, or paths forward
|
||||
|
||||
2. **Find the essence**:
|
||||
- What's the primary user goal? (There should be ONE)
|
||||
- What's actually necessary vs nice-to-have?
|
||||
- What can be removed, hidden, or combined?
|
||||
- What's the 20% that delivers 80% of value?
|
||||
|
||||
If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
|
||||
|
||||
**CRITICAL**: Simplicity is not about removing features - it's about removing obstacles between users and their goals. Every element should justify its existence.
|
||||
|
||||
## Plan Simplification
|
||||
|
||||
Create a ruthless editing strategy:
|
||||
|
||||
- **Core purpose**: What's the ONE thing this should accomplish?
|
||||
- **Essential elements**: What's truly necessary to achieve that purpose?
|
||||
- **Progressive disclosure**: What can be hidden until needed?
|
||||
- **Consolidation opportunities**: What can be combined or integrated?
|
||||
|
||||
**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
|
||||
|
||||
## Simplify the Design
|
||||
|
||||
Systematically remove complexity across these dimensions:
|
||||
|
||||
### Information Architecture
|
||||
- **Reduce scope**: Remove secondary actions, optional features, redundant information
|
||||
- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
|
||||
- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
|
||||
- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
|
||||
- **Remove redundancy**: If it's said elsewhere, don't repeat it here
|
||||
|
||||
### Visual Simplification
|
||||
- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
|
||||
- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
|
||||
- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
|
||||
- **Flatten structure**: Reduce nesting, remove unnecessary containers—never nest cards inside cards
|
||||
- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
|
||||
- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
|
||||
|
||||
### Layout Simplification
|
||||
- **Linear flow**: Replace complex grids with simple vertical flow where possible
|
||||
- **Remove sidebars**: Move secondary content inline or hide it
|
||||
- **Full-width**: Use available space generously instead of complex multi-column layouts
|
||||
- **Consistent alignment**: Pick left or center, stick with it
|
||||
- **Generous white space**: Let content breathe, don't pack everything tight
|
||||
|
||||
### Interaction Simplification
|
||||
- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
|
||||
- **Smart defaults**: Make common choices automatic, only ask when necessary
|
||||
- **Inline actions**: Replace modal flows with inline editing where possible
|
||||
- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
|
||||
- **Clear CTAs**: ONE obvious next step, not five competing actions
|
||||
|
||||
### Content Simplification
|
||||
- **Shorter copy**: Cut every sentence in half, then do it again
|
||||
- **Active voice**: "Save changes" not "Changes will be saved"
|
||||
- **Remove jargon**: Plain language always wins
|
||||
- **Scannable structure**: Short paragraphs, bullet points, clear headings
|
||||
- **Essential information only**: Remove marketing fluff, legalese, hedging
|
||||
- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
|
||||
|
||||
### Code Simplification
|
||||
- **Remove unused code**: Dead CSS, unused components, orphaned files
|
||||
- **Flatten component trees**: Reduce nesting depth
|
||||
- **Consolidate styles**: Merge similar styles, use utilities consistently
|
||||
- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
|
||||
|
||||
**NEVER**:
|
||||
- Remove necessary functionality (simplicity ≠ feature-less)
|
||||
- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
|
||||
- Make things so simple they're unclear (mystery ≠ minimalism)
|
||||
- Remove information users need to make decisions
|
||||
- Eliminate hierarchy completely (some things should stand out)
|
||||
- Oversimplify complex domains (match complexity to actual task complexity)
|
||||
|
||||
## Verify Simplification
|
||||
|
||||
Ensure simplification improves usability:
|
||||
|
||||
- **Faster task completion**: Can users accomplish goals more quickly?
|
||||
- **Reduced cognitive load**: Is it easier to understand what to do?
|
||||
- **Still complete**: Are all necessary features still accessible?
|
||||
- **Clearer hierarchy**: Is it obvious what matters most?
|
||||
- **Better performance**: Does simpler design load faster?
|
||||
|
||||
## Document Removed Complexity
|
||||
|
||||
If you removed features or options:
|
||||
- Document why they were removed
|
||||
- Consider if they need alternative access points
|
||||
- Note any user feedback to monitor
|
||||
|
||||
Remember: You have great taste and judgment. Simplification is an act of confidence - knowing what to keep and courage to remove the rest. As Antoine de Saint-Exupéry said: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
|
||||
@@ -0,0 +1,427 @@
|
||||
Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
|
||||
|
||||
DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
|
||||
|
||||
## The frontmatter: token schema
|
||||
|
||||
The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: <project title>
|
||||
description: <one-line tagline>
|
||||
colors:
|
||||
primary: "#b8422e"
|
||||
neutral-bg: "#faf7f2"
|
||||
# ...one entry per extracted color; key = descriptive slug
|
||||
typography:
|
||||
display:
|
||||
fontFamily: "Cormorant Garamond, Georgia, serif"
|
||||
fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
|
||||
fontWeight: 300
|
||||
lineHeight: 1
|
||||
letterSpacing: "normal"
|
||||
body:
|
||||
# ...
|
||||
rounded:
|
||||
sm: "4px"
|
||||
md: "8px"
|
||||
spacing:
|
||||
sm: "8px"
|
||||
md: "16px"
|
||||
components:
|
||||
button-primary:
|
||||
backgroundColor: "{colors.primary}"
|
||||
textColor: "{colors.neutral-bg}"
|
||||
rounded: "{rounded.sm}"
|
||||
padding: "16px 48px"
|
||||
button-primary-hover:
|
||||
backgroundColor: "{colors.primary-deep}"
|
||||
---
|
||||
```
|
||||
|
||||
Rules that matter:
|
||||
|
||||
- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
|
||||
- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
|
||||
- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter — none of those fit. Carry them in the sidecar (Step 4b).
|
||||
- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
|
||||
- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
|
||||
|
||||
## The markdown body: six sections (exact order)
|
||||
|
||||
1. `## Overview`
|
||||
2. `## Colors`
|
||||
3. `## Typography`
|
||||
4. `## Elevation`
|
||||
5. `## Components`
|
||||
6. `## Do's and Don'ts`
|
||||
|
||||
Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` — Stitch's own outputs do this — but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
|
||||
|
||||
## When to run
|
||||
|
||||
- The user just ran `/impeccable teach` and needs the visual side documented.
|
||||
- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
|
||||
- An existing `DESIGN.md` is stale (the design has drifted).
|
||||
- Before a large redesign, to capture the current state as a reference.
|
||||
|
||||
If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and STOP and call the AskUserQuestion tool to clarify. whether to refresh, overwrite, or merge.
|
||||
|
||||
## Two paths
|
||||
|
||||
- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
|
||||
- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
|
||||
|
||||
Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode — don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
|
||||
|
||||
## Scan mode (approach C: auto-extract, then confirm descriptive language)
|
||||
|
||||
### Step 1: Find the design assets
|
||||
|
||||
Search the codebase in priority order:
|
||||
|
||||
1. **CSS custom properties** — grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
|
||||
2. **Tailwind config** — if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
|
||||
3. **CSS-in-JS theme files** — styled-components, emotion, vanilla-extract, stitches: look for `theme.ts`, `tokens.ts`, or equivalent.
|
||||
4. **Design token files** — `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
|
||||
5. **Component library** — scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
|
||||
6. **Global stylesheet** — the root CSS file usually has the base typography and color assignments.
|
||||
7. **Visible rendered output** — if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
|
||||
|
||||
### Step 2: Auto-extract what can be auto-extracted
|
||||
|
||||
Build a structured draft from the discovered tokens. For each token class:
|
||||
|
||||
- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral — omit Secondary and Tertiary rather than inventing them.
|
||||
- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
|
||||
- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer — state it explicitly.
|
||||
- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
|
||||
- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
|
||||
|
||||
### Step 2b: Stage the frontmatter
|
||||
|
||||
From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer — what the live panel and Stitch's linter consume.
|
||||
|
||||
- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex — see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
|
||||
- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
|
||||
- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
|
||||
- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
|
||||
|
||||
Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
|
||||
|
||||
### Step 3: Ask the user for qualitative language
|
||||
|
||||
The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
|
||||
|
||||
- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
|
||||
- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
|
||||
- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
|
||||
- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
|
||||
- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
|
||||
|
||||
Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
|
||||
|
||||
### Step 4: Write DESIGN.md
|
||||
|
||||
The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: [Project Title]
|
||||
description: [one-line tagline]
|
||||
colors:
|
||||
# ... staged frontmatter from Step 2b
|
||||
---
|
||||
|
||||
# Design System: [Project Title]
|
||||
|
||||
## 1. Overview
|
||||
|
||||
**Creative North Star: "[Named metaphor in quotes]"**
|
||||
|
||||
[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
|
||||
|
||||
## 2. Colors
|
||||
|
||||
[Describe the palette character in one sentence.]
|
||||
|
||||
### Primary
|
||||
- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
|
||||
|
||||
### Secondary (optional — omit if the project has only one accent)
|
||||
- **[Descriptive Name]** (#HEX): [Role.]
|
||||
|
||||
### Tertiary (optional)
|
||||
- **[Descriptive Name]** (#HEX): [Role.]
|
||||
|
||||
### Neutral
|
||||
- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
|
||||
- [...]
|
||||
|
||||
### Named Rules (optional, powerful)
|
||||
**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine — e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
|
||||
|
||||
## 3. Typography
|
||||
|
||||
**Display Font:** [Family] (with [fallback])
|
||||
**Body Font:** [Family] (with [fallback])
|
||||
**Label/Mono Font:** [Family, if distinct]
|
||||
|
||||
**Character:** [1-2 sentence personality description of the pairing.]
|
||||
|
||||
### Hierarchy
|
||||
- **Display** ([weight], [size/clamp], [line-height]): [Purpose — where it appears.]
|
||||
- **Headline** ([weight], [size], [line-height]): [Purpose.]
|
||||
- **Title** ([weight], [size], [line-height]): [Purpose.]
|
||||
- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
|
||||
- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
|
||||
|
||||
### Named Rules (optional)
|
||||
**The [Rule Name] Rule.** [Short doctrine about type use.]
|
||||
|
||||
## 4. Elevation
|
||||
|
||||
[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
|
||||
|
||||
### Shadow Vocabulary (if applicable)
|
||||
- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
|
||||
- [...]
|
||||
|
||||
### Named Rules (optional)
|
||||
**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
|
||||
|
||||
## 5. Components
|
||||
|
||||
For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
|
||||
|
||||
### Buttons
|
||||
- **Shape:** [radius described, exact value in parens]
|
||||
- **Primary:** [color assignment + padding, in semantic + exact terms]
|
||||
- **Hover / Focus:** [transitions, treatments]
|
||||
- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
|
||||
|
||||
### Chips (if used)
|
||||
- **Style:** [background, text color, border treatment]
|
||||
- **State:** [selected / unselected, filter / action variants]
|
||||
|
||||
### Cards / Containers
|
||||
- **Corner Style:** [radius]
|
||||
- **Background:** [colors used]
|
||||
- **Shadow Strategy:** [reference Elevation section]
|
||||
- **Border:** [if any]
|
||||
- **Internal Padding:** [scale]
|
||||
|
||||
### Inputs / Fields
|
||||
- **Style:** [stroke, background, radius]
|
||||
- **Focus:** [treatment — glow, border shift, etc.]
|
||||
- **Error / Disabled:** [if applicable]
|
||||
|
||||
### Navigation
|
||||
- **Style, typography, default/hover/active states, mobile treatment.**
|
||||
|
||||
### [Signature Component] (optional — if the project has a distinctive custom component worth documenting)
|
||||
[Description.]
|
||||
|
||||
## 6. Do's and Don'ts
|
||||
|
||||
Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific — include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
|
||||
|
||||
### Do:
|
||||
- **Do** [specific prescription with exact values / named rule].
|
||||
- **Do** [...]
|
||||
|
||||
### Don't:
|
||||
- **Don't** [specific prohibition — e.g. "use border-left greater than 1px as a colored stripe"].
|
||||
- **Don't** [...]
|
||||
- **Don't** [...]
|
||||
```
|
||||
|
||||
### Step 4b: Write DESIGN.json sidecar (extensions only)
|
||||
|
||||
The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
|
||||
|
||||
Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.
|
||||
|
||||
#### Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"generatedAt": "ISO-8601 string",
|
||||
"title": "Design System: [Project Title]",
|
||||
"extensions": {
|
||||
"colorMeta": {
|
||||
"primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
|
||||
"warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
|
||||
},
|
||||
"typographyMeta": {
|
||||
"display": { "displayName": "Display", "purpose": "Hero headlines only." }
|
||||
},
|
||||
"shadows": [
|
||||
{ "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
|
||||
],
|
||||
"motion": [
|
||||
{ "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
|
||||
],
|
||||
"breakpoints": [
|
||||
{ "name": "sm", "value": "640px" }
|
||||
]
|
||||
},
|
||||
"components": [
|
||||
{
|
||||
"name": "Primary Button",
|
||||
"kind": "button | input | nav | chip | card | custom",
|
||||
"refersTo": "button-primary",
|
||||
"description": "One-line what and when.",
|
||||
"html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
|
||||
"css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
|
||||
}
|
||||
],
|
||||
"narrative": {
|
||||
"northStar": "The Editorial Sanctuary",
|
||||
"overview": "2-3 paragraphs of the philosophy — pulled from DESIGN.md Overview section.",
|
||||
"keyCharacteristics": ["...", "..."],
|
||||
"rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
|
||||
"dos": ["Do use ..."],
|
||||
"donts": ["Don't use ..."]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter — tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints — keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
|
||||
|
||||
#### Component translation rules
|
||||
|
||||
The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly — no post-processing, no framework runtime.
|
||||
|
||||
1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
|
||||
2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)` — they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
|
||||
3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
|
||||
4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
|
||||
5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
|
||||
6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
|
||||
|
||||
#### What to include
|
||||
|
||||
Aim for a tight set of **5-10 components** that best represent the visual system:
|
||||
|
||||
- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
|
||||
- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
|
||||
- **Skip the rest.** Utility components, form building blocks, wrapper layouts — not worth documenting unless visually distinctive.
|
||||
|
||||
If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.
|
||||
|
||||
#### Tonal ramps
|
||||
|
||||
For each color token, generate an 8-step `tonalRamp` array — dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
|
||||
|
||||
#### Narrative mapping
|
||||
|
||||
Pull directly from the DESIGN.md you just wrote:
|
||||
|
||||
- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
|
||||
- `narrative.overview` → the philosophy paragraphs from Overview
|
||||
- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
|
||||
- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
|
||||
- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
|
||||
|
||||
Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
|
||||
|
||||
### Step 5: Confirm, refine, and refresh session cache
|
||||
|
||||
1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
|
||||
2. Mention that `DESIGN.json` was also written alongside — the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
|
||||
3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
|
||||
4. **Refresh the session cache.** Run `node .claude/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
|
||||
|
||||
## Seed mode
|
||||
|
||||
For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
|
||||
|
||||
### Step 1: Confirm seed mode
|
||||
|
||||
Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
|
||||
|
||||
If the user prefers to skip, stop. No file.
|
||||
|
||||
### Step 2: Five questions
|
||||
|
||||
Group into one `AskUserQuestion` interaction. Options must be concrete.
|
||||
|
||||
1. **Color strategy.** Pick one:
|
||||
- Restrained — tinted neutrals + one accent ≤10%
|
||||
- Committed — one saturated color carries 30–60% of the surface
|
||||
- Full palette — 3–4 named color roles, each deliberate
|
||||
- Drenched — the surface IS the color
|
||||
|
||||
Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
|
||||
|
||||
2. **Typography direction.** Pick one (specific fonts come later):
|
||||
- Serif display + sans body
|
||||
- Single sans (warm / technical / geometric / humanist — pick a feel)
|
||||
- Display + mono
|
||||
- Mono-forward
|
||||
- Editorial script + sans
|
||||
|
||||
3. **Motion energy.** Pick one:
|
||||
- Restrained — state changes only
|
||||
- Responsive — feedback + transitions, no choreography
|
||||
- Choreographed — orchestrated entrances, scroll-driven sequences
|
||||
|
||||
4. **Three named references.** Brands, products, printed objects. Not adjectives.
|
||||
|
||||
5. **One anti-reference.** What it should NOT feel like. Also named.
|
||||
|
||||
### Step 3: Write seed DESIGN.md
|
||||
|
||||
Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
|
||||
|
||||
Lead the file with:
|
||||
|
||||
```markdown
|
||||
<!-- SEED — re-run /impeccable document once there's code to capture the actual tokens and components. -->
|
||||
```
|
||||
|
||||
Per-section guidance in seed mode:
|
||||
|
||||
- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
|
||||
- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values — mark as `[to be resolved during implementation]`.
|
||||
- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet — `[font pairing to be chosen at implementation]`.
|
||||
- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
|
||||
- **Components**: omit entirely — no components exist yet.
|
||||
- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
|
||||
|
||||
Seed mode writes a minimal frontmatter with `name` and `description` only — no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.
|
||||
|
||||
### Step 4: Confirm and refresh session cache
|
||||
|
||||
1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
|
||||
2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
|
||||
3. Run `node .claude/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
|
||||
|
||||
## Style guidelines
|
||||
|
||||
- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places — the frontmatter is normative.
|
||||
- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
|
||||
- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
|
||||
- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
|
||||
- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
|
||||
- **Exact values in parens**: hex codes, px/rem values, font weights — always the number in parens alongside the description.
|
||||
- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
|
||||
- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always" — not "consider", "might", "prefer". Match PRODUCT.md's tone.
|
||||
- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
|
||||
- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
|
||||
- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Don't paste raw CSS class names. Translate to descriptive language.
|
||||
- Don't extract every token. Stop at what's actually reused — one-offs pollute the system.
|
||||
- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
|
||||
- Don't overwrite an existing DESIGN.md without asking.
|
||||
- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
|
||||
- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
|
||||
- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
|
||||
- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
|
||||
- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
|
||||
@@ -0,0 +1,70 @@
|
||||
# Extract Flow
|
||||
|
||||
Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
|
||||
|
||||
## Step 1: Discover the Design System
|
||||
|
||||
Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
|
||||
|
||||
**CRITICAL**: If no design system exists, STOP and call the AskUserQuestion tool to clarify. before creating one. Understand the preferred location and structure first.
|
||||
|
||||
## Step 2: Identify Patterns
|
||||
|
||||
Look for extraction opportunities in the target area:
|
||||
|
||||
- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
|
||||
- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
|
||||
- **Inconsistent variations**: Multiple implementations of the same concept
|
||||
- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
|
||||
- **Type styles**: Repeated font-size + weight + line-height combinations
|
||||
- **Animation patterns**: Repeated easing, duration, or keyframe combinations
|
||||
|
||||
Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
|
||||
|
||||
## Step 3: Plan Extraction
|
||||
|
||||
Create a systematic plan:
|
||||
|
||||
- **Components to extract**: Which UI elements become reusable components?
|
||||
- **Tokens to create**: Which hard-coded values become design tokens?
|
||||
- **Variants to support**: What variations does each component need?
|
||||
- **Naming conventions**: Component names, token names, prop names that match existing patterns
|
||||
- **Migration path**: How to refactor existing uses to consume the new shared versions
|
||||
|
||||
**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
|
||||
|
||||
## Step 4: Extract & Enrich
|
||||
|
||||
Build improved, reusable versions:
|
||||
|
||||
- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
|
||||
- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
|
||||
- **Patterns**: When to use this pattern, code examples, variations and combinations
|
||||
|
||||
## Step 5: Migrate
|
||||
|
||||
Replace existing uses with the new shared versions:
|
||||
|
||||
- **Find all instances**: Search for the patterns you extracted
|
||||
- **Replace systematically**: Update each use to consume the shared version
|
||||
- **Test thoroughly**: Ensure visual and functional parity
|
||||
- **Delete dead code**: Remove the old implementations
|
||||
|
||||
## Step 6: Document
|
||||
|
||||
Update design system documentation:
|
||||
|
||||
- Add new components to the component library
|
||||
- Document token usage and values
|
||||
- Add examples and guidelines
|
||||
- Update any Storybook or component catalog
|
||||
|
||||
**NEVER**:
|
||||
- Extract one-off, context-specific implementations without generalization
|
||||
- Create components so generic they are useless
|
||||
- Extract without considering existing design system conventions
|
||||
- Skip proper TypeScript types or prop documentation
|
||||
- Create tokens for every single value (tokens should have semantic meaning)
|
||||
- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
|
||||
|
||||
Remember: A good design system is a living system. Extract patterns as they emerge, enrich them thoughtfully, and maintain them consistently.
|
||||
@@ -0,0 +1,347 @@
|
||||
Strengthen interfaces against edge cases, errors, internationalization issues, and real-world usage scenarios that break idealized designs.
|
||||
|
||||
## Assess Hardening Needs
|
||||
|
||||
Identify weaknesses and edge cases:
|
||||
|
||||
1. **Test with extreme inputs**:
|
||||
- Very long text (names, descriptions, titles)
|
||||
- Very short text (empty, single character)
|
||||
- Special characters (emoji, RTL text, accents)
|
||||
- Large numbers (millions, billions)
|
||||
- Many items (1000+ list items, 50+ options)
|
||||
- No data (empty states)
|
||||
|
||||
2. **Test error scenarios**:
|
||||
- Network failures (offline, slow, timeout)
|
||||
- API errors (400, 401, 403, 404, 500)
|
||||
- Validation errors
|
||||
- Permission errors
|
||||
- Rate limiting
|
||||
- Concurrent operations
|
||||
|
||||
3. **Test internationalization**:
|
||||
- Long translations (German is often 30% longer than English)
|
||||
- RTL languages (Arabic, Hebrew)
|
||||
- Character sets (Chinese, Japanese, Korean, emoji)
|
||||
- Date/time formats
|
||||
- Number formats (1,000 vs 1.000)
|
||||
- Currency symbols
|
||||
|
||||
**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
|
||||
|
||||
## Hardening Dimensions
|
||||
|
||||
Systematically improve resilience:
|
||||
|
||||
### Text Overflow & Wrapping
|
||||
|
||||
**Long text handling**:
|
||||
```css
|
||||
/* Single line with ellipsis */
|
||||
.truncate {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Multi-line with clamp */
|
||||
.line-clamp {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Allow wrapping */
|
||||
.wrap {
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
hyphens: auto;
|
||||
}
|
||||
```
|
||||
|
||||
**Flex/Grid overflow**:
|
||||
```css
|
||||
/* Prevent flex items from overflowing */
|
||||
.flex-item {
|
||||
min-width: 0; /* Allow shrinking below content size */
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Prevent grid items from overflowing */
|
||||
.grid-item {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
```
|
||||
|
||||
**Responsive text sizing**:
|
||||
- Use `clamp()` for fluid typography
|
||||
- Set minimum readable sizes (14px on mobile)
|
||||
- Test text scaling (zoom to 200%)
|
||||
- Ensure containers expand with text
|
||||
|
||||
### Internationalization (i18n)
|
||||
|
||||
**Text expansion**:
|
||||
- Add 30-40% space budget for translations
|
||||
- Use flexbox/grid that adapts to content
|
||||
- Test with longest language (usually German)
|
||||
- Avoid fixed widths on text containers
|
||||
|
||||
```jsx
|
||||
// ❌ Bad: Assumes short English text
|
||||
<button className="w-24">Submit</button>
|
||||
|
||||
// ✅ Good: Adapts to content
|
||||
<button className="px-4 py-2">Submit</button>
|
||||
```
|
||||
|
||||
**RTL (Right-to-Left) support**:
|
||||
```css
|
||||
/* Use logical properties */
|
||||
margin-inline-start: 1rem; /* Not margin-left */
|
||||
padding-inline: 1rem; /* Not padding-left/right */
|
||||
border-inline-end: 1px solid; /* Not border-right */
|
||||
|
||||
/* Or use dir attribute */
|
||||
[dir="rtl"] .arrow { transform: scaleX(-1); }
|
||||
```
|
||||
|
||||
**Character set support**:
|
||||
- Use UTF-8 encoding everywhere
|
||||
- Test with Chinese/Japanese/Korean (CJK) characters
|
||||
- Test with emoji (they can be 2-4 bytes)
|
||||
- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
|
||||
|
||||
**Date/Time formatting**:
|
||||
```javascript
|
||||
// ✅ Use Intl API for proper formatting
|
||||
new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
|
||||
new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
|
||||
|
||||
new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD'
|
||||
}).format(1234.56); // $1,234.56
|
||||
```
|
||||
|
||||
**Pluralization**:
|
||||
```javascript
|
||||
// ❌ Bad: Assumes English pluralization
|
||||
`${count} item${count !== 1 ? 's' : ''}`
|
||||
|
||||
// ✅ Good: Use proper i18n library
|
||||
t('items', { count }) // Handles complex plural rules
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
**Network errors**:
|
||||
- Show clear error messages
|
||||
- Provide retry button
|
||||
- Explain what happened
|
||||
- Offer offline mode (if applicable)
|
||||
- Handle timeout scenarios
|
||||
|
||||
```jsx
|
||||
// Error states with recovery
|
||||
{error && (
|
||||
<ErrorMessage>
|
||||
<p>Failed to load data. {error.message}</p>
|
||||
<button onClick={retry}>Try again</button>
|
||||
</ErrorMessage>
|
||||
)}
|
||||
```
|
||||
|
||||
**Form validation errors**:
|
||||
- Inline errors near fields
|
||||
- Clear, specific messages
|
||||
- Suggest corrections
|
||||
- Don't block submission unnecessarily
|
||||
- Preserve user input on error
|
||||
|
||||
**API errors**:
|
||||
- Handle each status code appropriately
|
||||
- 400: Show validation errors
|
||||
- 401: Redirect to login
|
||||
- 403: Show permission error
|
||||
- 404: Show not found state
|
||||
- 429: Show rate limit message
|
||||
- 500: Show generic error, offer support
|
||||
|
||||
**Graceful degradation**:
|
||||
- Core functionality works without JavaScript
|
||||
- Images have alt text
|
||||
- Progressive enhancement
|
||||
- Fallbacks for unsupported features
|
||||
|
||||
### Edge Cases & Boundary Conditions
|
||||
|
||||
**Empty states**:
|
||||
- No items in list
|
||||
- No search results
|
||||
- No notifications
|
||||
- No data to display
|
||||
- Provide clear next action
|
||||
|
||||
**Loading states**:
|
||||
- Initial load
|
||||
- Pagination load
|
||||
- Refresh
|
||||
- Show what's loading ("Loading your projects...")
|
||||
- Time estimates for long operations
|
||||
|
||||
**Large datasets**:
|
||||
- Pagination or virtual scrolling
|
||||
- Search/filter capabilities
|
||||
- Performance optimization
|
||||
- Don't load all 10,000 items at once
|
||||
|
||||
**Concurrent operations**:
|
||||
- Prevent double-submission (disable button while loading)
|
||||
- Handle race conditions
|
||||
- Optimistic updates with rollback
|
||||
- Conflict resolution
|
||||
|
||||
**Permission states**:
|
||||
- No permission to view
|
||||
- No permission to edit
|
||||
- Read-only mode
|
||||
- Clear explanation of why
|
||||
|
||||
**Browser compatibility**:
|
||||
- Polyfills for modern features
|
||||
- Fallbacks for unsupported CSS
|
||||
- Feature detection (not browser detection)
|
||||
- Test in target browsers
|
||||
|
||||
### Input Validation & Sanitization
|
||||
|
||||
**Client-side validation**:
|
||||
- Required fields
|
||||
- Format validation (email, phone, URL)
|
||||
- Length limits
|
||||
- Pattern matching
|
||||
- Custom validation rules
|
||||
|
||||
**Server-side validation** (always):
|
||||
- Never trust client-side only
|
||||
- Validate and sanitize all inputs
|
||||
- Protect against injection attacks
|
||||
- Rate limiting
|
||||
|
||||
**Constraint handling**:
|
||||
```html
|
||||
<!-- Set clear constraints -->
|
||||
<input
|
||||
type="text"
|
||||
maxlength="100"
|
||||
pattern="[A-Za-z0-9]+"
|
||||
required
|
||||
aria-describedby="username-hint"
|
||||
/>
|
||||
<small id="username-hint">
|
||||
Letters and numbers only, up to 100 characters
|
||||
</small>
|
||||
```
|
||||
|
||||
### Accessibility Resilience
|
||||
|
||||
**Keyboard navigation**:
|
||||
- All functionality accessible via keyboard
|
||||
- Logical tab order
|
||||
- Focus management in modals
|
||||
- Skip links for long content
|
||||
|
||||
**Screen reader support**:
|
||||
- Proper ARIA labels
|
||||
- Announce dynamic changes (live regions)
|
||||
- Descriptive alt text
|
||||
- Semantic HTML
|
||||
|
||||
**Motion sensitivity**:
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**High contrast mode**:
|
||||
- Test in Windows high contrast mode
|
||||
- Don't rely only on color
|
||||
- Provide alternative visual cues
|
||||
|
||||
### Performance Resilience
|
||||
|
||||
**Slow connections**:
|
||||
- Progressive image loading
|
||||
- Skeleton screens
|
||||
- Optimistic UI updates
|
||||
- Offline support (service workers)
|
||||
|
||||
**Memory leaks**:
|
||||
- Clean up event listeners
|
||||
- Cancel subscriptions
|
||||
- Clear timers/intervals
|
||||
- Abort pending requests on unmount
|
||||
|
||||
**Throttling & Debouncing**:
|
||||
```javascript
|
||||
// Debounce search input
|
||||
const debouncedSearch = debounce(handleSearch, 300);
|
||||
|
||||
// Throttle scroll handler
|
||||
const throttledScroll = throttle(handleScroll, 100);
|
||||
```
|
||||
|
||||
## Testing Strategies
|
||||
|
||||
**Manual testing**:
|
||||
- Test with extreme data (very long, very short, empty)
|
||||
- Test in different languages
|
||||
- Test offline
|
||||
- Test slow connection (throttle to 3G)
|
||||
- Test with screen reader
|
||||
- Test keyboard-only navigation
|
||||
- Test on old browsers
|
||||
|
||||
**Automated testing**:
|
||||
- Unit tests for edge cases
|
||||
- Integration tests for error scenarios
|
||||
- E2E tests for critical paths
|
||||
- Visual regression tests
|
||||
- Accessibility tests (axe, WAVE)
|
||||
|
||||
**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
|
||||
|
||||
**NEVER**:
|
||||
- Assume perfect input (validate everything)
|
||||
- Ignore internationalization (design for global)
|
||||
- Leave error messages generic ("Error occurred")
|
||||
- Forget offline scenarios
|
||||
- Trust client-side validation alone
|
||||
- Use fixed widths for text
|
||||
- Assume English-length text
|
||||
- Block entire interface when one component errors
|
||||
|
||||
## Verify Hardening
|
||||
|
||||
Test thoroughly with edge cases:
|
||||
|
||||
- **Long text**: Try names with 100+ characters
|
||||
- **Emoji**: Use emoji in all text fields
|
||||
- **RTL**: Test with Arabic or Hebrew
|
||||
- **CJK**: Test with Chinese/Japanese/Korean
|
||||
- **Network issues**: Disable internet, throttle connection
|
||||
- **Large datasets**: Test with 1000+ items
|
||||
- **Concurrent actions**: Click submit 10 times rapidly
|
||||
- **Errors**: Force API errors, test all error states
|
||||
- **Empty**: Remove all data, test empty states
|
||||
|
||||
Remember: You're hardening for production reality, not demo perfection. Expect users to input weird data, lose connection mid-flow, and use your product in unexpected ways. Build resilience into every component.
|
||||
@@ -0,0 +1,234 @@
|
||||
# Heuristics Scoring Guide
|
||||
|
||||
Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest — a 4 means genuinely excellent, not "good enough."
|
||||
|
||||
## Nielsen's 10 Heuristics
|
||||
|
||||
### 1. Visibility of System Status
|
||||
|
||||
Keep users informed about what's happening through timely, appropriate feedback.
|
||||
|
||||
**Check for**:
|
||||
- Loading indicators during async operations
|
||||
- Confirmation of user actions (save, submit, delete)
|
||||
- Progress indicators for multi-step processes
|
||||
- Current location in navigation (breadcrumbs, active states)
|
||||
- Form validation feedback (inline, not just on submit)
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | No feedback — user is guessing what happened |
|
||||
| 1 | Rare feedback — most actions produce no visible response |
|
||||
| 2 | Partial — some states communicated, major gaps remain |
|
||||
| 3 | Good — most operations give clear feedback, minor gaps |
|
||||
| 4 | Excellent — every action confirms, progress is always visible |
|
||||
|
||||
### 2. Match Between System and Real World
|
||||
|
||||
Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
|
||||
|
||||
**Check for**:
|
||||
- Familiar terminology (no unexplained jargon)
|
||||
- Logical information order matching user expectations
|
||||
- Recognizable icons and metaphors
|
||||
- Domain-appropriate language for the target audience
|
||||
- Natural reading flow (left-to-right, top-to-bottom priority)
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | Pure tech jargon, alien to users |
|
||||
| 1 | Mostly confusing — requires domain expertise to navigate |
|
||||
| 2 | Mixed — some plain language, some jargon leaks through |
|
||||
| 3 | Mostly natural — occasional term needs context |
|
||||
| 4 | Speaks the user's language fluently throughout |
|
||||
|
||||
### 3. User Control and Freedom
|
||||
|
||||
Users need a clear "emergency exit" from unwanted states without extended dialogue.
|
||||
|
||||
**Check for**:
|
||||
- Undo/redo functionality
|
||||
- Cancel buttons on forms and modals
|
||||
- Clear navigation back to safety (home, previous)
|
||||
- Easy way to clear filters, search, selections
|
||||
- Escape from long or multi-step processes
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | Users get trapped — no way out without refreshing |
|
||||
| 1 | Difficult exits — must find obscure paths to escape |
|
||||
| 2 | Some exits — main flows have escape, edge cases don't |
|
||||
| 3 | Good control — users can exit and undo most actions |
|
||||
| 4 | Full control — undo, cancel, back, and escape everywhere |
|
||||
|
||||
### 4. Consistency and Standards
|
||||
|
||||
Users shouldn't wonder whether different words, situations, or actions mean the same thing.
|
||||
|
||||
**Check for**:
|
||||
- Consistent terminology throughout the interface
|
||||
- Same actions produce same results everywhere
|
||||
- Platform conventions followed (standard UI patterns)
|
||||
- Visual consistency (colors, typography, spacing, components)
|
||||
- Consistent interaction patterns (same gesture = same behavior)
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | Inconsistent everywhere — feels like different products stitched together |
|
||||
| 1 | Many inconsistencies — similar things look/behave differently |
|
||||
| 2 | Partially consistent — main flows match, details diverge |
|
||||
| 3 | Mostly consistent — occasional deviation, nothing confusing |
|
||||
| 4 | Fully consistent — cohesive system, predictable behavior |
|
||||
|
||||
### 5. Error Prevention
|
||||
|
||||
Better than good error messages is a design that prevents problems in the first place.
|
||||
|
||||
**Check for**:
|
||||
- Confirmation before destructive actions (delete, overwrite)
|
||||
- Constraints preventing invalid input (date pickers, dropdowns)
|
||||
- Smart defaults that reduce errors
|
||||
- Clear labels that prevent misunderstanding
|
||||
- Autosave and draft recovery
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | Errors easy to make — no guardrails anywhere |
|
||||
| 1 | Few safeguards — some inputs validated, most aren't |
|
||||
| 2 | Partial prevention — common errors caught, edge cases slip |
|
||||
| 3 | Good prevention — most error paths blocked proactively |
|
||||
| 4 | Excellent — errors nearly impossible through smart constraints |
|
||||
|
||||
### 6. Recognition Rather Than Recall
|
||||
|
||||
Minimize memory load. Make objects, actions, and options visible or easily retrievable.
|
||||
|
||||
**Check for**:
|
||||
- Visible options (not buried in hidden menus)
|
||||
- Contextual help when needed (tooltips, inline hints)
|
||||
- Recent items and history
|
||||
- Autocomplete and suggestions
|
||||
- Labels on icons (not icon-only navigation)
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | Heavy memorization — users must remember paths and commands |
|
||||
| 1 | Mostly recall — many hidden features, few visible cues |
|
||||
| 2 | Some aids — main actions visible, secondary features hidden |
|
||||
| 3 | Good recognition — most things discoverable, few memory demands |
|
||||
| 4 | Everything discoverable — users never need to memorize |
|
||||
|
||||
### 7. Flexibility and Efficiency of Use
|
||||
|
||||
Accelerators — invisible to novices — speed up expert interaction.
|
||||
|
||||
**Check for**:
|
||||
- Keyboard shortcuts for common actions
|
||||
- Customizable interface elements
|
||||
- Recent items and favorites
|
||||
- Bulk/batch actions
|
||||
- Power user features that don't complicate the basics
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | One rigid path — no shortcuts or alternatives |
|
||||
| 1 | Limited flexibility — few alternatives to the main path |
|
||||
| 2 | Some shortcuts — basic keyboard support, limited bulk actions |
|
||||
| 3 | Good accelerators — keyboard nav, some customization |
|
||||
| 4 | Highly flexible — multiple paths, power features, customizable |
|
||||
|
||||
### 8. Aesthetic and Minimalist Design
|
||||
|
||||
Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
|
||||
|
||||
**Check for**:
|
||||
- Only necessary information visible at each step
|
||||
- Clear visual hierarchy directing attention
|
||||
- Purposeful use of color and emphasis
|
||||
- No decorative clutter competing for attention
|
||||
- Focused, uncluttered layouts
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | Overwhelming — everything competes for attention equally |
|
||||
| 1 | Cluttered — too much noise, hard to find what matters |
|
||||
| 2 | Some clutter — main content clear, periphery noisy |
|
||||
| 3 | Mostly clean — focused design, minor visual noise |
|
||||
| 4 | Perfectly minimal — every element earns its pixel |
|
||||
|
||||
### 9. Help Users Recognize, Diagnose, and Recover from Errors
|
||||
|
||||
Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
|
||||
|
||||
**Check for**:
|
||||
- Plain language error messages (no error codes for users)
|
||||
- Specific problem identification ("Email is missing @" not "Invalid input")
|
||||
- Actionable recovery suggestions
|
||||
- Errors displayed near the source of the problem
|
||||
- Non-blocking error handling (don't wipe the form)
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | Cryptic errors — codes, jargon, or no message at all |
|
||||
| 1 | Vague errors — "Something went wrong" with no guidance |
|
||||
| 2 | Clear but unhelpful — names the problem but not the fix |
|
||||
| 3 | Clear with suggestions — identifies problem and offers next steps |
|
||||
| 4 | Perfect recovery — pinpoints issue, suggests fix, preserves user work |
|
||||
|
||||
### 10. Help and Documentation
|
||||
|
||||
Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
|
||||
|
||||
**Check for**:
|
||||
- Searchable help or documentation
|
||||
- Contextual help (tooltips, inline hints, guided tours)
|
||||
- Task-focused organization (not feature-organized)
|
||||
- Concise, scannable content
|
||||
- Easy access without leaving current context
|
||||
|
||||
**Scoring**:
|
||||
| Score | Criteria |
|
||||
|-------|----------|
|
||||
| 0 | No help available anywhere |
|
||||
| 1 | Help exists but hard to find or irrelevant |
|
||||
| 2 | Basic help — FAQ or docs exist, not contextual |
|
||||
| 3 | Good documentation — searchable, mostly task-focused |
|
||||
| 4 | Excellent contextual help — right info at the right moment |
|
||||
|
||||
---
|
||||
|
||||
## Score Summary
|
||||
|
||||
**Total possible**: 40 points (10 heuristics × 4 max)
|
||||
|
||||
| Score Range | Rating | What It Means |
|
||||
|-------------|--------|---------------|
|
||||
| 36–40 | Excellent | Minor polish only — ship it |
|
||||
| 28–35 | Good | Address weak areas, solid foundation |
|
||||
| 20–27 | Acceptable | Significant improvements needed before users are happy |
|
||||
| 12–19 | Poor | Major UX overhaul required — core experience broken |
|
||||
| 0–11 | Critical | Redesign needed — unusable in current state |
|
||||
|
||||
---
|
||||
|
||||
## Issue Severity (P0–P3)
|
||||
|
||||
Tag each individual issue found during scoring with a priority level:
|
||||
|
||||
| Priority | Name | Description | Action |
|
||||
|----------|------|-------------|--------|
|
||||
| **P0** | Blocking | Prevents task completion entirely | Fix immediately — this is a showstopper |
|
||||
| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
|
||||
| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
|
||||
| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
|
||||
|
||||
**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
|
||||
@@ -0,0 +1,195 @@
|
||||
# Interaction Design
|
||||
|
||||
## The Eight Interactive States
|
||||
|
||||
Every interactive element needs these states designed:
|
||||
|
||||
| State | When | Visual Treatment |
|
||||
|-------|------|------------------|
|
||||
| **Default** | At rest | Base styling |
|
||||
| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
|
||||
| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
|
||||
| **Active** | Being pressed | Pressed in, darker |
|
||||
| **Disabled** | Not interactive | Reduced opacity, no pointer |
|
||||
| **Loading** | Processing | Spinner, skeleton |
|
||||
| **Error** | Invalid state | Red border, icon, message |
|
||||
| **Success** | Completed | Green check, confirmation |
|
||||
|
||||
**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
|
||||
|
||||
## Focus Rings: Do Them Right
|
||||
|
||||
**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
|
||||
|
||||
```css
|
||||
/* Hide focus ring for mouse/touch */
|
||||
button:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* Show focus ring for keyboard */
|
||||
button:focus-visible {
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
```
|
||||
|
||||
**Focus ring design**:
|
||||
- High contrast (3:1 minimum against adjacent colors)
|
||||
- 2-3px thick
|
||||
- Offset from element (not inside it)
|
||||
- Consistent across all interactive elements
|
||||
|
||||
## Form Design: The Non-Obvious
|
||||
|
||||
**Placeholders aren't labels**—they disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
|
||||
|
||||
## Loading States
|
||||
|
||||
**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**—they preview content shape and feel faster than generic spinners.
|
||||
|
||||
## Modals: The Inert Approach
|
||||
|
||||
Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
|
||||
|
||||
```html
|
||||
<!-- When modal is open -->
|
||||
<main inert>
|
||||
<!-- Content behind modal can't be focused or clicked -->
|
||||
</main>
|
||||
<dialog open>
|
||||
<h2>Modal Title</h2>
|
||||
<!-- Focus stays inside modal -->
|
||||
</dialog>
|
||||
```
|
||||
|
||||
Or use the native `<dialog>` element:
|
||||
|
||||
```javascript
|
||||
const dialog = document.querySelector('dialog');
|
||||
dialog.showModal(); // Opens with focus trap, closes on Escape
|
||||
```
|
||||
|
||||
## The Popover API
|
||||
|
||||
For tooltips, dropdowns, and non-modal overlays, use native popovers:
|
||||
|
||||
```html
|
||||
<button popovertarget="menu">Open menu</button>
|
||||
<div id="menu" popover>
|
||||
<button>Option 1</button>
|
||||
<button>Option 2</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
|
||||
|
||||
## Dropdown & Overlay Positioning
|
||||
|
||||
Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
|
||||
|
||||
### CSS Anchor Positioning
|
||||
|
||||
The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
|
||||
|
||||
```css
|
||||
.trigger {
|
||||
anchor-name: --menu-trigger;
|
||||
}
|
||||
|
||||
.dropdown {
|
||||
position: fixed;
|
||||
position-anchor: --menu-trigger;
|
||||
position-area: block-end span-inline-end;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Flip above if no room below */
|
||||
@position-try --flip-above {
|
||||
position-area: block-start span-inline-end;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
```
|
||||
|
||||
Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
|
||||
|
||||
### Popover + Anchor Combo
|
||||
|
||||
Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
|
||||
|
||||
```html
|
||||
<button popovertarget="menu" class="trigger">Open</button>
|
||||
<div id="menu" popover class="dropdown">
|
||||
<button>Option 1</button>
|
||||
<button>Option 2</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
|
||||
|
||||
### Portal / Teleport Pattern
|
||||
|
||||
In component frameworks, render the dropdown at the document root and position it with JavaScript:
|
||||
|
||||
- **React**: `createPortal(dropdown, document.body)`
|
||||
- **Vue**: `<Teleport to="body">`
|
||||
- **Svelte**: Use a portal library or mount to `document.body`
|
||||
|
||||
Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
|
||||
|
||||
### Fixed Positioning Fallback
|
||||
|
||||
For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
|
||||
|
||||
```css
|
||||
.dropdown {
|
||||
position: fixed;
|
||||
/* top/left set via JS from trigger's getBoundingClientRect() */
|
||||
}
|
||||
```
|
||||
|
||||
Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
|
||||
|
||||
### Anti-Patterns
|
||||
|
||||
- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
|
||||
- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
|
||||
- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
|
||||
|
||||
## Destructive Actions: Undo > Confirm
|
||||
|
||||
**Undo is better than confirmation dialogs**—users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
|
||||
|
||||
## Keyboard Navigation Patterns
|
||||
|
||||
### Roving Tabindex
|
||||
|
||||
For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
|
||||
|
||||
```html
|
||||
<div role="tablist">
|
||||
<button role="tab" tabindex="0">Tab 1</button>
|
||||
<button role="tab" tabindex="-1">Tab 2</button>
|
||||
<button role="tab" tabindex="-1">Tab 3</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
|
||||
|
||||
### Skip Links
|
||||
|
||||
Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
|
||||
|
||||
## Gesture Discoverability
|
||||
|
||||
Swipe-to-delete and similar gestures are invisible. Hint at their existence:
|
||||
|
||||
- **Partially reveal**: Show delete button peeking from edge
|
||||
- **Onboarding**: Coach marks on first use
|
||||
- **Alternative**: Always provide a visible fallback (menu with "Delete")
|
||||
|
||||
Don't rely on gestures as the only way to perform actions.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
|
||||
@@ -0,0 +1,141 @@
|
||||
Assess and improve layout and spacing that feels monotonous, crowded, or structurally weak — turning generic arrangements into intentional, rhythmic compositions.
|
||||
|
||||
---
|
||||
|
||||
## Register
|
||||
|
||||
Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast — tight groupings paired with generous separations.
|
||||
|
||||
Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
|
||||
|
||||
---
|
||||
|
||||
## Assess Current Layout
|
||||
|
||||
Analyze what's weak about the current spatial design:
|
||||
|
||||
1. **Spacing**:
|
||||
- Is spacing consistent or arbitrary? (Random padding/margin values)
|
||||
- Is all spacing the same? (Equal padding everywhere = no rhythm)
|
||||
- Are related elements grouped tightly, with generous space between groups?
|
||||
|
||||
2. **Visual hierarchy**:
|
||||
- Apply the squint test: blur your (metaphorical) eyes — can you still identify the most important element, second most important, and clear groupings?
|
||||
- Is hierarchy achieved effectively? (Space and weight alone can be enough — but is the current approach working?)
|
||||
- Does whitespace guide the eye to what matters?
|
||||
|
||||
3. **Grid & structure**:
|
||||
- Is there a clear underlying structure, or does the layout feel random?
|
||||
- Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
|
||||
- Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
|
||||
|
||||
4. **Rhythm & variety**:
|
||||
- Does the layout have visual rhythm? (Alternating tight/generous spacing)
|
||||
- Is every section structured the same way? (Monotonous repetition)
|
||||
- Are there intentional moments of surprise or emphasis?
|
||||
|
||||
5. **Density**:
|
||||
- Is the layout too cramped? (Not enough breathing room)
|
||||
- Is the layout too sparse? (Excessive whitespace without purpose)
|
||||
- Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
|
||||
|
||||
**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material — use it with intention.
|
||||
|
||||
## Plan Layout Improvements
|
||||
|
||||
Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
|
||||
|
||||
Create a systematic plan:
|
||||
|
||||
- **Spacing system**: Use a consistent scale — whether that's a framework's built-in scale (e.g., Tailwind), rem-based tokens, or a custom system. The specific values matter less than consistency.
|
||||
- **Hierarchy strategy**: How will space communicate importance?
|
||||
- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
|
||||
- **Rhythm**: Where should spacing be tight vs generous?
|
||||
|
||||
## Improve Layout Systematically
|
||||
|
||||
### Establish a Spacing System
|
||||
|
||||
- Use a consistent spacing scale — framework scales (Tailwind, etc.), rem-based tokens, or a custom scale all work. What matters is that values come from a defined set, not arbitrary numbers.
|
||||
- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
|
||||
- Use `gap` for sibling spacing instead of margins — eliminates margin collapse hacks
|
||||
- Apply `clamp()` for fluid spacing that breathes on larger screens
|
||||
|
||||
### Create Visual Rhythm
|
||||
|
||||
- **Tight grouping** for related elements (8-12px between siblings)
|
||||
- **Generous separation** between distinct sections (48-96px)
|
||||
- **Varied spacing** within sections — not every row needs the same gap
|
||||
- **Asymmetric compositions** — break the predictable centered-content pattern when it makes sense
|
||||
|
||||
### Choose the Right Layout Tool
|
||||
|
||||
- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
|
||||
- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
|
||||
- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
|
||||
- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
|
||||
- Use named grid areas (`grid-template-areas`) for complex page layouts — redefine at breakpoints.
|
||||
|
||||
### Break Card Grid Monotony
|
||||
|
||||
- Don't default to card grids for everything — spacing and alignment create visual grouping naturally
|
||||
- Use cards only when content is truly distinct and actionable — never nest cards inside cards
|
||||
- Vary card sizes, span columns, or mix cards with non-card content to break repetition
|
||||
|
||||
### Strengthen Visual Hierarchy
|
||||
|
||||
- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough — generous whitespace around an element draws the eye. Some of the most sophisticated designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
|
||||
- Be aware of reading flow — in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
|
||||
- Create clear content groupings through proximity and separation.
|
||||
|
||||
### Manage Depth & Elevation
|
||||
|
||||
- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
|
||||
- Build a consistent shadow scale (sm → md → lg → xl) — shadows should be subtle
|
||||
- Use elevation to reinforce hierarchy, not as decoration
|
||||
|
||||
### Optical Adjustments
|
||||
|
||||
- If an icon looks visually off-center despite being geometrically centered, nudge it — but only if you're confident it actually looks wrong. Don't adjust speculatively.
|
||||
|
||||
**NEVER**:
|
||||
- Use arbitrary spacing values outside your scale
|
||||
- Make all spacing equal — variety creates hierarchy
|
||||
- Wrap everything in cards — not everything needs a container
|
||||
- Nest cards inside cards — use spacing and dividers for hierarchy within
|
||||
- Use identical card grids everywhere (icon + heading + text, repeated)
|
||||
- Center everything — left-aligned with asymmetry feels more designed
|
||||
- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work — but it should display actual data, not decorative numbers.
|
||||
- Default to CSS Grid when Flexbox would be simpler — use the simplest tool for the job
|
||||
- Use arbitrary z-index values (999, 9999) — build a semantic scale
|
||||
|
||||
## Verify Layout Improvements
|
||||
|
||||
- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
|
||||
- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
|
||||
- **Hierarchy**: Is the most important content obvious within 2 seconds?
|
||||
- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
|
||||
- **Consistency**: Is the spacing system applied uniformly?
|
||||
- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
|
||||
|
||||
Remember: Space is the most underused design tool. A layout with the right rhythm and hierarchy can make even simple content feel polished and intentional.
|
||||
|
||||
## Live-mode signature params
|
||||
|
||||
Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)` — paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
|
||||
|
||||
```json
|
||||
{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
|
||||
```
|
||||
|
||||
For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
|
||||
|
||||
```json
|
||||
{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
|
||||
{"value":"stacked","label":"Stacked"},
|
||||
{"value":"grid","label":"Grid"},
|
||||
{"value":"bento","label":"Bento"}
|
||||
]}
|
||||
```
|
||||
|
||||
See `reference/live.md` for the full params contract.
|
||||
@@ -0,0 +1,513 @@
|
||||
Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
|
||||
|
||||
## The contract (read once)
|
||||
|
||||
Execute in order. No step skipped, no step reordered.
|
||||
|
||||
1. `live.mjs` — boot.
|
||||
2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL — it's the helper, not the app.
|
||||
3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
|
||||
4. On `generate` — read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
|
||||
5. On `accept` / `discard` — the poll script already cleaned up; just poll again.
|
||||
6. On `exit` — run the cleanup at the bottom.
|
||||
|
||||
Harness policy:
|
||||
- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
|
||||
- **Cursor**: run the poll in the **foreground** (blocking shell — not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
|
||||
- **Codex**: run the poll in the **foreground** (blocking shell — not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
|
||||
- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
|
||||
|
||||
Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
|
||||
|
||||
## Start
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/live.mjs
|
||||
```
|
||||
|
||||
Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation — **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
|
||||
|
||||
`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
|
||||
|
||||
If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
|
||||
|
||||
## Poll loop
|
||||
|
||||
```
|
||||
LOOP:
|
||||
node .claude/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
|
||||
Read JSON; dispatch on "type"
|
||||
|
||||
"generate" → Handle Generate; reply done; LOOP
|
||||
"accept" → Handle Accept; LOOP
|
||||
"discard" → Handle Discard; LOOP
|
||||
"prefetch" → Handle Prefetch; LOOP
|
||||
"timeout" → LOOP
|
||||
"exit" → break → Cleanup
|
||||
```
|
||||
|
||||
## Handle `generate`
|
||||
|
||||
Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
|
||||
|
||||
Speed matters — the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
|
||||
|
||||
### 1. Read the screenshot (if present)
|
||||
|
||||
`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning** — annotations encode user intent not recoverable from `element.outerHTML` alone.
|
||||
|
||||
When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
|
||||
|
||||
`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
|
||||
|
||||
Reading annotations precisely:
|
||||
|
||||
- **Comment position is load-bearing.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
|
||||
- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
|
||||
- **Strokes are gestures — read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
|
||||
- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
|
||||
|
||||
### 2. Wrap the element
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
|
||||
```
|
||||
|
||||
Flag mapping — keep them separate, don't collapse into `--query`:
|
||||
|
||||
- `--element-id` ← `event.element.id`
|
||||
- `--classes` ← `event.element.classes` joined with commas
|
||||
- `--tag` ← `event.element.tagName`
|
||||
|
||||
The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only — do not use it for normal element lookups.
|
||||
|
||||
Output on success: `{ file, insertLine, commentSyntax }`.
|
||||
|
||||
**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing — accepting a variant into a generated file is silent data loss. Three shapes:
|
||||
|
||||
- `{ error: "file_is_generated", file, hint }` — user-supplied `--file` points at a generated file.
|
||||
- `{ error: "element_not_in_source", generatedMatch, hint }` — element exists only in a generated file (the next build would wipe any edits).
|
||||
- `{ error: "element_not_found", hint }` — element isn't in any project file; likely runtime-injected (JS component, data-driven render).
|
||||
|
||||
All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
|
||||
|
||||
### 3. Load the action's reference
|
||||
|
||||
If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
|
||||
|
||||
Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
|
||||
|
||||
### 4. Plan three genuinely distinct directions
|
||||
|
||||
Before writing a single line of code, name each variant.
|
||||
|
||||
**For freeform (`action` is `impeccable`, or the user supplied a free prompt):** each variant must anchor to a different **archetype** — a real-world design analogue specific enough to be recognizable at a glance. Not "modern landing page." Not "minimal product hero." Examples:
|
||||
|
||||
- *Broadsheet masthead with rule-divided columns* (think NYT print edition)
|
||||
- *Klim Type Foundry specimen page* (dense, technical, catalog-driven)
|
||||
- *Japanese print-poster minimalism with a single oversize glyph*
|
||||
- *Bloomberg Terminal status bar*
|
||||
- *Condé Nast Traveler feature layout*
|
||||
|
||||
Then commit each variant to a different **primary axis** of difference:
|
||||
|
||||
1. **Hierarchy** — which element commands the eye?
|
||||
2. **Layout topology** — stacked / side-by-side / grid / asymmetric / overlay
|
||||
3. **Typographic system** — pairing, scale ratio, case/weight strategy
|
||||
4. **Color strategy** — Restrained / Committed / Full palette / Drenched
|
||||
5. **Density** — minimal / comfortable / dense
|
||||
6. **Structural decomposition** — merge, split, progressive disclosure
|
||||
|
||||
Three variants → three DIFFERENT primary axes, not three riffs on color.
|
||||
|
||||
**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for one dark-neutral-accent, one light-drenched, one full-palette-saturated — three color worlds, not three shades of the same.
|
||||
|
||||
**The squint test (before writing code).** Write the three one-sentence descriptions side by side:
|
||||
|
||||
> V1: Broadsheet masthead, ruled columns, 24px ink on cream.
|
||||
> V2: Enormous italic title, catalog spec rows, heavy monospace data.
|
||||
> V3: Card-framed poster with one oversize glyph, magenta veil.
|
||||
|
||||
If two of them rhyme ("both use big type" / "both are stacks of sections" / "both feature the CTA prominently"), rework the offender. Freeform variants failing the squint test is the primary failure mode of this flow — three-of-the-same with minor styling tweaks.
|
||||
|
||||
**For action-specific invocations**, each variant must vary along the dimension the action names:
|
||||
|
||||
- `bolder` — amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
|
||||
- `quieter` — pull back a different dimension (color / ornament / spacing).
|
||||
- `distill` — remove a different class of excess (visual noise / redundant content / nested structure).
|
||||
- `polish` — target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
|
||||
- `typeset` — different type pairing AND different scale ratio each. Not three riffs on one pairing.
|
||||
- `colorize` — different hue family each (not shades of one hue). Vary chroma and contrast strategy.
|
||||
- `layout` — different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
|
||||
- `adapt` — different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
|
||||
- `animate` — different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
|
||||
- `delight` — different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
|
||||
- `overdrive` — different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step — live mode is non-interactive.
|
||||
|
||||
### 5. Apply the freeform prompt (if present)
|
||||
|
||||
`event.freeformPrompt` is the user's ceiling on direction — all variants must honor it — but still explore meaningfully different *interpretations*. "Make it feel like a newspaper front page" → variant 1 = broadsheet masthead + rule-divided columns, variant 2 = tabloid headline + single dominant image, variant 3 = minimalist editorial with oversized drop cap. Not three newspapers in the same voice.
|
||||
|
||||
### 6. Write all variants in a single edit
|
||||
|
||||
Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
|
||||
|
||||
Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate scoped CSS as a `<style>` tag inside the variant wrapper — `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
|
||||
|
||||
```html
|
||||
<!-- Variants: insert below this line -->
|
||||
<style data-impeccable-css="SESSION_ID">
|
||||
@scope ([data-impeccable-variant="1"]) { ... }
|
||||
@scope ([data-impeccable-variant="2"]) { ... }
|
||||
</style>
|
||||
<div data-impeccable-variant="1">
|
||||
<!-- variant 1: full element replacement (single top-level element) -->
|
||||
</div>
|
||||
<div data-impeccable-variant="2" style="display: none">
|
||||
<!-- variant 2: full element replacement -->
|
||||
</div>
|
||||
<div data-impeccable-variant="3" style="display: none">
|
||||
<!-- variant 3: full element replacement -->
|
||||
</div>
|
||||
```
|
||||
|
||||
**Each variant div contains exactly one top-level element — the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
|
||||
|
||||
The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).
|
||||
|
||||
One edit, all variants — the browser's MutationObserver picks everything up in one pass.
|
||||
|
||||
### 7. Parameters (composition-sized, 0–4 per variant)
|
||||
|
||||
Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
|
||||
|
||||
**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
|
||||
|
||||
**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
|
||||
|
||||
**Freeform (`action` is `impeccable`) bias.** You did not load `reference/bolder.md` (etc.), so you must **choose** 1–2 signature-like axes yourself. Prefer knobs that sit on the same dimensions as your three directions (e.g. all three riffs on editorial density → expose `density` or a `steps` “air / snug / packed”; two directions differ mostly in chroma → add `color-amount`). A hero, section, or other **large** surface that ships with **0** params needs a one-line reason in your head (e.g. “truly a fixed-point A/B/C comparison, no shared dial”), not a default habit.
|
||||
|
||||
**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
|
||||
|
||||
- **Leaf / tiny** — a single button, icon, input, bare heading, solitary paragraph: **0 params.**
|
||||
- **Small composition** — labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
|
||||
- **Medium composition** — section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
|
||||
- **Large composition** — hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
|
||||
|
||||
**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
|
||||
|
||||
**Hard cap per variant** — at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
|
||||
|
||||
**How to declare.** Put a JSON manifest on the variant wrapper:
|
||||
|
||||
```html
|
||||
<div data-impeccable-variant="1" data-impeccable-params='[
|
||||
{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
|
||||
{"id":"density","kind":"steps","default":"snug","label":"Density","options":[
|
||||
{"value":"airy","label":"Airy"},
|
||||
{"value":"snug","label":"Snug"},
|
||||
{"value":"packed","label":"Packed"}
|
||||
]},
|
||||
{"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
|
||||
]'>
|
||||
...variant content...
|
||||
</div>
|
||||
```
|
||||
|
||||
**Three kinds:**
|
||||
|
||||
- `range` — smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
|
||||
- `steps` — segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
|
||||
- `toggle` — on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
|
||||
|
||||
**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
|
||||
|
||||
**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
|
||||
|
||||
**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
|
||||
|
||||
```html
|
||||
<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
|
||||
```
|
||||
|
||||
The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
|
||||
|
||||
### 8. Signal done
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
|
||||
```
|
||||
|
||||
`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.) — the browser fetches source directly if the dev server lacks HMR.
|
||||
|
||||
Then run `live-poll.mjs` again immediately.
|
||||
|
||||
## Handle fallback
|
||||
|
||||
When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
|
||||
|
||||
The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
|
||||
|
||||
### Step 1: Identify where the element actually lives
|
||||
|
||||
Use the error payload:
|
||||
|
||||
- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"` — the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
|
||||
- `element_not_found` — the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
|
||||
- `file_is_generated` with `file: "..."` — user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
|
||||
|
||||
Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
|
||||
|
||||
### Step 2: Show three variants in the DOM for preview
|
||||
|
||||
The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
|
||||
|
||||
1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces — `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
|
||||
2. Insert your three variant divs inside it, same shape as the deterministic path.
|
||||
3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
|
||||
|
||||
This served-file edit is **temporary** — next regen wipes it, and that's fine. The real work happens on accept.
|
||||
|
||||
### Step 3: On accept, write to true source
|
||||
|
||||
When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files — see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
|
||||
|
||||
- Structural change → edit the template / component source.
|
||||
- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
|
||||
- Data-driven → update the data source or the render logic.
|
||||
|
||||
Then remove the temporary wrapper from the served file if it's still there.
|
||||
|
||||
### Step 4: On discard, clean up the served file
|
||||
|
||||
Remove the wrapper you inserted in Step 2. Nothing else to do.
|
||||
|
||||
## Handle `accept`
|
||||
|
||||
Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.
|
||||
|
||||
- `_acceptResult.handled: true` and `carbonize: false` — nothing to do. Poll again.
|
||||
- `_acceptResult.handled: true` and `carbonize: true` — **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field and a stderr banner both list the steps explicitly; neither is decorative.
|
||||
- `_acceptResult.handled: false, mode: "fallback"` — the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
|
||||
- `_acceptResult.handled: false` without `mode` — manual cleanup: read file, find markers, edit.
|
||||
|
||||
### Required after accept (carbonize)
|
||||
|
||||
When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file — all of which accumulate across sessions.
|
||||
|
||||
Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
|
||||
|
||||
1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values — read it first; it drives steps 3 and 4 below.
|
||||
2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `public/css/workflow.css` for this repo, or the component's co-located CSS file for a Vite/Next project — pick whichever already owns styling for the surrounding element).
|
||||
3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
|
||||
4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it — those are live-mode plumbing, not source.
|
||||
5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one — those are dead code now.
|
||||
|
||||
Then poll again.
|
||||
|
||||
A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
|
||||
|
||||
## Handle `discard`
|
||||
|
||||
Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.
|
||||
|
||||
## Handle `prefetch`
|
||||
|
||||
Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut — it signals the user is likely about to Go on a page you haven't read yet.
|
||||
|
||||
Resolve `pageUrl` to the underlying file:
|
||||
|
||||
- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
|
||||
- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
|
||||
|
||||
Read the file into context, then poll again. No `--reply` — this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
|
||||
|
||||
Dedupe is the browser's job (one prefetch per unique pathname per session) — trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
|
||||
|
||||
## Exit
|
||||
|
||||
The user can stop live mode by:
|
||||
- Saying "stop live mode" / "exit live" in chat
|
||||
- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
|
||||
- The browser's exit button
|
||||
|
||||
When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
|
||||
|
||||
## Cleanup
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/live-server.mjs stop
|
||||
```
|
||||
|
||||
Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.
|
||||
|
||||
Then:
|
||||
- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
|
||||
- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
|
||||
|
||||
## First-time setup (config missing or invalid)
|
||||
|
||||
If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.
|
||||
|
||||
Schema:
|
||||
|
||||
```json
|
||||
{
|
||||
"files": ["<path-or-glob>", "<path-or-glob>", ...],
|
||||
"exclude": ["<optional-glob>", ...],
|
||||
"insertBefore": "</body>",
|
||||
"commentSyntax": "html",
|
||||
"cspChecked": true
|
||||
}
|
||||
```
|
||||
|
||||
`files` is the inject target — **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
|
||||
|
||||
`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
|
||||
|
||||
`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
|
||||
|
||||
**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
|
||||
|
||||
**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
|
||||
|
||||
| Framework | `files` | `insertBefore` | `commentSyntax` |
|
||||
|-----------|---------|----------------|-----------------|
|
||||
| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
|
||||
| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
|
||||
| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
|
||||
| Nuxt | `["app.vue"]` | `</body>` | `html` |
|
||||
| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
|
||||
| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
|
||||
| Multi-page (separate HTML per route) | `["public/**/*.html"]` — a glob covering the served directory | `</body>` | `html` |
|
||||
|
||||
Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
|
||||
|
||||
For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
|
||||
|
||||
For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected — it writes to true source via the fallback flow.
|
||||
|
||||
### Drift-heal warning
|
||||
|
||||
On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"serverPort": 8400,
|
||||
"pageFiles": [ "..." ],
|
||||
"configDrift": {
|
||||
"orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
|
||||
"orphanCount": 2,
|
||||
"hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When `configDrift` is present, surface it to the user once per session before entering the poll loop:
|
||||
|
||||
> Noticed N HTML file(s) in the project that aren't in `config.files`:
|
||||
>
|
||||
> - `public/new-section/index.html`
|
||||
> - `public/docs/new-command.html`
|
||||
>
|
||||
> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
|
||||
|
||||
Don't auto-update the config — let the user decide. `configDrift` is `null` when there's no drift.
|
||||
|
||||
### CSP detection (first-time only)
|
||||
|
||||
If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
|
||||
|
||||
Otherwise, run the detection helper:
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/detect-csp.mjs
|
||||
```
|
||||
|
||||
Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
|
||||
|
||||
- **`null`** — no CSP; skip to writing `config.json` with `cspChecked: true`.
|
||||
- **`append-arrays`** — CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
|
||||
- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
|
||||
- SvelteKit `kit.csp.directives`
|
||||
- Nuxt `nuxt-security` module's `contentSecurityPolicy`
|
||||
- **`append-string`** — CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
|
||||
- Inline `next.config.*` `headers()` with a CSP literal
|
||||
- Nuxt `routeRules` / `nitro.routeRules` headers
|
||||
- **`middleware`** or **`meta-tag`** — rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
|
||||
|
||||
#### Consent prompt template
|
||||
|
||||
Use this phrasing so the experience is consistent across agents:
|
||||
|
||||
> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400` — the live picker won't load without an allowance. Here's the change I'd make:
|
||||
>
|
||||
> ```diff
|
||||
> [file: <patchTarget>]
|
||||
> [exact diff, 2–5 lines]
|
||||
> ```
|
||||
>
|
||||
> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
|
||||
|
||||
On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
|
||||
|
||||
On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
|
||||
|
||||
#### append-arrays
|
||||
|
||||
CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
|
||||
|
||||
**Declare near the top of the file that holds the CSP arrays:**
|
||||
|
||||
```ts
|
||||
// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
|
||||
const __impeccableLiveDev =
|
||||
process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
|
||||
```
|
||||
|
||||
**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
|
||||
|
||||
- **Next.js + monorepo helper** — edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
|
||||
- **SvelteKit** — edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
|
||||
- **Nuxt + nuxt-security** — edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
|
||||
|
||||
Reference outputs:
|
||||
- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
|
||||
- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
|
||||
|
||||
Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
|
||||
|
||||
#### append-string
|
||||
|
||||
CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
|
||||
|
||||
```ts
|
||||
// Dev-only allowance so impeccable live mode can load.
|
||||
const __impeccableLiveDev =
|
||||
process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
|
||||
```
|
||||
|
||||
Then in the CSP value string:
|
||||
- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
|
||||
- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
|
||||
|
||||
(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
|
||||
|
||||
Per-framework specifics:
|
||||
- **Next.js inline `headers()`** — edit `next.config.*`, splicing the variable into the CSP value.
|
||||
- **Nuxt `routeRules`** — edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
|
||||
|
||||
Reference outputs:
|
||||
- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
|
||||
- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs` — setup will ask again.
|
||||
|
||||
Then re-run `live.mjs`.
|
||||
@@ -0,0 +1,99 @@
|
||||
# Motion Design
|
||||
|
||||
## Duration: The 100/300/500 Rule
|
||||
|
||||
Timing matters more than easing. These durations feel right for most UI:
|
||||
|
||||
| Duration | Use Case | Examples |
|
||||
|----------|----------|----------|
|
||||
| **100-150ms** | Instant feedback | Button press, toggle, color change |
|
||||
| **200-300ms** | State changes | Menu open, tooltip, hover states |
|
||||
| **300-500ms** | Layout changes | Accordion, modal, drawer |
|
||||
| **500-800ms** | Entrance animations | Page load, hero reveals |
|
||||
|
||||
**Exit animations are faster than entrances**—use ~75% of enter duration.
|
||||
|
||||
## Easing: Pick the Right Curve
|
||||
|
||||
**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
|
||||
|
||||
| Curve | Use For | CSS |
|
||||
|-------|---------|-----|
|
||||
| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
|
||||
| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
|
||||
| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
|
||||
|
||||
**For micro-interactions, use exponential curves**—they feel natural because they mimic real physics (friction, deceleration):
|
||||
|
||||
```css
|
||||
/* Quart out - smooth, refined (recommended default) */
|
||||
--ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
|
||||
|
||||
/* Quint out - slightly more dramatic */
|
||||
--ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
|
||||
|
||||
/* Expo out - snappy, confident */
|
||||
--ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
```
|
||||
|
||||
**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop—they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
|
||||
|
||||
## The Only Two Properties You Should Animate
|
||||
|
||||
**transform** and **opacity** only—everything else causes layout recalculation. For height animations (accordions), use `grid-template-rows: 0fr → 1fr` instead of animating `height` directly.
|
||||
|
||||
## Staggered Animations
|
||||
|
||||
Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**—10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
|
||||
|
||||
## Reduced Motion
|
||||
|
||||
This is not optional. Vestibular disorders affect ~35% of adults over 40.
|
||||
|
||||
```css
|
||||
/* Define animations normally */
|
||||
.card {
|
||||
animation: slide-up 500ms ease-out;
|
||||
}
|
||||
|
||||
/* Provide alternative for reduced motion */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.card {
|
||||
animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
|
||||
}
|
||||
}
|
||||
|
||||
/* Or disable entirely */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work—just without spatial movement.
|
||||
|
||||
## Perceived Performance
|
||||
|
||||
**Nobody cares how fast your site is—just how fast it feels.** Perception can be as effective as actual performance.
|
||||
|
||||
**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
|
||||
|
||||
**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
|
||||
|
||||
- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
|
||||
- **Early completion**: Show content progressively—don't wait for everything. Video buffering, progressive images, streaming HTML.
|
||||
- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline—the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
|
||||
|
||||
**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
|
||||
|
||||
**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
|
||||
|
||||
## Performance
|
||||
|
||||
Don't use `will-change` preemptively—only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
|
||||
@@ -0,0 +1,234 @@
|
||||
> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
|
||||
|
||||
Create or improve onboarding experiences that help users understand, adopt, and succeed with the product quickly.
|
||||
|
||||
## Assess Onboarding Needs
|
||||
|
||||
Understand what users need to learn and why:
|
||||
|
||||
1. **Identify the challenge**:
|
||||
- What are users trying to accomplish?
|
||||
- What's confusing or unclear about current experience?
|
||||
- Where do users get stuck or drop off?
|
||||
- What's the "aha moment" we want users to reach?
|
||||
|
||||
2. **Understand the users**:
|
||||
- What's their experience level? (Beginners, power users, mixed?)
|
||||
- What's their motivation? (Excited and exploring? Required by work?)
|
||||
- What's their time commitment? (5 minutes? 30 minutes?)
|
||||
- What alternatives do they know? (Coming from competitor? New to category?)
|
||||
|
||||
3. **Define success**:
|
||||
- What's the minimum users need to learn to be successful?
|
||||
- What's the key action we want them to take? (First project? First invite?)
|
||||
- How do we know onboarding worked? (Completion rate? Time to value?)
|
||||
|
||||
**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
|
||||
|
||||
## Onboarding Principles
|
||||
|
||||
Follow these core principles:
|
||||
|
||||
### Show, Don't Tell
|
||||
- Demonstrate with working examples, not just descriptions
|
||||
- Provide real functionality in onboarding, not separate tutorial mode
|
||||
- Use progressive disclosure, teach one thing at a time
|
||||
|
||||
### Make It Optional (When Possible)
|
||||
- Let experienced users skip onboarding
|
||||
- Don't block access to product
|
||||
- Provide "Skip" or "I'll explore on my own" options
|
||||
|
||||
### Time to Value
|
||||
- Get users to their "aha moment" ASAP
|
||||
- Front-load most important concepts
|
||||
- Teach 20% that delivers 80% of value
|
||||
- Save advanced features for contextual discovery
|
||||
|
||||
### Context Over Ceremony
|
||||
- Teach features when users need them, not upfront
|
||||
- Empty states are onboarding opportunities
|
||||
- Tooltips and hints at point of use
|
||||
|
||||
### Respect User Intelligence
|
||||
- Don't patronize or over-explain
|
||||
- Be concise and clear
|
||||
- Assume users can figure out standard patterns
|
||||
|
||||
## Design Onboarding Experiences
|
||||
|
||||
Create appropriate onboarding for the context:
|
||||
|
||||
### Initial Product Onboarding
|
||||
|
||||
**Welcome Screen**:
|
||||
- Clear value proposition (what is this product?)
|
||||
- What users will learn/accomplish
|
||||
- Time estimate (honest about commitment)
|
||||
- Option to skip (for experienced users)
|
||||
|
||||
**Account Setup**:
|
||||
- Minimal required information (collect more later)
|
||||
- Explain why you're asking for each piece of information
|
||||
- Smart defaults where possible
|
||||
- Social login when appropriate
|
||||
|
||||
**Core Concept Introduction**:
|
||||
- Introduce 1-3 core concepts (not everything)
|
||||
- Use simple language and examples
|
||||
- Interactive when possible (do, don't just read)
|
||||
- Progress indication (step 1 of 3)
|
||||
|
||||
**First Success**:
|
||||
- Guide users to accomplish something real
|
||||
- Pre-populated examples or templates
|
||||
- Celebrate completion (but don't overdo it)
|
||||
- Clear next steps
|
||||
|
||||
### Feature Discovery & Adoption
|
||||
|
||||
**Empty States**:
|
||||
Instead of blank space, show:
|
||||
- What will appear here (description + screenshot/illustration)
|
||||
- Why it's valuable
|
||||
- Clear CTA to create first item
|
||||
- Example or template option
|
||||
|
||||
Example:
|
||||
```
|
||||
No projects yet
|
||||
Projects help you organize your work and collaborate with your team.
|
||||
[Create your first project] or [Start from template]
|
||||
```
|
||||
|
||||
**Contextual Tooltips**:
|
||||
- Appear at relevant moment (first time user sees feature)
|
||||
- Point directly at relevant UI element
|
||||
- Brief explanation + benefit
|
||||
- Dismissable (with "Don't show again" option)
|
||||
- Optional "Learn more" link
|
||||
|
||||
**Feature Announcements**:
|
||||
- Highlight new features when they're released
|
||||
- Show what's new and why it matters
|
||||
- Let users try immediately
|
||||
- Dismissable
|
||||
|
||||
**Progressive Onboarding**:
|
||||
- Teach features when users encounter them
|
||||
- Badges or indicators on new/unused features
|
||||
- Unlock complexity gradually (don't show all options immediately)
|
||||
|
||||
### Guided Tours & Walkthroughs
|
||||
|
||||
**When to use**:
|
||||
- Complex interfaces with many features
|
||||
- Significant changes to existing product
|
||||
- Industry-specific tools needing domain knowledge
|
||||
|
||||
**How to design**:
|
||||
- Spotlight specific UI elements (dim rest of page)
|
||||
- Keep steps short (3-7 steps max per tour)
|
||||
- Allow users to click through tour freely
|
||||
- Include "Skip tour" option
|
||||
- Make replayable (help menu)
|
||||
|
||||
**Best practices**:
|
||||
- Interactive over passive (let users click real buttons)
|
||||
- Focus on workflow, not features ("Create a project" not "This is the project button")
|
||||
- Provide sample data so actions work
|
||||
|
||||
### Interactive Tutorials
|
||||
|
||||
**When to use**:
|
||||
- Users need hands-on practice
|
||||
- Concepts are complex or unfamiliar
|
||||
- High stakes (better to practice in safe environment)
|
||||
|
||||
**How to design**:
|
||||
- Sandbox environment with sample data
|
||||
- Clear objectives ("Create a chart showing sales by region")
|
||||
- Step-by-step guidance
|
||||
- Validation (confirm they did it right)
|
||||
- Graduation moment (you're ready!)
|
||||
|
||||
### Documentation & Help
|
||||
|
||||
**In-product help**:
|
||||
- Contextual help links throughout interface
|
||||
- Keyboard shortcut reference
|
||||
- Search-able help center
|
||||
- Video tutorials for complex workflows
|
||||
|
||||
**Help patterns**:
|
||||
- `?` icon near complex features
|
||||
- "Learn more" links in tooltips
|
||||
- Keyboard shortcut hints (`⌘K` shown on search box)
|
||||
|
||||
## Empty State Design
|
||||
|
||||
Every empty state needs:
|
||||
|
||||
### What Will Be Here
|
||||
"Your recent projects will appear here"
|
||||
|
||||
### Why It Matters
|
||||
"Projects help you organize your work and collaborate with your team"
|
||||
|
||||
### How to Get Started
|
||||
[Create project] or [Import from template]
|
||||
|
||||
### Visual Interest
|
||||
Illustration or icon (not just text on blank page)
|
||||
|
||||
### Contextual Help
|
||||
"Need help getting started? [Watch 2-min tutorial]"
|
||||
|
||||
**Empty state types**:
|
||||
- **First use**: Never used this feature (emphasize value, provide template)
|
||||
- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
|
||||
- **No results**: Search or filter returned nothing (suggest different query, clear filters)
|
||||
- **No permissions**: Can't access (explain why, how to get access)
|
||||
- **Error state**: Failed to load (explain what happened, retry option)
|
||||
|
||||
## Implementation Patterns
|
||||
|
||||
### Technical approaches:
|
||||
|
||||
**Tooltip libraries**: Tippy.js, Popper.js
|
||||
**Tour libraries**: Intro.js, Shepherd.js, React Joyride
|
||||
**Modal patterns**: Focus trap, backdrop, ESC to close
|
||||
**Progress tracking**: LocalStorage for "seen" states
|
||||
**Analytics**: Track completion, drop-off points
|
||||
|
||||
**Storage patterns**:
|
||||
```javascript
|
||||
// Track which onboarding steps user has seen
|
||||
localStorage.setItem('onboarding-completed', 'true');
|
||||
localStorage.setItem('feature-tooltip-seen-reports', 'true');
|
||||
```
|
||||
|
||||
**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
|
||||
|
||||
**NEVER**:
|
||||
- Force users through long onboarding before they can use product
|
||||
- Patronize users with obvious explanations
|
||||
- Show same tooltip repeatedly (respect dismissals)
|
||||
- Block all UI during tour (let users explore)
|
||||
- Create separate tutorial mode disconnected from real product
|
||||
- Overwhelm with information upfront (progressive disclosure!)
|
||||
- Hide "Skip" or make it hard to find
|
||||
- Forget about returning users (don't show initial onboarding again)
|
||||
|
||||
## Verify Onboarding Quality
|
||||
|
||||
Test with real users:
|
||||
|
||||
- **Time to completion**: Can users complete onboarding quickly?
|
||||
- **Comprehension**: Do users understand after completing?
|
||||
- **Action**: Do users take desired next step?
|
||||
- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
|
||||
- **Completion rate**: Are users completing? (If low, simplify)
|
||||
- **Time to value**: How long until users get first value?
|
||||
|
||||
Remember: You're a product educator with excellent teaching instincts. Get users to their "aha moment" as quickly as possible. Teach the essential, make it contextual, respect user time and intelligence.
|
||||
@@ -0,0 +1,258 @@
|
||||
Identify and fix performance issues to create faster, smoother user experiences.
|
||||
|
||||
## Assess Performance Issues
|
||||
|
||||
Understand current performance and identify problems:
|
||||
|
||||
1. **Measure current state**:
|
||||
- **Core Web Vitals**: LCP, FID/INP, CLS scores
|
||||
- **Load time**: Time to interactive, first contentful paint
|
||||
- **Bundle size**: JavaScript, CSS, image sizes
|
||||
- **Runtime performance**: Frame rate, memory usage, CPU usage
|
||||
- **Network**: Request count, payload sizes, waterfall
|
||||
|
||||
2. **Identify bottlenecks**:
|
||||
- What's slow? (Initial load? Interactions? Animations?)
|
||||
- What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
|
||||
- How bad is it? (Perceivable? Annoying? Blocking?)
|
||||
- Who's affected? (All users? Mobile only? Slow connections?)
|
||||
|
||||
**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
|
||||
|
||||
## Optimization Strategy
|
||||
|
||||
Create systematic improvement plan:
|
||||
|
||||
### Loading Performance
|
||||
|
||||
**Optimize Images**:
|
||||
- Use modern formats (WebP, AVIF)
|
||||
- Proper sizing (don't load 3000px image for 300px display)
|
||||
- Lazy loading for below-fold images
|
||||
- Responsive images (`srcset`, `picture` element)
|
||||
- Compress images (80-85% quality is usually imperceptible)
|
||||
- Use CDN for faster delivery
|
||||
|
||||
```html
|
||||
<img
|
||||
src="hero.webp"
|
||||
srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
|
||||
sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
|
||||
loading="lazy"
|
||||
alt="Hero image"
|
||||
/>
|
||||
```
|
||||
|
||||
**Reduce JavaScript Bundle**:
|
||||
- Code splitting (route-based, component-based)
|
||||
- Tree shaking (remove unused code)
|
||||
- Remove unused dependencies
|
||||
- Lazy load non-critical code
|
||||
- Use dynamic imports for large components
|
||||
|
||||
```javascript
|
||||
// Lazy load heavy component
|
||||
const HeavyChart = lazy(() => import('./HeavyChart'));
|
||||
```
|
||||
|
||||
**Optimize CSS**:
|
||||
- Remove unused CSS
|
||||
- Critical CSS inline, rest async
|
||||
- Minimize CSS files
|
||||
- Use CSS containment for independent regions
|
||||
|
||||
**Optimize Fonts**:
|
||||
- Use `font-display: swap` or `optional`
|
||||
- Subset fonts (only characters you need)
|
||||
- Preload critical fonts
|
||||
- Use system fonts when appropriate
|
||||
- Limit font weights loaded
|
||||
|
||||
```css
|
||||
@font-face {
|
||||
font-family: 'CustomFont';
|
||||
src: url('/fonts/custom.woff2') format('woff2');
|
||||
font-display: swap; /* Show fallback immediately */
|
||||
unicode-range: U+0020-007F; /* Basic Latin only */
|
||||
}
|
||||
```
|
||||
|
||||
**Optimize Loading Strategy**:
|
||||
- Critical resources first (async/defer non-critical)
|
||||
- Preload critical assets
|
||||
- Prefetch likely next pages
|
||||
- Service worker for offline/caching
|
||||
- HTTP/2 or HTTP/3 for multiplexing
|
||||
|
||||
### Rendering Performance
|
||||
|
||||
**Avoid Layout Thrashing**:
|
||||
```javascript
|
||||
// ❌ Bad: Alternating reads and writes (causes reflows)
|
||||
elements.forEach(el => {
|
||||
const height = el.offsetHeight; // Read (forces layout)
|
||||
el.style.height = height * 2; // Write
|
||||
});
|
||||
|
||||
// ✅ Good: Batch reads, then batch writes
|
||||
const heights = elements.map(el => el.offsetHeight); // All reads
|
||||
elements.forEach((el, i) => {
|
||||
el.style.height = heights[i] * 2; // All writes
|
||||
});
|
||||
```
|
||||
|
||||
**Optimize Rendering**:
|
||||
- Use CSS `contain` property for independent regions
|
||||
- Minimize DOM depth (flatter is faster)
|
||||
- Reduce DOM size (fewer elements)
|
||||
- Use `content-visibility: auto` for long lists
|
||||
- Virtual scrolling for very long lists (react-window, react-virtualized)
|
||||
|
||||
**Reduce Paint & Composite**:
|
||||
- Use `transform` and `opacity` for animations (GPU-accelerated)
|
||||
- Avoid animating layout properties (width, height, top, left)
|
||||
- Use `will-change` sparingly for known expensive operations
|
||||
- Minimize paint areas (smaller is faster)
|
||||
|
||||
### Animation Performance
|
||||
|
||||
**GPU Acceleration**:
|
||||
```css
|
||||
/* ✅ GPU-accelerated (fast) */
|
||||
.animated {
|
||||
transform: translateX(100px);
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* ❌ CPU-bound (slow) */
|
||||
.animated {
|
||||
left: 100px;
|
||||
width: 300px;
|
||||
}
|
||||
```
|
||||
|
||||
**Smooth 60fps**:
|
||||
- Target 16ms per frame (60fps)
|
||||
- Use `requestAnimationFrame` for JS animations
|
||||
- Debounce/throttle scroll handlers
|
||||
- Use CSS animations when possible
|
||||
- Avoid long-running JavaScript during animations
|
||||
|
||||
**Intersection Observer**:
|
||||
```javascript
|
||||
// Efficiently detect when elements enter viewport
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
// Element is visible, lazy load or animate
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### React/Framework Optimization
|
||||
|
||||
**React-specific**:
|
||||
- Use `memo()` for expensive components
|
||||
- `useMemo()` and `useCallback()` for expensive computations
|
||||
- Virtualize long lists
|
||||
- Code split routes
|
||||
- Avoid inline function creation in render
|
||||
- Use React DevTools Profiler
|
||||
|
||||
**Framework-agnostic**:
|
||||
- Minimize re-renders
|
||||
- Debounce expensive operations
|
||||
- Memoize computed values
|
||||
- Lazy load routes and components
|
||||
|
||||
### Network Optimization
|
||||
|
||||
**Reduce Requests**:
|
||||
- Combine small files
|
||||
- Use SVG sprites for icons
|
||||
- Inline small critical assets
|
||||
- Remove unused third-party scripts
|
||||
|
||||
**Optimize APIs**:
|
||||
- Use pagination (don't load everything)
|
||||
- GraphQL to request only needed fields
|
||||
- Response compression (gzip, brotli)
|
||||
- HTTP caching headers
|
||||
- CDN for static assets
|
||||
|
||||
**Optimize for Slow Connections**:
|
||||
- Adaptive loading based on connection (navigator.connection)
|
||||
- Optimistic UI updates
|
||||
- Request prioritization
|
||||
- Progressive enhancement
|
||||
|
||||
## Core Web Vitals Optimization
|
||||
|
||||
### Largest Contentful Paint (LCP < 2.5s)
|
||||
- Optimize hero images
|
||||
- Inline critical CSS
|
||||
- Preload key resources
|
||||
- Use CDN
|
||||
- Server-side rendering
|
||||
|
||||
### First Input Delay (FID < 100ms) / INP (< 200ms)
|
||||
- Break up long tasks
|
||||
- Defer non-critical JavaScript
|
||||
- Use web workers for heavy computation
|
||||
- Reduce JavaScript execution time
|
||||
|
||||
### Cumulative Layout Shift (CLS < 0.1)
|
||||
- Set dimensions on images and videos
|
||||
- Don't inject content above existing content
|
||||
- Use `aspect-ratio` CSS property
|
||||
- Reserve space for ads/embeds
|
||||
- Avoid animations that cause layout shifts
|
||||
|
||||
```css
|
||||
/* Reserve space for image */
|
||||
.image-container {
|
||||
aspect-ratio: 16 / 9;
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Monitoring
|
||||
|
||||
**Tools to use**:
|
||||
- Chrome DevTools (Lighthouse, Performance panel)
|
||||
- WebPageTest
|
||||
- Core Web Vitals (Chrome UX Report)
|
||||
- Bundle analyzers (webpack-bundle-analyzer)
|
||||
- Performance monitoring (Sentry, DataDog, New Relic)
|
||||
|
||||
**Key metrics**:
|
||||
- LCP, FID/INP, CLS (Core Web Vitals)
|
||||
- Time to Interactive (TTI)
|
||||
- First Contentful Paint (FCP)
|
||||
- Total Blocking Time (TBT)
|
||||
- Bundle size
|
||||
- Request count
|
||||
|
||||
**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
|
||||
|
||||
**NEVER**:
|
||||
- Optimize without measuring (premature optimization)
|
||||
- Sacrifice accessibility for performance
|
||||
- Break functionality while optimizing
|
||||
- Use `will-change` everywhere (creates new layers, uses memory)
|
||||
- Lazy load above-fold content
|
||||
- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
|
||||
- Forget about mobile performance (often slower devices, slower connections)
|
||||
|
||||
## Verify Improvements
|
||||
|
||||
Test that optimizations worked:
|
||||
|
||||
- **Before/after metrics**: Compare Lighthouse scores
|
||||
- **Real user monitoring**: Track improvements for real users
|
||||
- **Different devices**: Test on low-end Android, not just flagship iPhone
|
||||
- **Slow connections**: Throttle to 3G, test experience
|
||||
- **No regressions**: Ensure functionality still works
|
||||
- **User perception**: Does it *feel* faster?
|
||||
|
||||
Remember: Performance is a feature. Fast experiences feel more responsive, more polished, more professional. Optimize systematically, measure ruthlessly, and prioritize user-perceived performance.
|
||||
@@ -0,0 +1,130 @@
|
||||
Start your response with:
|
||||
|
||||
```
|
||||
──────────── ⚡ OVERDRIVE ─────────────
|
||||
》》》 Entering overdrive mode...
|
||||
```
|
||||
|
||||
Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
|
||||
|
||||
**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
|
||||
|
||||
### Propose Before Building
|
||||
|
||||
This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
|
||||
|
||||
1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
|
||||
2. **STOP and call the AskUserQuestion tool to clarify.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
|
||||
3. Only proceed with the direction the user confirms.
|
||||
|
||||
Skipping this step risks building something embarrassing that needs to be thrown away.
|
||||
|
||||
### Iterate with Browser Automation
|
||||
|
||||
Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
|
||||
|
||||
---
|
||||
|
||||
## Assess What "Extraordinary" Means Here
|
||||
|
||||
The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
|
||||
|
||||
### For visual/marketing surfaces
|
||||
Pages, hero sections, landing pages, portfolios — the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
|
||||
|
||||
### For functional UI
|
||||
Tables, forms, dialogs, navigation — the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
|
||||
|
||||
### For performance-critical UI
|
||||
The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
|
||||
|
||||
### For data-heavy interfaces
|
||||
Charts and dashboards — the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
|
||||
|
||||
**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
|
||||
|
||||
## The Toolkit
|
||||
|
||||
Organized by what you're trying to achieve, not by technology name.
|
||||
|
||||
### Make transitions feel cinematic
|
||||
- **View Transitions API** (same-document: all browsers; cross-document: no Firefox) — shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
|
||||
- **`@starting-style`** (all browsers) — animate elements from `display: none` to visible with CSS only, including entry keyframes
|
||||
- **Spring physics** — natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
|
||||
|
||||
### Tie animation to scroll position
|
||||
- **Scroll-driven animations** (`animation-timeline: scroll()`) — CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only — always provide a static fallback)
|
||||
|
||||
### Render beyond CSS
|
||||
- **WebGL** (all browsers) — shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
|
||||
- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only) — next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
|
||||
- **Canvas 2D / OffscreenCanvas** — custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
|
||||
- **SVG filter chains** — displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
|
||||
|
||||
### Make data feel alive
|
||||
- **Virtual scrolling** — render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
|
||||
- **GPU-accelerated charts** — Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
|
||||
- **Animated data transitions** — morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
|
||||
|
||||
### Animate complex properties
|
||||
- **`@property`** (all browsers) — register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
|
||||
- **Web Animations API** (all browsers) — JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
|
||||
|
||||
### Push performance boundaries
|
||||
- **Web Workers** — move computation off the main thread. Heavy data processing, image manipulation, search indexing — anything that would cause jank.
|
||||
- **OffscreenCanvas** — render in a Worker thread. The main thread stays free while complex visuals render in the background.
|
||||
- **WASM** — near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
|
||||
|
||||
### Interact with the device
|
||||
- **Web Audio API** — spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
|
||||
- **Device APIs** — orientation, ambient light, geolocation. Use sparingly and always with user permission.
|
||||
|
||||
**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
|
||||
|
||||
## Implement with Discipline
|
||||
|
||||
### Progressive enhancement is non-negotiable
|
||||
|
||||
Every technique must degrade gracefully. The experience without the enhancement must still be good.
|
||||
|
||||
```css
|
||||
@supports (animation-timeline: scroll()) {
|
||||
.hero { animation-timeline: scroll(); }
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
if ('gpu' in navigator) { /* WebGPU */ }
|
||||
else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
|
||||
/* CSS-only fallback must still look good */
|
||||
```
|
||||
|
||||
### Performance rules
|
||||
|
||||
- Target 60fps. If dropping below 50, simplify.
|
||||
- Respect `prefers-reduced-motion` — always. Provide a beautiful static alternative.
|
||||
- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
|
||||
- Pause off-screen rendering. Kill what you can't see.
|
||||
- Test on real mid-range devices, not just your development machine.
|
||||
|
||||
### Polish is the difference
|
||||
|
||||
The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works — ship the version that feels inevitable.
|
||||
|
||||
**NEVER**:
|
||||
- Ignore `prefers-reduced-motion` — this is an accessibility requirement, not a suggestion
|
||||
- Ship effects that cause jank on mid-range devices
|
||||
- Use bleeding-edge APIs without a functional fallback
|
||||
- Add sound without explicit user opt-in
|
||||
- Use technical ambition to mask weak design fundamentals; fix those first with other commands
|
||||
- Layer multiple competing extraordinary moments — focus creates impact, excess creates noise
|
||||
|
||||
## Verify the Result
|
||||
|
||||
- **The wow test**: Show it to someone who hasn't seen it. Do they react?
|
||||
- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
|
||||
- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
|
||||
- **The accessibility test**: Enable reduced motion. Still beautiful?
|
||||
- **The context test**: Does this make sense for THIS brand and audience?
|
||||
|
||||
Remember: "Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
|
||||
@@ -0,0 +1,178 @@
|
||||
# Persona-Based Design Testing
|
||||
|
||||
Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
|
||||
|
||||
**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags — not generic concerns.
|
||||
|
||||
---
|
||||
|
||||
## 1. Impatient Power User — "Alex"
|
||||
|
||||
**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
|
||||
|
||||
**Behaviors**:
|
||||
- Skips all onboarding and instructions
|
||||
- Looks for keyboard shortcuts immediately
|
||||
- Tries to bulk-select, batch-edit, and automate
|
||||
- Gets frustrated by required steps that feel unnecessary
|
||||
- Abandons if anything feels slow or patronizing
|
||||
|
||||
**Test Questions**:
|
||||
- Can Alex complete the core task in under 60 seconds?
|
||||
- Are there keyboard shortcuts for common actions?
|
||||
- Can onboarding be skipped entirely?
|
||||
- Do modals have keyboard dismiss (Esc)?
|
||||
- Is there a "power user" path (shortcuts, bulk actions)?
|
||||
|
||||
**Red Flags** (report these specifically):
|
||||
- Forced tutorials or unskippable onboarding
|
||||
- No keyboard navigation for primary actions
|
||||
- Slow animations that can't be skipped
|
||||
- One-item-at-a-time workflows where batch would be natural
|
||||
- Redundant confirmation steps for low-risk actions
|
||||
|
||||
---
|
||||
|
||||
## 2. Confused First-Timer — "Jordan"
|
||||
|
||||
**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
|
||||
|
||||
**Behaviors**:
|
||||
- Reads all instructions carefully
|
||||
- Hesitates before clicking anything unfamiliar
|
||||
- Looks for help or support constantly
|
||||
- Misunderstands jargon and abbreviations
|
||||
- Takes the most literal interpretation of any label
|
||||
|
||||
**Test Questions**:
|
||||
- Is the first action obviously clear within 5 seconds?
|
||||
- Are all icons labeled with text?
|
||||
- Is there contextual help at decision points?
|
||||
- Does terminology assume prior knowledge?
|
||||
- Is there a clear "back" or "undo" at every step?
|
||||
|
||||
**Red Flags** (report these specifically):
|
||||
- Icon-only navigation with no labels
|
||||
- Technical jargon without explanation
|
||||
- No visible help option or guidance
|
||||
- Ambiguous next steps after completing an action
|
||||
- No confirmation that an action succeeded
|
||||
|
||||
---
|
||||
|
||||
## 3. Accessibility-Dependent User — "Sam"
|
||||
|
||||
**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
|
||||
|
||||
**Behaviors**:
|
||||
- Tabs through the interface linearly
|
||||
- Relies on ARIA labels and heading structure
|
||||
- Cannot see hover states or visual-only indicators
|
||||
- Needs adequate color contrast (4.5:1 minimum)
|
||||
- May use browser zoom up to 200%
|
||||
|
||||
**Test Questions**:
|
||||
- Can the entire primary flow be completed keyboard-only?
|
||||
- Are all interactive elements focusable with visible focus indicators?
|
||||
- Do images have meaningful alt text?
|
||||
- Is color contrast WCAG AA compliant (4.5:1 for text)?
|
||||
- Does the screen reader announce state changes (loading, success, errors)?
|
||||
|
||||
**Red Flags** (report these specifically):
|
||||
- Click-only interactions with no keyboard alternative
|
||||
- Missing or invisible focus indicators
|
||||
- Meaning conveyed by color alone (red = error, green = success)
|
||||
- Unlabeled form fields or buttons
|
||||
- Time-limited actions without extension option
|
||||
- Custom components that break screen reader flow
|
||||
|
||||
---
|
||||
|
||||
## 4. Deliberate Stress Tester — "Riley"
|
||||
|
||||
**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
|
||||
|
||||
**Behaviors**:
|
||||
- Tests edge cases intentionally (empty states, long strings, special characters)
|
||||
- Submits forms with unexpected data (emoji, RTL text, very long values)
|
||||
- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
|
||||
- Looks for inconsistencies between what the UI promises and what actually happens
|
||||
- Documents problems methodically
|
||||
|
||||
**Test Questions**:
|
||||
- What happens at the edges (0 items, 1000 items, very long text)?
|
||||
- Do error states recover gracefully or leave the UI in a broken state?
|
||||
- What happens on refresh mid-workflow? Is state preserved?
|
||||
- Are there features that appear to work but produce broken results?
|
||||
- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
|
||||
|
||||
**Red Flags** (report these specifically):
|
||||
- Features that appear to work but silently fail or produce wrong results
|
||||
- Error handling that exposes technical details or leaves UI in a broken state
|
||||
- Empty states that show nothing useful ("No results" with no guidance)
|
||||
- Workflows that lose user data on refresh or navigation
|
||||
- Inconsistent behavior between similar interactions in different parts of the UI
|
||||
|
||||
---
|
||||
|
||||
## 5. Distracted Mobile User — "Casey"
|
||||
|
||||
**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
|
||||
|
||||
**Behaviors**:
|
||||
- Uses thumb only — prefers bottom-of-screen actions
|
||||
- Gets interrupted mid-flow and returns later
|
||||
- Switches between apps frequently
|
||||
- Has limited attention span and low patience
|
||||
- Types as little as possible, prefers taps and selections
|
||||
|
||||
**Test Questions**:
|
||||
- Are primary actions in the thumb zone (bottom half of screen)?
|
||||
- Is state preserved if the user leaves and returns?
|
||||
- Does it work on slow connections (3G)?
|
||||
- Can forms leverage autocomplete and smart defaults?
|
||||
- Are touch targets at least 44×44pt?
|
||||
|
||||
**Red Flags** (report these specifically):
|
||||
- Important actions positioned at the top of the screen (unreachable by thumb)
|
||||
- No state persistence — progress lost on tab switch or interruption
|
||||
- Large text inputs required where selection would work
|
||||
- Heavy assets loading on every page (no lazy loading)
|
||||
- Tiny tap targets or targets too close together
|
||||
|
||||
---
|
||||
|
||||
## Selecting Personas
|
||||
|
||||
Choose personas based on the interface type:
|
||||
|
||||
| Interface Type | Primary Personas | Why |
|
||||
|---------------|-----------------|-----|
|
||||
| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
|
||||
| Dashboard / admin | Alex, Sam | Power users, accessibility |
|
||||
| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
|
||||
| Onboarding flow | Jordan, Casey | Confusion, interruption |
|
||||
| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
|
||||
| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
|
||||
|
||||
---
|
||||
|
||||
## Project-Specific Personas
|
||||
|
||||
If `CLAUDE.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
|
||||
|
||||
1. Read the target audience description
|
||||
2. Identify the primary user archetype not covered by the 5 predefined personas
|
||||
3. Create a persona following this template:
|
||||
|
||||
```
|
||||
### [Role] — "[Name]"
|
||||
|
||||
**Profile**: [2-3 key characteristics derived from Design Context]
|
||||
|
||||
**Behaviors**: [3-4 specific behaviors based on the described audience]
|
||||
|
||||
**Red Flags**: [3-4 things that would alienate this specific user type]
|
||||
```
|
||||
|
||||
Only generate project-specific personas when real Design Context data is available. Don't invent audience details — use the 5 predefined personas when no context exists.
|
||||
@@ -0,0 +1,232 @@
|
||||
> **Additional context needed**: quality bar (MVP vs flagship).
|
||||
|
||||
Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
|
||||
|
||||
## Design System Discovery
|
||||
|
||||
Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
|
||||
|
||||
1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
|
||||
2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
|
||||
3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category — patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
|
||||
|
||||
If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask — never guess at design system principles.**
|
||||
|
||||
## Pre-Polish Assessment
|
||||
|
||||
Understand the current state and goals before touching anything:
|
||||
|
||||
1. **Review completeness**:
|
||||
- Is it functionally complete?
|
||||
- Are there known issues to preserve (mark with TODOs)?
|
||||
- What's the quality bar? (MVP vs flagship feature?)
|
||||
- When does it ship? (How much time for polish?)
|
||||
|
||||
2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish — a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
|
||||
|
||||
3. **Identify polish areas**:
|
||||
- Visual inconsistencies
|
||||
- Spacing and alignment issues
|
||||
- Interaction state gaps
|
||||
- Copy inconsistencies
|
||||
- Edge cases and error states
|
||||
- Loading and transition smoothness
|
||||
- Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
|
||||
|
||||
4. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent — never perfect one corner while leaving another rough.
|
||||
|
||||
**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
|
||||
|
||||
## Polish Systematically
|
||||
|
||||
Work through these dimensions methodically:
|
||||
|
||||
### Visual Alignment & Spacing
|
||||
|
||||
- **Pixel-perfect alignment**: Everything lines up to grid
|
||||
- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
|
||||
- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
|
||||
- **Responsive consistency**: Spacing and alignment work at all breakpoints
|
||||
- **Grid adherence**: Elements snap to baseline grid
|
||||
|
||||
**Check**:
|
||||
- Enable grid overlay and verify alignment
|
||||
- Check spacing with browser inspector
|
||||
- Test at multiple viewport sizes
|
||||
- Look for elements that "feel" off
|
||||
|
||||
### Information Architecture & Flow
|
||||
|
||||
Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
|
||||
|
||||
- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
|
||||
- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere — modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
|
||||
- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
|
||||
- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
|
||||
- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
|
||||
|
||||
### Typography Refinement
|
||||
|
||||
- **Hierarchy consistency**: Same elements use same sizes/weights throughout
|
||||
- **Line length**: 45-75 characters for body text
|
||||
- **Line height**: Appropriate for font size and context
|
||||
- **Widows & orphans**: No single words on last line
|
||||
- **Hyphenation**: Appropriate for language and column width
|
||||
- **Kerning**: Adjust letter spacing where needed (especially headlines)
|
||||
- **Font loading**: No FOUT/FOIT flashes
|
||||
|
||||
### Color & Contrast
|
||||
|
||||
- **Contrast ratios**: All text meets WCAG standards
|
||||
- **Consistent token usage**: No hard-coded colors, all use design tokens
|
||||
- **Theme consistency**: Works in all theme variants
|
||||
- **Color meaning**: Same colors mean same things throughout
|
||||
- **Accessible focus**: Focus indicators visible with sufficient contrast
|
||||
- **Tinted neutrals**: No pure gray or pure black—add subtle color tint (0.01 chroma)
|
||||
- **Gray on color**: Never put gray text on colored backgrounds—use a shade of that color or transparency
|
||||
|
||||
### Interaction States
|
||||
|
||||
Every interactive element needs all states:
|
||||
|
||||
- **Default**: Resting state
|
||||
- **Hover**: Subtle feedback (color, scale, shadow)
|
||||
- **Focus**: Keyboard focus indicator (never remove without replacement)
|
||||
- **Active**: Click/tap feedback
|
||||
- **Disabled**: Clearly non-interactive
|
||||
- **Loading**: Async action feedback
|
||||
- **Error**: Validation or error state
|
||||
- **Success**: Successful completion
|
||||
|
||||
**Missing states create confusion and broken experiences**.
|
||||
|
||||
### Micro-interactions & Transitions
|
||||
|
||||
- **Smooth transitions**: All state changes animated appropriately (150-300ms)
|
||||
- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic—they feel dated.
|
||||
- **No jank**: 60fps animations, only animate transform and opacity
|
||||
- **Appropriate motion**: Motion serves purpose, not decoration
|
||||
- **Reduced motion**: Respects `prefers-reduced-motion`
|
||||
|
||||
### Content & Copy
|
||||
|
||||
- **Consistent terminology**: Same things called same names throughout
|
||||
- **Consistent capitalization**: Title Case vs Sentence case applied consistently
|
||||
- **Grammar & spelling**: No typos
|
||||
- **Appropriate length**: Not too wordy, not too terse
|
||||
- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
|
||||
|
||||
### Icons & Images
|
||||
|
||||
- **Consistent style**: All icons from same family or matching style
|
||||
- **Appropriate sizing**: Icons sized consistently for context
|
||||
- **Proper alignment**: Icons align with adjacent text optically
|
||||
- **Alt text**: All images have descriptive alt text
|
||||
- **Loading states**: Images don't cause layout shift, proper aspect ratios
|
||||
- **Retina support**: 2x assets for high-DPI screens
|
||||
|
||||
### Forms & Inputs
|
||||
|
||||
- **Label consistency**: All inputs properly labeled
|
||||
- **Required indicators**: Clear and consistent
|
||||
- **Error messages**: Helpful and consistent
|
||||
- **Tab order**: Logical keyboard navigation
|
||||
- **Auto-focus**: Appropriate (don't overuse)
|
||||
- **Validation timing**: Consistent (on blur vs on submit)
|
||||
|
||||
### Edge Cases & Error States
|
||||
|
||||
- **Loading states**: All async actions have loading feedback
|
||||
- **Empty states**: Helpful empty states, not just blank space
|
||||
- **Error states**: Clear error messages with recovery paths
|
||||
- **Success states**: Confirmation of successful actions
|
||||
- **Long content**: Handles very long names, descriptions, etc.
|
||||
- **No content**: Handles missing data gracefully
|
||||
- **Offline**: Appropriate offline handling (if applicable)
|
||||
|
||||
### Responsiveness
|
||||
|
||||
- **All breakpoints**: Test mobile, tablet, desktop
|
||||
- **Touch targets**: 44x44px minimum on touch devices
|
||||
- **Readable text**: No text smaller than 14px on mobile
|
||||
- **No horizontal scroll**: Content fits viewport
|
||||
- **Appropriate reflow**: Content adapts logically
|
||||
|
||||
### Performance
|
||||
|
||||
- **Fast initial load**: Optimize critical path
|
||||
- **No layout shift**: Elements don't jump after load (CLS)
|
||||
- **Smooth interactions**: No lag or jank
|
||||
- **Optimized images**: Appropriate formats and sizes
|
||||
- **Lazy loading**: Off-screen content loads lazily
|
||||
|
||||
### Code Quality
|
||||
|
||||
- **Remove console logs**: No debug logging in production
|
||||
- **Remove commented code**: Clean up dead code
|
||||
- **Remove unused imports**: Clean up unused dependencies
|
||||
- **Consistent naming**: Variables and functions follow conventions
|
||||
- **Type safety**: No TypeScript `any` or ignored errors
|
||||
- **Accessibility**: Proper ARIA labels and semantic HTML
|
||||
|
||||
## Polish Checklist
|
||||
|
||||
Go through systematically:
|
||||
|
||||
- [ ] Aligned to the design system (drift named and resolved by root cause)
|
||||
- [ ] Information architecture and flow shape match neighboring features
|
||||
- [ ] Visual alignment perfect at all breakpoints
|
||||
- [ ] Spacing uses design tokens consistently
|
||||
- [ ] Typography hierarchy consistent
|
||||
- [ ] All interactive states implemented
|
||||
- [ ] All transitions smooth (60fps)
|
||||
- [ ] Copy is consistent and polished
|
||||
- [ ] Icons are consistent and properly sized
|
||||
- [ ] All forms properly labeled and validated
|
||||
- [ ] Error states are helpful
|
||||
- [ ] Loading states are clear
|
||||
- [ ] Empty states are welcoming
|
||||
- [ ] Touch targets are 44x44px minimum
|
||||
- [ ] Contrast ratios meet WCAG AA
|
||||
- [ ] Keyboard navigation works
|
||||
- [ ] Focus indicators visible
|
||||
- [ ] No console errors or warnings
|
||||
- [ ] No layout shift on load
|
||||
- [ ] Works in all supported browsers
|
||||
- [ ] Respects reduced motion preference
|
||||
- [ ] Code is clean (no TODOs, console.logs, commented code)
|
||||
|
||||
**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
|
||||
|
||||
**NEVER**:
|
||||
- Polish before it's functionally complete
|
||||
- Polish without aligning to the design system — that's decoration on drift
|
||||
- Guess at design system principles instead of asking when something is ambiguous
|
||||
- Spend hours on polish if it ships in 30 minutes (triage)
|
||||
- Introduce bugs while polishing (test thoroughly)
|
||||
- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
|
||||
- Perfect one thing while leaving others rough (consistent quality level)
|
||||
- Create new one-off components when design system equivalents exist
|
||||
- Hard-code values that should use design tokens
|
||||
- Introduce new patterns or flows that diverge from established ones
|
||||
|
||||
## Final Verification
|
||||
|
||||
Before marking as done:
|
||||
|
||||
- **Use it yourself**: Actually interact with the feature
|
||||
- **Test on real devices**: Not just browser DevTools
|
||||
- **Ask someone else to review**: Fresh eyes catch things
|
||||
- **Compare to design**: Match intended design
|
||||
- **Check all states**: Don't just test happy path
|
||||
|
||||
## Clean Up
|
||||
|
||||
After polishing, ensure code quality:
|
||||
|
||||
- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
|
||||
- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
|
||||
- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
|
||||
- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
|
||||
|
||||
Remember: You have impeccable attention to detail and exquisite taste. Polish until it feels effortless, looks intentional, and works flawlessly. Sweat the details - they matter.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user