mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-11 21:57:14 +03:00
Neo Kinpaku design system + Live Mode v3 (#169)
* Add neo kinpaku design system page * skill: rip out baked-in category recipes and saturated-default motion tropes Programmatic bias mining (impeccable-evals) traced four major defects back to specific lines in this skill that contradicted SKILL.md's own first-order-reflex warning: - brand.md "Pairing and voice" prescribed four category→aesthetic recipes (editorial → serif+sans, tech/dev/fintech → tight tracking, consumer/food/travel → script/display serif, creative → rule-break). These directly drove OpenAI's 76% extreme-negative letter-spacing on tech briefs and Anthropic/Google's 28-34% italic-serif-display slop on editorial/food briefs. Replaced with one sentence: the shape depends on the brand, not on the brand's category. - brand.md "Brand permissions" had "Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero." — a four-for-one slop driver behind 97% OpenAI comically-large H1, 42% bad-SVG illustration, and the editorial-italic slop. Deleted outright. - typeset.md and teach.md repeated the same category recipes; trimmed to the principle without the recipe. - SKILL.md Typography: added a hard hero-H1 ceiling (clamp() max ≤ 6rem ≈ 96px), with a <codex> block to make it explicit since OpenAI over-indexes here (97% ≥128px vs 24% for Anthropic). - animate.md, bolder.md, brand.md: removed "staggered reveals" and "scroll-triggered transitions" as the prescribed default ambitious motion. By 2026 that's the saturated AI tell, not a choreography. Reserved stagger for legitimate list-sibling rhythm. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: anti-cream + codex-specific defect bans + universal slop bans Second pass after measuring more biases against the eval corpus. - SKILL.md Color: explicit "cream/sand/beige body bg is the saturated AI default of 2026" rule. Tone down the "tint every neutral" line so it doesn't read as "default to warm-tinted near-white" (which OpenAI hits at 74% and Anthropic at 31%-47%). - SKILL.md Absolute bans: add universal bans for two slop patterns detected at 55-95% across providers — tiny uppercase tracked eyebrow above every section (the 2023-era kicker that's now AI grammar) and numbered section markers (01/02/03). Also explicit "text that overflows its container is the universal defect on tablet/mobile." - SKILL.md Absolute bans → <codex> block: ban the GPT-specific defects Paul annotated repeatedly — `border:1px solid` + soft-wide-shadow (≥16px blur) "ghost cards", `border-radius:32px+` over-rounding, hand-drawn/sketchy SVG illustrations (loose-sketch / *-sketch classes, feTurbulence paper-grain filters), repeating-linear-gradient stripes, "X theater" AI-slop copy phrases. - SKILL.md Motion → <gemini> block: the image :hover transform tell (38% Google skill-on rate). Hover effects on images add no info; the image isn't an action target. Animate card chrome, not the image. - SKILL.md Typography: hard display letter-spacing floor ≥-0.04em (OpenAI defaults to -0.075em → cramped). Existing hero ceiling <codex> block extended with the letter-spacing rule. - codex.md Step A example: stop seeding "warm-grounded (deep oxblood + cream)" as the warm-palette template, which primes the cream default. - colorize.md Tinted backgrounds: stop printing the literal cream recipe `oklch(97% 0.01 60)`; replace with brand-anchored guidance. - document.md examples: warm-ash-cream → cool-paper so the example doesn't seed cream as the canonical neutral example. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: universal anti-slop bans + contrast/font-count/all-caps-body rules Third pass after measuring the rest of the cross-provider matrix: - Color: explicit "Verify contrast" rule. Low-contrast text fires at 68% across all providers skill-on (90+% off). The most common failure is muted gray body on a tinted near-white; light-gray-for- elegance is named as the single biggest cause of unreadable AI pages. - Typography: max-3-font-families rule. Overused-fonts (>4 families) fires at 28% Anthropic / 36% Google / 0% OpenAI skill-on; >50% off. Also: universal "no all-caps body copy" (moved from brand-only ban to Shared design laws since product-register also overuses caps). - Copy: anti-aphoristic-cadence ban targets Anthropic's signature "X. No Y." / "X. Just Y." voice (63% skill-on copy-slop rate, 77% off — the worst rate in the matrix). Once-is-voice / three-or-more- is-tell framing per the runner's copy-slop detector. - Copy: anti-SaaS-buzzword-string ban with the literal phrase list the detector watches for (streamline/empower/supercharge, trusted- by-leading, best-in-class/enterprise-grade/cutting-edge, etc). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: strengthen anti-cream rule across full warm-neutral band Smoke validation showed the cream fix worked for Google + OpenAI but Anthropic Sonnet italian-restaurant still shipped `--paper: oklch(90% .018 88)` — cream just outside the L≥95% band the rule cited. Broaden the rule: - Band: OKLCH L 0.84-0.97, C < 0.06, hue 40-100 (was 95-97% / 60-95). - Name the token-name tells explicitly (paper / cream / sand / bone / flour / linen / parchment / wheat / biscuit / ivory) — the model defaults to one of these regardless of what hex it lands on. - Call out the specific brief patterns ("warm, traditional, family- coastal-Italian" / "editorial-restraint") that the model translates into cream by reflex. Then provide three explicit non-cream options: saturated brand color, true off-white at C=0, or darker mid-tone. Warmth in the brand is carried by accent + typography + imagery, not by body bg. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v3.2.0: skill bias-fix release Bumps version from 3.1.1 to mark the four-commit skill cleanup that rips out baked-in category recipes (brand.md), saturated-default motion tropes (staggered reveals everywhere), the cream/sand body-bg AI tell, codex-specific defects (1px+wide-shadow, over-rounding, hand-drawn SVGs, stripes, X-theater copy), the extreme-letter-spacing default, and universal slop bans (all-caps eyebrow on every section, numbered-section markers, all-caps body, font-family-count > 3, aphoristic copy cadence, SaaS buzzword strings). Plus a hard hero-H1 ceiling (clamp() ≤6rem) and a Gemini-specific image:hover transform block. Validated against ~190 post-fix samples — see impeccable-evals biases tab for per-provider deltas. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * drop "no pure black/white" rule entirely The rule was contested in the design world and causing more damage than good — pushing every page into the tinted-near-white default which is the cream/sand AI tell we already explicitly ban elsewhere. Vercel, SVKMS, Brutalist sites, et al. use pure black/white successfully; the skill shouldn't second-guess that. Skill markdown deletions: - SKILL.md Color: drop the "Never use #000 or #fff" bullet. - color-and-contrast.md: drop the "Never Use Pure Gray or Pure Black" subsection, the "Never pure black" table-row prescription, and the "Avoid: Using pure black for large areas" bullet. - colorize.md: drop the "NEVER use pure black or pure white for large areas" bullet. - polish.md: drop the "Tinted neutrals: No pure gray or pure black" half of the bullet (the gray-on-color bullet survives). Detector code (cli/engine): - registry/antipatterns.mjs: remove the `pure-black-white` entry. - rules/checks.mjs: remove the three `findings.push({ id: 'pure-black-white', ... })` emit points (inline #000 bg, Tailwind bg-black class, plain-HTML scan path). - engines/regex/detect-text.mjs: remove the two pure-black-white regex rules (CSS `background: #000…` + Tailwind `bg-black`). - detect-antipatterns-browser.js: regenerated via scripts/build-browser-detector.js. Tests: - detect-antipatterns-fixtures.test.mjs: invert the assertion that pure-black-white fires; expect it to NOT fire post-v3.2. Drop the Tailwind bg-black-opacity edge-case test (no longer relevant). - detect-antipatterns.test.js: drop the standalone "detects pure- black-white in styled-components" test and remove pure-black-white from the multi-detector assertions in PricingCard, globals.css, and GlobalStyle.tsx tests. 166 bun tests pass; 24 node fixture tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: strip example patterns from copy rules, strengthen gemini block v3.2 rerun validation surfaced two issues: 1. Copy-slop detector fires more on Gemini under v3.2 (48% → 84%) than under no-skill baseline. Root cause: the anti-aphoristic-cadence rule printed the literal "X. No Y." / "X. Just Y." patterns as examples, and Gemini imitated them as the recommended voice. Same recipe-becomes- bias trap we hit with brand.md:116's "Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines" enumeration. Fix: describe the cadence as a rhythm ("serious statement, then punchy short negation") without printing literal patterns. Buzzword list trimmed to a single inline phrase family rather than quoted strings. 2. Gemini image:hover transform Gemini-tell hadn't dropped (31% off → 32% v3.2). Strengthen the <gemini> block: explicit "Never animate <img> elements on hover", call out the Tailwind group-hover:scale / group-hover:rotate / group-hover:translate parent-hover patterns by name (Gemini was reaching for these via Tailwind even though the prior text talked about :hover on the image directly). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: simplify context loading and inline register directive Replaces load-context.mjs's JSON output with a tight markdown block from the renamed context.mjs. The script now extracts PRODUCT.md's `## Register` field and appends a `NEXT STEP:` directive naming the matching reference (brand.md / product.md), which moved Gemini from skipping the register load entirely to honoring it. Drops the `.impeccable.md` auto-migration; makes IMPECCABLE_CONTEXT_DIR a lazy escape hatch consulted only when the default paths come up empty. Setup is now four bullets in one list. The DESIGN.md nudge is gone; in its place, a "familiarize with the existing design system" step that calls out CSS / tokens / running app as authoritative sources alongside DESIGN.md. The standalone `### Register` H3 stays for the cascade rules (task cue → surface → register field). New LLM-backed test suite at tests/skill-behavior/ runs five scenarios against claude-haiku-4-5, gpt-5.4-mini, and gemini-3.1-flash-lite via Vercel AI SDK. Captures real tool traces, asserts on context.mjs calls, brand.md loads, and teach.md fallback. Skips cleanly when API keys are unset. 13-14/15 pass; only stable failure is the v3.2.0-era gpt-mini S4 "don't re-run" regression. Adds @ai-sdk/google as devDep and the test:skill-behavior npm script. Touches em-dashes in skill/SKILL.md and four reference files so `bun run build:skills` passes its skill-prose validator. teach.md and document.md drop their "re-run the loader to refresh session cache" steps since the agent's own write is now the freshest source. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: merge orphan reference files into command sub-skills + inline S-tier invariants Two related restructurings: 1. SKILL.md now carries the cross-domain invariants that catch defects in any project (contrast/placeholder/gray-on-color, similar-font pairing, text-wrap, tabular-nums, centered-stack default, Flex/Grid choice, auto-fit grids, semantic z-index, reduced motion, stagger vs section-fade, premium motion materials, focus-visible, placeholders-aren't-labels, dropdown overflow trap, button/link copy). Greenfield-only rules (theme picking, color strategy, tinted neutrals) live under "New projects only". 2. Reference files merged into their command counterparts: - spatial-design.md -> layout.md - motion-design.md -> animate.md - color-and-contrast.md -> colorize.md - responsive-design.md -> adapt.md - ux-writing.md -> clarify.md - typography.md -> typeset.md (bolder.md redirected) - cognitive-load.md + heuristics-scoring.md + personas.md -> critique.md craft.md and shape.md "load references" lists updated to new file homes. interaction-design.md stays standalone (no 1:1 command verb). Net: 36 -> 27 reference files. Same content, fewer files, no orphaned reference loaded only from craft.md. Also extends the routing rules: if the user's first word doesn't match a command but the intent clearly maps to one, load that command's reference and proceed as if invoked. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: add sub-command + existing-project scenarios; move sub-command load to step 2 Adds three new LLM-backed scenarios to tests/skill-behavior: - S6: `/impeccable polish` → loads polish.md - S7: `/impeccable audit` → loads audit.md - S8: existing SvelteKit project (PRODUCT.md + DESIGN.md + src/app.css + src/lib/components/*.svelte + src/routes/+page.svelte) → agent reads at least one project code file to understand the existing design system S6/S7 surface a real model-floor: gpt-5.4-mini reads brand.md, reads the target index.html, and just does the polish/audit without ever loading the sub-command reference. Stronger SKILL.md wording didn't move it. Captured in the README baseline as a known weakness. Claude and Gemini honor the load reliably. To fix Gemini on S6/S7, sub-command reference loading is now Setup step 2 (right after context.mjs), not step 4 — placing it before the model gets focused on "doing the work". Step 3 (design-system familiarization) is tightened to require at least one project code read even when a sub-command reference loads in step 2, so Claude doesn't laser-focus on the sub-command flow and skip the broader exploration. Two new fixtures: MINIMAL_LANDING_HTML (a tiny static landing page for S6/S7) and SVELTE_PROJECT_FILES (a minimal SvelteKit scaffold with tokens, components, and a routes/+page.svelte for S8). Both designed to look real enough that agents treat them as production code. Suite is now 24 tests across three providers; baseline is 21-22/24, with the stable failures being gpt-5.4-mini scenarios 6 and 7. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: add reveal-animation safety rule (must enhance, not gate visibility) Class-triggered visibility transitions pause on hidden tabs and headless renderers. The italian-restaurant smoke produced a build where 2 sections shipped opacity:0 because the CSS transition never advanced past currentTime=0 (timeline paused). Added one-liner under Motion to prevent the antipattern: reveals must enhance an already-visible default, never gate content visibility on a class-triggered transition. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: restore prescriptive cream/sand/beige paragraph Bisection across 5 historical skill commits on Gemini 3.5 flash fast lane n=3 found that0cf2debdwas the peak quality state. The regression between0cf2debdand HEAD came from simplifying the long anti-cream paragraph into a one-liner. Restoring the paragraph (with em-dashes replaced by parens to satisfy prose lint) recovers ~0.22pt average on Gemini vs HEAD, with the largest gains on: - 09-luxury-hotel: +0.50 (restores editorial drama in photo-led briefs) - 10-food-magazine: +0.67 - 03-italian-restaurant: +0.51 The paragraph's load-bearing parts are the (a)(b)(c) alternatives that give the model actionable replacements for cream-tinted body bg ("saturated brand color as body", "true off-white at chroma 0", "darker mid-tone tinted neutral"). Without them, the one-line warning left the model with no concrete alternative. Cross-provider validation showed the pattern matches historical behavior: Gemini benefits from prescriptive scaffold (+0.12 over off), Sonnet is roughly neutral (+0.01), GPT-5.5 slightly regresses (-0.11 matching the v3.1.0 pattern of -0.11). The skill has never been uniformly better than skill-off across providers; this is the closest achievable state without provider-specific rework. The structural improvements from the prior restructure stay (file merges, S-tier inlines, routing rule extension, reveal-animation safety rule). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: teach CLAUDE.md / AGENTS.md / DEVELOP.md about the skill-behavior tests Adds the `bun run test:skill-behavior` script to the test commands lists in all three docs. CLAUDE.md gets a full `### Skill-behavior tests` subsection paralleling the existing Live-mode E2E one: how the suite works (inlines source SKILL.md, scoped tools, asserts on the trace), which providers it always runs (claude-haiku-4-5, gpt-5.4-mini, gemini-3.1-flash-lite — all three every run), the eight scenarios, the baseline (21-22/24 with stable gpt-mini sub-command-routing failures), auth via repo-root `.env`, and how to add a scenario. AGENTS.md gets the one-liner plus a paragraph in Testing Guidelines that points contributors at the suite for Setup-touching edits (SKILL.md Setup section, context.mjs, teach.md, document.md, register / sub-command refs). DEVELOP.md gets a short Testing section that didn't exist before, plus a nudge in the "Test across providers" bullet pointing at the new suite as the automated way to do that. No code changes. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * detector: add 5 new antipatterns (em-dash-overuse, broken-image, marketing-buzzword, numbered-section-markers, aphoristic-cadence) Consolidates eval-side detection logic into the canonical impeccable detector. Before this change, the eval harness had its own duplicate implementations of em-dash, copy-slop, and broken-image checks. They now live alongside the existing 28 antipatterns in the impeccable registry, available to the CLI, browser extension, critique skill, and eval (via the existing slop grader child-process call). New antipatterns: - em-dash-overuse: 5+ em-dashes in body text content (threshold permits legitimate prose use of em-dash; only triggers on AI cadence-level density) - broken-image: <img> with empty src, missing src, or src="#" - marketing-buzzword: SaaS phrase list (streamline / empower / supercharge / enterprise-grade / cutting-edge / etc) - numbered-section-markers: repeated 01 / 02 / 03 sequence as section labels — the AI editorial scaffold one tier deeper than tracked eyebrow chips - aphoristic-cadence: 3+ manufactured-contrast ("Not a X. A Y.") or short-rebuttal ("Sentence. No clause." / "Sentence. Just clause.") constructions in body text Engine wiring: - broken-image runs as a static-html element rule (selector: img) and a fallback regex matcher (for non-HTML files) - em-dash / buzzword / numbered / aphoristic run as regex page-analyzers, factored into a new runTextContentAnalyzers() helper that both detectText (non-HTML) and detectHtml (HTML) call, so .html files get the same coverage as .css/.tsx Tests: 166 detector + 12 browser + 24 fixture all pass. Browser detector rebuilt (162.7 KB). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: drop unvalidated anti-centering rule; add image-led hero carve-out The anti-centering rule ("Don't default to centering everything") was added without empirical support. We have a detector for it (everything-centered, threshold ≥70%) that fires on 0 / 998 samples in the corpus — never validated, never useful. Meanwhile the rule was almost certainly responsible for collapsing Gemini 3.5 flash's luxury-hotel skill-on output from the canonical "full-bleed photo + centered overlay headline" cinematic hero (the shape skill-off Gemini chooses 67% of the time) to a 50/50 magazine grid (full-bleed rate drops to 18% under skill-on, -49pp). Changes: - skill/SKILL.md #### Layout: drop "Don't default to centering..." - skill/reference/brand.md ## Layout: drop the same rule; replace with a positive carve-out — image-led briefs (hotels, restaurants, magazines, photography) often want full-bleed hero with overlaid menu and centered headline; let the photograph be the design - skill/reference/layout.md: drop the assessment question and the "asymmetric breaks centered-content pattern" framing Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Apply neo-kinpaku design system and improve live picker UX Restyle the live picker to match the site kinpaku kit, persist pick mode in localStorage, fix DESIGN.md color swatches in the parser, and land the neo-kinpaku site refresh with new tokens, assets, palette script, and detector rules. Co-authored-by: Cursor <cursoragent@cursor.com> * Add live Steer end-to-end: poll protocol, browser UI, and E2E harness. Wire page-level Steer through the live server and agent poll loop with steer_done unlock semantics, extend live.md for agents, and add smoke tests with LLM handleSteer plus recovery for hidden heroes, HMR lag, and dev-tool overlays. Co-authored-by: Cursor <cursoragent@cursor.com> * Add experimental live-poll --stream mode; keep one-shot default for Cursor. Stream keeps one process alive with ack-aware resume, but live.md documents that Cursor should stay on one-shot background notify after testing showed ~5s pickup vs sub-second on exit-based notify. Co-authored-by: Cursor <cursoragent@cursor.com> * Sync harness output and fix build validators for poll stream release. Regenerate provider skills after live-poll --stream work, update homepage detection counts to 41, and replace em dashes in site/skill copy so bun run build passes prose and count checks. Co-authored-by: Cursor <cursoragent@cursor.com> * homepage: add testimonials marquee section A two-row testimonial marquee on a tinted graphite plinth, sitting between the hero and the slop teaser. 29 testimonials sourced via api.fxtwitter.com (lightly cleaned: leading @-mention reply targets stripped, trailing self-links removed). Avatars downloaded into site/public/assets/testimonials/ so they're served locally. Quote order curated for impact — both rows lead with the punchiest quotes (Ben Davis spotlight, "Impeccable > Claude design", "THIS. This shit works.", "Uninstall whatever frontend skill you're using.") so the first viewport is loaded with the most memorable testimonials. Engineering notes: - Section uses width:100vw + margin-left:calc(50% - 50vw) to escape main.site-content's max-width + side padding (cards now clip cleanly at the actual viewport edges). - Marquee runs at 110s linear infinite. Both rows share the same duration so on-screen speeds match; track is doubled so the loop back to 0 reads as continuous. - Hero min-height reduced from 100svh to calc(100svh - 115px) so the dotted divider and top of row A peek above the fold on landing, signalling the section is there. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * homepage: keep the hero demo clear of the fixed header on short viewports The hero centers its content in the full viewport (the site header is a fixed overlay), so on shorter screens the tall Live Mode demo tucked under the nav. Raise the hero's top padding above the 97px header (113px wide, 108/92px when stacked) so content always pins below the header while still centering on tall viewports, and cap the demo frame to the viewport so the whole demo stays on screen. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Add steer voice input and refine processing animation. Wire Web Speech API on the Steer mic with auto-submit, block Cursor's preview browser with a clear message, and replace truncated "Working" text with a dots-only processing state. Co-authored-by: Cursor <cursoragent@cursor.com> * Add agent poll connectivity indicator and tighten global bar spacing. Surface poller state on the Impeccable mark via SSE and /status, with an instant disconnected tooltip, steer timeout failsafe, and matched brand/chat section gaps. Co-authored-by: Cursor <cursoragent@cursor.com> * Fix steer focus to allow page text selection without losing type-to-steer. Blur the hidden steer input on page interaction, pause refocus during selection gestures, and reschedule focus recovery after clicks and cleared selections. Co-authored-by: Cursor <cursoragent@cursor.com> * site: rework "Design in production" section glyphs and audience band Put the three how-it-works steps back into thin-line cards and drop the overused browser-chrome bars from each glyph. Redraw the step 2 and 3 visuals to mirror the real Live Mode UI: step 2 shows the on-canvas pick outline with an attached comment bubble, step 3 shows the floating contextual accept bar plus the source-write confirmation. Re-treat the audience tiles as verdigris-lined text (no card box) under a "Who it's for" eyebrow, so each role reads as distinct from the gold step band. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Add live insert mode with HMR-safe placeholder recovery. Ships insert picking, scaffold helpers, variant cycling fixes for hidden variants, and placeholder snapshot/recreation so Astro HMR does not drop the wait-state box or re-anchor to the hero container. Co-authored-by: Cursor <cursoragent@cursor.com> * site: mobile pass — hamburger nav + designing hero overflow fix The header was rendering inline nav links + GitHub button that overflowed narrow viewports (~363px). Pre-existing display:none hacks hid Designing and Live to make the row fit, but those items still belonged in the menu. Header.astro: added a hamburger toggle button + inline script. The right cluster (nav + GitHub) becomes a collapsible drawer below the header on mobile, with data-nav-open driving the open/closed state and animating the two-line glyph into an X. kinpaku-kit.css: hamburger button (kinpaku-bordered glyph), mobile drawer panel (solid lacquer-deep bg, hairline separators between rows, full-width tappable rows), and overrides for the older sub-pages.css mobile rules (horizontal-scroll mask on the nav, hidden [data-nav="home"] item, hidden GitHub star label) — all redundant now that the drawer surfaces everything. home-kinpaku.css: dropped the @media (max-width: 560px) block that hid Designing / Live / GitHub. The drawer pattern shows them all. designing-kinpaku.css: hero h1 "Designing with Impeccable" was overflowing at narrow viewports. Three fixes: - grid-template-columns 1fr → minmax(0, 1fr) so the column shrinks to fit container instead of growing to "Impeccable"'s 472px intrinsic min-content width. - mobile h1 size override (clamp(2.2rem, 11vw, 3rem) at <=480px) since the display token's 3.4rem minimum is sized for desktop hero impact. - hide the decorative loop-wheel SVG below 600px (was overflowing 22px past the right edge). Verified clean at both 363px and 403px viewports across /, /docs, /docs/animate, /slop, /designing, /live-mode. scrollWidth matches viewport width on every page (no horizontal scroll). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * detector: refine new rules + run provider tells in browser env Follow-up to the detector port (rules landed in7648af00): - oversized-h1: flag long headlines set at display size, not punchy one/two-word heroes (length, not size alone, is the tell) - provider tells (--gpt/--gemini) now always run in a real browser env (detector page, live overlay, extension); gating is a CLI-output concern only, applied in the Node engine return paths - move theater-slop-phrase into checkHtmlPatterns so it runs in the bundled browser path, not just CLI/static (browser bundle excludes detect-text.mjs) - hero-eyebrow-chip overlay highlights the eyebrow, not the heading - gemini-tells fixture: data-URI images so the hover-zoom renders - rebuild browser bundle Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: migrate /detector lab to neo-kinpaku design system Rebuild the detector lab tool shell on --ks-* tokens (lacquer ground, gold hairlines, champagne/mono type) instead of the legacy warm-paper palette. Swap the "/" placeholder for the real carved-tile brand lockup, restyle the toolbar actions as kinpaku primary/secondary buttons, and recolor the finding overlay from off-brand magenta to vermilion. Update the global theme-color from #fafafa to #010101 (the sRGB render of the lacquer ground) so the browser chrome matches the dark site. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Homepage: hero finalist, compact live demo, real picker bar. Switch the hero to m-01-v2-01, tighten the in-hero demo layout, and replace the marketing gbar with a shared LiveDemoGbar that mirrors live-browser.js. Size the bar with max-content so controls are not clipped inside the capsule. Co-authored-by: Cursor <cursoragent@cursor.com> * site: migrate /cases/neo-mirai to neo-kinpaku design system Rebuild the Neo Mirai case-study page on --ks-* tokens: lacquer ground (drops the off-brand magenta radial spotlight), Alumni Sans Pinstripe display headings instead of the banned italic serif, gold eyebrow/labels, gold hairline image frames, kinpaku primary/secondary buttons, and a lacquer-deep command panel with a gold-bordered code block. Opt .neon-case-page into the shared kinpaku site-header/footer chrome in kinpaku-kit.css (per the "add new kinpaku pages to the selector list" note) so the global header and footer go dark to match the page. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: consolidate kinpaku header+footer into one reusable .kinpaku-chrome class The dark header/footer were not a reusable unit: the header was scoped to a per-page selector list, the github star pill was home-only, and the default footer was copy-pasted into four page stylesheets. Pages not on the lists (like /cases/neo-mirai) fell back to the legacy light chrome. Collapse all of it into one `.kinpaku-chrome` block in kinpaku-kit.css — header, github pill, and default footer — and opt every kinpaku page in via a single body class. Delete the four duplicated per-page footer blocks and the home-only github pill. The home page keeps its textured verdigris footer as a deliberate override, raised to body.home-kinpaku specificity so it wins regardless of import order. Genuinely light pages (privacy, tutorials) just omit the class. Fixes on /cases/neo-mirai: footer and github star now render dark/kinpaku (were legacy-light), and the content sections are wrapped in the .neon-case container so they sit in header-aligned gutters instead of bleeding to the viewport edge. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: migrate privacy + tutorials to kinpaku via a reusable surface class These were the last two light pages. Rather than rewrite their per-rule styling, add a reusable .kinpaku-surface class that remaps the legacy --color-* / --font-* tokens to kinpaku values at the body scope, so the existing legacy-token CSS (sub-pages.css prose, the pages' inline styles) renders dark for free. Same trick docs-kinpaku/slop-kinpaku use per page, lifted into one shared class. Pair it with .kinpaku-chrome for header + footer. privacy + both tutorials pages now carry both classes. Also force the sub-1.2rem headings (tutorial card titles, prose h1/h2) back to the upright body face: the legacy display face was italic serif, and the kinpaku Pinstripe face reads wrong synthesized-italic at small sizes. No light pages remain. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: re-add Tutorials to the /docs sidebar Tutorials lost its docs placement across two refactors: the Astro docs rebuild never carried over the sidebar tutorials list the old generated pages had, and the kinpaku homepage redesign dropped the "Full walkthrough" link. It survived only via /designing and /live-mode. Add a "Tutorials" group at the top of the docs sidebar (matching the command-category styling) linking the index plus all four tutorials, restoring the old information architecture. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: make kinpaku the default — flip legacy :root tokens to dark (phase 1) Repoint the legacy design tokens in tokens.css from light-mode to kinpaku: --font-* now reference the --ks-* brand faces (retiring Cormorant/Instrument/ Space Grotesk), surfaces carry dark-lacquer oklch, and --color-accent is gold instead of magenta. Values mirror the per-page kinpaku remaps. Every live page already overrides these at its body-class scope, so this changes the fallback (any classless/new page now renders kinpaku) without altering existing pages — verified home, designing, slop, live-mode, docs unchanged, and the deliberate-light demos (slop specimens, home's Aurelia mock) still render light via their own colors. First step toward removing the per-page remaps; those become redundant next. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * detector + slop: cream-palette rule, drop everything-centered, polish catalog - new deterministic cream-palette rule ("claude beige"): flags warm lightly-tinted off-white page backgrounds; wired into static + browser engines, with fixture + test - remove everything-centered rule entirely (no longer in the skill) from registry, regex analyzer (+ index-offset fix), checkPageLayout, and tests - catch Instrument Serif in overused-font (regex + OVERUSED_FONTS) - /slop: reconcile catalog (cream card in, everything-centered out; counts), and fix demo visuals — visible hairline border, gigantic clipped hero, more extreme crushed tracking, padded gray-on-color card, uniform-rhythm monotonous-spacing, long line-length line, elastic-overshoot dialog for bounce easing, real zooming image for image-hover; flip the demo surface off warm beige to a cool neutral Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * detector page: add cream-palette fixture to the catalog Surfaces the new cream/beige palette rule on /detector alongside the other Color specimens. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: shared docs sidebar + tutorial pages join the layout Extract the /docs section sidebar into a reusable DocsSidebar component and wire it into all three entry points so the navigation is consistent across docs index, command pages, and tutorial pages. site/components/DocsSidebar.astro (new): one source of truth. Loads the tutorials + skills collections, renders Tutorials → Commands grouped by category, and highlights the active entry via activeCommand / activeTutorial props. site/pages/docs/index.astro: swap the inline sidebar markup for the component. Drop the "All tutorials" link — the dedicated tutorials listing page wasn't earning its slot in the rail. site/layouts/Doc.astro: same swap. Command pages now also see the Tutorials section above Commands, matching /docs. site/pages/tutorials/[...slug].astro: rewrite from a standalone page (custom .tutorial-page wrapper, ad-hoc breadcrumb) to the full skills-layout shell with DocsSidebar in the left rail. Tutorial content now reads in the same layout as command reference pages. site/content/tutorials/brand-vs-product.md (deleted): the skill picks the register automatically from PRODUCT.md, so a tutorial telling users to pick it themselves was misleading. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * detector: catch Tailwind warm-light bg utilities in cream-palette The static engine can't resolve Tailwind classes to computed CSS, so a `bg-amber-50` on <body> slipped past the cream-palette rule. Add a class-list fallback that scans body/html for arbitrary `bg-[...]` values and named warm-light utilities (amber/orange/yellow/stone), each run through the same isCreamColor test so neutrals and over-saturated shades drop out. Fixture + test for the class-only case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: drop redundant per-page token remaps (phase 2) With kinpaku now the :root default, the --color-* / --font-* remap blocks in docs/slop/designing/live-mode-kinpaku.css re-declared values identical to :root. Removed them, keeping only the --ks-muted alias (still read by name in those files) and each page's shell (gradient bg, color, min-height). home-kinpaku.css keeps its remap: it uses home-specific values (e.g. --color-charcoal: var(--ks-text), --color-cream: var(--ks-lacquer-raised)) plus the --cat-* gradient overrides, so it is not redundant. Verified designing (PRODUCT.md viz), slop (specimens stay light), docs, live-mode unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: drop italic from 15 dead editorial-serif heading rules Audited every font-style: italic in sub-pages.css and main.css against the live markup. Removed italic from the 15 rules whose selectors don't appear in any page/component/content/script: sub-pages.css: docs-home-card-title, docs-category-title, tutorial-embed-caption, skill-demo-caption, skill-source-card-subtitle, skill-references-heading, skill-reference-title main.css: hero-title-combined, hero-tagline-combined, impeccable-title, loading-state, install-primary-howto .install-path-desc em, install-howto-steps > li::before, install-step-status, consulting-title These were dormant remnants of the retired Cormorant italic-serif look — the kinpaku Pinstripe face renders them as bad synthesized-italic, but no markup matches the selectors so nothing rendered. Removed only the font-style declaration; the rest of each rule stays (whole-rule cleanup is out of scope). Kept the 5 live selectors (slop-section-heading, tutorial-card-title, visual-mode-demo-caption, visual-mode-method-name, gallery-card-title) per the "if they're not used anywhere" condition, plus .prose em (real emphasis) and .prose blockquote (conventional blockquote italic). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: brand-seed palette.mjs + Setup step to run it New-brand color now starts from a curated seed color (129 OKLCH seeds) instead of the model guessing or defaulting to warm-cream. The script returns one seed + composition guidance (pure-bg architecture, perceptual text-on-fill, anti-cliché moods, jewel-tone range), with inverse-frequency hue weighting for fair rainbow exposure and deterministic --from picking. SKILL.md Setup step 5 makes it run for greenfield projects. Curation tooling lives in the impeccable-evals repo (tools/palette/). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Remove accidental live mode inject from Base.astro. The localhost live.js tag was left in the site layout after a dev session and should never ship in the Astro template. Co-authored-by: Cursor <cursoragent@cursor.com> * site: dedicated /changelog + /faq, epic v3.5.0 notes, Live Mode → Beta Split changelog and FAQ out of the homepage into two standalone kinpaku pages, linked from the footer (and a quiet hint under the Get-started CTA). /changelog: every release inline (no collapsible), newest first. The v3.5.0 entry leads with a one-line summary, a real before/after pair from the GPT-5.5 eval corpus (luxury-hotel brief, skill off vs on), and a stat row (74% cream-bg, 76% extreme tracking, 90%+ low-contrast — measured across ~190 samples). Then five scannable bold-led bullets, biggest takeaway first: per-provider skill compilation, the bias-fix, Live Mode, the 7 new detector rules, the tighter skill. Before/after JPGs optimized to ~470KB total (down from ~2.5MB PNGs). /faq: the six support questions, each deep-linkable. Live Mode is now Beta everywhere it surfaces: the /live-mode eyebrow badge and note, the homepage bento tile badge, and the changelog entry. The historical v3.0 changelog entry stays "Alpha" — accurate to what shipped then. Footer trimmed to the four links not already in the top nav (Changelog, FAQ, Privacy, GitHub). Version bumped 3.2.0 → 3.5.0 across the three plugin manifests; the 3.2 bias-fix work folds into this release rather than shipping separately. astro.config.mjs: disable the dev toolbar. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: point /design-system hero at the m-01-v2-01 finalist design-system.css referenced kintsugi-hero-v2.png, an untracked orphan that was never committed. Repoint it at the committed m-01-v2-01 finalist so /design-system and the homepage hero share one image, and the page no longer depends on a file outside the repo. The v2 orphan moved to tmp/. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * build: sync harness mirrors + green the prose gate Rebuild propagates the committed skill source (palette.mjs Setup step, detector rule updates, brand.md) into the 13 harness output dirs and the plugin subtree, which had drifted from source. Also fixes the prose validator, which had been red on six pre-existing hits across committed files: - Four em dashes in code comments (Testimonials.astro, LiveDemoGbar.astro, index.astro) and one in skill/reference/live.md — reworded to colons/commas. - Two in the slop catalog (an em-dash-overuse specimen and the marketing-buzzword rule naming "empower"). Those are intentional: the slop page documents every antipattern by example, so it must contain them. Exempted site/pages/slop from validateProse rather than neutering the specimens. `bun run build` is now green end to end: counts validate, prose passes, site builds. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * skill: rewrite no-section-fade rule to fix Gemini zero-motion overcorrection The old rule ("whole-section fade-on-scroll is the saturated AI motion reflex") drove Gemini to overcorrect into shipping pages with no motion at all: motion-variety 39% / zero-motion 12% with the skill on, vs ~74-78% variety and ~3% zero-motion without it. Rewrite keeps the legitimate-stagger carve-out, names the defect at shape level (one identical entrance on every section) without enumerating motion primitives, and adds an explicit clause that suppressing the reflex is never grounds for a static page. Validated on Gemini 3.5-flash (n=10, luxury-hotel + infra-platform): motion-variety 39% -> 70%, zero-motion 12% -> 0%, staggered-reveal stays 0% (reflex not re-inflated). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * release: bump CLI to 2.2.0 and extension to 1.1.0 Both ship the expanded detector: the 7 new rules (cream-palette, em-dash-overuse, marketing-buzzword, numbered-section-markers, aphoristic-cadence, broken-image, italic-serif-display) plus hero-eyebrow-chip, with everything-centered removed. 41 rules total. The extension settings page already supports toggling them: the rule list renders from detector/antipatterns.json, grouped by category, and disabledRules flows through chrome.storage.sync into the scan config, which detect.js honors by rule id. New rules are toggleable with no UI change. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * release: fix release.mjs for the moved changelog + add CLI/ext entries The changelog moved from site/pages/index.astro to its own site/pages/changelog.astro with new markup (cf-version / cf-entry / cf-items), which left release.mjs reading the wrong file with the old selectors. All three release commands would have failed at note extraction. Point it at changelog.astro, match cf-version, and scope notes to the <ul class="cf-items"> bullet list — that also skips the lead paragraph, before/after figure, and stat row on the v3.5.0 entry, keeping release notes to clean bullets. Add CLI v2.2.0 and Extension v1.1.0 changelog entries (the shared detector update: 7 new rules, everything-centered removed, 41 total; plus the extension's per-rule toggles) so release:cli and release:ext have notes to extract. Verified extraction for all three labels: v3.5.0 (5 bullets), CLI v2.2.0 (3), Extension v1.1.0 (2). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: correct dev server port to 4321 and drop stale pnpm-lock Astro serves on 4321, not 3000 as the docs claimed; update CLAUDE.md, AGENTS.md, and screenshot-antipatterns.js. Remove the leftover pnpm-lock.yaml from the Astro migration so Cloudflare's frozen install uses the maintained, in-sync bun.lock instead of a drifted pnpm lockfile. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: rework /designing flow, rhythm, Live Mode mock, and CTA Restructure the page so iteration reads as the core value, not net-new. The four loop phases are wrapped in a track with a sticky scroll-spy nav (Start/Iterate/Polish/Maintain) that pins under the header and highlights the active phase; the surfaces section (skill/CLI/extension) moves out of the loop into the post-loop context group so the loop runs uninterrupted. Fix the iterate split: shared subgrid row tracks so the terminal and the Live Mode mock align on the same baseline regardless of paragraph length, wider intro measure (52ch, was a crammed 36ch), and a deeper picker stage so the context and global bars breathe instead of stacking on the card. Rebuild the Live Mode mock to mirror the real picker: carved-tile mark plus Pick / Insert / Detect / DESIGN.md controls on lacquer-deep with the gold border, and a /impeccable live entry line so the reader knows how to start. Reframe Start as the hard mode, move h3 subheads off the thin display face onto Albert Sans, and trim Start so it no longer dominates the loop. Rework the closing CTA into two standalone raised cards (the bento plinth made them read as boxes nested in a box), and fix the tutorials copy: there are three walkthroughs now, and the brand-vs-product tutorial is gone, so drop it from the CTA and remove the dead lane link to it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: reorder Get Started so usage follows setup, link out to more Move the /impeccable usage examples below the Chrome extension, CLI, and Stay-updated block. Running a command is the logical next step once the skill, extension, CLI, and subscriptions are all in place, so the section now reads install -> set up the extras -> use it. Add a closing "Go deeper" line linking to the Designing with Impeccable workflow page and the docs. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: install compiled per-provider skill variants, not uncompiled source `npx skills add` (and `impeccable skills install`, which wrapped it) installed the uncompiled skill/ source verbatim: the skills CLI dedupes discovery by name and picks skill/SKILL.md first, so installs shipped unresolved {{placeholders}} and no vendored detector (#168). - Rename skill/SKILL.md -> skill/SKILL.src.md so the skills CLI's discovery skips the source and falls through to a compiled .agents variant; update the build reader, skill-behavior harness, and docs to match. - Refactor `impeccable skills install` to copy each harness's compiled variant from the universal bundle (real dirs, no npx skills, no symlink), with project/global harness detection and a --providers override. - Fix stale unit tests (replacePlaceholders, readPatterns, transformer prefix/summary) that asserted removed pre-v3.0 behavior, and wire the three orphaned test files into `bun run test` so the drift can't recur. - Split skills-cli.test.js: pure blocks run by default, network blocks move behind a new `bun run test:cli-e2e`; fix its stale update assertions. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: default to `npx impeccable skills install`, restore install-method panel Get Started recommended `npx skills add`, which installs a single shared build across harnesses. Make our CLI the default (it installs the build compiled for each harness) and bring back the "Other install methods" disclosure the neo-kinpaku redesign dropped. - Homepage: primary command is now `npx impeccable skills install`; a native <details> panel offers the Claude Code plugin and `npx skills` (caveated as installing one shared build rather than the per-harness one). - FAQ: recommend `npx impeccable skills install` to install, `--force` to reinstall, and note the npx skills shared-build caveat. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * site: reword craft tagline so it doesn't lead with "Shape" The craft card's tagline began with the word "Shape", which reads like the name of the sibling /shape command and made the two cards look swapped (#166). Reword to "Design it, then build it, all in one flow." No data was actually swapped; this is a copy collision fix. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * skill: rename teach -> init and expand its setup flow Rename the `/impeccable teach` command to `/impeccable init` across the skill, site, CLI, and tests. `teach` stays as a deprecated router alias and /docs/teach + /skills/teach redirect to /docs/init. Expand the command beyond writing PRODUCT.md/DESIGN.md: the same codebase crawl now also pre-configures `.impeccable/live/config.json` (Step 6, with CSP consent) so live mode boots with no first-time detour, and the flow ends by recommending the best commands to run next from what the scan surfaced (Step 7). Fold two items into the unreleased v3.5.0 changelog entry: the init rename and the brand-seed palette picker. No version bump. Regenerates all harness skill output dirs and the _redirects file. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs: lead README install + usage with the CLI installer Add `npx impeccable skills install` as the recommended install option and update the Usage section to the `/impeccable <command>` form, dropping the nonexistent `/normalize` example. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(skill-behavior): swap to production-tier models (sonnet + gpt-5.5) Replace the cheap-tier default lineup (claude-haiku-4-5, gpt-5.4-mini) with production-tier models (claude-sonnet-4-6, gpt-5.5) so the skill-behavior suite reflects what users actually run. gemini stays on flash-lite. Sync the docs (CLAUDE.md, AGENTS.md, tests/skill-behavior/README.md): new model names, cost estimate raised to ~$0.50-1.50/sweep, and the old 21-22/24 baseline reframed as previous-cheap-tier history pending re-measurement on the new lineup. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat: self-updating skill via boot-time version check context.mjs now polls a new lightweight /api/version endpoint at most once per day (cached globally in ~/.impeccable) and appends an UPDATE_AVAILABLE directive when a newer skill version has shipped, prompting the agent to offer `npx impeccable skills update`. Best-effort and silent on any failure; asks before updating; suppresses re-prompts for a declined version for a week. Opt out with IMPECCABLE_NO_UPDATE_CHECK=1. - skill/scripts/context.mjs: version read, throttle + anti-nag cache, directive - scripts/build.js + _redirects: /api/version endpoint (from plugin.json version) - skill/SKILL.src.md: document the UPDATE_AVAILABLE boot branch - tests/context.test.mjs: coverage for cached/newer/suppressed/opt-out paths - changelog: v3.5.0 entry - synced harness skill dirs via bun run build Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test: cover the self-update path (network + LLM behavior) context.test.mjs: add a localhost stub-server integration test for the live fetch path (poll /api/version, cache a newer version, stay silent on same-or-older, fail silent + stamp lastCheck when unreachable). Runs against 127.0.0.1 only, never the real site; uses async spawn so the in-process stub isn't deadlocked by spawnSync blocking the event loop. skill-behavior: add scenario 9 asserting the agent surfaces UPDATE_AVAILABLE but never auto-runs `npx impeccable skills update` without asking. New prepareWorkspace `skillVersion` copy-mode (so context.mjs has a SKILL.md to version-check), env threading through runTurn -> execBash, and bash-output capture to prove the agent actually received the directive. Passed on claude-sonnet-4-6, gpt-5.5, and gemini-3.1-flash-lite. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
Cursor
parent
84135db0e6
commit
9ffd3211d5
@@ -7,85 +7,84 @@ Designs and iterates production-grade frontend interfaces. Real working code, co
|
||||
|
||||
## Setup
|
||||
|
||||
Before any design work or file edits:
|
||||
You MUST do these steps before proceeding:
|
||||
|
||||
1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
|
||||
2. Identify the register and load the matching register reference (brand.md or product.md).
|
||||
3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
|
||||
1. Run `node .agents/skills/impeccable/scripts/context.mjs` once per session. If you've already seen its output in this conversation, do not re-run it. The script either prints the project's PRODUCT.md (and DESIGN.md when present) as a markdown block, or tells you it's missing. Follow whatever it prints. **If it reports `NO_PRODUCT_MD`, stop and follow `reference/init.md` before doing anything else.** If the output ends with an `UPDATE_AVAILABLE` directive, follow it (ask the user once about updating, then continue). It never blocks the current task.
|
||||
2. If the user invoked a sub-command (`craft`, `shape`, `audit`, `polish`, ...), you MUST read `reference/<command>.md` next. Non-optional. The reference defines the command's flow; without it you will skip steps the user expects.
|
||||
3. Familiarize yourself with any existing design system, conventions, and components in the code. Read at least one project file (CSS / tokens / theme / a representative component or page). **Required even when you've loaded a sub-command reference in step 2.** Don't reinvent the wheel; use what's there when it works, branch out when the UX wins.
|
||||
4. Read the matching register reference. **This is non-optional; skipping it produces generic output.** If the project is marketing, a landing page, a campaign, long-form content, or a portfolio (design IS the product), read `reference/brand.md`. If it is app UI, admin, a dashboard, or a tool (design SERVES the product), read `reference/product.md`. Pick by first match: (1) task cue ("landing page" vs "dashboard"); (2) surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md.
|
||||
5. **If the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .agents/skills/impeccable/scripts/palette.mjs` to receive a brand seed color and composition guidance. This is the anchor for your primary brand color. Compose the rest of the palette (bg, surface, ink, accent, muted) around it per the script's instructions. Use OKLCH throughout. **Skip this step only if step 3 found committed brand colors in existing tokens; in that case identity-preservation wins.**
|
||||
|
||||
Skipping these produces generic output that ignores the project.
|
||||
## Design guidance
|
||||
|
||||
### 1. Context gathering
|
||||
Produce ready-to-ship, production-grade code, not prototypes or starting points. Take no shortcuts unless the user asks for them (when in doubt, ask). Don't stop until arriving at a complete implementation (beautiful, responsive, fast, precise, bug-free, on brand). You take attention to detail seriously: every page, section or component crafted is battle tested using the tools available to you (browser screenshotting, computer use, etc). GPT is capable of extraordinary work. Don't hold back.
|
||||
|
||||
Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
|
||||
### General rules
|
||||
|
||||
- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
|
||||
- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
|
||||
#### Color
|
||||
|
||||
Load both in one call:
|
||||
- **Verify contrast.** Body text must hit ≥4.5:1 against its background; large text (≥18px or bold ≥14px) needs ≥3:1. Placeholder text needs the same 4.5:1, not the muted-gray default. The most common failure: muted gray body text on a tinted near-white. If the contrast is even close, bump the body color toward the ink end of the ramp; light gray "for elegance" is the single biggest reason AI designs feel hard to read.
|
||||
- Gray text on a colored background looks washed out. Use a darker shade of the background's own hue, or a transparency of the text color.
|
||||
|
||||
```bash
|
||||
node .agents/skills/impeccable/scripts/load-context.mjs
|
||||
```
|
||||
#### Typography
|
||||
|
||||
Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
|
||||
- Cap body line length at 65–75ch.
|
||||
- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
|
||||
- Cap font-family count at 3 (display + body + optional mono). More than 3 reads as indecision, not richness. One well-tuned family with weight contrast usually beats three competing typefaces.
|
||||
- Don't pair fonts that are similar but not identical (two geometric sans-serifs, two humanist sans-serifs). Pair on a contrast axis (serif + sans, geometric + humanist) or use one family in multiple weights.
|
||||
- No all-caps body copy. Reserve uppercase for short labels (≤4 words), section eyebrows (used sparingly per the Absolute bans), and badges. Sentences in ALL CAPS are unreadable at body sizes.
|
||||
- Hero / display heading ceiling: clamp() max ≤ 6rem (~96px). Above that the page is shouting, not designing.
|
||||
- Display heading letter-spacing floor: ≥ -0.04em. Anything tighter and letters touch; cramped, not "designed".
|
||||
- Use `text-wrap: balance` on h1–h3 for even line lengths; `text-wrap: pretty` on long prose to reduce orphans.
|
||||
|
||||
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.
|
||||
Two hard typographic ceilings you currently miss:
|
||||
- Hero clamp() max ≤ 6rem. 8–11rem (128–176px) reads as comically loud, not bold.
|
||||
- Display letter-spacing ≥ -0.04em. Your default of -0.05 to -0.085em on display H1s makes the letters touch and reads as cramped. -0.02 to -0.03em is plenty for tight grotesque display; -0.04em is the floor.
|
||||
|
||||
`$impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
|
||||
#### Layout
|
||||
|
||||
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 the original task was `$impeccable craft`, resume into `$impeccable shape` before any implementation work.
|
||||
- Vary spacing for rhythm.
|
||||
- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
|
||||
- Flexbox for 1D, Grid for 2D. Don't default to Grid when `flex-wrap` would be simpler.
|
||||
- For responsive grids without breakpoints: `repeat(auto-fit, minmax(280px, 1fr))`.
|
||||
- Build a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip). Never arbitrary values like 999 or 9999.
|
||||
|
||||
If DESIGN.md is missing: nudge once per session (*"Run `$impeccable document` for more on-brand output"*), then proceed.
|
||||
#### Motion
|
||||
- Motion should be intentional, and not be an afterthought. consider it as part of the build.
|
||||
- Don't animate CSS layout properties unless truly needed.
|
||||
- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
|
||||
- Use libraries for more advanced motion needs (e.g. motion, gsap, anime.js, lenis etc)
|
||||
- Reduced motion is not optional. Every animation needs a `@media (prefers-reduced-motion: reduce)` alternative: typically a crossfade or instant transition.
|
||||
- Staggering the items within one list is legitimate. The tell is the uniform reflex (one identical entrance applied to every section), not motion itself; each reveal should fit what it reveals. Suppressing the reflex is never a reason to ship a page with no motion at all.
|
||||
- Reveal animations must enhance an already-visible default. Don't gate content visibility on a class-triggered transition; transitions pause on hidden tabs and headless renderers, so the reveal never fires and the section ships blank.
|
||||
- Premium motion materials are not just transform/opacity. Blur, backdrop-filter, clip-path, mask, and shadow/glow are part of the palette when they materially improve the effect and stay smooth.
|
||||
|
||||
### 2. Register
|
||||
#### Interaction
|
||||
|
||||
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).
|
||||
- Dropdowns rendered with `position: absolute` inside an `overflow: hidden` or `overflow: auto` container will be clipped. Use the native `<dialog>` / popover API, `position: fixed`, or a portal to escape the stacking context.
|
||||
|
||||
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.
|
||||
### Copy
|
||||
|
||||
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.
|
||||
- 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 `--`.
|
||||
- **No aphoristic-cadence body copy as a default voice.** Don't fall into the rhythm of "serious statement, then punchy short negation" as the page's recurring voice. If three or more section copy blocks on the page land on a short rebuttal-shaped sentence, rewrite. Specific, not aphoristic.
|
||||
- **No marketing buzzwords.** The streamline / empower / supercharge / leverage / unleash / transform / seamless / world-class / enterprise-grade / next-generation / cutting-edge / game-changer / mission-critical family of phrases. Pick a specific noun and a verb that describes what the product literally does.
|
||||
- Button labels: verb + object. "Save changes" beats "OK"; "Delete project" beats "Yes". The label should say what will happen.
|
||||
- Link text needs standalone meaning. "View pricing plans" beats "Click here"; screen readers announce links out of context.
|
||||
|
||||
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.
|
||||
### New projects only (when no prior work exists)
|
||||
|
||||
## Shared design laws
|
||||
#### Color & Theme
|
||||
|
||||
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. GPT 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).
|
||||
- Use OKLCH.
|
||||
- **The cream / sand / beige body bg is the saturated AI default of 2026.** The whole warm-neutral band (OKLCH L 0.84-0.97, C < 0.06, hue 40-100) reads as cream/sand/paper/parchment regardless of what you call it. Token names like `--paper`, `--cream`, `--sand`, `--bone`, `--flour`, `--linen`, `--parchment`, `--wheat`, `--biscuit`, `--ivory` are tells in themselves. If the brief is "warm, traditional, family-coastal-Italian" or "magazine-warm" or "editorial-restraint", DO NOT translate that into a near-white warm-tinted bg; that's the AI move. Pick: (a) a saturated brand color as the body (terracotta, oxblood, deep ochre, near-black), (b) a true off-white at chroma 0 (or chroma toward the brand's own hue, not toward warmth-by-default), or (c) a darker mid-tone tinted neutral that's clearly the brand's own. "Warmth" in the brand is carried by accent + typography + imagery, not by body bg.
|
||||
- Tinted neutrals: add 0.005–0.015 chroma toward the brand's hue. Don't default-tint toward warm or cool "because the brand feels that way"; that's the cross-project monoculture move.
|
||||
- When picking a 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.
|
||||
- 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
|
||||
|
||||
@@ -96,12 +95,17 @@ Match-and-refuse. If you're about to write any of these, rewrite the element wit
|
||||
- **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.
|
||||
- **Tiny uppercase tracked eyebrow above every section.** The 2023-era kicker (small all-caps text with wide tracking, "ABOUT" "PROCESS" "PRICING" above each heading) is now the saturated AI scaffold; it appears on 55-95% of generations regardless of brief, which is the definition of a tell. One named kicker as a deliberate brand system is voice; an eyebrow on every section is AI grammar. Choose a different cadence.
|
||||
- **Numbered section markers as default scaffolding (01 / 02 / 03).** Putting `01 · About / 02 · Process / 03 · Pricing` above every section is the eyebrow trope one tier deeper: reach for it because "landing pages do this" and you're scaffolding by reflex. Numbers earn their place when the section actually IS a sequence (a real 3-step process, an ordered flow, a typed timeline) and the order carries information the reader needs. One deliberate numbered sequence on one page is voice; numbered eyebrows on every section across the site is AI grammar.
|
||||
- **Text that overflows its container.** Long heading words plus large clamp scales plus narrow grids cause headline overflow on tablet/mobile. Test the heading copy at every breakpoint; if it overflows, reduce the clamp max or rewrite the copy. The viewport is part of the design.
|
||||
|
||||
### Copy
|
||||
**Codex-specific defects** (your most-frequent giveaways; refuse-and-rewrite):
|
||||
|
||||
- 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 `--`.
|
||||
- **`border: 1px solid X` + `box-shadow: 0 Npx Mpx ...` with M ≥ 16px** on the same element. The "ghost-card" pattern: 1px border plus soft wide drop shadow on buttons and cards. Don't pair them. Pick one (a single solid border at the brand color, OR a defined shadow at no more than 8px blur), never both as decoration.
|
||||
- **`border-radius: 32px+` on cards / sections / inputs.** You over-round. Cards top out at 12–16px; full-pill is fine for tags/buttons. Picking 24/28/32/40px on a card is the codex tell; no brand wants "insanely rounded".
|
||||
- **Hand-drawn / sketchy SVG illustrations.** Class names like `loose-sketch`, `*-sketch`, `doodle`, `wavy`; `feTurbulence` / `feDisplacementMap` "paper grain" filters; 5-to-30 path crude scenes meant to depict a tangible subject (an otter, a table-and-fork, an album cover). All of these read as amateurish, not whimsical. If you can't render the scene with real assets, ship no illustration. Don't attempt sketchy SVG as a fallback.
|
||||
- **`repeating-linear-gradient(...)` stripe backgrounds.** Diagonal stripes in `body:before` or section backgrounds are pure codex decoration. Don't.
|
||||
- **"X theater" / "actually X" / "not just X, it's Y" copy.** "Productivity theater", "engagement theater", "growth theater": instant AI slop. Choose a specific noun, not a meta-criticism phrase.
|
||||
|
||||
### The AI slop test
|
||||
|
||||
@@ -109,7 +113,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
|
||||
|
||||
**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
|
||||
|
||||
- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
|
||||
- **First-order:** if someone could guess the theme + palette from the category alone, it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
|
||||
- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
|
||||
|
||||
## Commands
|
||||
@@ -118,7 +122,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
|
||||
|---|---|---|---|
|
||||
| `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) |
|
||||
| `init` | Build | Set up project context: PRODUCT.md, DESIGN.md, live config, next steps | [reference/init.md](reference/init.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) |
|
||||
@@ -146,11 +150,14 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
|
||||
|
||||
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.
|
||||
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
|
||||
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, 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`.
|
||||
|
||||
If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
|
||||
If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `init` as a blocker, finish init, refresh context, then resume the original command and target.
|
||||
|
||||
`teach` is a deprecated alias for `init`: if the user types it, load [reference/init.md](reference/init.md) and proceed as if they ran `init`.
|
||||
|
||||
## Pin / Unpin
|
||||
|
||||
|
||||
@@ -188,3 +188,124 @@ Test thoroughly across contexts:
|
||||
- **Slow connections**: Test on throttled network
|
||||
|
||||
When the adaptation feels native to each context, hand off to `$impeccable polish` for the final pass.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously `responsive-design.md` and live inline now so the adapt flow has its deep responsive reference in one place.
|
||||
|
||||
### Responsive Design
|
||||
|
||||
#### Mobile-First: Write It Right
|
||||
|
||||
Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
|
||||
|
||||
#### Breakpoints: Content-Driven
|
||||
|
||||
Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
|
||||
|
||||
#### Detect Input Method, Not Just Screen Size
|
||||
|
||||
**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
|
||||
|
||||
```css
|
||||
/* Fine pointer (mouse, trackpad) */
|
||||
@media (pointer: fine) {
|
||||
.button { padding: 8px 16px; }
|
||||
}
|
||||
|
||||
/* Coarse pointer (touch, stylus) */
|
||||
@media (pointer: coarse) {
|
||||
.button { padding: 12px 20px; } /* Larger touch target */
|
||||
}
|
||||
|
||||
/* Device supports hover */
|
||||
@media (hover: hover) {
|
||||
.card:hover { transform: translateY(-2px); }
|
||||
}
|
||||
|
||||
/* Device doesn't support hover (touch) */
|
||||
@media (hover: none) {
|
||||
.card { /* No hover state - use active instead */ }
|
||||
}
|
||||
```
|
||||
|
||||
**Critical**: Don't rely on hover for functionality. Touch users can't hover.
|
||||
|
||||
#### Safe Areas: Handle the Notch
|
||||
|
||||
Modern phones have notches, rounded corners, and home indicators. Use `env()`:
|
||||
|
||||
```css
|
||||
body {
|
||||
padding-top: env(safe-area-inset-top);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
padding-left: env(safe-area-inset-left);
|
||||
padding-right: env(safe-area-inset-right);
|
||||
}
|
||||
|
||||
/* With fallback */
|
||||
.footer {
|
||||
padding-bottom: max(1rem, env(safe-area-inset-bottom));
|
||||
}
|
||||
```
|
||||
|
||||
**Enable viewport-fit** in your meta tag:
|
||||
```html
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
```
|
||||
|
||||
#### Responsive Images: Get It Right
|
||||
|
||||
##### srcset with Width Descriptors
|
||||
|
||||
```html
|
||||
<img
|
||||
src="hero-800.jpg"
|
||||
srcset="
|
||||
hero-400.jpg 400w,
|
||||
hero-800.jpg 800w,
|
||||
hero-1200.jpg 1200w
|
||||
"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
alt="Hero image"
|
||||
>
|
||||
```
|
||||
|
||||
**How it works**:
|
||||
- `srcset` lists available images with their actual widths (`w` descriptors)
|
||||
- `sizes` tells the browser how wide the image will display
|
||||
- Browser picks the best file based on viewport width AND device pixel ratio
|
||||
|
||||
##### Picture Element for Art Direction
|
||||
|
||||
When you need different crops/compositions (not just resolutions):
|
||||
|
||||
```html
|
||||
<picture>
|
||||
<source media="(min-width: 768px)" srcset="wide.jpg">
|
||||
<source media="(max-width: 767px)" srcset="tall.jpg">
|
||||
<img src="fallback.jpg" alt="...">
|
||||
</picture>
|
||||
```
|
||||
|
||||
#### Layout Adaptation Patterns
|
||||
|
||||
**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
|
||||
|
||||
#### Testing: Don't Trust DevTools Alone
|
||||
|
||||
DevTools device emulation is useful for layout but misses:
|
||||
|
||||
- Actual touch interactions
|
||||
- Real CPU/memory constraints
|
||||
- Network latency patterns
|
||||
- Font rendering differences
|
||||
- Browser chrome/keyboard appearances
|
||||
|
||||
**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
|
||||
|
||||
@@ -6,7 +6,7 @@ Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut moti
|
||||
|
||||
## 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.
|
||||
Brand: motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions. The saturated AI default is fade-and-rise reveals on every scrolled section; that's a tell, not a choreography. Reserve scroll-triggered motion for moments that earn it.
|
||||
|
||||
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.
|
||||
|
||||
@@ -49,10 +49,11 @@ Create a purposeful animation plan:
|
||||
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
|
||||
- **List rhythm**: Sibling stagger is legitimate for cards-in-a-grid or list-items-appearing. Whole-section fade-on-scroll is not a list and is not legitimate. Cap total stagger time: 10 items at 50ms each = 500ms total. For more items, reduce per-item delay or cap the staggered count.
|
||||
|
||||
Use CSS custom properties for clean stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"`, `style="--i: 1"`, etc. on each item.
|
||||
|
||||
### Micro-interactions
|
||||
- **Button feedback**:
|
||||
@@ -97,11 +98,14 @@ 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)
|
||||
**Duration: the 100/300/500 rule.** Timing matters more than easing for "feels right":
|
||||
|
||||
| Duration | Use Case | Examples |
|
||||
|----------|----------|----------|
|
||||
| **100–150ms** | Instant feedback | Button press, toggle, color change |
|
||||
| **200–300ms** | State changes | Menu open, tooltip, hover state |
|
||||
| **300–500ms** | Layout changes | Accordion, modal, drawer |
|
||||
| **500–800ms** | Entrance animations | Page load, hero reveal |
|
||||
|
||||
**Easing curves (use these, not CSS defaults):**
|
||||
```css
|
||||
@@ -134,13 +138,35 @@ Use appropriate techniques for each animation:
|
||||
- GSAP for complex sequences
|
||||
```
|
||||
|
||||
### Motion Materials
|
||||
|
||||
Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties. Match material to effect:
|
||||
|
||||
- **Transform / opacity**: movement, press feedback, simple reveals, list choreography
|
||||
- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances
|
||||
- **Clip-path / masks**: wipes, reveals, editorial cropping, product-like transitions
|
||||
- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state
|
||||
- **Grid-template-rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly
|
||||
|
||||
The hard rule isn't "transform and opacity only." It's: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify smoothness in-browser on target viewports.
|
||||
|
||||
### Performance
|
||||
- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
|
||||
- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
|
||||
- **will-change**: Add sparingly for known expensive animations
|
||||
- **will-change**: Add sparingly for known expensive animations only (e.g. on `:hover` or an `.animating` class), never preemptively across the whole page
|
||||
- **Scroll triggers**: Use Intersection Observer instead of scroll event listeners; unobserve after the animation fires once
|
||||
- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
|
||||
- **Monitor FPS**: Ensure 60fps on target devices
|
||||
|
||||
### Perceived Performance
|
||||
|
||||
Nobody cares how fast your site *is*, only how fast it feels. The 80ms threshold: anything under ~80ms feels instant because our brains buffer sensory input for that long to synchronize perception. Target this for micro-interactions.
|
||||
|
||||
- **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 (progressive images, streaming HTML, skeleton fade-ins).
|
||||
- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Use for low-stakes actions (likes, follows). 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.
|
||||
- **Caution**: Too-fast responses can decrease perceived value for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
|
||||
|
||||
### Accessibility
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
@@ -50,7 +50,7 @@ Create a strategy to increase impact while maintaining coherence:
|
||||
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)
|
||||
- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and the [Reference Material section of typeset.md](typeset.md#reference-material) 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)
|
||||
@@ -78,10 +78,10 @@ Systematically increase impact across these dimensions:
|
||||
- **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, which cheapen the effect)
|
||||
- **Hero moment**: One signature entrance, once. Not on every visit and not on every section.
|
||||
- **Micro-interactions**: Satisfying hover effects, click feedback, state changes.
|
||||
- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect).
|
||||
- **Bolder ≠ scroll-fade-rise on every section.** That's the saturated AI default, the opposite of bold.
|
||||
|
||||
### Composition Boldness
|
||||
- **Hero moments**: Create clear focal points with dramatic treatment
|
||||
|
||||
@@ -43,17 +43,10 @@ The reflex-reject lists apply to **new design choices**. When the existing brand
|
||||
|
||||
### 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.
|
||||
Distinctive + refined is the goal. The specific shape depends on the brand, not on the brand's category. A category ("restaurant", "dev tool", "magazine", "fintech") is not a recipe; treating it as one is the first-order reflex SKILL.md warns against.
|
||||
|
||||
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.
|
||||
@@ -74,8 +67,7 @@ Brand surfaces have permission for Committed, Full palette, and Drenched strateg
|
||||
|
||||
- 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.
|
||||
- For image-led briefs (hotels, restaurants, magazines, photography), full-bleed hero imagery with overlaid menu and centered headline is a canonical move; let the photograph be the design.
|
||||
- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
|
||||
|
||||
## Imagery
|
||||
@@ -93,8 +85,7 @@ Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landin
|
||||
|
||||
## 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`.
|
||||
- One well-orchestrated page-load beats scattered micro-interactions, when the brand invites it. Some brands skip entrance motion entirely; the restraint is the voice.
|
||||
|
||||
## Brand bans (on top of the shared absolute bans)
|
||||
|
||||
@@ -111,8 +102,7 @@ Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landin
|
||||
|
||||
Brand can afford things product can't. Take them.
|
||||
|
||||
- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
|
||||
- Ambitious first-load motion. Reveals and typographic choreography that earn their place; not fade-on-scroll for every section.
|
||||
- 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.
|
||||
|
||||
@@ -172,3 +172,117 @@ Test that copy improvements work:
|
||||
- **Tone**: Is it appropriate for the situation?
|
||||
|
||||
When the copy reads cleanly, hand off to `$impeccable polish` for the final pass.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously `ux-writing.md` and live inline now so the clarify flow has its deep UX-writing reference in one place.
|
||||
|
||||
### UX Writing
|
||||
|
||||
#### The Button Label Problem
|
||||
|
||||
**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
|
||||
|
||||
| Bad | Good | Why |
|
||||
|-----|------|-----|
|
||||
| OK | Save changes | Says what will happen |
|
||||
| Submit | Create account | Outcome-focused |
|
||||
| Yes | Delete message | Confirms the action |
|
||||
| Cancel | Keep editing | Clarifies what "cancel" means |
|
||||
| Click here | Download PDF | Describes the destination |
|
||||
|
||||
**For destructive actions**, name the destruction:
|
||||
- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
|
||||
- "Delete 5 items" not "Delete selected" (show the count)
|
||||
|
||||
#### Error Messages: The Formula
|
||||
|
||||
Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
|
||||
|
||||
##### Error Message Templates
|
||||
|
||||
| Situation | Template |
|
||||
|-----------|----------|
|
||||
| **Format error** | "[Field] needs to be [format]. Example: [example]" |
|
||||
| **Missing required** | "Please enter [what's missing]" |
|
||||
| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
|
||||
| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
|
||||
| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
|
||||
|
||||
##### Don't Blame the User
|
||||
|
||||
Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
|
||||
|
||||
#### Empty States Are Opportunities
|
||||
|
||||
Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
|
||||
|
||||
#### Voice vs Tone
|
||||
|
||||
**Voice** is your brand's personality, consistent everywhere.
|
||||
**Tone** adapts to the moment.
|
||||
|
||||
| Moment | Tone Shift |
|
||||
|--------|------------|
|
||||
| Success | Celebratory, brief: "Done! Your changes are live." |
|
||||
| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
|
||||
| Loading | Reassuring: "Saving your work..." |
|
||||
| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
|
||||
|
||||
**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
|
||||
|
||||
#### Writing for Accessibility
|
||||
|
||||
**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
|
||||
|
||||
#### Writing for Translation
|
||||
|
||||
##### Plan for Expansion
|
||||
|
||||
German text is ~30% longer than English. Allocate space:
|
||||
|
||||
| Language | Expansion |
|
||||
|----------|-----------|
|
||||
| German | +30% |
|
||||
| French | +20% |
|
||||
| Finnish | +30-40% |
|
||||
| Chinese | -30% (fewer chars, but same width) |
|
||||
|
||||
##### Translation-Friendly Patterns
|
||||
|
||||
Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
|
||||
|
||||
#### Consistency: The Terminology Problem
|
||||
|
||||
Pick one term and stick with it:
|
||||
|
||||
| Inconsistent | Consistent |
|
||||
|--------------|------------|
|
||||
| Delete / Remove / Trash | Delete |
|
||||
| Settings / Preferences / Options | Settings |
|
||||
| Sign in / Log in / Enter | Sign in |
|
||||
| Create / Add / New | Create |
|
||||
|
||||
Build a terminology glossary and enforce it. Variety creates confusion.
|
||||
|
||||
#### Avoid Redundant Copy
|
||||
|
||||
If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
|
||||
|
||||
#### Loading States
|
||||
|
||||
Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
|
||||
|
||||
#### Confirmation Dialogs: Use Sparingly
|
||||
|
||||
Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
|
||||
|
||||
#### Form Instructions
|
||||
|
||||
Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
|
||||
|
||||
@@ -23,8 +23,8 @@ Before generating anything, run a brief direction conversation grounded in the s
|
||||
|
||||
Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
|
||||
|
||||
- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
|
||||
- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
|
||||
- "Brief says 'specimen-page restraint.' Are we closer to a quiet typographic page or a wider editorial spread with hero imagery?"
|
||||
- "Palette strategy from shape was 'Committed.' Which one color carries the surface (a brand-driven pick rather than a default warm-or-cool framing)? (And no, the answer isn't a cream/sand body bg; that's the saturated AI default.)"
|
||||
|
||||
**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
|
||||
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,105 +0,0 @@
|
||||
# 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).
|
||||
@@ -68,10 +68,10 @@ Add color systematically across these dimensions:
|
||||
- **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)`)
|
||||
- **Tinted backgrounds**: If you replace pure gray, tint toward the brand hue, not toward a generic-warm-or-cool pair. The default-warm-tint (`oklch(97% 0.01 60)` and its neighbors) is now the AI cream/sand giveaway. Be specific to the brand or stay neutral.
|
||||
- **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
|
||||
- **Cards & surfaces**: Tint cards or surfaces toward the brand, not "for warmth" by reflex
|
||||
|
||||
**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
|
||||
|
||||
@@ -124,8 +124,6 @@ Ensure color addition improves rather than overwhelms:
|
||||
- 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 depth
|
||||
- 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)
|
||||
@@ -152,3 +150,108 @@ When invoked from live mode, each variant MUST declare a `color-amount` param so
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously `color-and-contrast.md` and live inline now so the colorize flow has its deep color reference in one place.
|
||||
|
||||
### 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 |
|
||||
|
||||
##### Dangerous Color Combinations
|
||||
|
||||
These commonly fail contrast or cause readability issues:
|
||||
|
||||
- Light gray text on white (the #1 accessibility fail)
|
||||
- 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)
|
||||
|
||||
##### 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 | Either pure black or a deep surface that fits the brand (a brand-tinted near-black at oklch 12-18% works too) |
|
||||
|
||||
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. Skipping color blindness testing (8% of men affected).
|
||||
|
||||
@@ -56,15 +56,15 @@ If the harness has native image generation (Codex), a compact shape's "confirm o
|
||||
|
||||
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
|
||||
- [layout.md](layout.md) for layout, spacing, grid, container queries, optical adjustments
|
||||
- [typeset.md](typeset.md) for type hierarchy, font selection, web font loading, OpenType features (Reference Material section)
|
||||
|
||||
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)
|
||||
- Animation or transitions? Consult [animate.md](animate.md) (Reference Material covers motion materials, durations, easing, perceived performance)
|
||||
- Color-heavy or themed? Consult [colorize.md](colorize.md) (Reference Material covers OKLCH, palette structure, dark mode, contrast)
|
||||
- Responsive requirements? Consult [adapt.md](adapt.md) (Reference Material covers breakpoints, input methods, safe areas, responsive images)
|
||||
- Heavy on copy, labels, or errors? Consult [clarify.md](clarify.md) (Reference Material covers button labels, error formula, voice/tone, translation)
|
||||
|
||||
## Step 3: Visual Direction & Assets (Harness-Gated)
|
||||
|
||||
|
||||
@@ -46,9 +46,9 @@ Read relevant source files and visually inspect the live page when browser autom
|
||||
Evaluate:
|
||||
- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
|
||||
- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
|
||||
- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
|
||||
- **Cognitive load**: consult the [Cognitive Load Assessment](#cognitive-load-assessment) section below; report checklist failures and decision points with >4 visible options.
|
||||
- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
|
||||
- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
|
||||
- **Nielsen heuristics**: consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below; score all 10 heuristics 0-4.
|
||||
|
||||
Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
|
||||
|
||||
@@ -94,7 +94,7 @@ Codex final-answer note: `$impeccable critique` produces a report artifact, so t
|
||||
Structure your feedback as a design director would:
|
||||
|
||||
#### Design Health Score
|
||||
> *Consult [heuristics-scoring](heuristics-scoring.md)*
|
||||
> *Consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below.*
|
||||
|
||||
Present the Nielsen's 10 heuristics scores as a table:
|
||||
|
||||
@@ -133,16 +133,16 @@ 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):
|
||||
For each issue, tag with **P0-P3 severity** (see [Issue Severity below](#issue-severity-p0p3) for 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)*
|
||||
> *Consult the [Personas reference](#persona-based-design-testing) below.*
|
||||
|
||||
Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `AGENTS.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
|
||||
Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `AGENTS.md` contains a `## Design Context` section from `impeccable init`, 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:
|
||||
|
||||
@@ -257,3 +257,534 @@ 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.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously separate reference files (`cognitive-load.md`, `heuristics-scoring.md`, `personas.md`). They live inline now so the critique flow has all its deep context in one place.
|
||||
|
||||
### 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.
|
||||
|
||||
---
|
||||
|
||||
### 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.
|
||||
|
||||
---
|
||||
|
||||
### 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 use 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 `AGENTS.md` contains a `## Design Context` section (generated by `impeccable init`), 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.
|
||||
|
||||
@@ -45,7 +45,7 @@ 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.
|
||||
- **Scale keys are open-ended.** Use whatever names the project already uses (`oxblood-deep`, `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)
|
||||
@@ -61,7 +61,7 @@ Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] P
|
||||
|
||||
## When to run
|
||||
|
||||
- The user just ran `$impeccable teach` and needs the visual side documented.
|
||||
- The user just ran `$impeccable init` 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.
|
||||
@@ -71,7 +71,7 @@ If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user
|
||||
## 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.
|
||||
- **Seed mode**: the project is pre-implementation (fresh init, 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.
|
||||
|
||||
@@ -103,7 +103,7 @@ Build a structured draft from the discovered tokens. For each token class:
|
||||
|
||||
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.
|
||||
- **Colors**: one entry per extracted color. Key = descriptive slug (`oxblood-deep`, `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.
|
||||
@@ -253,7 +253,7 @@ Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user onl
|
||||
"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": ["...", "...", "..."] }
|
||||
"cool-paper": { "role": "neutral", "displayName": "Cool Paper", "canonical": "oklch(96% 0.005 230)", "tonalRamp": ["...", "...", "..."] }
|
||||
},
|
||||
"typographyMeta": {
|
||||
"display": { "displayName": "Display", "purpose": "Hero headlines only." }
|
||||
@@ -328,12 +328,13 @@ Pull directly from the DESIGN.md you just wrote:
|
||||
|
||||
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
|
||||
### Step 5: Confirm and refine
|
||||
|
||||
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 `.impeccable/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 .agents/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.
|
||||
|
||||
Your own write is the freshest source; subsequent commands in this session don't need a reload.
|
||||
|
||||
## Seed mode
|
||||
|
||||
@@ -394,11 +395,12 @@ Per-section guidance in seed mode:
|
||||
|
||||
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 `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
|
||||
|
||||
### Step 4: Confirm and refresh session cache
|
||||
### Step 4: Confirm
|
||||
|
||||
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 .agents/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
|
||||
|
||||
Your own write is the freshest source; no reload needed.
|
||||
|
||||
## Style guidelines
|
||||
|
||||
|
||||
@@ -1,234 +0,0 @@
|
||||
# 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.
|
||||
+38
-22
@@ -1,21 +1,16 @@
|
||||
# Teach Flow
|
||||
# Init Flow
|
||||
|
||||
Gathers design context for a project and writes two complementary files at the project root:
|
||||
The setup command for a project. One codebase crawl feeds everything it writes:
|
||||
|
||||
- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
|
||||
- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
|
||||
- **`.impeccable/live/config.json`** (live mode): pre-configured so `$impeccable live` boots straight into variant mode with no first-time detour.
|
||||
|
||||
Every other impeccable command reads these files before doing any work.
|
||||
It closes by pointing the user at the best command to run next. Every other impeccable command reads PRODUCT.md and DESIGN.md before doing any work.
|
||||
|
||||
## Step 1: Load current state
|
||||
|
||||
Run the shared loader first so you know what already exists:
|
||||
|
||||
```bash
|
||||
node .agents/skills/impeccable/scripts/load-context.mjs
|
||||
```
|
||||
|
||||
The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
|
||||
Check what already exists. PRODUCT.md and DESIGN.md live at the project root, or under `.agents/context/` or `docs/` (case-insensitive). Read whichever are present with your native file tool. Also note whether `.impeccable/live/config.json` already exists (Step 6 leaves it untouched if so).
|
||||
|
||||
Decision tree:
|
||||
- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
|
||||
@@ -26,14 +21,14 @@ Decision tree:
|
||||
|
||||
Never silently overwrite an existing file. Always confirm first.
|
||||
|
||||
If teach was invoked as a setup blocker by another command, such as `$impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
|
||||
If init was invoked as a setup blocker by another command, such as `$impeccable craft landing page`, pause that command here. Complete init, then resume the original command. Your own writes are the freshest source; no reload needed. For craft, resume into shape next; init creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
|
||||
|
||||
## Step 2: Explore the codebase
|
||||
|
||||
Before asking questions, thoroughly scan the project to discover what you can:
|
||||
Before asking questions, thoroughly scan the project to discover what you can. This single crawl feeds PRODUCT.md, DESIGN.md, **and** the live-mode framework detection in Step 6, so be thorough once rather than re-scanning later:
|
||||
|
||||
- **README and docs**: Project purpose, target audience, any stated goals
|
||||
- **Package.json / config files**: Tech stack, dependencies, existing design libraries
|
||||
- **Package.json / config files**: Tech stack, dependencies, existing design libraries, **and the framework** (Vite/SPA, Next.js, Nuxt, SvelteKit, Astro, multi-page static) plus the HTML entry the browser actually loads
|
||||
- **Existing components**: Current design patterns, spacing, typography in use
|
||||
- **Brand assets**: Logos, favicons, color values already defined
|
||||
- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
|
||||
@@ -46,7 +41,7 @@ Also form a **register hypothesis** from what you find:
|
||||
|
||||
Register is a hypothesis at this point, not a decision; Step 3 confirms it.
|
||||
|
||||
Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
|
||||
Note what you've learned and what remains unclear. Also note any rough edges worth a follow-up command (thin hierarchy, flat or gray palette, missing error/empty states, dull copy); Step 7 turns these into concrete recommendations without re-analyzing.
|
||||
|
||||
## Step 3: Ask strategic questions (for PRODUCT.md)
|
||||
|
||||
@@ -84,8 +79,7 @@ If the signal is genuinely split (e.g. a product with a big marketing landing),
|
||||
### Brand & Personality
|
||||
- How would you describe the brand personality in 3 words?
|
||||
- Reference sites or apps that capture the right feel? What specifically about them?
|
||||
- For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
|
||||
- For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
|
||||
- Push for specific named references with the *specific* thing about them that fits this brand, not generic "modern" adjectives or category-bucket lanes.
|
||||
- What should this explicitly NOT look like? Any anti-references?
|
||||
|
||||
### Accessibility & Inclusion
|
||||
@@ -141,16 +135,38 @@ If the user agrees, delegate to `$impeccable document` (it auto-detects scan vs
|
||||
|
||||
If the user prefers to skip, mention they can run `$impeccable document` any time later.
|
||||
|
||||
## Step 6: Confirm and wrap up
|
||||
## Step 6: Configure live mode (when code exists)
|
||||
|
||||
Summarize:
|
||||
If the project has code with HTML entries and a dev server (the same "code exists" condition that puts `$impeccable document` in scan mode), pre-configure live mode now. You already identified the framework and the served HTML entry in Step 2, so this is nearly free, and it spares the user the first-time setup detour when they later run `$impeccable live`.
|
||||
|
||||
**Skip this step for empty / pre-implementation projects** (nothing to inject into yet). Tell the user live mode will configure itself the first time they run it once there's code.
|
||||
|
||||
**If `.impeccable/live/config.json` already exists, leave it untouched** and note that live mode is already configured.
|
||||
|
||||
Otherwise:
|
||||
|
||||
1. Write `.impeccable/live/config.json`. Choose `files` (the HTML entries the browser actually loads), `insertBefore`, and `commentSyntax` from the framework table in [live.md](live.md)'s **First-time setup** section, using the framework you found in Step 2. That table is canonical; do not restate it here. For multi-page static sites, prefer a glob (`["public/**/*.html"]`) over a literal list.
|
||||
2. Run `node .agents/skills/impeccable/scripts/detect-csp.mjs`. If it reports a patchable shape (`append-arrays` / `append-string`), use the **consent prompt template** from live.md before editing any source file. On decline, skip the patch. For `middleware` / `meta-tag` shapes, surface the detected files and ask the user to add `http://localhost:8400` to `script-src` and `connect-src` manually. For `null`, there's nothing to do.
|
||||
3. Set `cspChecked: true` in the config once CSP is handled (patched, declined, manual, or not needed). The schema and per-shape patch details live in live.md's First-time setup; follow it rather than duplicating.
|
||||
|
||||
Writing the config file is harmless and needs no consent; only the CSP **source-file patch** requires a yes.
|
||||
|
||||
## Step 7: Recommend starting points, then wrap up
|
||||
|
||||
Summarize tersely:
|
||||
- Register captured (brand / product)
|
||||
- What was written (PRODUCT.md, DESIGN.md, or both)
|
||||
- What was written (PRODUCT.md, DESIGN.md, live config, or a subset)
|
||||
- The 3-5 strategic principles from PRODUCT.md that will guide future work
|
||||
- If DESIGN.md is pending, remind the user how to generate it later
|
||||
- If DESIGN.md or live config is pending, one line on how to set it up later
|
||||
|
||||
**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .agents/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
|
||||
Then recommend the **best commands to run next**, drawn from what your Step 2 crawl already surfaced. Do not run a fresh analysis here; surface observations you already have. Tailor to register and to what you saw, offer the 2-4 most relevant (not a menu dump), and give the exact command to type. Group by intent:
|
||||
|
||||
If teach was invoked as a blocker by another impeccable command (e.g. the user ran `$impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
|
||||
- **Build something new**: `$impeccable craft <feature>` (shape, then build end-to-end) or `$impeccable shape <feature>` (plan first). Lead with this for empty or early-stage projects.
|
||||
- **Improve what's there**: name the specific surface. `$impeccable critique <page>` for a scored UX review; `$impeccable audit <area>` for a11y / perf / responsive checks; `$impeccable polish <component>` for a pre-ship pass. When the crawl flagged a specific weakness, point the matching command at it: thin hierarchy or spacing → `layout`, flat or gray palette → `colorize`, missing error / empty states → `harden` or `onboard`, dull or unclear copy → `clarify`.
|
||||
- **Iterate visually**: `$impeccable live` (configured in Step 6) to pick elements in the browser and generate variants in place.
|
||||
|
||||
The full command menu is one bare `$impeccable` away; keep this list short and pointed.
|
||||
|
||||
If init was invoked as a blocker by another impeccable command (e.g. the user ran `$impeccable polish` with no PRODUCT.md), resume that original task now. Your own writes are the freshest source; no reload needed.
|
||||
|
||||
Optionally STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to AGENTS.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
|
||||
@@ -150,12 +150,6 @@ For browsers without anchor positioning support, `position: fixed` with manual c
|
||||
|
||||
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.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
|
||||
Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids) and fix the structure, not the surface.
|
||||
|
||||
---
|
||||
|
||||
@@ -27,7 +27,6 @@ Analyze what's weak about the current spatial design:
|
||||
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)
|
||||
@@ -43,8 +42,6 @@ Analyze what's weak about the current spatial design:
|
||||
|
||||
## 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 (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
|
||||
@@ -57,6 +54,7 @@ Create a systematic plan:
|
||||
### Establish a Spacing System
|
||||
|
||||
- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
|
||||
- Prefer a 4pt base scale (4, 8, 12, 16, 24, 32, 48, 64, 96px) over 8pt; 8pt is too coarse and you'll frequently need 12px between 8 and 16.
|
||||
- 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
|
||||
@@ -66,15 +64,22 @@ Create a systematic plan:
|
||||
- **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
|
||||
- **Asymmetric compositions**: a deliberate choice when the content invites it (not a default to chase).
|
||||
|
||||
### 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 Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals.
|
||||
- **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.
|
||||
- Use **container queries** for components, viewport queries for page layouts. A card in a narrow sidebar can stay compact while the same card in a main content area expands automatically:
|
||||
|
||||
```css
|
||||
.card-container { container-type: inline-size; }
|
||||
.card { display: grid; gap: var(--space-md); }
|
||||
@container (min-width: 400px) {
|
||||
.card { grid-template-columns: 120px 1fr; }
|
||||
}
|
||||
```
|
||||
|
||||
### Break Card Grid Monotony
|
||||
|
||||
@@ -85,18 +90,36 @@ Create a systematic plan:
|
||||
### 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 polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
|
||||
- The best hierarchy combines 2–3 dimensions at once. A heading that's larger, bolder, AND has more space above it reads as primary without trying:
|
||||
|
||||
| Tool | Strong Hierarchy | Weak Hierarchy |
|
||||
|------|------------------|----------------|
|
||||
| **Size** | 3:1 ratio or more | <2:1 ratio |
|
||||
| **Weight** | Bold vs Regular | Medium vs Regular |
|
||||
| **Color** | High contrast | Similar tones |
|
||||
| **Position** | Top/left (primary) | Bottom/right |
|
||||
| **Space** | Surrounded by white space | Crowded |
|
||||
|
||||
- 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.
|
||||
- Text at `margin-left: 0` looks slightly indented because of letterform whitespace; a negative margin (`-0.05em`) optically aligns it. Geometrically centered glyphs often look off-center (play icons need to shift right, arrows shift toward their direction).
|
||||
- Touch targets must be 44×44px minimum even when the visual element is smaller. Expand the hit area with padding or a pseudo-element:
|
||||
|
||||
```css
|
||||
.icon-button { width: 24px; height: 24px; position: relative; }
|
||||
.icon-button::before {
|
||||
content: ''; position: absolute; inset: -10px;
|
||||
}
|
||||
```
|
||||
|
||||
**NEVER**:
|
||||
- Use arbitrary spacing values outside your scale
|
||||
@@ -104,10 +127,7 @@ Create a systematic plan:
|
||||
- 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
|
||||
|
||||
|
||||
@@ -4,23 +4,28 @@ Interactive live variant mode: select elements in the browser, pick a design act
|
||||
|
||||
A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
|
||||
|
||||
Codex: run live helper commands, the app dev server, and any dependency-installing setup with `sandbox_permissions: "require_escalated"` from the start; live mode depends on localhost and package-manager network access that the sandbox blocks.
|
||||
|
||||
## 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.
|
||||
2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.
|
||||
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=`.
|
||||
|
||||
The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.
|
||||
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 runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
|
||||
6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
|
||||
7. On `exit`: run the cleanup at the bottom.
|
||||
5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.
|
||||
6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
|
||||
7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
|
||||
8. 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.
|
||||
- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).
|
||||
- **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.
|
||||
- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.
|
||||
|
||||
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.
|
||||
|
||||
@@ -30,7 +35,7 @@ Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodi
|
||||
node .agents/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.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. 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.
|
||||
Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath }`. `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.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt.
|
||||
|
||||
`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).
|
||||
|
||||
@@ -38,12 +43,15 @@ If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`,
|
||||
|
||||
## Poll loop
|
||||
|
||||
**Default (portable, all harnesses):**
|
||||
|
||||
```
|
||||
LOOP:
|
||||
node .agents/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
|
||||
Read JSON; dispatch on "type"
|
||||
|
||||
"generate" → Handle Generate; reply done; LOOP
|
||||
"steer" → Handle Steer; reply steer_done; LOOP
|
||||
"accept" → Handle Accept; complete carbonize cleanup if required; LOOP
|
||||
"discard" → Handle Discard; LOOP
|
||||
"prefetch" → Handle Prefetch; LOOP
|
||||
@@ -51,6 +59,16 @@ LOOP:
|
||||
"exit" → break → Cleanup
|
||||
```
|
||||
|
||||
**Stream mode (experimental, not for Cursor):**
|
||||
|
||||
```
|
||||
node .agents/skills/impeccable/scripts/live-poll.mjs --stream # stays running; one JSON line per event
|
||||
Handle event; run --reply in a separate command
|
||||
Repeat until "exit" line → Cleanup
|
||||
```
|
||||
|
||||
Stream keeps one process alive and waits for `--reply` ack before polling again. Useful only when the harness reads incremental stdout reliably and quickly. **Cursor is not one of those:** background pattern notify on a long-running shell was ~5s to pick up events vs sub-second for one-shot exit notify. Default to one-shot everywhere unless you have measured otherwise.
|
||||
|
||||
## Recovery commands
|
||||
|
||||
The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
|
||||
@@ -71,9 +89,32 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues
|
||||
|
||||
## Handle `generate`
|
||||
|
||||
Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
|
||||
**Replace mode** (default): `{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.
|
||||
**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.
|
||||
|
||||
Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.
|
||||
|
||||
### Insert mode branch
|
||||
|
||||
When `event.mode === "insert"`:
|
||||
|
||||
1. Read the screenshot if `event.screenshotPath` is present (annotations only).
|
||||
2. Run the insert helper instead of wrap:
|
||||
|
||||
```bash
|
||||
node .agents/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \
|
||||
--element-id "ANCHOR_ID" --classes "class1,class2" --tag "section" --text "ANCHOR_TEXT"
|
||||
```
|
||||
|
||||
- `--position` ← `event.insert.position` (`before` | `after`)
|
||||
- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)
|
||||
|
||||
The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.
|
||||
|
||||
On accept/discard, `live-accept.mjs` removes the wrapper block; the anchor element is untouched.
|
||||
|
||||
### Replace mode (default)
|
||||
|
||||
### 1. Read the screenshot (if present)
|
||||
|
||||
@@ -424,6 +465,28 @@ A background agent may be used for the rewrite, but the current thread is respon
|
||||
|
||||
Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
|
||||
|
||||
## Handle `steer`
|
||||
|
||||
Event: `{id, message, pageUrl}`. The user typed or spoke into the global bar **Steer** control: page-level direction without picking an element or launching variant generation.
|
||||
|
||||
The mic button uses the browser **Web Speech API** (MVP): click to start, speak, stop automatically when the utterance ends, then the transcript submits as a steer event. Click again while listening to cancel without submitting.
|
||||
|
||||
This is lighter than `generate`: no screenshot, no element context, no variant cycling. Read `message` and inspect the live page or project files as needed, then either make edits or answer in prose.
|
||||
|
||||
When finished:
|
||||
|
||||
```bash
|
||||
node .agents/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID steer_done ["Optional short note for a browser toast"]
|
||||
```
|
||||
|
||||
On failure:
|
||||
|
||||
```bash
|
||||
node .agents/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
|
||||
```
|
||||
|
||||
Then poll again immediately. Do not send a separate "picked up" reply. The Steer bar stays locked until `steer_done` or `error` arrives over SSE.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
# 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.
|
||||
|
||||
## Premium Motion Materials
|
||||
|
||||
Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
|
||||
|
||||
Use the right material for the effect:
|
||||
|
||||
- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
|
||||
- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
|
||||
- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
|
||||
- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
|
||||
- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
|
||||
|
||||
The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
|
||||
|
||||
## 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.
|
||||
@@ -1,179 +0,0 @@
|
||||
# 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 use 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 `AGENTS.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.
|
||||
@@ -91,7 +91,6 @@ Visual polish on a misshapen flow is wasted work. Match the *shape* of the exper
|
||||
- **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
|
||||
|
||||
@@ -10,7 +10,6 @@ Product UI's failure mode isn't flatness, it's strangeness without purpose: over
|
||||
|
||||
## Typography
|
||||
|
||||
- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
|
||||
- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
|
||||
- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
|
||||
- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
|
||||
@@ -26,8 +25,6 @@ Product defaults to Restrained. A single surface can earn Committed (a dashboard
|
||||
|
||||
## Layout
|
||||
|
||||
- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
|
||||
- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
|
||||
- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
|
||||
|
||||
## Components
|
||||
@@ -51,6 +48,7 @@ Every interactive component has: default, hover, focus, active, disabled, loadin
|
||||
- Display fonts in UI labels, buttons, data.
|
||||
- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
|
||||
- Heavy color or full-saturation accents on inactive states.
|
||||
- Modal as first thought. Modals are usually laziness. Exhaust inline / progressive alternatives first.
|
||||
|
||||
## Product permissions
|
||||
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
# Responsive Design
|
||||
|
||||
## Mobile-First: Write It Right
|
||||
|
||||
Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
|
||||
|
||||
## Breakpoints: Content-Driven
|
||||
|
||||
Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
|
||||
|
||||
## Detect Input Method, Not Just Screen Size
|
||||
|
||||
**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
|
||||
|
||||
```css
|
||||
/* Fine pointer (mouse, trackpad) */
|
||||
@media (pointer: fine) {
|
||||
.button { padding: 8px 16px; }
|
||||
}
|
||||
|
||||
/* Coarse pointer (touch, stylus) */
|
||||
@media (pointer: coarse) {
|
||||
.button { padding: 12px 20px; } /* Larger touch target */
|
||||
}
|
||||
|
||||
/* Device supports hover */
|
||||
@media (hover: hover) {
|
||||
.card:hover { transform: translateY(-2px); }
|
||||
}
|
||||
|
||||
/* Device doesn't support hover (touch) */
|
||||
@media (hover: none) {
|
||||
.card { /* No hover state - use active instead */ }
|
||||
}
|
||||
```
|
||||
|
||||
**Critical**: Don't rely on hover for functionality. Touch users can't hover.
|
||||
|
||||
## Safe Areas: Handle the Notch
|
||||
|
||||
Modern phones have notches, rounded corners, and home indicators. Use `env()`:
|
||||
|
||||
```css
|
||||
body {
|
||||
padding-top: env(safe-area-inset-top);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
padding-left: env(safe-area-inset-left);
|
||||
padding-right: env(safe-area-inset-right);
|
||||
}
|
||||
|
||||
/* With fallback */
|
||||
.footer {
|
||||
padding-bottom: max(1rem, env(safe-area-inset-bottom));
|
||||
}
|
||||
```
|
||||
|
||||
**Enable viewport-fit** in your meta tag:
|
||||
```html
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
```
|
||||
|
||||
## Responsive Images: Get It Right
|
||||
|
||||
### srcset with Width Descriptors
|
||||
|
||||
```html
|
||||
<img
|
||||
src="hero-800.jpg"
|
||||
srcset="
|
||||
hero-400.jpg 400w,
|
||||
hero-800.jpg 800w,
|
||||
hero-1200.jpg 1200w
|
||||
"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
alt="Hero image"
|
||||
>
|
||||
```
|
||||
|
||||
**How it works**:
|
||||
- `srcset` lists available images with their actual widths (`w` descriptors)
|
||||
- `sizes` tells the browser how wide the image will display
|
||||
- Browser picks the best file based on viewport width AND device pixel ratio
|
||||
|
||||
### Picture Element for Art Direction
|
||||
|
||||
When you need different crops/compositions (not just resolutions):
|
||||
|
||||
```html
|
||||
<picture>
|
||||
<source media="(min-width: 768px)" srcset="wide.jpg">
|
||||
<source media="(max-width: 767px)" srcset="tall.jpg">
|
||||
<img src="fallback.jpg" alt="...">
|
||||
</picture>
|
||||
```
|
||||
|
||||
## Layout Adaptation Patterns
|
||||
|
||||
**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
|
||||
|
||||
## Testing: Don't Trust DevTools Alone
|
||||
|
||||
DevTools device emulation is useful for layout but misses:
|
||||
|
||||
- Actual touch interactions
|
||||
- Real CPU/memory constraints
|
||||
- Network latency patterns
|
||||
- Font rendering differences
|
||||
- Browser chrome/keyboard appearances
|
||||
|
||||
**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
|
||||
@@ -151,7 +151,7 @@ How users interact with this feature. What happens on click, hover, scroll? What
|
||||
What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
|
||||
|
||||
**9. Recommended References**
|
||||
Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
|
||||
Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., layout.md for complex layouts, animate.md for animated features, interaction-design.md for form-heavy features, typeset.md for typography-driven pages, colorize.md for color-led brands).
|
||||
|
||||
**10. Open Questions**
|
||||
Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
# Spatial Design
|
||||
|
||||
## Spacing Systems
|
||||
|
||||
### Use 4pt Base, Not 8pt
|
||||
|
||||
8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
|
||||
|
||||
### Name Tokens Semantically
|
||||
|
||||
Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
|
||||
|
||||
## Grid Systems
|
||||
|
||||
### The Self-Adjusting Grid
|
||||
|
||||
Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
|
||||
|
||||
## Visual Hierarchy
|
||||
|
||||
### The Squint Test
|
||||
|
||||
Blur your eyes (or screenshot and blur). Can you still identify:
|
||||
- The most important element?
|
||||
- The second most important?
|
||||
- Clear groupings?
|
||||
|
||||
If everything looks the same weight blurred, you have a hierarchy problem.
|
||||
|
||||
### Hierarchy Through Multiple Dimensions
|
||||
|
||||
Don't rely on size alone. Combine:
|
||||
|
||||
| Tool | Strong Hierarchy | Weak Hierarchy |
|
||||
|------|------------------|----------------|
|
||||
| **Size** | 3:1 ratio or more | <2:1 ratio |
|
||||
| **Weight** | Bold vs Regular | Medium vs Regular |
|
||||
| **Color** | High contrast | Similar tones |
|
||||
| **Position** | Top/left (primary) | Bottom/right |
|
||||
| **Space** | Surrounded by white space | Crowded |
|
||||
|
||||
**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
|
||||
|
||||
### Cards Are Not Required
|
||||
|
||||
Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
|
||||
|
||||
## Container Queries
|
||||
|
||||
Viewport queries are for page layouts. **Container queries are for components**:
|
||||
|
||||
```css
|
||||
.card-container {
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: grid;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
|
||||
/* Card layout changes based on its container, not viewport */
|
||||
@container (min-width: 400px) {
|
||||
.card {
|
||||
grid-template-columns: 120px 1fr;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
|
||||
|
||||
## Optical Adjustments
|
||||
|
||||
Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
|
||||
|
||||
### Touch Targets vs Visual Size
|
||||
|
||||
Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
|
||||
|
||||
```css
|
||||
.icon-button {
|
||||
width: 24px; /* Visual size */
|
||||
height: 24px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.icon-button::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: -10px; /* Expand tap target to 44px */
|
||||
}
|
||||
```
|
||||
|
||||
## Depth & Elevation
|
||||
|
||||
Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
|
||||
@@ -4,7 +4,7 @@ Typography carries most of the information on the page. Replace generic defaults
|
||||
|
||||
## Register
|
||||
|
||||
Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
|
||||
Brand: run the font selection procedure in [brand.md](brand.md). Fluid `clamp()` scale, ≥1.25 ratio between steps.
|
||||
|
||||
Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
|
||||
|
||||
@@ -43,7 +43,7 @@ Analyze what's weak or generic about the current type:
|
||||
|
||||
## Plan Typography Improvements
|
||||
|
||||
Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
|
||||
Consult the [Reference Material](#reference-material) section below for detailed guidance on scales, pairing, and loading strategies.
|
||||
|
||||
Create a systematic plan:
|
||||
|
||||
@@ -122,3 +122,158 @@ Each variant MUST declare a `scale` param controlling the hierarchy ratio. Expre
|
||||
Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
|
||||
|
||||
See `reference/live.md` for the full params contract.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously `typography.md` and live inline now so the typeset flow has its deep typography reference in one place. `bolder.md` also references this section.
|
||||
|
||||
### Typography
|
||||
|
||||
#### Classic Typography Principles
|
||||
|
||||
##### Vertical Rhythm
|
||||
|
||||
Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
|
||||
|
||||
##### Modular Scale & Hierarchy
|
||||
|
||||
The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
|
||||
|
||||
**Use fewer sizes with more contrast.** A 5-size system covers most needs:
|
||||
|
||||
| Role | Typical Ratio | Use Case |
|
||||
|------|---------------|----------|
|
||||
| xs | 0.75rem | Captions, legal |
|
||||
| sm | 0.875rem | Secondary UI, metadata |
|
||||
| base | 1rem | Body text |
|
||||
| lg | 1.25-1.5rem | Subheadings, lead text |
|
||||
| xl+ | 2-4rem | Headlines, hero text |
|
||||
|
||||
Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
|
||||
|
||||
##### Readability & Measure
|
||||
|
||||
Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
|
||||
|
||||
**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
|
||||
|
||||
**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
|
||||
|
||||
#### Font Selection & Pairing
|
||||
|
||||
The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
|
||||
|
||||
##### Anti-reflexes worth defending against
|
||||
|
||||
- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
|
||||
- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
|
||||
- A children's product does NOT need a rounded display font. Kids' books use real type.
|
||||
- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
|
||||
|
||||
**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
|
||||
|
||||
##### Pairing Principles
|
||||
|
||||
**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
|
||||
|
||||
When pairing, contrast on multiple axes:
|
||||
- Serif + Sans (structure contrast)
|
||||
- Geometric + Humanist (personality contrast)
|
||||
- Condensed display + Wide body (proportion contrast)
|
||||
|
||||
##### Web Font Loading
|
||||
|
||||
The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
|
||||
|
||||
```css
|
||||
/* 1. Use font-display: swap for visibility */
|
||||
@font-face {
|
||||
font-family: 'CustomFont';
|
||||
src: url('font.woff2') format('woff2');
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* 2. Match fallback metrics to minimize shift */
|
||||
@font-face {
|
||||
font-family: 'CustomFont-Fallback';
|
||||
src: local('Arial');
|
||||
size-adjust: 105%; /* Scale to match x-height */
|
||||
ascent-override: 90%; /* Match ascender height */
|
||||
descent-override: 20%; /* Match descender depth */
|
||||
line-gap-override: 10%; /* Match line spacing */
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
|
||||
}
|
||||
```
|
||||
|
||||
Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
|
||||
|
||||
**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
|
||||
|
||||
**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
|
||||
|
||||
**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
|
||||
|
||||
#### Modern Web Typography
|
||||
|
||||
##### Fluid Type
|
||||
|
||||
Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
|
||||
|
||||
**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
|
||||
|
||||
**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
|
||||
|
||||
**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
|
||||
|
||||
**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
|
||||
|
||||
##### OpenType Features
|
||||
|
||||
Most developers don't know these exist. Use them for polish:
|
||||
|
||||
```css
|
||||
/* Proper fractions */
|
||||
.recipe-amount { font-variant-numeric: diagonal-fractions; }
|
||||
|
||||
/* Small caps for abbreviations */
|
||||
abbr { font-variant-caps: all-small-caps; }
|
||||
|
||||
/* Disable ligatures in code */
|
||||
code { font-variant-ligatures: none; }
|
||||
|
||||
/* Enable kerning (usually on by default, but be explicit) */
|
||||
body { font-kerning: normal; }
|
||||
```
|
||||
|
||||
Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
|
||||
|
||||
##### Rendering polish
|
||||
|
||||
```css
|
||||
/* Variable fonts: pick the right optical-size master automatically */
|
||||
body { font-optical-sizing: auto; }
|
||||
```
|
||||
|
||||
**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
|
||||
|
||||
#### Typography System Architecture
|
||||
|
||||
Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
|
||||
|
||||
#### Accessibility Considerations
|
||||
|
||||
Beyond contrast ratios (which are well-documented), consider:
|
||||
|
||||
- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
|
||||
- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
|
||||
- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
|
||||
- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
# Typography
|
||||
|
||||
## Classic Typography Principles
|
||||
|
||||
### Vertical Rhythm
|
||||
|
||||
Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
|
||||
|
||||
### Modular Scale & Hierarchy
|
||||
|
||||
The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
|
||||
|
||||
**Use fewer sizes with more contrast.** A 5-size system covers most needs:
|
||||
|
||||
| Role | Typical Ratio | Use Case |
|
||||
|------|---------------|----------|
|
||||
| xs | 0.75rem | Captions, legal |
|
||||
| sm | 0.875rem | Secondary UI, metadata |
|
||||
| base | 1rem | Body text |
|
||||
| lg | 1.25-1.5rem | Subheadings, lead text |
|
||||
| xl+ | 2-4rem | Headlines, hero text |
|
||||
|
||||
Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
|
||||
|
||||
### Readability & Measure
|
||||
|
||||
Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
|
||||
|
||||
**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
|
||||
|
||||
**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
|
||||
|
||||
## Font Selection & Pairing
|
||||
|
||||
The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
|
||||
|
||||
### Anti-reflexes worth defending against
|
||||
|
||||
- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
|
||||
- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
|
||||
- A children's product does NOT need a rounded display font. Kids' books use real type.
|
||||
- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
|
||||
|
||||
**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
|
||||
|
||||
### Pairing Principles
|
||||
|
||||
**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
|
||||
|
||||
When pairing, contrast on multiple axes:
|
||||
- Serif + Sans (structure contrast)
|
||||
- Geometric + Humanist (personality contrast)
|
||||
- Condensed display + Wide body (proportion contrast)
|
||||
|
||||
**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
|
||||
|
||||
### Web Font Loading
|
||||
|
||||
The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
|
||||
|
||||
```css
|
||||
/* 1. Use font-display: swap for visibility */
|
||||
@font-face {
|
||||
font-family: 'CustomFont';
|
||||
src: url('font.woff2') format('woff2');
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* 2. Match fallback metrics to minimize shift */
|
||||
@font-face {
|
||||
font-family: 'CustomFont-Fallback';
|
||||
src: local('Arial');
|
||||
size-adjust: 105%; /* Scale to match x-height */
|
||||
ascent-override: 90%; /* Match ascender height */
|
||||
descent-override: 20%; /* Match descender depth */
|
||||
line-gap-override: 10%; /* Match line spacing */
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
|
||||
}
|
||||
```
|
||||
|
||||
Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
|
||||
|
||||
**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
|
||||
|
||||
**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
|
||||
|
||||
**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
|
||||
|
||||
## Modern Web Typography
|
||||
|
||||
### Fluid Type
|
||||
|
||||
Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
|
||||
|
||||
**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
|
||||
|
||||
**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
|
||||
|
||||
**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
|
||||
|
||||
**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
|
||||
|
||||
### OpenType Features
|
||||
|
||||
Most developers don't know these exist. Use them for polish:
|
||||
|
||||
```css
|
||||
/* Tabular numbers for data alignment */
|
||||
.data-table { font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* Proper fractions */
|
||||
.recipe-amount { font-variant-numeric: diagonal-fractions; }
|
||||
|
||||
/* Small caps for abbreviations */
|
||||
abbr { font-variant-caps: all-small-caps; }
|
||||
|
||||
/* Disable ligatures in code */
|
||||
code { font-variant-ligatures: none; }
|
||||
|
||||
/* Enable kerning (usually on by default, but be explicit) */
|
||||
body { font-kerning: normal; }
|
||||
```
|
||||
|
||||
Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
|
||||
|
||||
### Rendering polish
|
||||
|
||||
```css
|
||||
/* Even out heading line lengths (browser picks better break points) */
|
||||
h1, h2, h3 { text-wrap: balance; }
|
||||
|
||||
/* Reduce orphans and ragged endings in long prose */
|
||||
article p { text-wrap: pretty; }
|
||||
|
||||
/* Variable fonts: pick the right optical-size master automatically */
|
||||
body { font-optical-sizing: auto; }
|
||||
```
|
||||
|
||||
**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
|
||||
|
||||
## Typography System Architecture
|
||||
|
||||
Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
|
||||
|
||||
## Accessibility Considerations
|
||||
|
||||
Beyond contrast ratios (which are well-documented), consider:
|
||||
|
||||
- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
|
||||
- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
|
||||
- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
|
||||
- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
|
||||
@@ -1,107 +0,0 @@
|
||||
# UX Writing
|
||||
|
||||
## The Button Label Problem
|
||||
|
||||
**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
|
||||
|
||||
| Bad | Good | Why |
|
||||
|-----|------|-----|
|
||||
| OK | Save changes | Says what will happen |
|
||||
| Submit | Create account | Outcome-focused |
|
||||
| Yes | Delete message | Confirms the action |
|
||||
| Cancel | Keep editing | Clarifies what "cancel" means |
|
||||
| Click here | Download PDF | Describes the destination |
|
||||
|
||||
**For destructive actions**, name the destruction:
|
||||
- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
|
||||
- "Delete 5 items" not "Delete selected" (show the count)
|
||||
|
||||
## Error Messages: The Formula
|
||||
|
||||
Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
|
||||
|
||||
### Error Message Templates
|
||||
|
||||
| Situation | Template |
|
||||
|-----------|----------|
|
||||
| **Format error** | "[Field] needs to be [format]. Example: [example]" |
|
||||
| **Missing required** | "Please enter [what's missing]" |
|
||||
| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
|
||||
| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
|
||||
| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
|
||||
|
||||
### Don't Blame the User
|
||||
|
||||
Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
|
||||
|
||||
## Empty States Are Opportunities
|
||||
|
||||
Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
|
||||
|
||||
## Voice vs Tone
|
||||
|
||||
**Voice** is your brand's personality, consistent everywhere.
|
||||
**Tone** adapts to the moment.
|
||||
|
||||
| Moment | Tone Shift |
|
||||
|--------|------------|
|
||||
| Success | Celebratory, brief: "Done! Your changes are live." |
|
||||
| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
|
||||
| Loading | Reassuring: "Saving your work..." |
|
||||
| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
|
||||
|
||||
**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
|
||||
|
||||
## Writing for Accessibility
|
||||
|
||||
**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
|
||||
|
||||
## Writing for Translation
|
||||
|
||||
### Plan for Expansion
|
||||
|
||||
German text is ~30% longer than English. Allocate space:
|
||||
|
||||
| Language | Expansion |
|
||||
|----------|-----------|
|
||||
| German | +30% |
|
||||
| French | +20% |
|
||||
| Finnish | +30-40% |
|
||||
| Chinese | -30% (fewer chars, but same width) |
|
||||
|
||||
### Translation-Friendly Patterns
|
||||
|
||||
Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
|
||||
|
||||
## Consistency: The Terminology Problem
|
||||
|
||||
Pick one term and stick with it:
|
||||
|
||||
| Inconsistent | Consistent |
|
||||
|--------------|------------|
|
||||
| Delete / Remove / Trash | Delete |
|
||||
| Settings / Preferences / Options | Settings |
|
||||
| Sign in / Log in / Enter | Sign in |
|
||||
| Create / Add / New | Create |
|
||||
|
||||
Build a terminology glossary and enforce it. Variety creates confusion.
|
||||
|
||||
## Avoid Redundant Copy
|
||||
|
||||
If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
|
||||
|
||||
## Loading States
|
||||
|
||||
Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
|
||||
|
||||
## Confirmation Dialogs: Use Sparingly
|
||||
|
||||
Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
|
||||
|
||||
## Form Instructions
|
||||
|
||||
Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
|
||||
@@ -25,7 +25,7 @@ import { join, resolve } from 'node:path';
|
||||
const DEPRECATED_NAMES = [
|
||||
// v2.0 renames
|
||||
'frontend-design', // renamed to impeccable
|
||||
'teach-impeccable', // folded into /impeccable teach
|
||||
'teach-impeccable', // folded into /impeccable init
|
||||
// v2.1 merges
|
||||
'arrange', // renamed to layout
|
||||
'normalize', // merged into polish
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
"description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
|
||||
"argumentHint": "[feature description]"
|
||||
},
|
||||
"teach": {
|
||||
"description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
|
||||
"init": {
|
||||
"description": "Sets up a project for impeccable. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles); offers DESIGN.md (visual: colors, typography, components) when code exists; pre-configures live mode; then recommends the best commands to run next. Every other command reads these files before doing work. Use once per project.",
|
||||
"argumentHint": ""
|
||||
},
|
||||
"document": {
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Context loader: prints PRODUCT.md (and DESIGN.md if present) as one
|
||||
* markdown block on stdout, or exits with empty stdout when no PRODUCT.md
|
||||
* is found anywhere. The skill keys off "empty stdout" to branch into the
|
||||
* init flow.
|
||||
*
|
||||
* Path resolution (first match wins):
|
||||
* 1. cwd, if PRODUCT.md or DESIGN.md is there
|
||||
* 2. .agents/context/ then docs/
|
||||
* 3. $IMPECCABLE_CONTEXT_DIR (absolute or cwd-relative) — power-user
|
||||
* escape hatch, only consulted when defaults are empty
|
||||
* 4. cwd as a "nothing found" default
|
||||
*
|
||||
* `resolveContextDir()` and `loadContext()` are also exported for the
|
||||
* server-side scripts (live.mjs, live-server.mjs) that need the structured
|
||||
* shape rather than the markdown block.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
|
||||
// ─── Update check ──────────────────────────────────────────────────────────
|
||||
// Piggyback a lightweight skill-version check on the once-per-session boot.
|
||||
// When a newer skill ships, append an UPDATE_AVAILABLE directive so the agent
|
||||
// can offer `npx impeccable skills update`. Everything here is best-effort and
|
||||
// silent on failure: a network problem, sandbox, or missing cache must never
|
||||
// block context output or print an error.
|
||||
|
||||
const UPDATE_HOST = (process.env.IMPECCABLE_UPDATE_HOST || 'https://impeccable.style').replace(/\/$/, '');
|
||||
const UPDATE_CACHE_PATH =
|
||||
process.env.IMPECCABLE_UPDATE_CACHE || path.join(os.homedir(), '.impeccable', 'update-check.json');
|
||||
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // throttle the network poll to once a day
|
||||
const RENOTIFY_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; // don't re-surface the same version for a week
|
||||
const FETCH_TIMEOUT_MS = 1200;
|
||||
|
||||
export function resolveContextDir(cwd = process.cwd()) {
|
||||
if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
|
||||
return cwd;
|
||||
}
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const candidate = path.resolve(cwd, rel);
|
||||
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
|
||||
if (envDir && envDir.trim()) {
|
||||
const trimmed = envDir.trim();
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
return cwd;
|
||||
}
|
||||
|
||||
export function loadContext(cwd = process.cwd()) {
|
||||
const contextDir = resolveContextDir(cwd);
|
||||
const productPath = firstExisting(contextDir, PRODUCT_NAMES);
|
||||
const designPath = firstExisting(contextDir, DESIGN_NAMES);
|
||||
const product = productPath ? safeRead(productPath) : null;
|
||||
const design = designPath ? safeRead(designPath) : null;
|
||||
return {
|
||||
hasProduct: !!product,
|
||||
product,
|
||||
productPath: productPath ? path.relative(cwd, productPath) : null,
|
||||
hasDesign: !!design,
|
||||
design,
|
||||
designPath: designPath ? path.relative(cwd, designPath) : null,
|
||||
contextDir,
|
||||
};
|
||||
}
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function safeRead(p) {
|
||||
try {
|
||||
return fs.readFileSync(p, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull the register (`brand` or `product`) out of PRODUCT.md by looking
|
||||
* for a `## Register` section and reading the first non-empty line that
|
||||
* follows it. Returns null when the file is legacy / register-less.
|
||||
*/
|
||||
function extractRegister(product) {
|
||||
if (!product) return null;
|
||||
const lines = product.split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (/^##\s+Register\b/i.test(lines[i].trim())) {
|
||||
for (let j = i + 1; j < lines.length; j++) {
|
||||
const next = lines[j].trim();
|
||||
if (!next) continue;
|
||||
const word = next.toLowerCase();
|
||||
if (word === 'brand' || word === 'product') return word;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the installed skill's own version from the sibling SKILL.md frontmatter
|
||||
* (this file lives at `<skill>/scripts/context.mjs`). Returns null when the
|
||||
* frontmatter is missing or unreadable.
|
||||
*/
|
||||
function readLocalSkillVersion() {
|
||||
try {
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const skillMd = path.join(here, '..', 'SKILL.md');
|
||||
const content = fs.readFileSync(skillMd, 'utf-8');
|
||||
const match = content.match(/^version:\s*(.+)$/m);
|
||||
return match ? match[1].trim().replace(/^["']|["']$/g, '') : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readUpdateCache() {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(UPDATE_CACHE_PATH, 'utf-8'));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeUpdateCache(cache) {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(UPDATE_CACHE_PATH), { recursive: true });
|
||||
fs.writeFileSync(UPDATE_CACHE_PATH, JSON.stringify(cache));
|
||||
} catch {
|
||||
// Best-effort: a read-only home dir just means we re-poll next session.
|
||||
}
|
||||
}
|
||||
|
||||
/** Compare dotted numeric versions. Returns >0 when a is newer than b. */
|
||||
function compareSemver(a, b) {
|
||||
const pa = String(a).split('.').map(n => parseInt(n, 10) || 0);
|
||||
const pb = String(b).split('.').map(n => parseInt(n, 10) || 0);
|
||||
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
||||
const diff = (pa[i] || 0) - (pb[i] || 0);
|
||||
if (diff !== 0) return diff;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function fetchLatestSkillVersion() {
|
||||
try {
|
||||
const res = await fetch(`${UPDATE_HOST}/api/version`, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
return typeof data?.skills === 'string' ? data.skills : null;
|
||||
} catch {
|
||||
return null; // offline, sandboxed, timed out, or bad JSON: all non-fatal
|
||||
}
|
||||
}
|
||||
|
||||
function buildUpdateDirective(localVersion, latestVersion) {
|
||||
return (
|
||||
`UPDATE_AVAILABLE: A newer Impeccable skill is available ` +
|
||||
`(installed v${localVersion}, latest v${latestVersion}). ` +
|
||||
`Before continuing, ask the user once: "A newer Impeccable (v${latestVersion}) is available. ` +
|
||||
`Update now? It runs \`npx impeccable skills update\`." ` +
|
||||
`If they agree, run \`npx impeccable skills update\` (the update applies to the next session, not this one). ` +
|
||||
`Either way, continue the current task without waiting, and do not raise this again.`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort update directive for the boot output. Returns a string to append
|
||||
* or null. Polls the version endpoint at most once per day (cached globally in
|
||||
* the user's home dir) and re-surfaces a given version at most once per week so
|
||||
* the agent never nags. Opt out entirely with IMPECCABLE_NO_UPDATE_CHECK=1.
|
||||
*/
|
||||
async function computeUpdateDirective(now = Date.now()) {
|
||||
try {
|
||||
if (process.env.IMPECCABLE_NO_UPDATE_CHECK) return null;
|
||||
const localVersion = readLocalSkillVersion();
|
||||
if (!localVersion) return null;
|
||||
|
||||
const cache = readUpdateCache();
|
||||
|
||||
// Poll the network only when the throttle window has elapsed. Stamp
|
||||
// lastCheck even on failure so an offline machine doesn't poll every boot.
|
||||
if (!cache.lastCheck || now - cache.lastCheck > CHECK_INTERVAL_MS) {
|
||||
const latest = await fetchLatestSkillVersion();
|
||||
cache.lastCheck = now;
|
||||
if (latest) cache.latestVersion = latest;
|
||||
writeUpdateCache(cache);
|
||||
}
|
||||
|
||||
const latest = cache.latestVersion;
|
||||
if (!latest || compareSemver(latest, localVersion) <= 0) return null;
|
||||
|
||||
// Anti-nag: surface a given version at most once per RENOTIFY window.
|
||||
if (cache.notifiedVersion === latest && cache.notifiedAt && now - cache.notifiedAt < RENOTIFY_INTERVAL_MS) {
|
||||
return null;
|
||||
}
|
||||
cache.notifiedVersion = latest;
|
||||
cache.notifiedAt = now;
|
||||
writeUpdateCache(cache);
|
||||
|
||||
return buildUpdateDirective(localVersion, latest);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function cli() {
|
||||
const ctx = loadContext(process.cwd());
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
// Direct stdout message instead of relying on empty output as a signal
|
||||
// — cheap models miss the empty case more often than the explicit one.
|
||||
const parts = [
|
||||
'NO_PRODUCT_MD: This project has no PRODUCT.md yet. ' +
|
||||
'Stop the current task, load reference/init.md, and follow its ' +
|
||||
'instructions to write PRODUCT.md before resuming.',
|
||||
];
|
||||
if (updateDirective) parts.push(updateDirective);
|
||||
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const parts = [`# PRODUCT.md\n\n${ctx.product.trim()}`];
|
||||
if (ctx.hasDesign) {
|
||||
parts.push(`# DESIGN.md\n\n${ctx.design.trim()}`);
|
||||
}
|
||||
const register = extractRegister(ctx.product);
|
||||
const next = register
|
||||
? `NEXT STEP: This project's register is \`${register}\`. You MUST now read \`reference/${register}.md\` before producing any design output.`
|
||||
: `NEXT STEP: You MUST now read the matching register reference (\`reference/brand.md\` or \`reference/product.md\`) before producing any design output. Pick based on PRODUCT.md above.`;
|
||||
parts.push(next);
|
||||
if (updateDirective) parts.push(updateDirective);
|
||||
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
|
||||
}
|
||||
|
||||
const _running = process.argv[1];
|
||||
if (_running?.endsWith('context.mjs') || _running?.endsWith('context.mjs/')) {
|
||||
cli();
|
||||
}
|
||||
@@ -63,7 +63,7 @@ function parseYamlSubset(yaml) {
|
||||
}
|
||||
|
||||
const key = content.slice(0, colonIdx).trim();
|
||||
const rest = content.slice(colonIdx + 1).trim();
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
@@ -93,6 +93,21 @@ function findTopLevelColon(s) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
|
||||
@@ -9,8 +9,21 @@ if (IS_BROWSER) {
|
||||
const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
|
||||
|| document.documentElement.dataset.impeccableExtension === 'true';
|
||||
|
||||
const BRAND_COLOR = 'oklch(55% 0.25 350)';
|
||||
const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
|
||||
// Kinpaku gold — pinned to the site's brand token (see
|
||||
// site/styles/kinpaku-tokens.css --ks-kinpaku). Keep this in sync with
|
||||
// the picker's C.brand in skill/scripts/live-browser.js and the kit's
|
||||
// picker section in site/styles/kinpaku-kit.css.
|
||||
//
|
||||
// One color across both light and dark host pages. The outline is a
|
||||
// 2px gesture pointing at an element + a labeled tag — it's a marker,
|
||||
// not body text, so it doesn't need WCAG AA against the page. The
|
||||
// label text inside the gold tag is dark (LABEL_INK) which has ~16:1
|
||||
// against the leaf gold, so reading the rule name is solid in both
|
||||
// modes. Hover deepens the gold (preserves chroma — never drops it,
|
||||
// dropping chroma washes the gold into a sand/olive tone).
|
||||
const BRAND_COLOR = 'oklch(84% 0.19 80.46)';
|
||||
const BRAND_COLOR_HOVER = 'oklch(74% 0.18 80)';
|
||||
const LABEL_INK = 'oklch(4% 0.004 95)';
|
||||
const LABEL_BG = BRAND_COLOR;
|
||||
const OUTLINE_COLOR = BRAND_COLOR;
|
||||
|
||||
@@ -278,7 +291,7 @@ if (IS_BROWSER) {
|
||||
display: 'flex', alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
|
||||
color: 'white', lineHeight: '14px',
|
||||
color: LABEL_INK, lineHeight: '14px',
|
||||
background: LABEL_BG,
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
borderRadius: '4px 4px 0 0',
|
||||
@@ -398,7 +411,7 @@ if (IS_BROWSER) {
|
||||
banner.className = 'impeccable-overlay impeccable-banner';
|
||||
Object.assign(banner.style, {
|
||||
position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
|
||||
background: LABEL_BG, color: 'white',
|
||||
background: LABEL_BG, color: LABEL_INK,
|
||||
fontFamily: 'system-ui, sans-serif', fontSize: '13px',
|
||||
display: 'flex', alignItems: 'center', pointerEvents: 'auto',
|
||||
height: '36px', overflow: 'hidden', maxWidth: '100vw',
|
||||
@@ -1223,12 +1236,12 @@ if (IS_BROWSER) {
|
||||
}
|
||||
console.group(
|
||||
`%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
|
||||
'color: oklch(60% 0.25 350); font-weight: bold'
|
||||
'color: oklch(84% 0.19 80.46); font-weight: bold'
|
||||
);
|
||||
for (const { el, findings } of allFindings) {
|
||||
for (const f of findings) {
|
||||
console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
|
||||
'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
|
||||
'color: oklch(84% 0.19 80.46); font-weight: bold', 'color: inherit', el);
|
||||
}
|
||||
}
|
||||
console.groupEnd();
|
||||
@@ -1249,6 +1262,10 @@ if (IS_BROWSER) {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
// output concern, applied in the Node engines' detect* return paths.
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
// Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
|
||||
@@ -1270,11 +1287,23 @@ if (IS_BROWSER) {
|
||||
...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementOversizedH1DOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
|
||||
// Hero eyebrow: the offending element is the eyebrow above the heading,
|
||||
// not the heading itself — highlight the previous sibling instead.
|
||||
const eyebrowFindings = checkElementHeroEyebrowDOM(el)
|
||||
.map(f => ({ type: f.id, detail: f.snippet }))
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (eyebrowFindings.length > 0 && el.previousElementSibling) {
|
||||
addBrowserFindings(groupMap, el.previousElementSibling, eyebrowFindings);
|
||||
}
|
||||
}
|
||||
|
||||
const pageLevelFindings = [];
|
||||
@@ -1306,6 +1335,14 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, qualityFindings);
|
||||
}
|
||||
|
||||
const creamFindings = checkCreamPalette(document)
|
||||
.map(f => ({ type: f.id, detail: f.snippet }))
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (creamFindings.length > 0) {
|
||||
pageLevelFindings.push(...creamFindings);
|
||||
addBrowserFindings(groupMap, document.body, creamFindings);
|
||||
}
|
||||
|
||||
// Regex-on-HTML checks (shared with Node)
|
||||
// Clone the document and strip impeccable-live overlay nodes before the
|
||||
// regex scan, so the inspector's own inline styles (transitions on top/
|
||||
|
||||
@@ -41,7 +41,7 @@ function formatFindings(findings, jsonMode) {
|
||||
// Stdin handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function handleStdin() {
|
||||
async function handleStdin(options = {}) {
|
||||
const chunks = [];
|
||||
for await (const chunk of process.stdin) chunks.push(chunk);
|
||||
const input = Buffer.concat(chunks).toString('utf-8');
|
||||
@@ -50,10 +50,10 @@ async function handleStdin() {
|
||||
const fp = parsed?.tool_input?.file_path;
|
||||
if (fp && fs.existsSync(fp)) {
|
||||
return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
|
||||
? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
|
||||
? detectHtml(fp, options) : detectText(fs.readFileSync(fp, 'utf-8'), fp, options);
|
||||
}
|
||||
} catch { /* not JSON */ }
|
||||
return detectText(input, '<stdin>');
|
||||
return detectText(input, '<stdin>', options);
|
||||
}
|
||||
|
||||
|
||||
@@ -81,6 +81,8 @@ Scan files or URLs for UI anti-patterns and design quality issues.
|
||||
Options:
|
||||
--fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--help Show this help message
|
||||
|
||||
Detection modes:
|
||||
@@ -106,6 +108,10 @@ async function detectCli() {
|
||||
const jsonMode = args.includes('--json');
|
||||
const helpMode = args.includes('--help');
|
||||
const fastMode = args.includes('--fast');
|
||||
const providers = [];
|
||||
if (args.includes('--gpt')) providers.push('gpt');
|
||||
if (args.includes('--gemini')) providers.push('gemini');
|
||||
const scanOptions = { providers };
|
||||
const targets = args.filter(a => !a.startsWith('--'));
|
||||
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
@@ -113,7 +119,7 @@ async function detectCli() {
|
||||
let allFindings = [];
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin();
|
||||
allFindings = await handleStdin(scanOptions);
|
||||
} else {
|
||||
const paths = targets.length > 0 ? targets : [process.cwd()];
|
||||
const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
|
||||
@@ -124,8 +130,8 @@ async function detectCli() {
|
||||
if (/^https?:\/\//i.test(target)) {
|
||||
try {
|
||||
const scanner = browserDetector
|
||||
? (url) => browserDetector.detectUrl(url)
|
||||
: (url) => detectUrl(url);
|
||||
? (url) => browserDetector.detectUrl(url, scanOptions)
|
||||
: (url) => detectUrl(url, scanOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
continue;
|
||||
@@ -192,9 +198,9 @@ async function detectCli() {
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
let fileFindings;
|
||||
if (!fastMode && HTML_EXTENSIONS.has(ext)) {
|
||||
fileFindings = await detectHtml(file);
|
||||
fileFindings = await detectHtml(file, scanOptions);
|
||||
} else {
|
||||
fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
|
||||
fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file, scanOptions);
|
||||
}
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
@@ -209,9 +215,9 @@ async function detectCli() {
|
||||
} else if (stat.isFile()) {
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (!fastMode && HTML_EXTENSIONS.has(ext)) {
|
||||
allFindings.push(...await detectHtml(resolved));
|
||||
allFindings.push(...await detectHtml(resolved, scanOptions));
|
||||
} else {
|
||||
allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
|
||||
allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved, scanOptions));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ const OVERUSED_FONTS = new Set([
|
||||
// Older monoculture (still ubiquitous):
|
||||
'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
|
||||
// Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
|
||||
'fraunces', 'instrument sans',
|
||||
'fraunces', 'instrument sans', 'instrument serif',
|
||||
'geist', 'geist sans', 'geist mono',
|
||||
'mona sans',
|
||||
'plus jakarta sans', 'space grotesk', 'recoleta',
|
||||
@@ -165,6 +165,15 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'AI color palette',
|
||||
},
|
||||
{
|
||||
id: 'cream-palette',
|
||||
category: 'slop',
|
||||
name: 'Cream / beige palette',
|
||||
description:
|
||||
'A warm cream or beige page background has become the default "tasteful" AI surface, reached for by reflex. Choose a background that comes from a deliberate palette, not the safe warm off-white.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'cream and beige as the default surface',
|
||||
},
|
||||
{
|
||||
id: 'nested-cards',
|
||||
category: 'slop',
|
||||
@@ -183,15 +192,6 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'same spacing everywhere',
|
||||
},
|
||||
{
|
||||
id: 'everything-centered',
|
||||
category: 'slop',
|
||||
name: 'Everything centered',
|
||||
description:
|
||||
'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'Center everything',
|
||||
},
|
||||
{
|
||||
id: 'bounce-easing',
|
||||
category: 'slop',
|
||||
@@ -247,17 +247,72 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
|
||||
},
|
||||
{
|
||||
id: 'numbered-section-markers',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
name: 'Numbered section markers (01 / 02 / 03)',
|
||||
description:
|
||||
'Numbered display markers as section labels (01, 02, 03) are the AI editorial scaffold one tier deeper than tracked eyebrow chips. If you find yourself reaching for them, choose a different section cadence.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'numbered section markers',
|
||||
},
|
||||
{
|
||||
id: 'em-dash-overuse',
|
||||
category: 'slop',
|
||||
name: 'Em-dash overuse',
|
||||
description:
|
||||
'More than two em-dashes (— or --) in body copy is an AI cadence tell. Use commas, colons, periods, or parentheses instead.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'no em dashes',
|
||||
},
|
||||
{
|
||||
id: 'marketing-buzzword',
|
||||
category: 'slop',
|
||||
name: 'Marketing buzzword',
|
||||
description:
|
||||
'Generic SaaS phrases (streamline / empower / supercharge / world-class / enterprise-grade / next-generation / cutting-edge / etc) are instant AI tells. Pick a specific verb and noun that says what the product literally does.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'marketing buzzwords',
|
||||
},
|
||||
{
|
||||
id: 'aphoristic-cadence',
|
||||
category: 'slop',
|
||||
name: 'Aphoristic-cadence copy',
|
||||
description:
|
||||
'Three or more sections landing on a short rebuttal sentence ("X. No Y." / "X. Just Y.") or a manufactured-contrast aphorism ("Not a feature. A platform.") reads as AI cadence, not voice. Once is fine; the pattern is the tell.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'aphoristic cadence',
|
||||
},
|
||||
{
|
||||
id: 'oversized-h1',
|
||||
category: 'slop',
|
||||
name: 'Oversized hero headline',
|
||||
description:
|
||||
'A full-sentence headline set at display size ends up dominating the viewport, leaving no room for anything else above the fold. A punchy one- or two-word headline at that size is fine — the problem is a long headline blown up too large. Set long headlines smaller, or tighten the copy.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'long headline set at display size',
|
||||
},
|
||||
{
|
||||
id: 'extreme-negative-tracking',
|
||||
category: 'slop',
|
||||
name: 'Crushed letter spacing',
|
||||
description:
|
||||
'Letter-spacing pulled tighter than the point where characters keep their own shapes costs legibility. Tighten display type optically, not destructively.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'letter spacing crushed past legibility',
|
||||
},
|
||||
{
|
||||
id: 'broken-image',
|
||||
category: 'quality',
|
||||
name: 'Broken or placeholder image',
|
||||
description:
|
||||
'<img> tags with empty src, missing src, or placeholder values ship as broken-image boxes. Use real images, generated assets, or remove the tag.',
|
||||
skillSection: 'Imagery',
|
||||
skillGuideline: 'broken image references',
|
||||
},
|
||||
|
||||
// ── Quality: general design and accessibility issues ──
|
||||
{
|
||||
id: 'pure-black-white',
|
||||
category: 'quality',
|
||||
name: 'Pure black background',
|
||||
description:
|
||||
'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'pure black (#000)',
|
||||
},
|
||||
{
|
||||
id: 'gray-on-color',
|
||||
category: 'quality',
|
||||
@@ -297,7 +352,9 @@ const ANTIPATTERNS = [
|
||||
category: 'quality',
|
||||
name: 'Cramped padding',
|
||||
description:
|
||||
'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
|
||||
'Text is too close to the edge of its container. Two shapes: (1) an element with its own text where the padding is too low for the font size, and (2) a wrapper with text-bearing children and near-zero padding against a visible boundary (border, outline, or non-transparent background) — children land flush against the boundary line. Add at least 8px (ideally 12–16px) of padding inside bordered, outlined, or colored containers.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'inside bordered or colored containers',
|
||||
},
|
||||
{
|
||||
id: 'body-text-viewport-edge',
|
||||
@@ -350,6 +407,70 @@ const ANTIPATTERNS = [
|
||||
description:
|
||||
'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
|
||||
},
|
||||
{
|
||||
id: 'text-overflow',
|
||||
category: 'quality',
|
||||
name: 'Content overflowing its container',
|
||||
description:
|
||||
'Content renders wider than its container, spilling out or forcing a horizontal scrollbar. Let text wrap, constrain widths, or give the region a deliberate scroll affordance.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'content wider than its container',
|
||||
},
|
||||
{
|
||||
id: 'clipped-overflow-container',
|
||||
category: 'quality',
|
||||
name: 'Positioned child clipped by overflow container',
|
||||
description:
|
||||
'A clipping container (overflow hidden or clip) wrapping an absolutely-positioned child cuts off tooltips, menus, and popovers that need to escape. Let the overflow be visible, or move the positioned layer out of the clip.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
id: 'gpt-thin-border-wide-shadow',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Hairline border with wide shadow',
|
||||
description:
|
||||
'A hairline border paired with a wide, diffuse shadow is a recurring generated-UI signature. Commit to one — a defined edge or a soft elevation — rather than both at once.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'hairline border plus wide diffuse shadow',
|
||||
},
|
||||
{
|
||||
id: 'repeating-stripes-gradient',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Repeating-gradient stripes',
|
||||
description:
|
||||
'Repeating-gradient stripes used as surface decoration are a recurring generated-UI signature. Reach for a deliberate texture or leave the surface plain.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'repeating-gradient decorative stripes',
|
||||
},
|
||||
{
|
||||
id: 'theater-slop-phrase',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Theater framing copy',
|
||||
description:
|
||||
'Dismissing something as "theater" is a recurring generated-copy tic. Say plainly what the thing does or does not do.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'theater framing copy',
|
||||
},
|
||||
{
|
||||
id: 'image-hover-transform',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gemini',
|
||||
name: 'Image hover transform',
|
||||
description:
|
||||
'Scaling or rotating an image on hover is a recurring generated-UI signature. Let imagery sit still, or use a subtler, purposeful interaction.',
|
||||
skillSection: 'Motion',
|
||||
skillGuideline: 'image scale or rotate on hover',
|
||||
},
|
||||
];
|
||||
|
||||
// --- cli/engine/shared/color.mjs ---
|
||||
@@ -527,11 +648,6 @@ function checkColors(opts) {
|
||||
}
|
||||
const findings = [];
|
||||
|
||||
// Pure black background (only solid or near-solid, not semi-transparent overlays)
|
||||
if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
|
||||
findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
|
||||
}
|
||||
|
||||
if (hasDirectText && textColor && !isEmojiOnly) {
|
||||
// Run background-dependent checks against either a solid bg or, if the
|
||||
// ancestor is a gradient, against every gradient stop (use the worst case).
|
||||
@@ -587,9 +703,6 @@ function checkColors(opts) {
|
||||
// Tailwind class checks
|
||||
if (classList) {
|
||||
const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
|
||||
if (/\bbg-black\b(?!\/)/.test(classStr)) {
|
||||
findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
|
||||
}
|
||||
|
||||
const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
|
||||
const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
|
||||
@@ -905,12 +1018,6 @@ function checkHtmlPatterns(html) {
|
||||
|
||||
// --- Color ---
|
||||
|
||||
// Pure black background
|
||||
const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
|
||||
if (pureBlackBgRe.test(html)) {
|
||||
findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
|
||||
}
|
||||
|
||||
// AI color palette: purple/violet
|
||||
const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
|
||||
if (purpleHexRe.test(html)) {
|
||||
@@ -1027,6 +1134,39 @@ function checkHtmlPatterns(html) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): repeating-gradient stripes (GPT) ---
|
||||
if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(html)) {
|
||||
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
|
||||
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
|
||||
// runs in the bundled browser path too, not just the CLI/static path.
|
||||
{
|
||||
const bodyText = html
|
||||
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<[^>]+>/g, ' ');
|
||||
const tm = /\b(\w+)\s+theater\b/i.exec(bodyText);
|
||||
if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` });
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): image hover transform (Gemini) ---
|
||||
// A CSS `img...:hover { transform: ... }` rule, or a Tailwind hover:scale /
|
||||
// hover:rotate / hover:translate utility on an <img>. Each distinct
|
||||
// mechanism is its own finding.
|
||||
const imgHoverCss = /\bimg\b[^,{}]*:hover\b[^{}]*\{[^}]*\btransform\s*:\s*(?:scale|rotate|translate|matrix|skew)/i;
|
||||
if (imgHoverCss.test(html)) {
|
||||
findings.push({ id: 'image-hover-transform', snippet: 'img:hover { transform } rule' });
|
||||
}
|
||||
const imgTagRe = /<img\b[^>]*\bclass\s*=\s*"([^"]*)"/gi;
|
||||
let im;
|
||||
while ((im = imgTagRe.exec(html)) !== null) {
|
||||
if (/\bhover:(?:scale|rotate|translate|skew)-/.test(im[1])) {
|
||||
findings.push({ id: 'image-hover-transform', snippet: 'Tailwind hover transform on <img>' });
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
@@ -1673,7 +1813,7 @@ function resolveLengthPx(value, fontSizePx) {
|
||||
// Both adapters resolve font-size, line-height and letter-spacing to pixels
|
||||
// before calling this so the pure function only deals with numbers.
|
||||
function checkQuality(opts) {
|
||||
const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
|
||||
const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0, win = null } = opts;
|
||||
const findings = [];
|
||||
// Skip browser extension injected elements
|
||||
const elId = el.id || '';
|
||||
@@ -1724,6 +1864,155 @@ function checkQuality(opts) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flush against a visible boundary ---
|
||||
// Fires when a container has a visible boundary (border, outline, OR a
|
||||
// non-transparent background) AND near-zero padding on the bounded
|
||||
// side(s) AND text-bearing children land flush against the boundary.
|
||||
//
|
||||
// Distinct from cramped-padding: that rule needs the element itself to
|
||||
// have direct text (hasDirectText). This rule targets the OPPOSITE
|
||||
// shape — a container with NO direct text, only children — which is
|
||||
// exactly what cramped-padding misses (a section wrapping a label +
|
||||
// list lands a free pass).
|
||||
//
|
||||
// The classic shape: agent writes `padding: 28px 0 0` shorthand on a
|
||||
// section that also has a border, zeroing horizontal padding so the
|
||||
// text-bearing children touch the side borders. Background and
|
||||
// outline count too: a colored card with zero padding has the same
|
||||
// visual failure mode.
|
||||
{
|
||||
const FLUSH_SKIP_TAGS = new Set(['HTML', 'BODY', 'MAIN', 'HEADER', 'FOOTER', 'NAV', 'ARTICLE', 'ASIDE', 'BUTTON', 'A', 'LABEL', 'SUMMARY', 'CODE', 'PRE', 'INPUT', 'TEXTAREA', 'SELECT', 'FORM', 'FIGURE', 'TABLE', 'TBODY', 'THEAD', 'TR', 'TD', 'TH']);
|
||||
const upperTag = tag ? tag.toUpperCase() : '';
|
||||
const elPosition = style.position || '';
|
||||
if (
|
||||
!FLUSH_SKIP_TAGS.has(upperTag) &&
|
||||
!hasDirectText &&
|
||||
!['fixed', 'absolute'].includes(elPosition) &&
|
||||
el.children && el.children.length > 0
|
||||
) {
|
||||
const isTransparent = (c) =>
|
||||
!c || c === 'transparent' || c === 'rgba(0, 0, 0, 0)' ||
|
||||
/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0(?:\.0+)?\s*\)$/.test(c);
|
||||
|
||||
const borderW = {
|
||||
top: parseFloat(style.borderTopWidth) || 0,
|
||||
right: parseFloat(style.borderRightWidth) || 0,
|
||||
bottom: parseFloat(style.borderBottomWidth) || 0,
|
||||
left: parseFloat(style.borderLeftWidth) || 0,
|
||||
};
|
||||
const borderVisible = {
|
||||
top: borderW.top > 0 && !isTransparent(style.borderTopColor),
|
||||
right: borderW.right > 0 && !isTransparent(style.borderRightColor),
|
||||
bottom: borderW.bottom > 0 && !isTransparent(style.borderBottomColor),
|
||||
left: borderW.left > 0 && !isTransparent(style.borderLeftColor),
|
||||
};
|
||||
// Outline detection. jsdom decomposes `border` shorthand into
|
||||
// border{Top,…}Width/Color but does NOT decompose `outline` —
|
||||
// the longhands come back empty when the value was set via the
|
||||
// shorthand. Fall back to parsing `style.outline` ourselves.
|
||||
let outlineW = parseFloat(style.outlineWidth) || 0;
|
||||
let outlineStyleVal = style.outlineStyle || '';
|
||||
let outlineColorVal = style.outlineColor || '';
|
||||
if (!outlineW && style.outline) {
|
||||
const wMatch = style.outline.match(/(\d+(?:\.\d+)?)\s*px/);
|
||||
if (wMatch) outlineW = parseFloat(wMatch[1]) || 0;
|
||||
if (!outlineStyleVal) {
|
||||
outlineStyleVal = /\b(solid|dashed|dotted|double|groove|ridge|inset|outset)\b/.test(style.outline) ? 'solid' : '';
|
||||
}
|
||||
if (!outlineColorVal) {
|
||||
const cMatch = style.outline.match(/(rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}|[a-zA-Z]+)\s*$/);
|
||||
if (cMatch) outlineColorVal = cMatch[1];
|
||||
}
|
||||
}
|
||||
const outlineVisible = outlineW > 0 && !isTransparent(outlineColorVal) && outlineStyleVal && outlineStyleVal !== 'none';
|
||||
const bgVisible = !isTransparent(style.backgroundColor);
|
||||
|
||||
const anyVisible = borderVisible.top || borderVisible.right || borderVisible.bottom || borderVisible.left || outlineVisible || bgVisible;
|
||||
if (anyVisible) {
|
||||
// Resolve padding to px (jsdom returns raw "1.5rem" etc., not the
|
||||
// computed px value; parseFloat would strip the unit and treat
|
||||
// 1.5rem as 1.5px, false-flagging legitimate insets).
|
||||
const pad = {
|
||||
top: resolveLengthPx(style.paddingTop, fontSize) ?? 0,
|
||||
right: resolveLengthPx(style.paddingRight, fontSize) ?? 0,
|
||||
bottom: resolveLengthPx(style.paddingBottom, fontSize) ?? 0,
|
||||
left: resolveLengthPx(style.paddingLeft, fontSize) ?? 0,
|
||||
};
|
||||
const PAD_THRESHOLD = 2;
|
||||
// Children-insulate-this-side: a side is insulated if ANY direct
|
||||
// child has its own padding ≥ 4px on that side. Rationale: in
|
||||
// typical flow, only the first/last (or leftmost/rightmost)
|
||||
// children actually sit at the parent's edges. If even one of
|
||||
// them has its own padding, the visual flush is broken on that
|
||||
// side. Classic example: a column-flow card frame where the
|
||||
// top child (header) has padding-top:12 and the bottom child
|
||||
// (footer) has padding-bottom:8 — the parent's padding:0 doesn't
|
||||
// matter; nothing is actually flush. The `any-child-insulates`
|
||||
// heuristic accepts some false negatives (a card with one heavily
|
||||
// padded middle child won't flag) for far fewer false positives.
|
||||
const CHILD_INSULATE_THRESHOLD = 4;
|
||||
const childrenInsulate = { top: false, right: false, bottom: false, left: false };
|
||||
for (const child of el.children) {
|
||||
let childStyle = null;
|
||||
if (win && typeof win.getComputedStyle === 'function') {
|
||||
try { childStyle = win.getComputedStyle(child); } catch {}
|
||||
}
|
||||
if (!childStyle && typeof getComputedStyle === 'function') {
|
||||
try { childStyle = getComputedStyle(child); } catch {}
|
||||
}
|
||||
if (!childStyle) continue;
|
||||
const childPad = {
|
||||
top: resolveLengthPx(childStyle.paddingTop, fontSize) ?? 0,
|
||||
right: resolveLengthPx(childStyle.paddingRight, fontSize) ?? 0,
|
||||
bottom: resolveLengthPx(childStyle.paddingBottom, fontSize) ?? 0,
|
||||
left: resolveLengthPx(childStyle.paddingLeft, fontSize) ?? 0,
|
||||
};
|
||||
for (const s of ['top', 'right', 'bottom', 'left']) {
|
||||
if (childPad[s] >= CHILD_INSULATE_THRESHOLD) childrenInsulate[s] = true;
|
||||
}
|
||||
}
|
||||
|
||||
const flushSides = [];
|
||||
for (const side of ['top', 'right', 'bottom', 'left']) {
|
||||
const sideBounded = borderVisible[side] || outlineVisible || bgVisible;
|
||||
if (sideBounded && pad[side] <= PAD_THRESHOLD && !childrenInsulate[side]) {
|
||||
flushSides.push(side);
|
||||
}
|
||||
}
|
||||
|
||||
if (flushSides.length > 0) {
|
||||
// Confirm at least one direct child has substantial text content
|
||||
// (> 4 chars). Without this, the flush is harmless: e.g. an
|
||||
// image-only card.
|
||||
let hasTextChild = false;
|
||||
for (const child of el.children) {
|
||||
const childText = (child.textContent || '').trim();
|
||||
if (childText.length > 4) { hasTextChild = true; break; }
|
||||
}
|
||||
if (hasTextChild) {
|
||||
const cls = (typeof el.className === 'string' && el.className.trim())
|
||||
? el.className.trim().split(/\s+/)[0]
|
||||
: '';
|
||||
const boundaryParts = [];
|
||||
const borderSidesVisible = ['top', 'right', 'bottom', 'left'].filter(s => borderVisible[s]);
|
||||
if (borderSidesVisible.length === 4) boundaryParts.push('border');
|
||||
else if (borderSidesVisible.length > 0) boundaryParts.push(`border-${borderSidesVisible.join('/')}`);
|
||||
if (outlineVisible) boundaryParts.push('outline');
|
||||
if (bgVisible) boundaryParts.push('bg');
|
||||
const sidesLabel = flushSides.length === 4 ? 'all sides' : flushSides.join('/');
|
||||
const ident = cls
|
||||
? `<${tag.toLowerCase()}> "${cls}"`
|
||||
: `<${tag.toLowerCase()}>`;
|
||||
findings.push({
|
||||
id: 'cramped-padding',
|
||||
snippet: `${ident}: children flush against ${boundaryParts.join('+')} on ${sidesLabel} (no inset)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Body text touching viewport edge --- (browser-only: needs rect)
|
||||
// Catches the failure mode where the agent ships body paragraphs
|
||||
// with NO container providing horizontal padding — text bleeds
|
||||
@@ -1804,6 +2093,20 @@ function checkQuality(opts) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Crushed letter spacing (mirror of wide-tracking) ---
|
||||
// Tracking pulled tighter than ~-0.05em crushes characters into each other.
|
||||
// Optical tightening that display type legitimately wants (around -0.02em)
|
||||
// stays well above this floor.
|
||||
if (hasDirectText && textLen > 20 && fontSize > 0) {
|
||||
if (letterSpacingPx != null && letterSpacingPx < 0) {
|
||||
const trackingEm = letterSpacingPx / fontSize;
|
||||
if (trackingEm <= -0.05) {
|
||||
const excerpt = (el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 40);
|
||||
findings.push({ id: 'extreme-negative-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em — "${excerpt}"` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
@@ -1820,7 +2123,7 @@ function checkElementQualityDOM(el) {
|
||||
const rect = el.getBoundingClientRect();
|
||||
const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
|
||||
const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth, win: typeof window !== 'undefined' ? window : null });
|
||||
}
|
||||
|
||||
// Pure page-level skipped-heading walk. Takes a Document so it works in both
|
||||
@@ -1862,7 +2165,7 @@ function checkElementQuality(el, style, tag, window) {
|
||||
const fontSize = resolveFontSizePx(el, window);
|
||||
const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
|
||||
const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null, win: window });
|
||||
}
|
||||
|
||||
function checkElementBorders(tag, style, overrides, resolvedRadius) {
|
||||
@@ -2303,40 +2606,213 @@ function checkPageLayout(doc, win) {
|
||||
}
|
||||
}
|
||||
|
||||
// Everything centered
|
||||
const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
|
||||
let centeredCount = 0;
|
||||
let totalText = 0;
|
||||
for (const el of textEls) {
|
||||
const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
|
||||
if (!hasDirectText) continue;
|
||||
totalText++;
|
||||
|
||||
let cur = el;
|
||||
let isCentered = false;
|
||||
while (cur && cur.nodeType === 1) {
|
||||
const rawStyle = cur.getAttribute?.('style') || '';
|
||||
const cls = cur.getAttribute?.('class') || '';
|
||||
if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
|
||||
isCentered = true;
|
||||
break;
|
||||
}
|
||||
if (cur.tagName === 'BODY') break;
|
||||
cur = cur.parentElement;
|
||||
}
|
||||
if (isCentered) centeredCount++;
|
||||
}
|
||||
|
||||
if (totalText >= 5 && centeredCount / totalText > 0.7) {
|
||||
findings.push({
|
||||
id: 'everything-centered',
|
||||
snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
|
||||
});
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Cream / beige palette (the default "tasteful" AI surface) ────────────────
|
||||
// A warm, lightly-tinted off-white page background — light, with R≥G≥B and a
|
||||
// small warm tint (not white, not a strong color). The current reflex surface.
|
||||
function isCreamColor(rgb) {
|
||||
if (!rgb) return false;
|
||||
const { r, g, b } = rgb;
|
||||
if (Math.min(r, g, b) < 209) return false; // must be light
|
||||
if (!(r >= g && g >= b)) return false; // warm ordering
|
||||
const warmth = r - b;
|
||||
return warmth >= 6 && warmth <= 48; // tinted, not white, not strong
|
||||
}
|
||||
|
||||
// Tailwind background utilities that render as a warm off-white surface. The
|
||||
// static engine doesn't fetch Tailwind's CSS, so a `bg-amber-50` on <body>
|
||||
// resolves to nothing in computed style — catch it from the class list
|
||||
// instead. Candidate tokens map to their actual Tailwind hex and are still
|
||||
// filtered through isCreamColor, so neutral grays (stone) and over-saturated
|
||||
// shades drop out on their own.
|
||||
const TAILWIND_BG_HEX = {
|
||||
'bg-amber-50': '#fffbeb', 'bg-amber-100': '#fef3c7',
|
||||
'bg-orange-50': '#fff7ed', 'bg-orange-100': '#ffedd5',
|
||||
'bg-yellow-50': '#fefce8',
|
||||
'bg-stone-50': '#fafaf9', 'bg-stone-100': '#f5f5f4', 'bg-stone-200': '#e7e5e4',
|
||||
};
|
||||
|
||||
function creamFromClassList(cls) {
|
||||
if (!cls) return null;
|
||||
// Arbitrary value: bg-[#f5f0e6] / bg-[rgb(245_240_230)] (underscores = spaces).
|
||||
const arb = cls.match(/\bbg-\[([^\]]+)\]/);
|
||||
if (arb && isCreamColor(parseAnyColor(arb[1].replace(/_/g, ' ')))) return `bg-[${arb[1]}]`;
|
||||
// Named warm-light utilities.
|
||||
for (const [tok, hex] of Object.entries(TAILWIND_BG_HEX)) {
|
||||
if (new RegExp(`(^|\\s)${tok}($|\\s)`).test(cls) && isCreamColor(parseAnyColor(hex))) return tok;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkCreamPalette(doc, win) {
|
||||
const findings = [];
|
||||
const body = doc.body || (doc.querySelector ? doc.querySelector('body') : null);
|
||||
if (!body) return findings;
|
||||
const html = doc.documentElement;
|
||||
const getCS = (el) => (win ? win.getComputedStyle(el) : getComputedStyle(el));
|
||||
|
||||
// 1. Computed background — covers inline / <style> / linked CSS, and Tailwind
|
||||
// once it's actually rendered (browser path).
|
||||
let bg = readOwnBackgroundColor(body, getCS(body));
|
||||
if (!bg || bg.a === 0) {
|
||||
if (html) bg = readOwnBackgroundColor(html, getCS(html));
|
||||
}
|
||||
if (isCreamColor(bg)) {
|
||||
findings.push({ id: 'cream-palette', snippet: `cream/beige page background rgb(${bg.r}, ${bg.g}, ${bg.b})` });
|
||||
return findings;
|
||||
}
|
||||
|
||||
// 2. Tailwind class fallback — for the static path, where utility classes
|
||||
// never resolve to computed CSS.
|
||||
for (const el of [body, html]) {
|
||||
const tok = creamFromClassList(el && el.getAttribute ? el.getAttribute('class') : '');
|
||||
if (tok) {
|
||||
findings.push({ id: 'cream-palette', snippet: `cream/beige page background (Tailwind ${tok})` });
|
||||
break;
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Oversized hero headline ────────────────────────────────────────────────
|
||||
// Fires when a *long* headline is set at display size, so a full sentence ends
|
||||
// up dominating the viewport. A punchy one- or two-word headline at the same
|
||||
// size is a legitimate stylistic choice and must pass — length, not size
|
||||
// alone, is the tell.
|
||||
const OVERSIZED_H1_FONT_PX = 72;
|
||||
const OVERSIZED_H1_MIN_CHARS = 40;
|
||||
function checkOversizedH1({ tag, fontSize, headingText }) {
|
||||
if (tag !== 'h1') return [];
|
||||
const textLen = headingText.length;
|
||||
if (fontSize >= OVERSIZED_H1_FONT_PX && textLen >= OVERSIZED_H1_MIN_CHARS) {
|
||||
return [{ id: 'oversized-h1', snippet: `${Math.round(fontSize)}px h1, ${textLen} chars "${headingText.slice(0, 60)}"` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function checkElementOversizedH1(el, style, tag, window) {
|
||||
if (tag !== 'h1') return [];
|
||||
const fontSize = resolveFontSizePx(el, window);
|
||||
const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
|
||||
return checkOversizedH1({ tag, fontSize, headingText });
|
||||
}
|
||||
|
||||
function checkElementOversizedH1DOM(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (tag !== 'h1') return [];
|
||||
const style = getComputedStyle(el);
|
||||
const fontSize = parseFloat(style.fontSize) || 0;
|
||||
const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
|
||||
return checkOversizedH1({ tag, fontSize, headingText });
|
||||
}
|
||||
|
||||
// ─── GPT tell: hairline border + wide diffuse shadow (gated --gpt) ────────────
|
||||
function shadowMaxBlurPx(boxShadow) {
|
||||
if (!boxShadow || boxShadow === 'none') return 0;
|
||||
let maxBlur = 0;
|
||||
// Split into layers on commas not inside parentheses (rgba(...) etc.).
|
||||
for (const layer of boxShadow.split(/,(?![^()]*\))/)) {
|
||||
// Strip colors and keywords (rgba()/hsl()/hex/named/inset/px), leaving the
|
||||
// ordered length tokens: offsetX offsetY blur [spread]. Static jsdom keeps
|
||||
// unitless zeros ("0 0 24px"); browsers normalize to px ("0px 0px 24px") —
|
||||
// both reduce to the same numbers here.
|
||||
const cleaned = layer.replace(/rgba?\([^)]*\)|hsla?\([^)]*\)|#[0-9a-f]+|\b[a-z]+\b/gi, ' ');
|
||||
const nums = [...cleaned.matchAll(/-?\d*\.?\d+/g)].map(m => parseFloat(m[0]));
|
||||
if (nums.length >= 3) maxBlur = Math.max(maxBlur, nums[2]);
|
||||
}
|
||||
return maxBlur;
|
||||
}
|
||||
|
||||
function checkGptThinBorderWideShadow({ borderWidths, boxShadow }) {
|
||||
const maxBorder = Math.max(0, ...borderWidths);
|
||||
const hasThinBorder = maxBorder > 0 && maxBorder <= 1.5;
|
||||
const blur = shadowMaxBlurPx(boxShadow);
|
||||
if (hasThinBorder && blur >= 16) {
|
||||
return [{ id: 'gpt-thin-border-wide-shadow', snippet: `${maxBorder}px border + ${Math.round(blur)}px shadow blur` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function borderWidthsFromStyle(style) {
|
||||
return [
|
||||
parseFloat(style.borderTopWidth) || 0,
|
||||
parseFloat(style.borderRightWidth) || 0,
|
||||
parseFloat(style.borderBottomWidth) || 0,
|
||||
parseFloat(style.borderLeftWidth) || 0,
|
||||
];
|
||||
}
|
||||
|
||||
function checkElementGptBorderShadow(el, style) {
|
||||
return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
|
||||
}
|
||||
|
||||
function checkElementGptBorderShadowDOM(el) {
|
||||
const style = getComputedStyle(el);
|
||||
return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
|
||||
}
|
||||
|
||||
// ─── Clipped overflow container ───────────────────────────────────────────────
|
||||
// A clipping container (overflow hidden/clip, not a scroll region) wrapping an
|
||||
// absolutely/fixed-positioned descendant clips popovers/menus that must escape.
|
||||
function classSelector(el) {
|
||||
const cls = (el.getAttribute ? el.getAttribute('class') : el.className) || '';
|
||||
const tokens = String(cls).trim().split(/\s+/).filter(Boolean);
|
||||
const tag = el.tagName ? el.tagName.toLowerCase() : 'el';
|
||||
return tokens.length ? `${tag}.${tokens.join('.')}` : tag;
|
||||
}
|
||||
|
||||
function checkClippedOverflow(el, style, getStyle) {
|
||||
const clips = (v) => v === 'hidden' || v === 'clip';
|
||||
const scrolls = (v) => v === 'auto' || v === 'scroll';
|
||||
const ox = style.overflowX || '', oy = style.overflowY || '', ov = style.overflow || '';
|
||||
const anyClip = clips(ox) || clips(oy) || clips(ov);
|
||||
const anyScroll = scrolls(ox) || scrolls(oy) || scrolls(ov);
|
||||
if (!anyClip || anyScroll) return [];
|
||||
if (!el.querySelectorAll) return [];
|
||||
for (const child of el.querySelectorAll('*')) {
|
||||
const pos = (getStyle(child).position) || '';
|
||||
if (pos === 'absolute' || pos === 'fixed') {
|
||||
return [{ id: 'clipped-overflow-container', snippet: `${classSelector(el)} clips a positioned child` }];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function checkElementClippedOverflow(el, style, tag, window) {
|
||||
return checkClippedOverflow(el, style, (n) => window.getComputedStyle(n));
|
||||
}
|
||||
|
||||
function checkElementClippedOverflowDOM(el) {
|
||||
const style = getComputedStyle(el);
|
||||
return checkClippedOverflow(el, style, (n) => getComputedStyle(n));
|
||||
}
|
||||
|
||||
// ─── Text overflow (browser-only: needs scrollWidth/clientWidth) ──────────────
|
||||
const TEXT_OVERFLOW_SKIP_TAGS = new Set(['pre', 'code', 'textarea', 'svg', 'canvas', 'select', 'option', 'marquee']);
|
||||
|
||||
function checkElementTextOverflowDOM(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (TEXT_OVERFLOW_SKIP_TAGS.has(tag)) return [];
|
||||
// Only the element that actually owns overflowing text — not its ancestors,
|
||||
// which inherit a wider scrollWidth from the spilling descendant.
|
||||
const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
|
||||
if (!hasDirectText) return [];
|
||||
const style = getComputedStyle(el);
|
||||
const isScrollRegion = (s) => /(auto|scroll)/.test(s.overflowX || '') || /(auto|scroll)/.test(s.overflow || '');
|
||||
if (isScrollRegion(style)) return [];
|
||||
// A scrollable ancestor means this overflow is intentional and scrollable.
|
||||
for (let p = el.parentElement; p; p = p.parentElement) {
|
||||
if (isScrollRegion(getComputedStyle(p))) return [];
|
||||
}
|
||||
const delta = el.scrollWidth - el.clientWidth;
|
||||
if (el.clientWidth > 0 && delta >= 16) {
|
||||
return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its box by ${Math.round(delta)}px` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// --- cli/engine/browser/injected/index.mjs ---
|
||||
const IS_BROWSER = typeof window !== 'undefined';
|
||||
|
||||
@@ -2349,8 +2825,21 @@ if (IS_BROWSER) {
|
||||
const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
|
||||
|| document.documentElement.dataset.impeccableExtension === 'true';
|
||||
|
||||
const BRAND_COLOR = 'oklch(55% 0.25 350)';
|
||||
const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
|
||||
// Kinpaku gold — pinned to the site's brand token (see
|
||||
// site/styles/kinpaku-tokens.css --ks-kinpaku). Keep this in sync with
|
||||
// the picker's C.brand in skill/scripts/live-browser.js and the kit's
|
||||
// picker section in site/styles/kinpaku-kit.css.
|
||||
//
|
||||
// One color across both light and dark host pages. The outline is a
|
||||
// 2px gesture pointing at an element + a labeled tag — it's a marker,
|
||||
// not body text, so it doesn't need WCAG AA against the page. The
|
||||
// label text inside the gold tag is dark (LABEL_INK) which has ~16:1
|
||||
// against the leaf gold, so reading the rule name is solid in both
|
||||
// modes. Hover deepens the gold (preserves chroma — never drops it,
|
||||
// dropping chroma washes the gold into a sand/olive tone).
|
||||
const BRAND_COLOR = 'oklch(84% 0.19 80.46)';
|
||||
const BRAND_COLOR_HOVER = 'oklch(74% 0.18 80)';
|
||||
const LABEL_INK = 'oklch(4% 0.004 95)';
|
||||
const LABEL_BG = BRAND_COLOR;
|
||||
const OUTLINE_COLOR = BRAND_COLOR;
|
||||
|
||||
@@ -2618,7 +3107,7 @@ if (IS_BROWSER) {
|
||||
display: 'flex', alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
|
||||
color: 'white', lineHeight: '14px',
|
||||
color: LABEL_INK, lineHeight: '14px',
|
||||
background: LABEL_BG,
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
borderRadius: '4px 4px 0 0',
|
||||
@@ -2738,7 +3227,7 @@ if (IS_BROWSER) {
|
||||
banner.className = 'impeccable-overlay impeccable-banner';
|
||||
Object.assign(banner.style, {
|
||||
position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
|
||||
background: LABEL_BG, color: 'white',
|
||||
background: LABEL_BG, color: LABEL_INK,
|
||||
fontFamily: 'system-ui, sans-serif', fontSize: '13px',
|
||||
display: 'flex', alignItems: 'center', pointerEvents: 'auto',
|
||||
height: '36px', overflow: 'hidden', maxWidth: '100vw',
|
||||
@@ -3563,12 +4052,12 @@ if (IS_BROWSER) {
|
||||
}
|
||||
console.group(
|
||||
`%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
|
||||
'color: oklch(60% 0.25 350); font-weight: bold'
|
||||
'color: oklch(84% 0.19 80.46); font-weight: bold'
|
||||
);
|
||||
for (const { el, findings } of allFindings) {
|
||||
for (const f of findings) {
|
||||
console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
|
||||
'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
|
||||
'color: oklch(84% 0.19 80.46); font-weight: bold', 'color: inherit', el);
|
||||
}
|
||||
}
|
||||
console.groupEnd();
|
||||
@@ -3589,6 +4078,10 @@ if (IS_BROWSER) {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
// output concern, applied in the Node engines' detect* return paths.
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
// Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
|
||||
@@ -3610,11 +4103,23 @@ if (IS_BROWSER) {
|
||||
...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementOversizedH1DOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
|
||||
// Hero eyebrow: the offending element is the eyebrow above the heading,
|
||||
// not the heading itself — highlight the previous sibling instead.
|
||||
const eyebrowFindings = checkElementHeroEyebrowDOM(el)
|
||||
.map(f => ({ type: f.id, detail: f.snippet }))
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (eyebrowFindings.length > 0 && el.previousElementSibling) {
|
||||
addBrowserFindings(groupMap, el.previousElementSibling, eyebrowFindings);
|
||||
}
|
||||
}
|
||||
|
||||
const pageLevelFindings = [];
|
||||
@@ -3646,6 +4151,14 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, qualityFindings);
|
||||
}
|
||||
|
||||
const creamFindings = checkCreamPalette(document)
|
||||
.map(f => ({ type: f.id, detail: f.snippet }))
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (creamFindings.length > 0) {
|
||||
pageLevelFindings.push(...creamFindings);
|
||||
addBrowserFindings(groupMap, document.body, creamFindings);
|
||||
}
|
||||
|
||||
// Regex-on-HTML checks (shared with Node)
|
||||
// Clone the document and strip impeccable-live overlay nodes before the
|
||||
// regex scan, so the inspector's own inline styles (transitions on top/
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
|
||||
|
||||
@@ -212,7 +213,7 @@ async function detectUrl(url, options = {}) {
|
||||
}, () => browser.close());
|
||||
}
|
||||
}
|
||||
return results.map(f => finding(f.id, url, f.snippet));
|
||||
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
|
||||
}
|
||||
|
||||
async function createBrowserDetector(options = {}) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { GENERIC_FONTS } from '../../shared/constants.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindings, profileStep } from '../../profile/profiler.mjs';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -11,6 +12,17 @@ const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
|
||||
const hasBorderRadius = (line) => /border-radius/i.test(line);
|
||||
const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
|
||||
|
||||
/** Strip HTML to plain text — drops script/style/comments/tags so
|
||||
* content-text analyzers don't false-positive on code or CSS. */
|
||||
function stripHtmlToText(html) {
|
||||
return html
|
||||
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<!--[\s\S]*?-->/g, ' ')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function isNeutralBorderColor(str) {
|
||||
const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
|
||||
if (!m) return false;
|
||||
@@ -57,16 +69,12 @@ const REGEX_MATCHERS = [
|
||||
test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
|
||||
fmt: (m) => m[0] },
|
||||
// --- Overused font ---
|
||||
{ id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
|
||||
{ id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans|Instrument Serif)\b/gi,
|
||||
test: () => true,
|
||||
fmt: (m) => m[0] },
|
||||
{ id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
|
||||
{ id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Instrument\+Serif|Mona\+Sans|Geist)\b/gi,
|
||||
test: () => true,
|
||||
fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
|
||||
// --- Pure black background ---
|
||||
{ id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
|
||||
test: () => true,
|
||||
fmt: (m) => m[0] },
|
||||
// --- Gradient text ---
|
||||
{ id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
|
||||
test: (m, line) => /gradient/i.test(line),
|
||||
@@ -75,10 +83,6 @@ const REGEX_MATCHERS = [
|
||||
{ id: 'gradient-text', regex: /\bbg-clip-text\b/g,
|
||||
test: (m, line) => /\bbg-gradient-to-/i.test(line),
|
||||
fmt: () => 'bg-clip-text + bg-gradient' },
|
||||
// --- Tailwind pure black background ---
|
||||
{ id: 'pure-black-white', regex: /\bbg-black\b/g,
|
||||
test: () => true,
|
||||
fmt: (m) => m[0] },
|
||||
// --- Tailwind gray on colored bg ---
|
||||
{ id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
|
||||
test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
|
||||
@@ -124,6 +128,14 @@ const REGEX_MATCHERS = [
|
||||
const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
|
||||
return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
|
||||
} },
|
||||
// --- Broken image: src="" or src="#" or src=" " ---
|
||||
{ id: 'broken-image', regex: /<img\b[^>]*?\bsrc\s*=\s*(?:""|''|"\s+"|'\s+'|"#"|'#')/gi,
|
||||
test: () => true,
|
||||
fmt: (m) => m[0].slice(0, 100) },
|
||||
// --- Broken image: <img> with no src attribute at all ---
|
||||
{ id: 'broken-image', regex: /<img\b(?:(?!\bsrc\s*=)[^>])*>/gi,
|
||||
test: (m) => !/\bsrc\s*=/i.test(m[0]),
|
||||
fmt: (m) => m[0].slice(0, 100) },
|
||||
];
|
||||
|
||||
const REGEX_ANALYZERS = [
|
||||
@@ -197,18 +209,86 @@ const REGEX_ANALYZERS = [
|
||||
const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
|
||||
return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
|
||||
},
|
||||
// Everything centered (regex)
|
||||
// Em-dash overuse: 5+ em-dashes or "--" in body text content
|
||||
// (occasional em-dash use in prose is fine; the pattern fires only
|
||||
// when count crosses into AI-cadence territory).
|
||||
(content, filePath) => {
|
||||
const lines = content.split('\n');
|
||||
let centered = 0, total = 0;
|
||||
for (const line of lines) {
|
||||
if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
|
||||
total++;
|
||||
if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
|
||||
const text = stripHtmlToText(content);
|
||||
let count = 0;
|
||||
const re = /[—]|--(?=\S)/g;
|
||||
while (re.exec(text) !== null) count++;
|
||||
if (count < 5) return [];
|
||||
return [finding('em-dash-overuse', filePath, `${count} em-dashes in body text`)];
|
||||
},
|
||||
// Marketing buzzwords: SaaS phrase list
|
||||
(content, filePath) => {
|
||||
const text = stripHtmlToText(content);
|
||||
const lower = text.toLowerCase();
|
||||
const BUZZWORDS = [
|
||||
'streamline your', 'empower your', 'supercharge your',
|
||||
'unleash your', 'unleash the power', 'leverage the power',
|
||||
'built for the modern', 'trusted by leading', 'trusted by the world',
|
||||
'best-in-class', 'industry-leading', 'world-class', 'enterprise-grade',
|
||||
'next-generation', 'cutting-edge', 'transform your business',
|
||||
'revolutionize', 'game-changer', 'game changing',
|
||||
'mission-critical', 'best of breed', 'future-proof', 'future proof',
|
||||
'seamless experience', 'seamlessly integrate',
|
||||
'drive engagement', 'drive growth', 'drive results',
|
||||
'harness the power',
|
||||
];
|
||||
let count = 0;
|
||||
let firstSample = '';
|
||||
for (const phrase of BUZZWORDS) {
|
||||
let from = 0;
|
||||
while (true) {
|
||||
const idx = lower.indexOf(phrase, from);
|
||||
if (idx === -1) break;
|
||||
count++;
|
||||
if (!firstSample) {
|
||||
firstSample = text.slice(Math.max(0, idx - 12), Math.min(text.length, idx + phrase.length + 12)).trim();
|
||||
}
|
||||
from = idx + phrase.length;
|
||||
}
|
||||
}
|
||||
if (total < 5 || centered / total <= 0.7) return [];
|
||||
return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
|
||||
if (count === 0) return [];
|
||||
return [finding('marketing-buzzword', filePath, `${count} buzzword phrase${count === 1 ? '' : 's'}: "${firstSample}"`)];
|
||||
},
|
||||
// Numbered section markers (01 / 02 / 03 ...)
|
||||
(content, filePath) => {
|
||||
const text = stripHtmlToText(content);
|
||||
const re = /\b(0[1-9]|1[0-2])\b/g;
|
||||
const seen = new Set();
|
||||
let m;
|
||||
while ((m = re.exec(text)) !== null) seen.add(m[1]);
|
||||
if (seen.size < 3) return [];
|
||||
const sorted = [...seen].sort();
|
||||
let sequential = 0;
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
if (parseInt(sorted[i], 10) === parseInt(sorted[i - 1], 10) + 1) sequential++;
|
||||
}
|
||||
if (sequential < 2) return [];
|
||||
return [finding('numbered-section-markers', filePath, `Sequence: ${sorted.slice(0, 6).join(', ')}`)];
|
||||
},
|
||||
// Aphoristic cadence: manufactured-contrast + short-rebuttal
|
||||
(content, filePath) => {
|
||||
const text = stripHtmlToText(content);
|
||||
const NOT_A_RE = /\bNot an? [a-z][^.!?]{1,40}[.!]\s+[A-Z][^.!?]{1,60}[.!]/g;
|
||||
const SHORT_REBUTTAL_RE = /\b[A-Z][^.!?]{4,80}[.!]\s+(No|Just)\s+[a-z][^.!?]{2,60}[.!]/g;
|
||||
let count = 0;
|
||||
let firstSample = '';
|
||||
let m;
|
||||
NOT_A_RE.lastIndex = 0;
|
||||
while ((m = NOT_A_RE.exec(text)) !== null) {
|
||||
count++;
|
||||
if (!firstSample) firstSample = m[0].trim().slice(0, 80);
|
||||
}
|
||||
SHORT_REBUTTAL_RE.lastIndex = 0;
|
||||
while ((m = SHORT_REBUTTAL_RE.exec(text)) !== null) {
|
||||
count++;
|
||||
if (!firstSample) firstSample = m[0].trim().slice(0, 80);
|
||||
}
|
||||
if (count < 3) return [];
|
||||
return [finding('aphoristic-cadence', filePath, `${count} aphoristic constructions: "${firstSample}"`)];
|
||||
},
|
||||
// Dark glow (page-level: dark bg + colored box-shadow with blur)
|
||||
(content, filePath) => {
|
||||
@@ -328,6 +408,36 @@ function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null,
|
||||
return findings;
|
||||
}
|
||||
|
||||
/** Page-level analyzers that scan rendered text content (em-dash use,
|
||||
* buzzword phrases, numbered section markers, aphoristic cadence).
|
||||
* These are detector-agnostic — they work on any HTML/text source
|
||||
* and don't need a parsed DOM. Exported so detectHtml can call them
|
||||
* for `.html` files (which otherwise skip the regex engine). */
|
||||
const TEXT_CONTENT_ANALYZER_IDS = [
|
||||
'em-dash-overuse',
|
||||
'marketing-buzzword',
|
||||
'numbered-section-markers',
|
||||
'aphoristic-cadence',
|
||||
];
|
||||
|
||||
function runTextContentAnalyzers(content, filePath, options = {}) {
|
||||
const profile = options?.profile;
|
||||
if (!isFullPage(content)) return [];
|
||||
// The 4 text-content analyzers are at indices 3-6 in REGEX_ANALYZERS.
|
||||
const findings = [];
|
||||
for (let i = 0; i < TEXT_CONTENT_ANALYZER_IDS.length; i++) {
|
||||
const analyzer = REGEX_ANALYZERS[3 + i];
|
||||
const ruleId = TEXT_CONTENT_ANALYZER_IDS[i];
|
||||
findings.push(...profileFindings(profile, {
|
||||
engine: 'regex',
|
||||
phase: 'text-content',
|
||||
ruleId,
|
||||
target: filePath,
|
||||
}, () => analyzer(content, filePath)));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function detectText(content, filePath, options = {}) {
|
||||
const profile = options?.profile;
|
||||
const findings = [];
|
||||
@@ -393,7 +503,10 @@ function detectText(content, filePath, options = {}) {
|
||||
'single-font',
|
||||
'flat-type-hierarchy',
|
||||
'monotonous-spacing',
|
||||
'everything-centered',
|
||||
'em-dash-overuse',
|
||||
'marketing-buzzword',
|
||||
'numbered-section-markers',
|
||||
'aphoristic-cadence',
|
||||
'dark-glow',
|
||||
];
|
||||
for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
|
||||
@@ -407,14 +520,16 @@ function detectText(content, filePath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
return deduped;
|
||||
return filterByProviders(deduped, options?.providers);
|
||||
}
|
||||
|
||||
export {
|
||||
REGEX_MATCHERS,
|
||||
REGEX_ANALYZERS,
|
||||
TEXT_CONTENT_ANALYZER_IDS,
|
||||
extractStyleBlocks,
|
||||
extractCSSinJS,
|
||||
runRegexMatchers,
|
||||
runTextContentAnalyzers,
|
||||
detectText,
|
||||
};
|
||||
|
||||
@@ -241,6 +241,9 @@ const STATIC_DEFAULT_STYLE = {
|
||||
borderBottomColor: 'rgb(0, 0, 0)',
|
||||
borderLeftColor: 'rgb(0, 0, 0)',
|
||||
borderRadius: '0px',
|
||||
outlineWidth: '0px',
|
||||
outlineColor: 'rgb(0, 0, 0)',
|
||||
outlineStyle: 'none',
|
||||
boxShadow: 'none',
|
||||
fontFamily: '',
|
||||
fontSize: '16px',
|
||||
@@ -266,6 +269,9 @@ const STATIC_DEFAULT_STYLE = {
|
||||
paddingLeft: '0px',
|
||||
position: 'static',
|
||||
display: '',
|
||||
overflow: 'visible',
|
||||
overflowX: 'visible',
|
||||
overflowY: 'visible',
|
||||
};
|
||||
|
||||
const STATIC_PROP_MAP = {
|
||||
@@ -282,6 +288,9 @@ const STATIC_PROP_MAP = {
|
||||
'border-right-color': 'borderRightColor',
|
||||
'border-bottom-color': 'borderBottomColor',
|
||||
'border-left-color': 'borderLeftColor',
|
||||
'outline-width': 'outlineWidth',
|
||||
'outline-color': 'outlineColor',
|
||||
'outline-style': 'outlineStyle',
|
||||
'box-shadow': 'boxShadow',
|
||||
'font-family': 'fontFamily',
|
||||
'font-size': 'fontSize',
|
||||
@@ -305,6 +314,9 @@ const STATIC_PROP_MAP = {
|
||||
'padding-left': 'paddingLeft',
|
||||
'position': 'position',
|
||||
'display': 'display',
|
||||
'overflow': 'overflow',
|
||||
'overflow-x': 'overflowX',
|
||||
'overflow-y': 'overflowY',
|
||||
};
|
||||
|
||||
const STATIC_NAMED_COLORS = {
|
||||
@@ -511,6 +523,26 @@ function expandStaticDeclaration(prop, value) {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (p === 'outline') {
|
||||
// `outline` shorthand: width | style | color, in any order. Reuse the
|
||||
// border parser for width + color, then sniff a style keyword from the
|
||||
// tokens (solid|dashed|...). `outline: 0` (single-token zero) zeros
|
||||
// the width and effectively hides the outline.
|
||||
const tokens = splitCssTokens(v);
|
||||
const parsed = parseStaticBorder(v);
|
||||
const styleToken = tokens.find(t =>
|
||||
/^(none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/i.test(t)
|
||||
);
|
||||
const out = [];
|
||||
if (parsed.width) out.push(['outlineWidth', parsed.width]);
|
||||
if (parsed.color) out.push(['outlineColor', parsed.color]);
|
||||
if (styleToken) out.push(['outlineStyle', styleToken.toLowerCase()]);
|
||||
// `outline: 0` with no other tokens: explicit zero width.
|
||||
if (!parsed.width && /^0(?:px|rem|em|%)?$/.test(v.trim())) {
|
||||
out.push(['outlineWidth', '0px']);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
|
||||
if (sideMatch) {
|
||||
const parsed = parseStaticBorder(v);
|
||||
|
||||
@@ -7,13 +7,17 @@ import { finding } from '../../findings.mjs';
|
||||
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import {
|
||||
checkElementBorders,
|
||||
checkElementClippedOverflow,
|
||||
checkElementColors,
|
||||
checkElementGlow,
|
||||
checkElementGptBorderShadow,
|
||||
checkElementHeroEyebrow,
|
||||
checkElementIconTile,
|
||||
checkElementItalicSerif,
|
||||
checkElementMotion,
|
||||
checkElementOversizedH1,
|
||||
checkElementQuality,
|
||||
checkCreamPalette,
|
||||
checkHtmlPatterns,
|
||||
checkPageLayout,
|
||||
checkPageQualityFromDoc,
|
||||
@@ -21,7 +25,8 @@ import {
|
||||
resolveBackground,
|
||||
resolveBorderRadiusPx,
|
||||
} from '../../rules/checks.mjs';
|
||||
import { detectText } from '../regex/detect-text.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { detectText, runTextContentAnalyzers } from '../regex/detect-text.mjs';
|
||||
import {
|
||||
StaticDocument,
|
||||
buildStaticStyleMap,
|
||||
@@ -64,6 +69,20 @@ function checkStaticPageTypography(document, window) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
function checkElementBrokenImage(el) {
|
||||
const src = (el.getAttribute && el.getAttribute('src')) ?? el.attribs?.src;
|
||||
// Missing src attribute entirely
|
||||
if (src === undefined || src === null) {
|
||||
return [{ id: 'broken-image', snippet: '<img> with no src attribute' }];
|
||||
}
|
||||
const trimmed = String(src).trim();
|
||||
// Empty or placeholder-only src values
|
||||
if (trimmed === '' || trimmed === '#') {
|
||||
return [{ id: 'broken-image', snippet: `<img src="${src}">` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
const STATIC_ELEMENT_RULES = [
|
||||
{ id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
|
||||
{ id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
|
||||
@@ -72,7 +91,11 @@ const STATIC_ELEMENT_RULES = [
|
||||
{ id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
|
||||
{ id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
|
||||
{ id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
|
||||
{ id: 'broken-image', selector: 'img', run: (el) => checkElementBrokenImage(el) },
|
||||
{ id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
|
||||
{ id: 'oversized-h1', selector: 'h1', run: (el, tag, style, window) => checkElementOversizedH1(el, style, tag, window) },
|
||||
{ id: 'clipped-overflow-container', selector: '*', run: (el, tag, style, window) => checkElementClippedOverflow(el, style, tag, window) },
|
||||
{ id: 'gpt-thin-border-wide-shadow', selector: '*', run: (el, tag, style) => checkElementGptBorderShadow(el, style) },
|
||||
];
|
||||
|
||||
async function detectHtml(filePath, options = {}) {
|
||||
@@ -158,6 +181,9 @@ async function detectHtml(filePath, options = {}) {
|
||||
for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
for (const f of runPageCheck('cream-palette', () => checkCreamPalette(document, window))) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
@@ -166,9 +192,17 @@ async function detectHtml(filePath, options = {}) {
|
||||
))) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
// Text-content analyzers (em-dash overuse, marketing buzzwords,
|
||||
// numbered section markers, aphoristic cadence) live in the regex
|
||||
// engine. Call them from here so .html files get the same coverage
|
||||
// as .css/.tsx files. These are scoped to text content only and
|
||||
// don't overlap with static-html's element/page rules.
|
||||
for (const f of runPageCheck('text-content', () => runTextContentAnalyzers(html, filePath, options))) {
|
||||
findings.push(finding(f.antipattern, filePath, f.snippet));
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
return filterByProviders(findings, options.providers);
|
||||
}
|
||||
|
||||
export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
|
||||
|
||||
@@ -63,6 +63,15 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'AI color palette',
|
||||
},
|
||||
{
|
||||
id: 'cream-palette',
|
||||
category: 'slop',
|
||||
name: 'Cream / beige palette',
|
||||
description:
|
||||
'A warm cream or beige page background has become the default "tasteful" AI surface, reached for by reflex. Choose a background that comes from a deliberate palette, not the safe warm off-white.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'cream and beige as the default surface',
|
||||
},
|
||||
{
|
||||
id: 'nested-cards',
|
||||
category: 'slop',
|
||||
@@ -81,15 +90,6 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'same spacing everywhere',
|
||||
},
|
||||
{
|
||||
id: 'everything-centered',
|
||||
category: 'slop',
|
||||
name: 'Everything centered',
|
||||
description:
|
||||
'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'Center everything',
|
||||
},
|
||||
{
|
||||
id: 'bounce-easing',
|
||||
category: 'slop',
|
||||
@@ -145,17 +145,72 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
|
||||
},
|
||||
{
|
||||
id: 'numbered-section-markers',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
name: 'Numbered section markers (01 / 02 / 03)',
|
||||
description:
|
||||
'Numbered display markers as section labels (01, 02, 03) are the AI editorial scaffold one tier deeper than tracked eyebrow chips. If you find yourself reaching for them, choose a different section cadence.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'numbered section markers',
|
||||
},
|
||||
{
|
||||
id: 'em-dash-overuse',
|
||||
category: 'slop',
|
||||
name: 'Em-dash overuse',
|
||||
description:
|
||||
'More than two em-dashes (— or --) in body copy is an AI cadence tell. Use commas, colons, periods, or parentheses instead.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'no em dashes',
|
||||
},
|
||||
{
|
||||
id: 'marketing-buzzword',
|
||||
category: 'slop',
|
||||
name: 'Marketing buzzword',
|
||||
description:
|
||||
'Generic SaaS phrases (streamline / empower / supercharge / world-class / enterprise-grade / next-generation / cutting-edge / etc) are instant AI tells. Pick a specific verb and noun that says what the product literally does.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'marketing buzzwords',
|
||||
},
|
||||
{
|
||||
id: 'aphoristic-cadence',
|
||||
category: 'slop',
|
||||
name: 'Aphoristic-cadence copy',
|
||||
description:
|
||||
'Three or more sections landing on a short rebuttal sentence ("X. No Y." / "X. Just Y.") or a manufactured-contrast aphorism ("Not a feature. A platform.") reads as AI cadence, not voice. Once is fine; the pattern is the tell.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'aphoristic cadence',
|
||||
},
|
||||
{
|
||||
id: 'oversized-h1',
|
||||
category: 'slop',
|
||||
name: 'Oversized hero headline',
|
||||
description:
|
||||
'A full-sentence headline set at display size ends up dominating the viewport, leaving no room for anything else above the fold. A punchy one- or two-word headline at that size is fine — the problem is a long headline blown up too large. Set long headlines smaller, or tighten the copy.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'long headline set at display size',
|
||||
},
|
||||
{
|
||||
id: 'extreme-negative-tracking',
|
||||
category: 'slop',
|
||||
name: 'Crushed letter spacing',
|
||||
description:
|
||||
'Letter-spacing pulled tighter than the point where characters keep their own shapes costs legibility. Tighten display type optically, not destructively.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'letter spacing crushed past legibility',
|
||||
},
|
||||
{
|
||||
id: 'broken-image',
|
||||
category: 'quality',
|
||||
name: 'Broken or placeholder image',
|
||||
description:
|
||||
'<img> tags with empty src, missing src, or placeholder values ship as broken-image boxes. Use real images, generated assets, or remove the tag.',
|
||||
skillSection: 'Imagery',
|
||||
skillGuideline: 'broken image references',
|
||||
},
|
||||
|
||||
// ── Quality: general design and accessibility issues ──
|
||||
{
|
||||
id: 'pure-black-white',
|
||||
category: 'quality',
|
||||
name: 'Pure black background',
|
||||
description:
|
||||
'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'pure black (#000)',
|
||||
},
|
||||
{
|
||||
id: 'gray-on-color',
|
||||
category: 'quality',
|
||||
@@ -195,7 +250,9 @@ const ANTIPATTERNS = [
|
||||
category: 'quality',
|
||||
name: 'Cramped padding',
|
||||
description:
|
||||
'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
|
||||
'Text is too close to the edge of its container. Two shapes: (1) an element with its own text where the padding is too low for the font size, and (2) a wrapper with text-bearing children and near-zero padding against a visible boundary (border, outline, or non-transparent background) — children land flush against the boundary line. Add at least 8px (ideally 12–16px) of padding inside bordered, outlined, or colored containers.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'inside bordered or colored containers',
|
||||
},
|
||||
{
|
||||
id: 'body-text-viewport-edge',
|
||||
@@ -248,6 +305,70 @@ const ANTIPATTERNS = [
|
||||
description:
|
||||
'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
|
||||
},
|
||||
{
|
||||
id: 'text-overflow',
|
||||
category: 'quality',
|
||||
name: 'Content overflowing its container',
|
||||
description:
|
||||
'Content renders wider than its container, spilling out or forcing a horizontal scrollbar. Let text wrap, constrain widths, or give the region a deliberate scroll affordance.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'content wider than its container',
|
||||
},
|
||||
{
|
||||
id: 'clipped-overflow-container',
|
||||
category: 'quality',
|
||||
name: 'Positioned child clipped by overflow container',
|
||||
description:
|
||||
'A clipping container (overflow hidden or clip) wrapping an absolutely-positioned child cuts off tooltips, menus, and popovers that need to escape. Let the overflow be visible, or move the positioned layer out of the clip.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
id: 'gpt-thin-border-wide-shadow',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Hairline border with wide shadow',
|
||||
description:
|
||||
'A hairline border paired with a wide, diffuse shadow is a recurring generated-UI signature. Commit to one — a defined edge or a soft elevation — rather than both at once.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'hairline border plus wide diffuse shadow',
|
||||
},
|
||||
{
|
||||
id: 'repeating-stripes-gradient',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Repeating-gradient stripes',
|
||||
description:
|
||||
'Repeating-gradient stripes used as surface decoration are a recurring generated-UI signature. Reach for a deliberate texture or leave the surface plain.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'repeating-gradient decorative stripes',
|
||||
},
|
||||
{
|
||||
id: 'theater-slop-phrase',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Theater framing copy',
|
||||
description:
|
||||
'Dismissing something as "theater" is a recurring generated-copy tic. Say plainly what the thing does or does not do.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'theater framing copy',
|
||||
},
|
||||
{
|
||||
id: 'image-hover-transform',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gemini',
|
||||
name: 'Image hover transform',
|
||||
description:
|
||||
'Scaling or rotating an image on hover is a recurring generated-UI signature. Let imagery sit still, or use a subtler, purposeful interaction.',
|
||||
skillSection: 'Motion',
|
||||
skillGuideline: 'image scale or rotate on hover',
|
||||
},
|
||||
];
|
||||
|
||||
const RULE_ENGINE_SUPPORT = {
|
||||
@@ -269,10 +390,30 @@ function getRuleEngineSupport(engine) {
|
||||
return RULE_ENGINE_SUPPORT[engine] || new Set();
|
||||
}
|
||||
|
||||
// Set of provider tags that gate rules off by default (e.g. 'gpt', 'gemini').
|
||||
const GATED_PROVIDERS = new Set(
|
||||
ANTIPATTERNS.map(rule => rule.gated).filter(Boolean),
|
||||
);
|
||||
|
||||
// Drop findings for rules gated behind a provider tag unless that provider
|
||||
// was explicitly enabled (CLI --gpt / --gemini). Non-gated findings always
|
||||
// pass through. `findings` carry the rule id on `.antipattern`.
|
||||
function filterByProviders(findings, providers = []) {
|
||||
const enabled = new Set(providers || []);
|
||||
if (!GATED_PROVIDERS.size) return findings;
|
||||
return findings.filter(f => {
|
||||
const rule = getAntipattern(f.antipattern);
|
||||
if (!rule || !rule.gated) return true;
|
||||
return enabled.has(rule.gated);
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
ANTIPATTERNS,
|
||||
RULE_ENGINE_SUPPORT,
|
||||
GATED_PROVIDERS,
|
||||
getAntipattern,
|
||||
getRulesForCategory,
|
||||
getRuleEngineSupport,
|
||||
filterByProviders,
|
||||
};
|
||||
|
||||
@@ -78,11 +78,6 @@ function checkColors(opts) {
|
||||
}
|
||||
const findings = [];
|
||||
|
||||
// Pure black background (only solid or near-solid, not semi-transparent overlays)
|
||||
if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
|
||||
findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
|
||||
}
|
||||
|
||||
if (hasDirectText && textColor && !isEmojiOnly) {
|
||||
// Run background-dependent checks against either a solid bg or, if the
|
||||
// ancestor is a gradient, against every gradient stop (use the worst case).
|
||||
@@ -138,9 +133,6 @@ function checkColors(opts) {
|
||||
// Tailwind class checks
|
||||
if (classList) {
|
||||
const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
|
||||
if (/\bbg-black\b(?!\/)/.test(classStr)) {
|
||||
findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
|
||||
}
|
||||
|
||||
const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
|
||||
const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
|
||||
@@ -456,12 +448,6 @@ function checkHtmlPatterns(html) {
|
||||
|
||||
// --- Color ---
|
||||
|
||||
// Pure black background
|
||||
const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
|
||||
if (pureBlackBgRe.test(html)) {
|
||||
findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
|
||||
}
|
||||
|
||||
// AI color palette: purple/violet
|
||||
const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
|
||||
if (purpleHexRe.test(html)) {
|
||||
@@ -578,6 +564,39 @@ function checkHtmlPatterns(html) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): repeating-gradient stripes (GPT) ---
|
||||
if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(html)) {
|
||||
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
|
||||
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
|
||||
// runs in the bundled browser path too, not just the CLI/static path.
|
||||
{
|
||||
const bodyText = html
|
||||
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<[^>]+>/g, ' ');
|
||||
const tm = /\b(\w+)\s+theater\b/i.exec(bodyText);
|
||||
if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` });
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): image hover transform (Gemini) ---
|
||||
// A CSS `img...:hover { transform: ... }` rule, or a Tailwind hover:scale /
|
||||
// hover:rotate / hover:translate utility on an <img>. Each distinct
|
||||
// mechanism is its own finding.
|
||||
const imgHoverCss = /\bimg\b[^,{}]*:hover\b[^{}]*\{[^}]*\btransform\s*:\s*(?:scale|rotate|translate|matrix|skew)/i;
|
||||
if (imgHoverCss.test(html)) {
|
||||
findings.push({ id: 'image-hover-transform', snippet: 'img:hover { transform } rule' });
|
||||
}
|
||||
const imgTagRe = /<img\b[^>]*\bclass\s*=\s*"([^"]*)"/gi;
|
||||
let im;
|
||||
while ((im = imgTagRe.exec(html)) !== null) {
|
||||
if (/\bhover:(?:scale|rotate|translate|skew)-/.test(im[1])) {
|
||||
findings.push({ id: 'image-hover-transform', snippet: 'Tailwind hover transform on <img>' });
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
@@ -1224,7 +1243,7 @@ function resolveLengthPx(value, fontSizePx) {
|
||||
// Both adapters resolve font-size, line-height and letter-spacing to pixels
|
||||
// before calling this so the pure function only deals with numbers.
|
||||
function checkQuality(opts) {
|
||||
const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
|
||||
const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0, win = null } = opts;
|
||||
const findings = [];
|
||||
// Skip browser extension injected elements
|
||||
const elId = el.id || '';
|
||||
@@ -1275,6 +1294,155 @@ function checkQuality(opts) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flush against a visible boundary ---
|
||||
// Fires when a container has a visible boundary (border, outline, OR a
|
||||
// non-transparent background) AND near-zero padding on the bounded
|
||||
// side(s) AND text-bearing children land flush against the boundary.
|
||||
//
|
||||
// Distinct from cramped-padding: that rule needs the element itself to
|
||||
// have direct text (hasDirectText). This rule targets the OPPOSITE
|
||||
// shape — a container with NO direct text, only children — which is
|
||||
// exactly what cramped-padding misses (a section wrapping a label +
|
||||
// list lands a free pass).
|
||||
//
|
||||
// The classic shape: agent writes `padding: 28px 0 0` shorthand on a
|
||||
// section that also has a border, zeroing horizontal padding so the
|
||||
// text-bearing children touch the side borders. Background and
|
||||
// outline count too: a colored card with zero padding has the same
|
||||
// visual failure mode.
|
||||
{
|
||||
const FLUSH_SKIP_TAGS = new Set(['HTML', 'BODY', 'MAIN', 'HEADER', 'FOOTER', 'NAV', 'ARTICLE', 'ASIDE', 'BUTTON', 'A', 'LABEL', 'SUMMARY', 'CODE', 'PRE', 'INPUT', 'TEXTAREA', 'SELECT', 'FORM', 'FIGURE', 'TABLE', 'TBODY', 'THEAD', 'TR', 'TD', 'TH']);
|
||||
const upperTag = tag ? tag.toUpperCase() : '';
|
||||
const elPosition = style.position || '';
|
||||
if (
|
||||
!FLUSH_SKIP_TAGS.has(upperTag) &&
|
||||
!hasDirectText &&
|
||||
!['fixed', 'absolute'].includes(elPosition) &&
|
||||
el.children && el.children.length > 0
|
||||
) {
|
||||
const isTransparent = (c) =>
|
||||
!c || c === 'transparent' || c === 'rgba(0, 0, 0, 0)' ||
|
||||
/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0(?:\.0+)?\s*\)$/.test(c);
|
||||
|
||||
const borderW = {
|
||||
top: parseFloat(style.borderTopWidth) || 0,
|
||||
right: parseFloat(style.borderRightWidth) || 0,
|
||||
bottom: parseFloat(style.borderBottomWidth) || 0,
|
||||
left: parseFloat(style.borderLeftWidth) || 0,
|
||||
};
|
||||
const borderVisible = {
|
||||
top: borderW.top > 0 && !isTransparent(style.borderTopColor),
|
||||
right: borderW.right > 0 && !isTransparent(style.borderRightColor),
|
||||
bottom: borderW.bottom > 0 && !isTransparent(style.borderBottomColor),
|
||||
left: borderW.left > 0 && !isTransparent(style.borderLeftColor),
|
||||
};
|
||||
// Outline detection. jsdom decomposes `border` shorthand into
|
||||
// border{Top,…}Width/Color but does NOT decompose `outline` —
|
||||
// the longhands come back empty when the value was set via the
|
||||
// shorthand. Fall back to parsing `style.outline` ourselves.
|
||||
let outlineW = parseFloat(style.outlineWidth) || 0;
|
||||
let outlineStyleVal = style.outlineStyle || '';
|
||||
let outlineColorVal = style.outlineColor || '';
|
||||
if (!outlineW && style.outline) {
|
||||
const wMatch = style.outline.match(/(\d+(?:\.\d+)?)\s*px/);
|
||||
if (wMatch) outlineW = parseFloat(wMatch[1]) || 0;
|
||||
if (!outlineStyleVal) {
|
||||
outlineStyleVal = /\b(solid|dashed|dotted|double|groove|ridge|inset|outset)\b/.test(style.outline) ? 'solid' : '';
|
||||
}
|
||||
if (!outlineColorVal) {
|
||||
const cMatch = style.outline.match(/(rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}|[a-zA-Z]+)\s*$/);
|
||||
if (cMatch) outlineColorVal = cMatch[1];
|
||||
}
|
||||
}
|
||||
const outlineVisible = outlineW > 0 && !isTransparent(outlineColorVal) && outlineStyleVal && outlineStyleVal !== 'none';
|
||||
const bgVisible = !isTransparent(style.backgroundColor);
|
||||
|
||||
const anyVisible = borderVisible.top || borderVisible.right || borderVisible.bottom || borderVisible.left || outlineVisible || bgVisible;
|
||||
if (anyVisible) {
|
||||
// Resolve padding to px (jsdom returns raw "1.5rem" etc., not the
|
||||
// computed px value; parseFloat would strip the unit and treat
|
||||
// 1.5rem as 1.5px, false-flagging legitimate insets).
|
||||
const pad = {
|
||||
top: resolveLengthPx(style.paddingTop, fontSize) ?? 0,
|
||||
right: resolveLengthPx(style.paddingRight, fontSize) ?? 0,
|
||||
bottom: resolveLengthPx(style.paddingBottom, fontSize) ?? 0,
|
||||
left: resolveLengthPx(style.paddingLeft, fontSize) ?? 0,
|
||||
};
|
||||
const PAD_THRESHOLD = 2;
|
||||
// Children-insulate-this-side: a side is insulated if ANY direct
|
||||
// child has its own padding ≥ 4px on that side. Rationale: in
|
||||
// typical flow, only the first/last (or leftmost/rightmost)
|
||||
// children actually sit at the parent's edges. If even one of
|
||||
// them has its own padding, the visual flush is broken on that
|
||||
// side. Classic example: a column-flow card frame where the
|
||||
// top child (header) has padding-top:12 and the bottom child
|
||||
// (footer) has padding-bottom:8 — the parent's padding:0 doesn't
|
||||
// matter; nothing is actually flush. The `any-child-insulates`
|
||||
// heuristic accepts some false negatives (a card with one heavily
|
||||
// padded middle child won't flag) for far fewer false positives.
|
||||
const CHILD_INSULATE_THRESHOLD = 4;
|
||||
const childrenInsulate = { top: false, right: false, bottom: false, left: false };
|
||||
for (const child of el.children) {
|
||||
let childStyle = null;
|
||||
if (win && typeof win.getComputedStyle === 'function') {
|
||||
try { childStyle = win.getComputedStyle(child); } catch {}
|
||||
}
|
||||
if (!childStyle && typeof getComputedStyle === 'function') {
|
||||
try { childStyle = getComputedStyle(child); } catch {}
|
||||
}
|
||||
if (!childStyle) continue;
|
||||
const childPad = {
|
||||
top: resolveLengthPx(childStyle.paddingTop, fontSize) ?? 0,
|
||||
right: resolveLengthPx(childStyle.paddingRight, fontSize) ?? 0,
|
||||
bottom: resolveLengthPx(childStyle.paddingBottom, fontSize) ?? 0,
|
||||
left: resolveLengthPx(childStyle.paddingLeft, fontSize) ?? 0,
|
||||
};
|
||||
for (const s of ['top', 'right', 'bottom', 'left']) {
|
||||
if (childPad[s] >= CHILD_INSULATE_THRESHOLD) childrenInsulate[s] = true;
|
||||
}
|
||||
}
|
||||
|
||||
const flushSides = [];
|
||||
for (const side of ['top', 'right', 'bottom', 'left']) {
|
||||
const sideBounded = borderVisible[side] || outlineVisible || bgVisible;
|
||||
if (sideBounded && pad[side] <= PAD_THRESHOLD && !childrenInsulate[side]) {
|
||||
flushSides.push(side);
|
||||
}
|
||||
}
|
||||
|
||||
if (flushSides.length > 0) {
|
||||
// Confirm at least one direct child has substantial text content
|
||||
// (> 4 chars). Without this, the flush is harmless: e.g. an
|
||||
// image-only card.
|
||||
let hasTextChild = false;
|
||||
for (const child of el.children) {
|
||||
const childText = (child.textContent || '').trim();
|
||||
if (childText.length > 4) { hasTextChild = true; break; }
|
||||
}
|
||||
if (hasTextChild) {
|
||||
const cls = (typeof el.className === 'string' && el.className.trim())
|
||||
? el.className.trim().split(/\s+/)[0]
|
||||
: '';
|
||||
const boundaryParts = [];
|
||||
const borderSidesVisible = ['top', 'right', 'bottom', 'left'].filter(s => borderVisible[s]);
|
||||
if (borderSidesVisible.length === 4) boundaryParts.push('border');
|
||||
else if (borderSidesVisible.length > 0) boundaryParts.push(`border-${borderSidesVisible.join('/')}`);
|
||||
if (outlineVisible) boundaryParts.push('outline');
|
||||
if (bgVisible) boundaryParts.push('bg');
|
||||
const sidesLabel = flushSides.length === 4 ? 'all sides' : flushSides.join('/');
|
||||
const ident = cls
|
||||
? `<${tag.toLowerCase()}> "${cls}"`
|
||||
: `<${tag.toLowerCase()}>`;
|
||||
findings.push({
|
||||
id: 'cramped-padding',
|
||||
snippet: `${ident}: children flush against ${boundaryParts.join('+')} on ${sidesLabel} (no inset)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Body text touching viewport edge --- (browser-only: needs rect)
|
||||
// Catches the failure mode where the agent ships body paragraphs
|
||||
// with NO container providing horizontal padding — text bleeds
|
||||
@@ -1355,6 +1523,20 @@ function checkQuality(opts) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Crushed letter spacing (mirror of wide-tracking) ---
|
||||
// Tracking pulled tighter than ~-0.05em crushes characters into each other.
|
||||
// Optical tightening that display type legitimately wants (around -0.02em)
|
||||
// stays well above this floor.
|
||||
if (hasDirectText && textLen > 20 && fontSize > 0) {
|
||||
if (letterSpacingPx != null && letterSpacingPx < 0) {
|
||||
const trackingEm = letterSpacingPx / fontSize;
|
||||
if (trackingEm <= -0.05) {
|
||||
const excerpt = (el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 40);
|
||||
findings.push({ id: 'extreme-negative-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em — "${excerpt}"` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
@@ -1371,7 +1553,7 @@ function checkElementQualityDOM(el) {
|
||||
const rect = el.getBoundingClientRect();
|
||||
const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
|
||||
const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth, win: typeof window !== 'undefined' ? window : null });
|
||||
}
|
||||
|
||||
// Pure page-level skipped-heading walk. Takes a Document so it works in both
|
||||
@@ -1413,7 +1595,7 @@ function checkElementQuality(el, style, tag, window) {
|
||||
const fontSize = resolveFontSizePx(el, window);
|
||||
const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
|
||||
const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null, win: window });
|
||||
}
|
||||
|
||||
function checkElementBorders(tag, style, overrides, resolvedRadius) {
|
||||
@@ -1854,40 +2036,213 @@ function checkPageLayout(doc, win) {
|
||||
}
|
||||
}
|
||||
|
||||
// Everything centered
|
||||
const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
|
||||
let centeredCount = 0;
|
||||
let totalText = 0;
|
||||
for (const el of textEls) {
|
||||
const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
|
||||
if (!hasDirectText) continue;
|
||||
totalText++;
|
||||
|
||||
let cur = el;
|
||||
let isCentered = false;
|
||||
while (cur && cur.nodeType === 1) {
|
||||
const rawStyle = cur.getAttribute?.('style') || '';
|
||||
const cls = cur.getAttribute?.('class') || '';
|
||||
if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
|
||||
isCentered = true;
|
||||
break;
|
||||
}
|
||||
if (cur.tagName === 'BODY') break;
|
||||
cur = cur.parentElement;
|
||||
}
|
||||
if (isCentered) centeredCount++;
|
||||
}
|
||||
|
||||
if (totalText >= 5 && centeredCount / totalText > 0.7) {
|
||||
findings.push({
|
||||
id: 'everything-centered',
|
||||
snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
|
||||
});
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Cream / beige palette (the default "tasteful" AI surface) ────────────────
|
||||
// A warm, lightly-tinted off-white page background — light, with R≥G≥B and a
|
||||
// small warm tint (not white, not a strong color). The current reflex surface.
|
||||
function isCreamColor(rgb) {
|
||||
if (!rgb) return false;
|
||||
const { r, g, b } = rgb;
|
||||
if (Math.min(r, g, b) < 209) return false; // must be light
|
||||
if (!(r >= g && g >= b)) return false; // warm ordering
|
||||
const warmth = r - b;
|
||||
return warmth >= 6 && warmth <= 48; // tinted, not white, not strong
|
||||
}
|
||||
|
||||
// Tailwind background utilities that render as a warm off-white surface. The
|
||||
// static engine doesn't fetch Tailwind's CSS, so a `bg-amber-50` on <body>
|
||||
// resolves to nothing in computed style — catch it from the class list
|
||||
// instead. Candidate tokens map to their actual Tailwind hex and are still
|
||||
// filtered through isCreamColor, so neutral grays (stone) and over-saturated
|
||||
// shades drop out on their own.
|
||||
const TAILWIND_BG_HEX = {
|
||||
'bg-amber-50': '#fffbeb', 'bg-amber-100': '#fef3c7',
|
||||
'bg-orange-50': '#fff7ed', 'bg-orange-100': '#ffedd5',
|
||||
'bg-yellow-50': '#fefce8',
|
||||
'bg-stone-50': '#fafaf9', 'bg-stone-100': '#f5f5f4', 'bg-stone-200': '#e7e5e4',
|
||||
};
|
||||
|
||||
function creamFromClassList(cls) {
|
||||
if (!cls) return null;
|
||||
// Arbitrary value: bg-[#f5f0e6] / bg-[rgb(245_240_230)] (underscores = spaces).
|
||||
const arb = cls.match(/\bbg-\[([^\]]+)\]/);
|
||||
if (arb && isCreamColor(parseAnyColor(arb[1].replace(/_/g, ' ')))) return `bg-[${arb[1]}]`;
|
||||
// Named warm-light utilities.
|
||||
for (const [tok, hex] of Object.entries(TAILWIND_BG_HEX)) {
|
||||
if (new RegExp(`(^|\\s)${tok}($|\\s)`).test(cls) && isCreamColor(parseAnyColor(hex))) return tok;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkCreamPalette(doc, win) {
|
||||
const findings = [];
|
||||
const body = doc.body || (doc.querySelector ? doc.querySelector('body') : null);
|
||||
if (!body) return findings;
|
||||
const html = doc.documentElement;
|
||||
const getCS = (el) => (win ? win.getComputedStyle(el) : getComputedStyle(el));
|
||||
|
||||
// 1. Computed background — covers inline / <style> / linked CSS, and Tailwind
|
||||
// once it's actually rendered (browser path).
|
||||
let bg = readOwnBackgroundColor(body, getCS(body));
|
||||
if (!bg || bg.a === 0) {
|
||||
if (html) bg = readOwnBackgroundColor(html, getCS(html));
|
||||
}
|
||||
if (isCreamColor(bg)) {
|
||||
findings.push({ id: 'cream-palette', snippet: `cream/beige page background rgb(${bg.r}, ${bg.g}, ${bg.b})` });
|
||||
return findings;
|
||||
}
|
||||
|
||||
// 2. Tailwind class fallback — for the static path, where utility classes
|
||||
// never resolve to computed CSS.
|
||||
for (const el of [body, html]) {
|
||||
const tok = creamFromClassList(el && el.getAttribute ? el.getAttribute('class') : '');
|
||||
if (tok) {
|
||||
findings.push({ id: 'cream-palette', snippet: `cream/beige page background (Tailwind ${tok})` });
|
||||
break;
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Oversized hero headline ────────────────────────────────────────────────
|
||||
// Fires when a *long* headline is set at display size, so a full sentence ends
|
||||
// up dominating the viewport. A punchy one- or two-word headline at the same
|
||||
// size is a legitimate stylistic choice and must pass — length, not size
|
||||
// alone, is the tell.
|
||||
const OVERSIZED_H1_FONT_PX = 72;
|
||||
const OVERSIZED_H1_MIN_CHARS = 40;
|
||||
function checkOversizedH1({ tag, fontSize, headingText }) {
|
||||
if (tag !== 'h1') return [];
|
||||
const textLen = headingText.length;
|
||||
if (fontSize >= OVERSIZED_H1_FONT_PX && textLen >= OVERSIZED_H1_MIN_CHARS) {
|
||||
return [{ id: 'oversized-h1', snippet: `${Math.round(fontSize)}px h1, ${textLen} chars "${headingText.slice(0, 60)}"` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function checkElementOversizedH1(el, style, tag, window) {
|
||||
if (tag !== 'h1') return [];
|
||||
const fontSize = resolveFontSizePx(el, window);
|
||||
const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
|
||||
return checkOversizedH1({ tag, fontSize, headingText });
|
||||
}
|
||||
|
||||
function checkElementOversizedH1DOM(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (tag !== 'h1') return [];
|
||||
const style = getComputedStyle(el);
|
||||
const fontSize = parseFloat(style.fontSize) || 0;
|
||||
const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
|
||||
return checkOversizedH1({ tag, fontSize, headingText });
|
||||
}
|
||||
|
||||
// ─── GPT tell: hairline border + wide diffuse shadow (gated --gpt) ────────────
|
||||
function shadowMaxBlurPx(boxShadow) {
|
||||
if (!boxShadow || boxShadow === 'none') return 0;
|
||||
let maxBlur = 0;
|
||||
// Split into layers on commas not inside parentheses (rgba(...) etc.).
|
||||
for (const layer of boxShadow.split(/,(?![^()]*\))/)) {
|
||||
// Strip colors and keywords (rgba()/hsl()/hex/named/inset/px), leaving the
|
||||
// ordered length tokens: offsetX offsetY blur [spread]. Static jsdom keeps
|
||||
// unitless zeros ("0 0 24px"); browsers normalize to px ("0px 0px 24px") —
|
||||
// both reduce to the same numbers here.
|
||||
const cleaned = layer.replace(/rgba?\([^)]*\)|hsla?\([^)]*\)|#[0-9a-f]+|\b[a-z]+\b/gi, ' ');
|
||||
const nums = [...cleaned.matchAll(/-?\d*\.?\d+/g)].map(m => parseFloat(m[0]));
|
||||
if (nums.length >= 3) maxBlur = Math.max(maxBlur, nums[2]);
|
||||
}
|
||||
return maxBlur;
|
||||
}
|
||||
|
||||
function checkGptThinBorderWideShadow({ borderWidths, boxShadow }) {
|
||||
const maxBorder = Math.max(0, ...borderWidths);
|
||||
const hasThinBorder = maxBorder > 0 && maxBorder <= 1.5;
|
||||
const blur = shadowMaxBlurPx(boxShadow);
|
||||
if (hasThinBorder && blur >= 16) {
|
||||
return [{ id: 'gpt-thin-border-wide-shadow', snippet: `${maxBorder}px border + ${Math.round(blur)}px shadow blur` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function borderWidthsFromStyle(style) {
|
||||
return [
|
||||
parseFloat(style.borderTopWidth) || 0,
|
||||
parseFloat(style.borderRightWidth) || 0,
|
||||
parseFloat(style.borderBottomWidth) || 0,
|
||||
parseFloat(style.borderLeftWidth) || 0,
|
||||
];
|
||||
}
|
||||
|
||||
function checkElementGptBorderShadow(el, style) {
|
||||
return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
|
||||
}
|
||||
|
||||
function checkElementGptBorderShadowDOM(el) {
|
||||
const style = getComputedStyle(el);
|
||||
return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
|
||||
}
|
||||
|
||||
// ─── Clipped overflow container ───────────────────────────────────────────────
|
||||
// A clipping container (overflow hidden/clip, not a scroll region) wrapping an
|
||||
// absolutely/fixed-positioned descendant clips popovers/menus that must escape.
|
||||
function classSelector(el) {
|
||||
const cls = (el.getAttribute ? el.getAttribute('class') : el.className) || '';
|
||||
const tokens = String(cls).trim().split(/\s+/).filter(Boolean);
|
||||
const tag = el.tagName ? el.tagName.toLowerCase() : 'el';
|
||||
return tokens.length ? `${tag}.${tokens.join('.')}` : tag;
|
||||
}
|
||||
|
||||
function checkClippedOverflow(el, style, getStyle) {
|
||||
const clips = (v) => v === 'hidden' || v === 'clip';
|
||||
const scrolls = (v) => v === 'auto' || v === 'scroll';
|
||||
const ox = style.overflowX || '', oy = style.overflowY || '', ov = style.overflow || '';
|
||||
const anyClip = clips(ox) || clips(oy) || clips(ov);
|
||||
const anyScroll = scrolls(ox) || scrolls(oy) || scrolls(ov);
|
||||
if (!anyClip || anyScroll) return [];
|
||||
if (!el.querySelectorAll) return [];
|
||||
for (const child of el.querySelectorAll('*')) {
|
||||
const pos = (getStyle(child).position) || '';
|
||||
if (pos === 'absolute' || pos === 'fixed') {
|
||||
return [{ id: 'clipped-overflow-container', snippet: `${classSelector(el)} clips a positioned child` }];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function checkElementClippedOverflow(el, style, tag, window) {
|
||||
return checkClippedOverflow(el, style, (n) => window.getComputedStyle(n));
|
||||
}
|
||||
|
||||
function checkElementClippedOverflowDOM(el) {
|
||||
const style = getComputedStyle(el);
|
||||
return checkClippedOverflow(el, style, (n) => getComputedStyle(n));
|
||||
}
|
||||
|
||||
// ─── Text overflow (browser-only: needs scrollWidth/clientWidth) ──────────────
|
||||
const TEXT_OVERFLOW_SKIP_TAGS = new Set(['pre', 'code', 'textarea', 'svg', 'canvas', 'select', 'option', 'marquee']);
|
||||
|
||||
function checkElementTextOverflowDOM(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (TEXT_OVERFLOW_SKIP_TAGS.has(tag)) return [];
|
||||
// Only the element that actually owns overflowing text — not its ancestors,
|
||||
// which inherit a wider scrollWidth from the spilling descendant.
|
||||
const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
|
||||
if (!hasDirectText) return [];
|
||||
const style = getComputedStyle(el);
|
||||
const isScrollRegion = (s) => /(auto|scroll)/.test(s.overflowX || '') || /(auto|scroll)/.test(s.overflow || '');
|
||||
if (isScrollRegion(style)) return [];
|
||||
// A scrollable ancestor means this overflow is intentional and scrollable.
|
||||
for (let p = el.parentElement; p; p = p.parentElement) {
|
||||
if (isScrollRegion(getComputedStyle(p))) return [];
|
||||
}
|
||||
const delta = el.scrollWidth - el.clientWidth;
|
||||
if (el.clientWidth > 0 && delta >= 16) {
|
||||
return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its box by ${Math.round(delta)}px` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export {
|
||||
checkBorders,
|
||||
isEmojiOnlyText,
|
||||
@@ -1945,4 +2300,17 @@ export {
|
||||
checkPageTypography,
|
||||
isCardLike,
|
||||
checkPageLayout,
|
||||
isCreamColor,
|
||||
checkCreamPalette,
|
||||
checkOversizedH1,
|
||||
checkElementOversizedH1,
|
||||
checkElementOversizedH1DOM,
|
||||
shadowMaxBlurPx,
|
||||
checkGptThinBorderWideShadow,
|
||||
checkElementGptBorderShadow,
|
||||
checkElementGptBorderShadowDOM,
|
||||
checkClippedOverflow,
|
||||
checkElementClippedOverflow,
|
||||
checkElementClippedOverflowDOM,
|
||||
checkElementTextOverflowDOM,
|
||||
};
|
||||
|
||||
@@ -24,7 +24,7 @@ const OVERUSED_FONTS = new Set([
|
||||
// Older monoculture (still ubiquitous):
|
||||
'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
|
||||
// Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
|
||||
'fraunces', 'instrument sans',
|
||||
'fraunces', 'instrument sans', 'instrument serif',
|
||||
'geist', 'geist sans', 'geist mono',
|
||||
'mona sans',
|
||||
'plus jakarta sans', 'space grotesk', 'recoleta',
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Shared event validation for the live helper server.
|
||||
* Extracted for unit testing (insert mode rules).
|
||||
*/
|
||||
|
||||
import { canCreateInsert } from './live-insert-ui.mjs';
|
||||
|
||||
export const VISUAL_ACTIONS = [
|
||||
'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
|
||||
'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
|
||||
];
|
||||
|
||||
const ID_PATTERN = /^[0-9a-f]{8}$/;
|
||||
const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
|
||||
const INSERT_POSITIONS = new Set(['before', 'after']);
|
||||
|
||||
function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
|
||||
function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
|
||||
|
||||
function validateAnnotationFields(msg) {
|
||||
if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') {
|
||||
return 'generate: screenshotPath must be string';
|
||||
}
|
||||
if (msg.comments !== undefined && !Array.isArray(msg.comments)) {
|
||||
return 'generate: comments must be array';
|
||||
}
|
||||
if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) {
|
||||
return 'generate: strokes must be array';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateInsertGenerate(msg) {
|
||||
if (!msg.insert || typeof msg.insert !== 'object') return 'generate: insert mode requires insert object';
|
||||
if (!INSERT_POSITIONS.has(msg.insert.position)) return 'generate: insert.position must be before or after';
|
||||
const anchor = msg.insert.anchor;
|
||||
if (!anchor || typeof anchor !== 'object') return 'generate: insert.anchor required';
|
||||
if (!anchor.tagName && !anchor.outerHTML && !(Array.isArray(anchor.classes) && anchor.classes.length)) {
|
||||
return 'generate: insert.anchor needs tagName, classes, or outerHTML';
|
||||
}
|
||||
if (!msg.placeholder || typeof msg.placeholder !== 'object') return 'generate: insert mode requires placeholder dimensions';
|
||||
if (!Number.isFinite(msg.placeholder.width) || !Number.isFinite(msg.placeholder.height)) {
|
||||
return 'generate: placeholder width and height must be numbers';
|
||||
}
|
||||
if (!canCreateInsert({
|
||||
prompt: msg.freeformPrompt,
|
||||
comments: msg.comments,
|
||||
strokes: msg.strokes,
|
||||
})) {
|
||||
return 'generate: insert requires freeformPrompt or annotations';
|
||||
}
|
||||
return validateAnnotationFields(msg);
|
||||
}
|
||||
|
||||
function validateReplaceGenerate(msg) {
|
||||
if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
|
||||
if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
|
||||
return validateAnnotationFields(msg);
|
||||
}
|
||||
|
||||
export function validateEvent(msg) {
|
||||
if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
|
||||
switch (msg.type) {
|
||||
case 'generate':
|
||||
if (!isValidId(msg.id)) return 'generate: missing or malformed id';
|
||||
if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
|
||||
if (msg.mode === 'insert') return validateInsertGenerate(msg);
|
||||
return validateReplaceGenerate(msg);
|
||||
case 'accept':
|
||||
if (!isValidId(msg.id)) return 'accept: missing or malformed id';
|
||||
if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
|
||||
if (msg.paramValues !== undefined) {
|
||||
if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
|
||||
return 'accept: paramValues must be an object';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
case 'discard':
|
||||
return isValidId(msg.id) ? null : 'discard: missing or malformed id';
|
||||
case 'checkpoint':
|
||||
if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
|
||||
if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
|
||||
if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
|
||||
return 'checkpoint: paramValues must be an object';
|
||||
}
|
||||
return null;
|
||||
case 'exit':
|
||||
return null;
|
||||
case 'prefetch':
|
||||
if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
|
||||
return null;
|
||||
case 'steer':
|
||||
if (!isValidId(msg.id)) return 'steer: missing or malformed id';
|
||||
if (typeof msg.message !== 'string' || !msg.message.trim()) return 'steer: message required';
|
||||
if (msg.message.length > 4000) return 'steer: message too long';
|
||||
if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';
|
||||
return null;
|
||||
default:
|
||||
return 'Unknown event type: ' + msg.type;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
/**
|
||||
* Pure helpers for live-mode insert UI (browser + tests).
|
||||
* Kept separate from live-browser.js so insert logic is unit-testable.
|
||||
*/
|
||||
|
||||
export const PLACEHOLDER_DEFAULT_HEIGHT = 80;
|
||||
export const PLACEHOLDER_MIN_HEIGHT = 48;
|
||||
export const PLACEHOLDER_MIN_WIDTH = 120;
|
||||
|
||||
/** @typedef {'before' | 'after'} InsertPosition */
|
||||
/** @typedef {'row' | 'column'} InsertAxis */
|
||||
|
||||
/**
|
||||
* Infer sibling flow axis from a container's computed layout styles.
|
||||
* @param {{ display?: string, flexDirection?: string, gridTemplateColumns?: string, gridAutoFlow?: string }} style
|
||||
* @returns {InsertAxis}
|
||||
*/
|
||||
export function detectInsertAxisFromStyle(style) {
|
||||
const display = style?.display || 'block';
|
||||
if (display.includes('flex')) {
|
||||
const dir = style.flexDirection || 'row';
|
||||
return dir.startsWith('row') ? 'row' : 'column';
|
||||
}
|
||||
if (display === 'grid' || display === 'inline-grid') {
|
||||
const flow = style.gridAutoFlow || 'row';
|
||||
if (flow.includes('column')) return 'column';
|
||||
const cols = (style.gridTemplateColumns || '').trim();
|
||||
if (cols && cols !== 'none') {
|
||||
const colCount = cols.split(/\s+/).filter(Boolean).length;
|
||||
if (colCount > 1) return 'row';
|
||||
}
|
||||
return 'row';
|
||||
}
|
||||
return 'column';
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick insertion side from pointer position against an anchor element box.
|
||||
* @param {number} clientX
|
||||
* @param {number} clientY
|
||||
* @param {{ top: number, left: number, width: number, height: number, bottom?: number, right?: number }} rect
|
||||
* @param {InsertAxis} [axis]
|
||||
* @returns {InsertPosition}
|
||||
*/
|
||||
export function computeInsertPosition(clientX, clientY, rect, axis = 'column') {
|
||||
if (!rect) return 'after';
|
||||
if (axis === 'row') {
|
||||
if (!Number.isFinite(rect.left) || !Number.isFinite(rect.width) || rect.width <= 0) return 'after';
|
||||
const mid = rect.left + rect.width / 2;
|
||||
return clientX < mid ? 'before' : 'after';
|
||||
}
|
||||
if (!Number.isFinite(rect.top) || !Number.isFinite(rect.height) || rect.height <= 0) return 'after';
|
||||
const mid = rect.top + rect.height / 2;
|
||||
return clientY < mid ? 'before' : 'after';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Create is allowed for an insert session.
|
||||
* Requires a non-empty prompt OR at least one annotation.
|
||||
*/
|
||||
export function canCreateInsert({ prompt, comments, strokes }) {
|
||||
const hasPrompt = typeof prompt === 'string' && prompt.trim().length > 0;
|
||||
const hasComments = Array.isArray(comments) && comments.length > 0;
|
||||
const hasStrokes = Array.isArray(strokes) && strokes.some(
|
||||
(s) => Array.isArray(s?.points) && s.points.length >= 2,
|
||||
);
|
||||
return hasPrompt || hasComments || hasStrokes;
|
||||
}
|
||||
|
||||
/** Tooltip/title when Create is disabled. */
|
||||
export function insertCreateDisabledReason({ prompt, comments, strokes }) {
|
||||
if (canCreateInsert({ prompt, comments, strokes })) return null;
|
||||
return 'Add a prompt or annotate the placeholder to create';
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixed-position insert line coordinates (viewport px).
|
||||
* @param {{ top: number, left: number, width: number, height: number, bottom?: number, right?: number }} rect
|
||||
* @param {InsertPosition} position
|
||||
* @param {InsertAxis} [axis]
|
||||
*/
|
||||
export function insertLineCoords(rect, position, axis = 'column') {
|
||||
if (axis === 'row') {
|
||||
const right = rect.right ?? rect.left + rect.width;
|
||||
const x = position === 'before' ? rect.left - 2 : right + 2;
|
||||
return { axis: 'row', top: rect.top, left: x, width: 0, height: rect.height };
|
||||
}
|
||||
const bottom = rect.bottom ?? rect.top + rect.height;
|
||||
const y = position === 'before' ? rect.top - 2 : bottom + 2;
|
||||
return { axis: 'column', top: y, left: rect.left, width: rect.width, height: 0 };
|
||||
}
|
||||
|
||||
/** Cursor while hovering an insert boundary. */
|
||||
export function cursorForInsertAxis(axis) {
|
||||
return axis === 'row' ? 'ew-resize' : 'ns-resize';
|
||||
}
|
||||
|
||||
function groupSiblingRows(siblings, rowThreshold = 8) {
|
||||
const sorted = [...siblings].sort((a, b) => a.rect.top - b.rect.top || a.rect.left - b.rect.left);
|
||||
const rows = [];
|
||||
for (const entry of sorted) {
|
||||
let placed = false;
|
||||
for (const row of rows) {
|
||||
if (Math.abs(entry.rect.top - row[0].rect.top) <= rowThreshold) {
|
||||
row.push(entry);
|
||||
placed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!placed) rows.push([entry]);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function horizontalOverlap(a, b) {
|
||||
const left = Math.max(a.left, b.left);
|
||||
const right = Math.min(a.right ?? a.left + a.width, b.right ?? b.left + b.width);
|
||||
return Math.max(0, right - left);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hit-test the gap between adjacent siblings (flex rows, grid columns, stacked blocks).
|
||||
* @param {number} clientX
|
||||
* @param {number} clientY
|
||||
* @param {Array<{ el: unknown, rect: { top: number, left: number, width: number, height: number, bottom?: number, right?: number } }>} siblings
|
||||
* @param {{ slop?: number, minOverlap?: number }} [opts]
|
||||
*/
|
||||
export function hitSiblingInsertGap(clientX, clientY, siblings, opts = {}) {
|
||||
if (!Array.isArray(siblings) || siblings.length < 2) return null;
|
||||
const slop = opts.slop ?? 12;
|
||||
const minOverlap = opts.minOverlap ?? 0.25;
|
||||
|
||||
for (const row of groupSiblingRows(siblings)) {
|
||||
if (row.length < 2) continue;
|
||||
const sorted = [...row].sort((a, b) => a.rect.left - b.rect.left);
|
||||
for (let i = 0; i < sorted.length - 1; i++) {
|
||||
const a = sorted[i];
|
||||
const b = sorted[i + 1];
|
||||
const aRight = a.rect.right ?? a.rect.left + a.rect.width;
|
||||
const bLeft = b.rect.left;
|
||||
if (bLeft <= aRight) continue;
|
||||
const top = Math.max(a.rect.top, b.rect.top);
|
||||
const aBottom = a.rect.bottom ?? a.rect.top + a.rect.height;
|
||||
const bBottom = b.rect.bottom ?? b.rect.top + b.rect.height;
|
||||
const bottom = Math.min(aBottom, bBottom);
|
||||
const span = bottom - top;
|
||||
const minH = Math.min(a.rect.height, b.rect.height);
|
||||
if (span < minH * minOverlap) continue;
|
||||
|
||||
const inX = clientX >= aRight - slop && clientX <= bLeft + slop;
|
||||
const inY = clientY >= top - slop && clientY <= bottom + slop;
|
||||
if (!inX || !inY) continue;
|
||||
|
||||
const midX = (aRight + bLeft) / 2;
|
||||
return {
|
||||
anchor: b.el,
|
||||
position: 'before',
|
||||
axis: 'row',
|
||||
line: { axis: 'row', left: midX, top, width: 0, height: span },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const sortedCol = [...siblings].sort((a, b) => a.rect.top - b.rect.top || a.rect.left - b.rect.left);
|
||||
for (let i = 0; i < sortedCol.length - 1; i++) {
|
||||
const a = sortedCol[i];
|
||||
const b = sortedCol[i + 1];
|
||||
const overlap = horizontalOverlap(a.rect, b.rect);
|
||||
const minW = Math.min(a.rect.width, b.rect.width);
|
||||
if (overlap < minW * minOverlap) continue;
|
||||
|
||||
const aBottom = a.rect.bottom ?? a.rect.top + a.rect.height;
|
||||
const gapTop = aBottom;
|
||||
const gapBottom = b.rect.top;
|
||||
if (gapBottom <= gapTop) continue;
|
||||
|
||||
const overlapLeft = Math.max(a.rect.left, b.rect.left);
|
||||
const overlapRight = Math.min(
|
||||
a.rect.right ?? a.rect.left + a.rect.width,
|
||||
b.rect.right ?? b.rect.left + b.rect.width,
|
||||
);
|
||||
const inY = clientY >= gapTop - slop && clientY <= gapBottom + slop;
|
||||
const inX = clientX >= overlapLeft - slop && clientX <= overlapRight + slop;
|
||||
if (!inY || !inX) continue;
|
||||
|
||||
const midY = (gapTop + gapBottom) / 2;
|
||||
return {
|
||||
anchor: b.el,
|
||||
position: 'before',
|
||||
axis: 'column',
|
||||
line: { axis: 'column', top: midY, left: overlapLeft, width: overlap, height: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve insert hover target, side, axis, and indicator line for the pointer.
|
||||
*/
|
||||
export function resolveInsertHover({ clientX, clientY, target, rect, axis, siblings }) {
|
||||
const gap = hitSiblingInsertGap(clientX, clientY, siblings);
|
||||
if (gap) return gap;
|
||||
|
||||
const position = computeInsertPosition(clientX, clientY, rect, axis);
|
||||
const line = insertLineCoords(rect, position, axis);
|
||||
return { anchor: target, position, axis, line };
|
||||
}
|
||||
|
||||
/**
|
||||
* How the in-flow placeholder should participate in layout.
|
||||
* Prefer implicit sizing (flex / %) so row inserts don't inherit the full parent width in px.
|
||||
* @returns {{ kind: 'flex', flex: string, minWidth: number } | { kind: 'percent' } | { kind: 'auto' } | { kind: 'explicit', width: number }}
|
||||
*/
|
||||
export function placeholderSizing({ axis, parentDisplay, parentWidth, anchorFlex }) {
|
||||
const display = parentDisplay || 'block';
|
||||
const w = Number.isFinite(parentWidth) ? parentWidth : 0;
|
||||
|
||||
if (axis === 'row') {
|
||||
if (display.includes('flex')) {
|
||||
const flex = anchorFlex && anchorFlex !== 'none' && anchorFlex !== '0 1 auto'
|
||||
? anchorFlex
|
||||
: '1 1 0';
|
||||
return { kind: 'flex', flex, minWidth: 0 };
|
||||
}
|
||||
if (display === 'grid' || display === 'inline-grid') {
|
||||
return { kind: 'auto' };
|
||||
}
|
||||
}
|
||||
|
||||
if (w >= PLACEHOLDER_MIN_WIDTH) {
|
||||
return { kind: 'percent' };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'explicit',
|
||||
width: Math.max(PLACEHOLDER_MIN_WIDTH, w || PLACEHOLDER_MIN_WIDTH),
|
||||
};
|
||||
}
|
||||
|
||||
/** Width kinds that need materializing to px before edge-resize. */
|
||||
export function placeholderWidthIsImplicit(kind) {
|
||||
return kind === 'flex' || kind === 'percent' || kind === 'auto';
|
||||
}
|
||||
|
||||
/**
|
||||
* Clamp user-resized placeholder dimensions.
|
||||
*/
|
||||
export function clampPlaceholderSize(width, height, parentWidth, opts = {}) {
|
||||
const minW = opts.minWidth ?? PLACEHOLDER_MIN_WIDTH;
|
||||
const minH = opts.minHeight ?? PLACEHOLDER_MIN_HEIGHT;
|
||||
const maxW = opts.maxWidth ?? Math.max(minW, parentWidth || minW);
|
||||
return {
|
||||
width: Math.min(maxW, Math.max(minW, Math.round(width))),
|
||||
height: Math.max(minH, Math.round(height)),
|
||||
};
|
||||
}
|
||||
|
||||
/** CSS cursor for a placeholder edge resize handle. */
|
||||
export function cursorForPlaceholderEdge(edge) {
|
||||
if (edge === 'n' || edge === 's') return 'ns-resize';
|
||||
if (edge === 'e' || edge === 'w') return 'ew-resize';
|
||||
return 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute placeholder box after dragging one edge (in-flow margins shift for n/w).
|
||||
* @param {{ width: number, height: number, marginLeft?: number, marginTop?: number }} start
|
||||
* @param {'n'|'e'|'s'|'w'} edge
|
||||
* @param {number} dx pointer delta X since drag start
|
||||
* @param {number} dy pointer delta Y since drag start
|
||||
* @param {number} parentWidth
|
||||
*/
|
||||
export function resizePlaceholderFromEdge(start, edge, dx, dy, parentWidth, opts = {}) {
|
||||
const base = {
|
||||
width: start.width,
|
||||
height: start.height,
|
||||
marginLeft: start.marginLeft ?? 0,
|
||||
marginTop: start.marginTop ?? 0,
|
||||
};
|
||||
if (edge === 'e') base.width = start.width + dx;
|
||||
else if (edge === 'w') {
|
||||
base.width = start.width - dx;
|
||||
base.marginLeft = start.marginLeft + dx;
|
||||
} else if (edge === 's') base.height = start.height + dy;
|
||||
else if (edge === 'n') {
|
||||
base.height = start.height - dy;
|
||||
base.marginTop = start.marginTop + dy;
|
||||
}
|
||||
|
||||
const clamped = clampPlaceholderSize(base.width, base.height, parentWidth, opts);
|
||||
if (edge === 'w') {
|
||||
base.marginLeft = start.marginLeft + start.width - clamped.width;
|
||||
} else if (edge === 'n') {
|
||||
base.marginTop = start.marginTop + start.height - clamped.height;
|
||||
}
|
||||
|
||||
return {
|
||||
width: clamped.width,
|
||||
height: clamped.height,
|
||||
marginLeft: Math.round(base.marginLeft),
|
||||
marginTop: Math.round(base.marginTop),
|
||||
};
|
||||
}
|
||||
|
||||
/** Pick and insert toggles are independent but turning one ON turns the other OFF. */
|
||||
export function applyPickToggle(pickActive, insertActive) {
|
||||
const nextPick = !pickActive;
|
||||
return {
|
||||
pickActive: nextPick,
|
||||
insertActive: nextPick ? false : insertActive,
|
||||
};
|
||||
}
|
||||
|
||||
export function applyInsertToggle(pickActive, insertActive) {
|
||||
const nextInsert = !insertActive;
|
||||
return {
|
||||
pickActive: nextInsert ? false : pickActive,
|
||||
insertActive: nextInsert,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the browser generate payload for insert mode.
|
||||
*/
|
||||
export function buildInsertGeneratePayload({
|
||||
id,
|
||||
count,
|
||||
pageUrl,
|
||||
anchorContext,
|
||||
position,
|
||||
placeholder,
|
||||
freeformPrompt,
|
||||
comments,
|
||||
strokes,
|
||||
screenshotPath,
|
||||
}) {
|
||||
const payload = {
|
||||
type: 'generate',
|
||||
mode: 'insert',
|
||||
id,
|
||||
count,
|
||||
pageUrl,
|
||||
insert: {
|
||||
position,
|
||||
anchor: anchorContext,
|
||||
},
|
||||
placeholder,
|
||||
freeformPrompt: freeformPrompt?.trim() || undefined,
|
||||
};
|
||||
if (comments?.length) payload.comments = comments;
|
||||
if (strokes?.length) payload.strokes = strokes;
|
||||
if (screenshotPath) payload.screenshotPath = screenshotPath;
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a variant wrapper is currently shown (handles `hidden` and display:none).
|
||||
* @param {{ hidden?: boolean, style?: { display?: string } } | null | undefined} el
|
||||
*/
|
||||
export function isVariantShown(el) {
|
||||
if (!el) return false;
|
||||
if (el.hidden) return false;
|
||||
if (el.style?.display === 'none') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show or hide a variant wrapper for cycling.
|
||||
* @param {{ hidden?: boolean, style?: { display?: string }, removeAttribute?: (name: string) => void, setAttribute?: (name: string, value?: string) => void } | null | undefined} el
|
||||
* @param {boolean} shown
|
||||
*/
|
||||
export function setVariantShown(el, shown) {
|
||||
if (!el) return;
|
||||
if (shown) {
|
||||
el.removeAttribute?.('hidden');
|
||||
if (el.style) el.style.display = '';
|
||||
} else {
|
||||
el.setAttribute?.('hidden', '');
|
||||
if (el.style) el.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the best live anchor during an insert session (placeholder until variants land).
|
||||
* @param {{
|
||||
* wrapper?: unknown,
|
||||
* variantCount?: number,
|
||||
* visibleVariant?: number,
|
||||
* placeholder?: unknown,
|
||||
* insertAnchor?: unknown,
|
||||
* pickVariantContent?: (wrapper: unknown, index: number) => unknown,
|
||||
* }} opts
|
||||
*/
|
||||
export function resolveInsertSessionAnchor(opts) {
|
||||
const {
|
||||
wrapper,
|
||||
variantCount = 0,
|
||||
visibleVariant = 0,
|
||||
placeholder,
|
||||
insertAnchor,
|
||||
pickVariantContent,
|
||||
} = opts || {};
|
||||
if (wrapper && variantCount > 0 && visibleVariant > 0 && pickVariantContent) {
|
||||
const vis = pickVariantContent(wrapper, visibleVariant);
|
||||
if (vis) return vis;
|
||||
}
|
||||
return placeholder || insertAnchor || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot placeholder geometry + anchor fingerprint so HMR can recreate the box.
|
||||
* @param {{
|
||||
* tagName?: string,
|
||||
* className?: string,
|
||||
* textContent?: string,
|
||||
* }} anchor
|
||||
* @param {{
|
||||
* offsetWidth?: number,
|
||||
* offsetHeight?: number,
|
||||
* style?: { marginLeft?: string, marginTop?: string },
|
||||
* }} placeholder
|
||||
* @param {{ position: 'before' | 'after', layoutAxis?: 'row' | 'column' }} meta
|
||||
*/
|
||||
export function buildInsertPlaceholderSnapshot(anchor, placeholder, { position, layoutAxis }) {
|
||||
return {
|
||||
width: Math.round(placeholder.offsetWidth || 0),
|
||||
height: Math.round(placeholder.offsetHeight || PLACEHOLDER_DEFAULT_HEIGHT),
|
||||
marginLeft: parseFloat(placeholder.style?.marginLeft || '') || 0,
|
||||
marginTop: parseFloat(placeholder.style?.marginTop || '') || 0,
|
||||
position,
|
||||
layoutAxis: layoutAxis || 'column',
|
||||
anchorTag: anchor.tagName || 'DIV',
|
||||
anchorClasses: anchor.className || '',
|
||||
anchorText: (anchor.textContent || '').trim().slice(0, 120),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-find an insert anchor after framework HMR replaced the live DOM node.
|
||||
* @param {Pick<Document, 'body' | 'querySelectorAll'>} doc
|
||||
* @param {ReturnType<typeof buildInsertPlaceholderSnapshot> | null | undefined} snapshot
|
||||
* @param {Element | null | undefined} liveAnchor
|
||||
*/
|
||||
export function findInsertAnchorInDom(doc, snapshot, liveAnchor = null) {
|
||||
if (liveAnchor && doc.body.contains(liveAnchor)) return liveAnchor;
|
||||
if (!snapshot) return null;
|
||||
const tag = (snapshot.anchorTag || 'div').toLowerCase();
|
||||
const cls = (snapshot.anchorClasses || '').split(/\s+/).filter(Boolean)[0];
|
||||
const needle = snapshot.anchorText || '';
|
||||
const sel = cls ? `${tag}.${cls}` : tag;
|
||||
const candidates = doc.querySelectorAll(sel);
|
||||
for (const candidate of candidates) {
|
||||
if (needle && !(candidate.textContent || '').includes(needle.slice(0, 40))) continue;
|
||||
return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
/**
|
||||
* CLI helper: find an anchor element in source and splice an insert-variant
|
||||
* wrapper before or after it (no original variant — net-new content).
|
||||
*
|
||||
* Usage:
|
||||
* node live-insert.mjs --id SESSION_ID --count N --position after \
|
||||
* --classes "hero" --tag section [--file path]
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { isGeneratedFile } from './is-generated.mjs';
|
||||
import {
|
||||
buildSearchQueries,
|
||||
findElement,
|
||||
findAllElements,
|
||||
filterByText,
|
||||
findFileWithQuery,
|
||||
detectCommentSyntax,
|
||||
detectStyleMode,
|
||||
buildCssAuthoring,
|
||||
buildCssSelectorPrefixExamples,
|
||||
} from './live-wrap.mjs';
|
||||
|
||||
const INSERT_POSITIONS = new Set(['before', 'after']);
|
||||
|
||||
export function isInsertPosition(value) {
|
||||
return INSERT_POSITIONS.has(value);
|
||||
}
|
||||
|
||||
export function computeInsertLine(startLine, endLine, position) {
|
||||
return position === 'before' ? startLine : endLine + 1;
|
||||
}
|
||||
|
||||
export function buildInsertWrapperLines({ id, count, indent, commentSyntax, isJsx }) {
|
||||
const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
|
||||
const attrs =
|
||||
'data-impeccable-variants="' + id + '" ' +
|
||||
'data-impeccable-mode="insert" ' +
|
||||
'data-impeccable-variant-count="' + count + '" ' +
|
||||
styleContents;
|
||||
|
||||
if (isJsx) {
|
||||
return [
|
||||
indent + '<div ' + attrs + '>',
|
||||
indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
|
||||
indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
|
||||
indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
|
||||
indent + '</div>',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
|
||||
indent + '<div ' + attrs + '>',
|
||||
indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
|
||||
indent + '</div>',
|
||||
indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
|
||||
];
|
||||
}
|
||||
|
||||
function argVal(args, flag) {
|
||||
const idx = args.indexOf(flag);
|
||||
return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
|
||||
}
|
||||
|
||||
function resolveElementMatch({ lines, queries, tag, text }) {
|
||||
if (text) {
|
||||
const candidates = [];
|
||||
for (const q of queries) {
|
||||
const all = findAllElements(lines, q, tag);
|
||||
for (const c of all) {
|
||||
if (!candidates.some((x) => x.startLine === c.startLine)) candidates.push(c);
|
||||
}
|
||||
if (candidates.length === 1) break;
|
||||
}
|
||||
if (candidates.length === 0) return { error: 'element_not_found' };
|
||||
if (candidates.length === 1) return { match: candidates[0] };
|
||||
const filtered = filterByText(candidates, lines, text);
|
||||
if (filtered.length === 1) return { match: filtered[0] };
|
||||
if (filtered.length === 0) return { match: candidates[0] };
|
||||
return { error: 'element_ambiguous', candidates: filtered };
|
||||
}
|
||||
|
||||
for (const q of queries) {
|
||||
const match = findElement(lines, q, tag);
|
||||
if (match) return { match };
|
||||
}
|
||||
return { error: 'element_not_found' };
|
||||
}
|
||||
|
||||
export async function insertCli() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.includes('--help') || args.includes('-h')) {
|
||||
console.log(`Usage: node live-insert.mjs [options]
|
||||
|
||||
Find an anchor element in source and splice an insert-variant wrapper.
|
||||
|
||||
Required:
|
||||
--id ID Session ID for the variant wrapper
|
||||
--count N Number of expected variants (1-8)
|
||||
--position POS before | after (relative to the anchor element)
|
||||
|
||||
Element identification (at least one required):
|
||||
--element-id ID HTML id attribute of the anchor element
|
||||
--classes A,B,C Comma-separated CSS class names
|
||||
--tag TAG Tag name (div, section, etc.)
|
||||
--query TEXT Fallback: raw text to search for
|
||||
|
||||
Optional:
|
||||
--file PATH Source file to search in (skips auto-detection)
|
||||
--text TEXT Anchor textContent for disambiguation (~80 chars)
|
||||
|
||||
Output (JSON):
|
||||
{ mode: "insert", file, position, insertLine, commentSyntax, styleMode, styleTag, cssAuthoring }`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const id = argVal(args, '--id');
|
||||
const count = parseInt(argVal(args, '--count') || '3', 10);
|
||||
const position = argVal(args, '--position');
|
||||
const elementId = argVal(args, '--element-id');
|
||||
const classes = argVal(args, '--classes');
|
||||
const tag = argVal(args, '--tag');
|
||||
const query = argVal(args, '--query');
|
||||
const filePath = argVal(args, '--file');
|
||||
const text = argVal(args, '--text');
|
||||
|
||||
if (!id) { console.error('Missing --id'); process.exit(1); }
|
||||
if (!position) { console.error('Missing --position (before | after)'); process.exit(1); }
|
||||
if (!isInsertPosition(position)) { console.error('Invalid --position: ' + position); process.exit(1); }
|
||||
if (!elementId && !classes && !query) {
|
||||
console.error('Need at least one of: --element-id, --classes, --query');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const queries = buildSearchQueries(elementId, classes, tag, query);
|
||||
const genOpts = { cwd: process.cwd() };
|
||||
|
||||
let targetFile = filePath;
|
||||
if (!targetFile) {
|
||||
for (const q of queries) {
|
||||
targetFile = findFileWithQuery(q, process.cwd(), genOpts);
|
||||
if (targetFile) break;
|
||||
}
|
||||
if (!targetFile) {
|
||||
let generatedHit = null;
|
||||
for (const q of queries) {
|
||||
generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
|
||||
if (generatedHit) break;
|
||||
}
|
||||
console.error(JSON.stringify({
|
||||
error: generatedHit ? 'element_not_in_source' : 'element_not_found',
|
||||
fallback: 'agent-driven',
|
||||
hint: 'See "Handle fallback" in live.md.',
|
||||
}));
|
||||
process.exit(1);
|
||||
}
|
||||
} else if (isGeneratedFile(targetFile, genOpts)) {
|
||||
console.error(JSON.stringify({
|
||||
error: 'file_is_generated',
|
||||
fallback: 'agent-driven',
|
||||
file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
|
||||
}));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(targetFile, 'utf-8');
|
||||
const lines = content.split('\n');
|
||||
const resolved = resolveElementMatch({ lines, queries, tag, text });
|
||||
|
||||
if (resolved.error === 'element_ambiguous') {
|
||||
console.error(JSON.stringify({
|
||||
error: 'element_ambiguous',
|
||||
fallback: 'agent-driven',
|
||||
file: path.relative(process.cwd(), targetFile),
|
||||
candidates: resolved.candidates.map((c) => ({
|
||||
startLine: c.startLine + 1,
|
||||
endLine: c.endLine + 1,
|
||||
})),
|
||||
}));
|
||||
process.exit(1);
|
||||
}
|
||||
if (!resolved.match) {
|
||||
console.error(JSON.stringify({ error: 'element_not_found', fallback: 'agent-driven' }));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { startLine, endLine } = resolved.match;
|
||||
const commentSyntax = detectCommentSyntax(targetFile);
|
||||
const styleMode = detectStyleMode(targetFile);
|
||||
const isJsx = commentSyntax.open === '{/*';
|
||||
const spliceIndex = computeInsertLine(startLine, endLine, position);
|
||||
const indent = lines[spliceIndex]?.match(/^(\s*)/)?.[1]
|
||||
?? lines[startLine]?.match(/^(\s*)/)?.[1]
|
||||
?? '';
|
||||
|
||||
const wrapperLines = buildInsertWrapperLines({
|
||||
id,
|
||||
count,
|
||||
indent,
|
||||
commentSyntax,
|
||||
isJsx,
|
||||
});
|
||||
|
||||
const newLines = [
|
||||
...lines.slice(0, spliceIndex),
|
||||
...wrapperLines,
|
||||
...lines.slice(spliceIndex),
|
||||
];
|
||||
fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
|
||||
|
||||
const insertLine = spliceIndex + 3;
|
||||
|
||||
console.log(JSON.stringify({
|
||||
mode: 'insert',
|
||||
position,
|
||||
file: path.relative(process.cwd(), targetFile),
|
||||
insertLine: insertLine + 1,
|
||||
commentSyntax,
|
||||
styleMode: styleMode.mode,
|
||||
styleTag: styleMode.styleTag,
|
||||
cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
|
||||
cssAuthoring: buildCssAuthoring(styleMode, count),
|
||||
}));
|
||||
}
|
||||
|
||||
const _running = process.argv[1];
|
||||
if (_running?.endsWith('live-insert.mjs') || _running?.endsWith('live-insert.mjs/')) {
|
||||
insertCli();
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
*
|
||||
* Usage:
|
||||
* npx impeccable poll # Block until browser event, print JSON
|
||||
* npx impeccable poll --stream # Experimental: keep polling; one JSON line per event
|
||||
* npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
|
||||
* npx impeccable poll --reply <id> done # Reply "done" to event <id>
|
||||
* npx impeccable poll --reply <id> error "msg" # Reply with error
|
||||
@@ -18,7 +19,9 @@ import { readLiveServerInfo } from './impeccable-paths.mjs';
|
||||
// timeout that can't be lowered per-request. We cap each request below
|
||||
// that ceiling and loop in `pollOnce` to synthesize a long poll without
|
||||
// depending on the standalone undici package.
|
||||
const PER_REQUEST_TIMEOUT_MS = 270_000;
|
||||
export const PER_REQUEST_TIMEOUT_MS = 270_000;
|
||||
|
||||
const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer']);
|
||||
|
||||
function readServerInfo() {
|
||||
const record = readLiveServerInfo(process.cwd());
|
||||
@@ -33,7 +36,11 @@ export function buildPollReplyPayload(token, { id, type, message, file, data })
|
||||
return { token, id, type, message, file, data };
|
||||
}
|
||||
|
||||
async function postReply(base, token, reply) {
|
||||
export function requiresAgentReply(event) {
|
||||
return EVENT_TYPES_NEEDING_AGENT_REPLY.has(event?.type);
|
||||
}
|
||||
|
||||
export async function postReply(base, token, reply) {
|
||||
const res = await fetch(`${base}/poll`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -45,6 +52,178 @@ async function postReply(base, token, reply) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchServerStatus(base, token) {
|
||||
const res = await fetch(`${base}/status?token=${token}`);
|
||||
if (res.status === 401) {
|
||||
const err = new Error('Authentication failed. The server token may have changed.');
|
||||
err.code = 'AUTH_FAILED';
|
||||
throw err;
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(`Status failed: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export function isEventPending(status, eventId) {
|
||||
return (status.pendingEvents || []).some((entry) => entry.id === eventId);
|
||||
}
|
||||
|
||||
export async function waitForEventAck(base, token, eventId, {
|
||||
pollIntervalMs = 400,
|
||||
maxWaitMs = 600_000,
|
||||
} = {}) {
|
||||
const deadline = Date.now() + maxWaitMs;
|
||||
while (Date.now() < deadline) {
|
||||
const status = await fetchServerStatus(base, token);
|
||||
if (!isEventPending(status, eventId)) return true;
|
||||
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function fetchNextEvent(base, token, { totalDeadline } = {}) {
|
||||
while (true) {
|
||||
if (totalDeadline && Date.now() >= totalDeadline) {
|
||||
return { type: 'timeout' };
|
||||
}
|
||||
|
||||
const remaining = totalDeadline
|
||||
? totalDeadline - Date.now()
|
||||
: PER_REQUEST_TIMEOUT_MS;
|
||||
const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);
|
||||
const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}`);
|
||||
|
||||
if (res.status === 401) {
|
||||
const err = new Error('Authentication failed. The server token may have changed.');
|
||||
err.code = 'AUTH_FAILED';
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Poll failed: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const next = await res.json();
|
||||
if (next?.type === 'timeout') {
|
||||
if (totalDeadline && Date.now() < totalDeadline) continue;
|
||||
if (!totalDeadline) continue;
|
||||
return next;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
export async function augmentEventWithAcceptHandling(event, base, token) {
|
||||
if (event.type !== 'accept' && event.type !== 'discard') return event;
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const acceptScript = path.join(__dirname, 'live-accept.mjs');
|
||||
const scriptArgs = event.type === 'discard'
|
||||
? ['--id', event.id, '--discard']
|
||||
: ['--id', event.id, '--variant', event.variantId];
|
||||
if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
|
||||
scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
|
||||
}
|
||||
|
||||
try {
|
||||
const out = execFileSync(
|
||||
'node',
|
||||
[acceptScript, ...scriptArgs],
|
||||
{ encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 },
|
||||
);
|
||||
event._acceptResult = JSON.parse(out.trim());
|
||||
} catch (err) {
|
||||
event._acceptResult = { handled: false, mode: 'error', error: err.message };
|
||||
}
|
||||
|
||||
const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
|
||||
try {
|
||||
await postReply(base, token, {
|
||||
id: event.id,
|
||||
type: completionType,
|
||||
message: event._acceptResult?.error,
|
||||
file: event._acceptResult?.file,
|
||||
data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
|
||||
});
|
||||
} catch (err) {
|
||||
event._completionAck = { ok: false, error: err.message };
|
||||
}
|
||||
if (!event._completionAck) {
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
export function writeCarbonizeBanner(event) {
|
||||
if (event._acceptResult?.carbonize === true) {
|
||||
process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
|
||||
}
|
||||
}
|
||||
|
||||
export function printPollEvent(event) {
|
||||
console.log(JSON.stringify(event));
|
||||
}
|
||||
|
||||
export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {
|
||||
const deadline = Date.now() + totalTimeout;
|
||||
const event = await fetchNextEvent(base, token, { totalDeadline: deadline });
|
||||
await augmentEventWithAcceptHandling(event, base, token);
|
||||
writeCarbonizeBanner(event);
|
||||
printPollEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
export async function runPollStream(base, token, {
|
||||
ackTimeoutMs = 600_000,
|
||||
ackPollIntervalMs = 400,
|
||||
shouldContinue = () => true,
|
||||
} = {}) {
|
||||
process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');
|
||||
|
||||
while (shouldContinue()) {
|
||||
const event = await fetchNextEvent(base, token);
|
||||
await augmentEventWithAcceptHandling(event, base, token);
|
||||
writeCarbonizeBanner(event);
|
||||
printPollEvent(event);
|
||||
|
||||
if (event.type === 'exit') return event;
|
||||
|
||||
if (requiresAgentReply(event)) {
|
||||
const acked = await waitForEventAck(base, token, event.id, {
|
||||
pollIntervalMs: ackPollIntervalMs,
|
||||
maxWaitMs: ackTimeoutMs,
|
||||
});
|
||||
if (!acked) {
|
||||
const err = new Error(`Timed out waiting for --reply on event ${event.id}`);
|
||||
err.code = 'ACK_TIMEOUT';
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function handlePollError(err) {
|
||||
if (err.code === 'AUTH_FAILED') {
|
||||
console.error(err.message);
|
||||
console.error('Try restarting: npx impeccable live stop && npx impeccable live');
|
||||
process.exit(1);
|
||||
}
|
||||
if (err.cause?.code === 'ECONNREFUSED') {
|
||||
console.error('Live server not running. Start one with: npx impeccable live');
|
||||
process.exit(1);
|
||||
}
|
||||
if (err.code === 'ACK_TIMEOUT') {
|
||||
console.error(err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
console.error('Poll failed:', err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
export async function pollCli() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
@@ -54,13 +233,20 @@ export async function pollCli() {
|
||||
Wait for a browser event from the live variant server, or reply to one.
|
||||
|
||||
Modes:
|
||||
poll Block until a browser event arrives, print JSON
|
||||
poll --reply <id> done Reply "done" to event <id>
|
||||
poll Block until a browser event arrives, print JSON, exit
|
||||
poll --stream Keep polling; print one JSON line per event (see live.md)
|
||||
poll --reply <id> done Reply "done" to event <id> (replace or insert generate)
|
||||
poll --reply <id> steer_done Reply after handling a steer event (unlocks Steer bar)
|
||||
poll --reply <id> error "msg" Reply with an error message
|
||||
|
||||
Options:
|
||||
--timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
|
||||
--help Show this help message`);
|
||||
--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode
|
||||
--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)
|
||||
--help Show this help message
|
||||
|
||||
Harness note:
|
||||
Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.
|
||||
--stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
@@ -74,7 +260,6 @@ Options:
|
||||
const status = args[replyIdx + 2] || 'done';
|
||||
const fileIdx = args.indexOf('--file');
|
||||
const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
|
||||
// Message is any remaining positional arg that isn't a flag
|
||||
const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
|
||||
|
||||
if (!id) {
|
||||
@@ -84,8 +269,6 @@ Options:
|
||||
|
||||
try {
|
||||
await postReply(base, info.token, { id, type: status, message, file: filePath });
|
||||
|
||||
// Success — silent exit (agent doesn't need output for replies)
|
||||
} catch (err) {
|
||||
if (err.cause?.code === 'ECONNREFUSED') {
|
||||
console.error('Live server not running. Start one with: npx impeccable live');
|
||||
@@ -97,99 +280,21 @@ Options:
|
||||
return;
|
||||
}
|
||||
|
||||
// Poll mode: block until browser event. Default 10 min. Node's built-in
|
||||
// fetch enforces a 300s headers timeout, so we loop in slices under that
|
||||
// ceiling and keep re-polling until we get a real event or the user's
|
||||
// total timeout runs out.
|
||||
const timeoutArg = args.find(a => a.startsWith('--timeout='));
|
||||
const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
|
||||
const streamMode = args.includes('--stream');
|
||||
const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));
|
||||
const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;
|
||||
|
||||
const deadline = Date.now() + totalTimeout;
|
||||
let event;
|
||||
try {
|
||||
while (true) {
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) {
|
||||
event = { type: 'timeout' };
|
||||
break;
|
||||
}
|
||||
const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
|
||||
const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
|
||||
|
||||
if (res.status === 401) {
|
||||
console.error('Authentication failed. The server token may have changed.');
|
||||
console.error('Try restarting: npx impeccable live stop && npx impeccable live');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
console.error(`Poll failed: ${res.status} ${res.statusText}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const next = await res.json();
|
||||
// Server-side timeout means no browser event arrived in this slice.
|
||||
// Loop and re-poll until we get a real event or we hit the user's
|
||||
// total deadline.
|
||||
if (next?.type === 'timeout' && Date.now() < deadline) continue;
|
||||
event = next;
|
||||
break;
|
||||
if (streamMode) {
|
||||
await runPollStream(base, info.token, { ackTimeoutMs });
|
||||
return;
|
||||
}
|
||||
|
||||
// Auto-handle accept/discard via deterministic script
|
||||
if (event.type === 'accept' || event.type === 'discard') {
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const acceptScript = path.join(__dirname, 'live-accept.mjs');
|
||||
const scriptArgs = event.type === 'discard'
|
||||
? ['--id', event.id, '--discard']
|
||||
: ['--id', event.id, '--variant', event.variantId];
|
||||
if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
|
||||
scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
|
||||
}
|
||||
try {
|
||||
const out = execFileSync(
|
||||
'node',
|
||||
[acceptScript, ...scriptArgs],
|
||||
{ encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
|
||||
);
|
||||
event._acceptResult = JSON.parse(out.trim());
|
||||
} catch (err) {
|
||||
event._acceptResult = { handled: false, mode: 'error', error: err.message };
|
||||
}
|
||||
|
||||
const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
|
||||
try {
|
||||
await postReply(base, info.token, {
|
||||
id: event.id,
|
||||
type: completionType,
|
||||
message: event._acceptResult?.error,
|
||||
file: event._acceptResult?.file,
|
||||
data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
|
||||
});
|
||||
} catch (err) {
|
||||
event._completionAck = { ok: false, error: err.message };
|
||||
}
|
||||
if (!event._completionAck) {
|
||||
event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
|
||||
}
|
||||
}
|
||||
|
||||
// Second signal path: stderr banner in case the agent parses stdout
|
||||
// JSON but skips nested fields. One line is enough — the full checklist
|
||||
// is in reference/live.md.
|
||||
if (event._acceptResult?.carbonize === true) {
|
||||
process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
|
||||
}
|
||||
|
||||
// Print the event as JSON — the agent reads this from stdout
|
||||
console.log(JSON.stringify(event));
|
||||
const timeoutArg = args.find((a) => a.startsWith('--timeout='));
|
||||
const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;
|
||||
await runPollOnce(base, info.token, { totalTimeout });
|
||||
} catch (err) {
|
||||
if (err.cause?.code === 'ECONNREFUSED') {
|
||||
console.error('Live server not running. Start one with: npx impeccable live');
|
||||
} else {
|
||||
console.error('Poll failed:', err.message);
|
||||
}
|
||||
process.exit(1);
|
||||
handlePollError(err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,8 +21,9 @@ import path from 'node:path';
|
||||
import net from 'node:net';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parseDesignMd } from './design-parser.mjs';
|
||||
import { resolveContextDir } from './load-context.mjs';
|
||||
import { resolveContextDir } from './context.mjs';
|
||||
import { createLiveSessionStore } from './live-session-store.mjs';
|
||||
import { validateEvent } from './live-event-validation.mjs';
|
||||
import {
|
||||
getDesignSidecarPath,
|
||||
getLiveAnnotationsDir,
|
||||
@@ -33,7 +34,7 @@ import {
|
||||
} from './impeccable-paths.mjs';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
|
||||
// PRODUCT.md / DESIGN.md live wherever context.mjs resolves. The generated
|
||||
// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
|
||||
// DESIGN.json fallback for existing projects.
|
||||
const CONTEXT_DIR = resolveContextDir(process.cwd());
|
||||
@@ -65,6 +66,7 @@ const state = {
|
||||
sseClients: new Set(), // SSE response objects (server→browser push)
|
||||
pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
|
||||
pendingPolls: [], // agent poll callbacks waiting for browser events
|
||||
lastAgentPollingBroadcast: null,
|
||||
exitTimer: null,
|
||||
sessionDir: null, // per-session tmp dir for annotation screenshots
|
||||
sessionStore: null,
|
||||
@@ -130,16 +132,31 @@ function scheduleLeaseFlush() {
|
||||
}
|
||||
|
||||
function flushPendingPolls() {
|
||||
let changed = false;
|
||||
while (state.pendingPolls.length > 0) {
|
||||
const entry = findAvailablePendingEvent();
|
||||
if (!entry) {
|
||||
scheduleLeaseFlush();
|
||||
broadcastAgentPollingIfChanged();
|
||||
return;
|
||||
}
|
||||
const poll = state.pendingPolls.shift();
|
||||
poll.resolve(leaseEvent(entry, poll.leaseMs));
|
||||
changed = true;
|
||||
}
|
||||
scheduleLeaseFlush();
|
||||
if (changed) broadcastAgentPollingIfChanged();
|
||||
}
|
||||
|
||||
function agentPollingConnected() {
|
||||
return state.pendingPolls.length > 0;
|
||||
}
|
||||
|
||||
function broadcastAgentPollingIfChanged() {
|
||||
const connected = agentPollingConnected();
|
||||
if (state.lastAgentPollingBroadcast === connected) return;
|
||||
state.lastAgentPollingBroadcast = connected;
|
||||
broadcast({ type: 'agent_polling', connected });
|
||||
}
|
||||
|
||||
/** Push a message to all connected SSE clients. */
|
||||
@@ -187,8 +204,7 @@ function loadBrowserScripts() {
|
||||
function hasProjectContext() {
|
||||
// PRODUCT.md carries brand voice / anti-references — that's what determines
|
||||
// whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
|
||||
// concern, surfaced by the design panel's own empty state. Legacy
|
||||
// .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
|
||||
// concern, surfaced by the design panel's own empty state.
|
||||
try {
|
||||
fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
|
||||
return true;
|
||||
@@ -199,66 +215,6 @@ function statOrNull(filePath) {
|
||||
try { return fs.statSync(filePath); } catch { return null; }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Validation (inline — no external import needed for self-contained script)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const VISUAL_ACTIONS = [
|
||||
'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
|
||||
'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
|
||||
];
|
||||
|
||||
// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
|
||||
// and variantIds via String(small integer). Restrict to those shapes so
|
||||
// any value that reaches a downstream child_process or DOM selector is
|
||||
// inert by construction.
|
||||
const ID_PATTERN = /^[0-9a-f]{8}$/;
|
||||
const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
|
||||
|
||||
function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
|
||||
function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
|
||||
|
||||
function validateEvent(msg) {
|
||||
if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
|
||||
switch (msg.type) {
|
||||
case 'generate':
|
||||
if (!isValidId(msg.id)) return 'generate: missing or malformed id';
|
||||
if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
|
||||
if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
|
||||
if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
|
||||
// Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
|
||||
if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
|
||||
if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
|
||||
if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
|
||||
return null;
|
||||
case 'accept':
|
||||
if (!isValidId(msg.id)) return 'accept: missing or malformed id';
|
||||
if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
|
||||
if (msg.paramValues !== undefined) {
|
||||
if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
|
||||
return 'accept: paramValues must be an object';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
case 'discard':
|
||||
return isValidId(msg.id) ? null : 'discard: missing or malformed id';
|
||||
case 'checkpoint':
|
||||
if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
|
||||
if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
|
||||
if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
|
||||
return 'checkpoint: paramValues must be an object';
|
||||
}
|
||||
return null;
|
||||
case 'exit':
|
||||
return null;
|
||||
case 'prefetch':
|
||||
if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
|
||||
return null;
|
||||
default:
|
||||
return 'Unknown event type: ' + msg.type;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HTTP request handler
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -396,6 +352,7 @@ function createRequestHandler({ detectScript, sessionPath, livePath }) {
|
||||
status: 'ok',
|
||||
port: state.port,
|
||||
connectedClients: state.sseClients.size,
|
||||
agentPolling: agentPollingConnected(),
|
||||
pendingEvents: state.pendingEvents.map((entry) => ({
|
||||
id: entry.event?.id,
|
||||
type: entry.event?.type,
|
||||
@@ -506,6 +463,7 @@ function createRequestHandler({ detectScript, sessionPath, livePath }) {
|
||||
res.write('data: ' + JSON.stringify({
|
||||
type: 'connected',
|
||||
hasProjectContext: hasProjectContext(),
|
||||
agentPolling: agentPollingConnected(),
|
||||
}) + '\n\n');
|
||||
|
||||
state.sseClients.add(res);
|
||||
@@ -614,6 +572,7 @@ function handlePollGet(req, res, url) {
|
||||
const timer = setTimeout(() => {
|
||||
const idx = state.pendingPolls.indexOf(poll);
|
||||
if (idx !== -1) state.pendingPolls.splice(idx, 1);
|
||||
broadcastAgentPollingIfChanged();
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ type: 'timeout' }));
|
||||
}, timeout);
|
||||
@@ -623,11 +582,13 @@ function handlePollGet(req, res, url) {
|
||||
res.end(JSON.stringify(event));
|
||||
}
|
||||
state.pendingPolls.push(poll);
|
||||
broadcastAgentPollingIfChanged();
|
||||
scheduleLeaseFlush();
|
||||
req.on('close', () => {
|
||||
clearTimeout(timer);
|
||||
const idx = state.pendingPolls.indexOf(poll);
|
||||
if (idx !== -1) state.pendingPolls.splice(idx, 1);
|
||||
broadcastAgentPollingIfChanged();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -649,13 +610,15 @@ function handlePollPost(req, res) {
|
||||
acknowledgePendingEvent(msg.id);
|
||||
if (state.sessionStore && msg.id) {
|
||||
try {
|
||||
const eventType = msg.type === 'discard' || msg.type === 'discarded'
|
||||
? 'discarded'
|
||||
: msg.type === 'complete'
|
||||
? 'complete'
|
||||
: msg.type === 'error'
|
||||
? 'agent_error'
|
||||
: 'agent_done';
|
||||
const eventType = msg.type === 'steer_done'
|
||||
? 'steer_done'
|
||||
: msg.type === 'discard' || msg.type === 'discarded'
|
||||
? 'discarded'
|
||||
: msg.type === 'complete'
|
||||
? 'complete'
|
||||
: msg.type === 'error'
|
||||
? 'agent_error'
|
||||
: 'agent_done';
|
||||
state.sessionStore.appendEvent({
|
||||
type: eventType,
|
||||
id: msg.id,
|
||||
|
||||
@@ -209,6 +209,17 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
|
||||
next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
|
||||
next.pendingEvent = toPendingEvent(event);
|
||||
break;
|
||||
case 'steer':
|
||||
next.phase = 'steer_requested';
|
||||
next.pageUrl = event.pageUrl ?? next.pageUrl;
|
||||
next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
|
||||
next.pendingEvent = toPendingEvent(event);
|
||||
break;
|
||||
case 'steer_done':
|
||||
next.phase = 'steer_done';
|
||||
next.pendingEventSeq = null;
|
||||
next.pendingEvent = null;
|
||||
break;
|
||||
case 'discard':
|
||||
next.phase = 'discard_requested';
|
||||
next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
|
||||
|
||||
@@ -31,6 +31,7 @@ export async function statusCli() {
|
||||
status: server.status,
|
||||
port: server.port,
|
||||
connectedClients: server.connectedClients,
|
||||
agentPolling: server.agentPolling,
|
||||
pendingEvents: server.pendingEvents,
|
||||
} : null,
|
||||
activeSessions: server?.activeSessions || activeSessions,
|
||||
|
||||
@@ -370,11 +370,14 @@ function buildCssAuthoring(styleMode, count) {
|
||||
selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
|
||||
requirements: [
|
||||
'Use the styleTag exactly; the is:inline attribute is required for this file.',
|
||||
'Put raw CSS directly between the styleTag opening and a plain </style> close.',
|
||||
'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
|
||||
'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
|
||||
],
|
||||
forbidden: [
|
||||
'Do not use @scope for this styleMode.',
|
||||
'Do not wrap style content in a JSX/TSX template literal ({` ... `}); that syntax is for .tsx/.jsx only.',
|
||||
'Do not put { immediately after the style opening tag; Astro parses { as expression syntax.',
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -629,4 +632,15 @@ if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/'))
|
||||
}
|
||||
|
||||
// Test exports (used by tests/live-wrap.test.mjs)
|
||||
export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
|
||||
export {
|
||||
buildSearchQueries,
|
||||
findElement,
|
||||
findClosingLine,
|
||||
detectCommentSyntax,
|
||||
findAllElements,
|
||||
filterByText,
|
||||
findFileWithQuery,
|
||||
detectStyleMode,
|
||||
buildCssAuthoring,
|
||||
buildCssSelectorPrefixExamples,
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ import { execSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { loadContext } from './load-context.mjs';
|
||||
import { loadContext } from './context.mjs';
|
||||
import { resolveFiles } from './live-inject.mjs';
|
||||
import { readLiveServerInfo } from './impeccable-paths.mjs';
|
||||
|
||||
@@ -80,7 +80,7 @@ The agent should then:
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
|
||||
// 4. Load PRODUCT.md + DESIGN.md context.
|
||||
const ctx = loadContext(process.cwd());
|
||||
|
||||
// 5. Compute drift-heal: compare resolved inject targets against the
|
||||
@@ -102,7 +102,6 @@ The agent should then:
|
||||
hasDesign: ctx.hasDesign,
|
||||
design: ctx.design,
|
||||
designPath: ctx.designPath,
|
||||
migrated: ctx.migrated,
|
||||
}, null, 2));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
/**
|
||||
* Shared context loader for every impeccable command that needs to know
|
||||
* "who is this for" and "what does this look like".
|
||||
*
|
||||
* Input: project root (process.cwd()).
|
||||
*
|
||||
* Output (JSON to stdout):
|
||||
* {
|
||||
* hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
|
||||
* product: string | null, // PRODUCT.md contents
|
||||
* productPath: string | null, // relative path
|
||||
* hasDesign: boolean, // DESIGN.md found
|
||||
* design: string | null, // DESIGN.md contents
|
||||
* designPath: string | null,
|
||||
* migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
|
||||
* contextDir: string, // absolute path of the directory the files were found in
|
||||
* }
|
||||
*
|
||||
* Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
|
||||
* Google DESIGN.md convention is uppercase at repo root; Kiro-style and
|
||||
* lowercase variants are also matched so users don't get punished for case.
|
||||
*
|
||||
* Lookup directory resolution (first match wins):
|
||||
* 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
|
||||
* 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
|
||||
* 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
|
||||
* 4. cwd as a default "no context found" location
|
||||
*
|
||||
* Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
|
||||
* fallback directories are read-only as far as auto-rename is concerned.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const LEGACY_NAMES = ['.impeccable.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
|
||||
/**
|
||||
* Resolve the directory that holds PRODUCT.md / DESIGN.md for
|
||||
* this project. Exported so other scripts (e.g. live-server.mjs) can read the
|
||||
* design files from the same location the loader uses.
|
||||
*/
|
||||
export function resolveContextDir(cwd = process.cwd()) {
|
||||
// 1. Explicit override
|
||||
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
|
||||
if (envDir && envDir.trim()) {
|
||||
const trimmed = envDir.trim();
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
// 2. cwd wins if any canonical or legacy file is there. We check legacy too
|
||||
// so the auto-migration path in loadContext stays predictable.
|
||||
if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
|
||||
return cwd;
|
||||
}
|
||||
|
||||
// 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
|
||||
// legacy `.impeccable.md` does not pull the lookup into a fallback dir.
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const candidate = path.resolve(cwd, rel);
|
||||
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Nothing found — keep the historical "default to cwd" behaviour so the
|
||||
// caller's `hasProduct === false` branch still fires the same way.
|
||||
return cwd;
|
||||
}
|
||||
|
||||
export function loadContext(cwd = process.cwd()) {
|
||||
let migrated = false;
|
||||
const contextDir = resolveContextDir(cwd);
|
||||
|
||||
// 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
|
||||
let productPath = firstExisting(contextDir, PRODUCT_NAMES);
|
||||
|
||||
// 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
|
||||
// it in place. We only migrate at the root — fallback dirs are read-only
|
||||
// so we don't surprise users by mutating files under docs/ or .agents/.
|
||||
if (!productPath && contextDir === cwd) {
|
||||
const legacyPath = firstExisting(cwd, LEGACY_NAMES);
|
||||
if (legacyPath) {
|
||||
const newPath = path.join(cwd, 'PRODUCT.md');
|
||||
try {
|
||||
fs.renameSync(legacyPath, newPath);
|
||||
productPath = newPath;
|
||||
migrated = true;
|
||||
} catch {
|
||||
// Rename failed (permissions, etc.) — fall back to reading legacy in place
|
||||
productPath = legacyPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. DESIGN.md (case-insensitive)
|
||||
const designPath = firstExisting(contextDir, DESIGN_NAMES);
|
||||
|
||||
const product = productPath ? safeRead(productPath) : null;
|
||||
const design = designPath ? safeRead(designPath) : null;
|
||||
|
||||
return {
|
||||
hasProduct: !!product,
|
||||
product,
|
||||
productPath: productPath ? path.relative(cwd, productPath) : null,
|
||||
hasDesign: !!design,
|
||||
design,
|
||||
designPath: designPath ? path.relative(cwd, designPath) : null,
|
||||
migrated,
|
||||
contextDir,
|
||||
};
|
||||
}
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function safeRead(p) {
|
||||
try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CLI mode — print the context as JSON
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function cli() {
|
||||
const result = loadContext(process.cwd());
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
|
||||
const _running = process.argv[1];
|
||||
if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
|
||||
cli();
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Brand-seed picker. Returns one OKLCH seed color + the mood it most
|
||||
* naturally evokes, and teaches the model how to compose a full palette
|
||||
* around it.
|
||||
*
|
||||
* The seed is the brand's anchor color. The 5-role palette (bg, surface,
|
||||
* ink, accent, muted) is composed by the caller at runtime using their
|
||||
* judgment + the brief (PRODUCT.md / DESIGN.md / user prompt), NOT picked
|
||||
* from a frozen 4-color preset.
|
||||
*
|
||||
* Why: 4-color frozen palettes drift toward safe defaults (warm-cream bg,
|
||||
* complementary accent on near-white) regardless of brief. A single seed +
|
||||
* the model's own composition lets the same seed produce a dark-mode jazz
|
||||
* club or a light-mode hospitality brand depending on what the brief calls
|
||||
* for. Tested empirically against curated 4-color palettes; seed approach
|
||||
* wins on mood-fit in 3 of 5 cases and ties on the rest.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/palette.mjs # pick at random
|
||||
* node scripts/palette.mjs --id seed-021 # pick a specific seed
|
||||
* node scripts/palette.mjs --from <key> # hash <key> to a seed (deterministic)
|
||||
*
|
||||
* Env vars:
|
||||
* IMPECCABLE_PALETTE_SEED — same as --from; useful for the eval harness
|
||||
* to make runs reproducible.
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
// Seeds are inlined (129 entries, hand-curated via a tinder review of
|
||||
// ~400 candidates from ColorHunt + synthesis + Radix/brand/Pantone anchors).
|
||||
// Each carries a mood + strategy the judging model produced — surfaced as
|
||||
// hints, not commands; the brief still drives composition.
|
||||
const SEEDS = [
|
||||
{ id: "seed-200", oklch: [0.360, 0.137, 0.0],
|
||||
mood: "Aesop apothecary shelf — oxblood bottle glass against linen, considered and unhurried",
|
||||
strategy: "Seed is a deep desaturated red-brown that reads as brand ink itself; I push primary darker toward bottle-glass oxblood, pair with a pure white surface so the red does the work, and use a clear pale-blush accent that can carry dark text in pills." },
|
||||
{ id: "seed-000", oklch: [0.400, 0.130, 0.0],
|
||||
mood: "oxblood leather banquette in a 1940s steakhouse — low lamplight on dark wood and burgundy",
|
||||
strategy: "Near-black bg with the faintest red undertone lets the oxblood primary glow like lamplit leather; warm cream ink and a brass accent complete the chophouse register." },
|
||||
{ id: "seed-002", oklch: [0.450, 0.150, 0.0],
|
||||
mood: "darkroom red light — analog photography, blood-warm safelight glow on chemical trays",
|
||||
strategy: "Near-black surface with a deep oxblood primary lets the seed function like a safelight in a darkroom — the bg disappears so the red becomes the only emotional signal." },
|
||||
{ id: "seed-003", oklch: [0.500, 0.194, 0.0],
|
||||
mood: "darkroom safelight — the deep oxblood glow of analog photography, chemical and contemplative",
|
||||
strategy: "Anchored the seed as primary against pure near-black so the red reads like a single illuminated bulb in a developing room, with cool desaturated ink to evoke silver gelatin print tones." },
|
||||
{ id: "seed-004", oklch: [0.546, 0.204, 3.4],
|
||||
mood: "midnight boudoir — velvet rose under low lamplight, perfumed and intimate",
|
||||
strategy: "Near-black surface lets the rose seed glow like silk in shadow; a warm champagne accent provides the candle-flame counterpoint without breaking the hush." },
|
||||
{ id: "seed-005", oklch: [0.550, 0.180, 0.0],
|
||||
mood: "smoldering vermillion at dusk — the last red ember in a blacksmith's forge, iron-rich and quietly violent",
|
||||
strategy: "Near-black gallery surround lets the seed read as glowing forged metal; ink stays warm-off-white, accent shifts to a hotter ember orange so the primary feels like cooling steel against a fresh strike." },
|
||||
{ id: "seed-201", oklch: [0.647, 0.262, 0.3],
|
||||
mood: "Figma plugin marketplace red — confident product-brand crimson, the kind a modern dev tool uses for a 'live' indicator or a primary CTA on a pristine docs page",
|
||||
strategy: "Pure white surface lets a high-chroma crimson primary do all the brand work, paired with a hue-shifted warm coral accent for hierarchy without competing saturation" },
|
||||
{ id: "seed-006", oklch: [0.650, 0.160, 0.0],
|
||||
mood: "1960s Italian cinema — Technicolor lipstick red against a darkened theater",
|
||||
strategy: "Pure near-black surface lets a saturated cinematic red and its warm peach accent perform like film light projected in a dark room — the brand colors carry the drama, the bg disappears." },
|
||||
{ id: "seed-008", oklch: [0.520, 0.200, 10.4],
|
||||
mood: "Negroni hour at a Milanese bar — bittersweet crimson, vermouth and amaro under low tungsten",
|
||||
strategy: "Seed is a saturated red-crimson with cinematic weight, so I sit it on near-black to let the primary glow like backlit liquor, with a warmer amber accent acting as the citrus twist against the bitter red." },
|
||||
{ id: "seed-010", oklch: [0.563, 0.223, 11.0],
|
||||
mood: "Negroni hour on a Milan rooftop — bittersweet crimson, aperitivo light, polished restraint",
|
||||
strategy: "Seed is a vivid carmine-red with strong chroma, so the surface gets out of the way (pure white) and lets the primary do the aperitivo work, with a cooled garnet accent for tension." },
|
||||
{ id: "seed-202", oklch: [0.643, 0.247, 7.0],
|
||||
mood: "Glossier brand pink — modern beauty editorial, confident and current",
|
||||
strategy: "Pure white bg lets a saturated rose-red primary do all the brand work, paired with a deeper crimson accent for hierarchy — the Stripe/Glossier move where the color carries the mood." },
|
||||
{ id: "seed-013", oklch: [0.400, 0.130, 20.0],
|
||||
mood: "Tuscan cellar at dusk — aged terracotta, oxidized iron, the deep red of decanted Sangiovese",
|
||||
strategy: "Black surface lets the oxblood seed and copper accent glow like firelight on cellar stone; brand colors carry all the warmth while the room recedes." },
|
||||
{ id: "seed-014", oklch: [0.450, 0.150, 20.0],
|
||||
mood: "smoldering tannery — oxblood leather, cured under low workshop light",
|
||||
strategy: "Anchor the deep oxblood seed as primary against a near-black architectural ground, then lift with a single warm ember accent so the leather reads burnished rather than bloody." },
|
||||
{ id: "seed-016", oklch: [0.550, 0.180, 20.0],
|
||||
mood: "Negroni hour on a Roman terrace — bitter campari red, vermouth, late golden light spilling on white linen",
|
||||
strategy: "Pure white surface lets the campari-red primary do all the emotional work, paired with a deeper oxblood accent for bittersweet depth — Italian aperitivo restraint, not warmth-washed." },
|
||||
{ id: "seed-205", oklch: [0.634, 0.254, 17.6],
|
||||
mood: "Aesop apothecary bottle — considered red-coral on a clinical white surface, the kind of brand restraint where one saturated object does all the work",
|
||||
strategy: "Default A pure white surface lets a single coral-red primary carry the entire brand voice; accent shifts to a deeper oxblood for hierarchy without competing chroma." },
|
||||
{ id: "seed-011", oklch: [0.639, 0.207, 13.5],
|
||||
mood: "Aperitivo hour in Milan — Campari glow on a white marble bar, crisp and effervescent",
|
||||
strategy: "Pure white gallery backdrop lets the Campari-red primary ring like a single bitter note; ink is near-black with a whisper of warmth, accent shifts to a deeper oxblood for hierarchy without competing hues." },
|
||||
{ id: "seed-015", oklch: [0.527, 0.202, 22.7],
|
||||
mood: "Negroni hour on a Milanese terrace — bittersweet vermillion, aperitivo glassware catching low sun",
|
||||
strategy: "Seed becomes a saturated aperitivo-red primary against pure white so the color carries the bittersweet warmth alone, paired with a deep oxblood accent for typographic gravitas." },
|
||||
{ id: "seed-023", oklch: [0.427, 0.175, 29.2],
|
||||
mood: "blacksmith's forge at dusk — iron heated to ember red, the deep glow of oxidized metal and quenching oil",
|
||||
strategy: "Pure black bg lets the seed's ember-red glow radiate like hot iron in a dark forge; accent shifts to a copper-amber to suggest scaling metal and sparks, while ink stays near-white for tool-precise legibility." },
|
||||
{ id: "seed-206", oklch: [0.614, 0.234, 28.2],
|
||||
mood: "Aesop apothecary bottle — considered red-orange on lab-white, calm utility with a single confident pigment",
|
||||
strategy: "Pure white surface lets a saturated vermilion primary do all the brand work, paired with a deep oxblood accent for hierarchy without introducing a second hue family" },
|
||||
{ id: "seed-029", oklch: [0.665, 0.222, 25.7],
|
||||
mood: "Negroni hour at a Milanese bar — bittersweet orange-red liqueur catching late afternoon light on polished marble",
|
||||
strategy: "Pure white surface lets the seed's vermilion read like Campari in a glass; a deeper oxblood accent provides the bitter depth, with neutral graphite ink keeping the editorial restraint of Italian design." },
|
||||
{ id: "seed-022", oklch: [0.418, 0.155, 27.2],
|
||||
mood: "Pompeiian red fresco — oxidized cinnabar on a museum wall, archaeological gravity",
|
||||
strategy: "Pure black gallery surface lets the seed's iron-oxide red read as a lit artifact; accent shifts to an aged terracotta amber, so primary and accent form a fired-clay duet against neutral void." },
|
||||
{ id: "seed-024", oklch: [0.464, 0.169, 26.9],
|
||||
mood: "Mid-century darkroom under the safelight — developer trays, oxblood leather, the quiet patience of a print emerging",
|
||||
strategy: "Seed becomes a deep oxblood primary; surface stays pure black so the red glows like a safelight, with a warmer ember accent for hierarchy" },
|
||||
{ id: "seed-026", oklch: [0.489, 0.190, 28.3],
|
||||
mood: "smoldering ember in a blacksmith's forge — iron-hot rust, soot, and controlled fire",
|
||||
strategy: "Near-black soot background lets the seed's red-orange glow like heated metal; ink is bone-white, accent is a cooler tempered-steel orange that creates internal heat gradient with the primary." },
|
||||
{ id: "seed-027", oklch: [0.568, 0.208, 27.1],
|
||||
mood: "Sicilian blood orange at golden hour — citrus rind, terracotta, sun on stucco",
|
||||
strategy: "Seed reads as vivid blood-orange — picked pure white surface so the citrus-red primary and a deep oxblood accent do all the emotional work, like a Loro Piana editorial spread." },
|
||||
{ id: "seed-028", oklch: [0.591, 0.172, 24.0],
|
||||
mood: "Sienna-fired ceramic studio at dusk — terracotta cooling on a wheel, hands still dusted with slip",
|
||||
strategy: "Pure black stage lets the fired-clay primary glow like a kiln ember, with a deeper oxblood accent providing tonal weight rather than hue contrast — a monochrome warm-axis play." },
|
||||
{ id: "seed-033", oklch: [0.544, 0.169, 31.3],
|
||||
mood: "1960s Italian terracotta workshop — fired clay, espresso, late-afternoon Mediterranean dust",
|
||||
strategy: "Pure black ground lets the seed's burnt-sienna primary glow like a lit kiln, with a deeper oxblood accent for restrained warmth tension — the brand carries the heat, the surface stays out." },
|
||||
{ id: "seed-207", oklch: [0.564, 0.231, 29.1],
|
||||
mood: "Aesop apothecary bottle — considered red oxide, the calm authority of a well-made object on a white shelf",
|
||||
strategy: "Seed becomes the singular brand voice against pure white, with a deeper oxblood accent for hierarchy — the surface disappears so the red does all the speaking." },
|
||||
{ id: "seed-035", oklch: [0.663, 0.153, 32.1],
|
||||
mood: "Aesop apothecary bottle — clay-fired warmth, considered retail",
|
||||
strategy: "Pure white surface lets the terracotta primary do the brand work, paired with a deep umber ink and a cooler clay accent for editorial tension." },
|
||||
{ id: "seed-037", oklch: [0.590, 0.188, 35.8],
|
||||
mood: "Aesop apothecary bottle — considered terracotta, herbalist restraint, the warmth comes from the glass not the room",
|
||||
strategy: "Seed becomes a muted terracotta primary against pure white so the brand's warmth carries entirely through the color itself; accent shifts to a deeper umber for quiet hierarchy." },
|
||||
{ id: "seed-038", oklch: [0.652, 0.229, 34.8],
|
||||
mood: "blown-glass furnace at dusk — molten orange iron pulled from the kiln, a craftsman's signature heat",
|
||||
strategy: "Pure black stage so the seed reads as live ember; primary holds the seed's heat, accent shifts to a brass-amber a hue-step away for a 1.7+ contrast pairing without leaving the fire." },
|
||||
{ id: "seed-039", oklch: [0.653, 0.185, 33.5],
|
||||
mood: "Aesop apothecary bottle — considered terracotta, quiet retail craft",
|
||||
strategy: "Seed becomes a grounded clay primary against pure white, paired with a deeper umber accent so the warmth lives entirely in the brand marks, not the surface." },
|
||||
{ id: "seed-167", oklch: [0.495, 0.134, 36.0],
|
||||
mood: "Aesop apothecary shelf — burnished terracotta on clinical white, considered craft pharmacy",
|
||||
strategy: "Treat the seed as a brand-carrying burnt-sienna against a pure paper-white surface so the warmth lives entirely in the primary, with a deep umber accent pulled along the same warm axis for typographic gravity." },
|
||||
{ id: "seed-147", oklch: [0.500, 0.151, 40.0],
|
||||
mood: "Aesop apothecary shelf — considered terracotta, pharmacy restraint, the brand color does the work against clinical white",
|
||||
strategy: "Anchor the seed's burnt-sienna primary against a pure white surface so the rust speaks alone, with a deep umber ink and a cooler clay accent to give the palette product-brand discipline rather than environmental warmth." },
|
||||
{ id: "seed-040", oklch: [0.660, 0.201, 40.0],
|
||||
mood: "Aesop apothecary bottle — amber glass on a clean dispensary shelf, considered and clinical-warm",
|
||||
strategy: "Seed becomes a burnt-amber primary against pure white so the bottle-glass color does the emotional work; accent shifts to a deep olive-bronze for the apothecary-label pairing." },
|
||||
{ id: "seed-041", oklch: [0.673, 0.217, 38.6],
|
||||
mood: "Aesop apothecary shelf — considered orange glass, clinical retail restraint",
|
||||
strategy: "Pure white surface lets the burnt-orange primary do all the brand work, with a deep ink-brown for editorial gravity and a muted clay accent that reads as a sibling, not a contrast." },
|
||||
{ id: "seed-042", oklch: [0.688, 0.133, 35.8],
|
||||
mood: "Aesop apothecary shelf — terracotta glass, considered retail",
|
||||
strategy: "Seed becomes a warm clay primary against pure white so the bottle-on-marble retail feel comes from the brand color alone; a deeper umber accent gives the label-print contrast." },
|
||||
{ id: "seed-043", oklch: [0.781, 0.119, 38.1],
|
||||
mood: "Aesop apothecary catalogue — considered terracotta, dermatological restraint, the warm color doing all the work against clinical white",
|
||||
strategy: "Pure white surface lets the seed's warm clay tone read as the entire brand voice, paired with a deeper umber accent for hierarchy without competing with the primary's warmth." },
|
||||
{ id: "seed-168", oklch: [0.400, 0.103, 50.0],
|
||||
mood: "Aesop apothecary bottle — amber glass on a clinical white shelf, considered and pharmaceutical",
|
||||
strategy: "Pure white surface lets the deep amber primary act like tinted glass against a clean shelf; accent is a muted clay that complements without competing, keeping the brand quiet and product-led." },
|
||||
{ id: "seed-044", oklch: [0.568, 0.149, 45.9],
|
||||
mood: "1970s desert highway at golden hour — sun-faded terracotta, denim dust, the warmth of a Polaroid pulled from a glovebox",
|
||||
strategy: "Seed becomes a burnt-sienna primary against pure white so the terracotta does all the emotional work; a deep indigo accent acts as the denim shadow opposing the sun, creating the era's signature warm/cool tension without tinting the page." },
|
||||
{ id: "seed-045", oklch: [0.607, 0.163, 47.7],
|
||||
mood: "Aesop apothecary shelf — considered amber glass, clinical restraint, craft pharmacy",
|
||||
strategy: "Pure white bg lets the burnt-amber primary do the apothecary work alone, paired with a deeper umber accent and graphite ink for editorial calm." },
|
||||
{ id: "seed-046", oklch: [0.653, 0.175, 45.0],
|
||||
mood: "Aesop apothecary shelf — considered amber glass, quiet luxury, restrained craft",
|
||||
strategy: "Pure black backdrop lets the warm amber primary glow like backlit apothecary glass, with a deeper rust accent providing tonal depth in the same hue family — monochromatic warm against neutral void." },
|
||||
{ id: "seed-047", oklch: [0.695, 0.205, 43.2],
|
||||
mood: "Aesop apothecary label — sun-warmed amber glass on a clinical countertop, restrained botanical pharmacy",
|
||||
strategy: "Pure white surface lets the burnt-amber primary and a deeper sienna accent do all the brand work, like an apothecary bottle photographed under daylight." },
|
||||
{ id: "seed-051", oklch: [0.704, 0.189, 49.0],
|
||||
mood: "blacksmith's forge at dusk — glowing iron, hammered copper, ember light against cooling steel",
|
||||
strategy: "Pure near-black surface lets the seed's molten orange burn like heated metal; accent shifts to a deeper amber-red to suggest the cooling end of the same iron, while ink stays a clean off-white so type reads like chalk on slate." },
|
||||
{ id: "seed-171", oklch: [0.550, 0.124, 60.0],
|
||||
mood: "Klim Type Foundry specimen page — considered ochre on paper, design-school-honest",
|
||||
strategy: "Seed becomes a muted ochre primary on pure white; accent is a deep ink-navy pulled across the wheel for editorial contrast without warmth-pooling in the bg" },
|
||||
{ id: "seed-148", oklch: [0.650, 0.146, 60.0],
|
||||
mood: "Klim-style editorial gold — late-afternoon paper light on a serif specimen sheet, considered and dry",
|
||||
strategy: "Hold the seed's amber as primary on a pure white page so the gold reads as ink rather than atmosphere, and pair with a deep aubergine accent for typographic contrast." },
|
||||
{ id: "seed-052", oklch: [0.700, 0.130, 60.0],
|
||||
mood: "late-afternoon terracotta studio — sun-warmed clay, hands-on craft, the hour before dusk",
|
||||
strategy: "Seed is a saturated amber-ochre with strong environmental association (ceramics, adobe, sunlit plaster), so I lean into Exception (a) with a faintly warm bone surface that reads as lime-washed wall, then deepen the seed slightly for primary and pair it with a fired-clay rust accent for hand-thrown warmth." },
|
||||
{ id: "seed-053", oklch: [0.773, 0.157, 56.6],
|
||||
mood: "late-summer apricot orchard at golden hour — sun-warmed fruit, considered Californian craft",
|
||||
strategy: "Seed is a juicy mid-warm orange at daylight luminance — leaning optimistic/editorial, so pure white surface lets the apricot primary glow without muddying it; a deep wine accent provides the bite." },
|
||||
{ id: "seed-149", oklch: [0.600, 0.124, 70.0],
|
||||
mood: "1970s desert highway — late-afternoon amber light on chrome and asphalt",
|
||||
strategy: "Anchor the amber seed as primary against pure black so the warm hue reads as headlight glow against night; a cooler dusk-mauve accent provides the complementary tension of horizon vs. sun." },
|
||||
{ id: "seed-054", oklch: [0.740, 0.162, 68.1],
|
||||
mood: "late-afternoon honey on terracotta — Mediterranean stucco at golden hour, sun-baked amber",
|
||||
strategy: "Seed is a saturated honey-amber at high lightness; pairing it with pure black lets the warmth read as luminous gold against gravity, like lamplight in a dark room." },
|
||||
{ id: "seed-055", oklch: [0.774, 0.174, 65.1],
|
||||
mood: "late-summer honey hour — amber light slanting through a west-facing window, optimistic and golden",
|
||||
strategy: "Anchor a saturated honey-amber primary on pure white so the warmth radiates from the brand itself, then pair with a deep teak accent for grounded contrast rather than tinting the canvas." },
|
||||
{ id: "seed-056", oklch: [0.691, 0.146, 74.6],
|
||||
mood: "Klim-style modern publishing house — late-afternoon paper warmth, considered editorial gold",
|
||||
strategy: "Pure white surface so the amber seed becomes the brand voice; ink stays near-black neutral and accent shifts to a deep ink-blue to give the gold something structural to lean on." },
|
||||
{ id: "seed-150", oklch: [0.750, 0.148, 80.0],
|
||||
mood: "Klim Type Foundry specimen page — late-summer editorial gold, considered and grown-up",
|
||||
strategy: "Pure white surface lets a single restrained ochre primary do all the brand work, paired with a deep ink-blue accent for typographic contrast in the Klim/Commercial Type tradition." },
|
||||
{ id: "seed-058", oklch: [0.764, 0.120, 77.1],
|
||||
mood: "Klim Type Foundry specimen page — late-afternoon ochre, considered editorial typography",
|
||||
strategy: "Pure white surface lets the ochre primary do the brand work, paired with a deep ink-blue accent for editorial contrast — the type-foundry move where one warm hue carries the whole feeling against neutral paper." },
|
||||
{ id: "seed-059", oklch: [0.784, 0.144, 79.8],
|
||||
mood: "late afternoon in a Tuscan limonaia — sun-cured amber on whitewashed plaster",
|
||||
strategy: "Pure white surface lets the saffron-amber primary and a deep olive accent carry the Mediterranean warmth, with split-complementary tension between gold and a quiet evergreen." },
|
||||
{ id: "seed-061", oklch: [0.817, 0.161, 75.1],
|
||||
mood: "late-afternoon honey on Tuscan limestone — golden hour, slow and luminous",
|
||||
strategy: "Pure white surface lets the amber primary glow like sunlight on a wall, paired with a deep terracotta accent for warm tonal contrast within the same hue family." },
|
||||
{ id: "seed-063", oklch: [0.842, 0.165, 91.3],
|
||||
mood: "late-afternoon Tuscan sun on limestone — golden hour, considered, optimistic",
|
||||
strategy: "Pure white surface lets the amber-gold primary radiate as the mood-carrier, with a deep aubergine accent providing the long shadow that golden light needs to feel three-dimensional." },
|
||||
{ id: "seed-174", oklch: [0.350, 0.075, 110.0],
|
||||
mood: "olive grove at late afternoon — sun-cured leaves, dust, and quiet Mediterranean weight",
|
||||
strategy: "Pure white surface lets a deep, sun-cured olive primary do the emotional work, with a burnt-terracotta accent providing the warm-earth counterpoint olive groves are known for." },
|
||||
{ id: "seed-117", oklch: [0.650, 0.100, 110.0],
|
||||
mood: "Klim-style editorial sage — late-summer foundry catalogue, considered olive-yellow on paper",
|
||||
strategy: "Seed sits at olive-chartreuse; treating it as a quiet typographic primary on pure paper, with a deeper bronze-olive accent for hierarchy — the color does the work, the page disappears." },
|
||||
{ id: "seed-118", oklch: [0.750, 0.090, 110.0],
|
||||
mood: "Klim Type Foundry specimen page — late-summer olive light on a working specimen, the honesty of a type designer showing their work",
|
||||
strategy: "Pure white bg lets a desaturated olive-yellow primary do the editorial work, with a deeper olive-bronze accent providing typographic emphasis the way a specimen uses one heavy weight against the body roman." },
|
||||
{ id: "seed-065", oklch: [0.797, 0.166, 113.1],
|
||||
mood: "late-summer olive grove at noon — sun-bleached leaves, dry stone, Mediterranean glare",
|
||||
strategy: "Hold the seed as a luminous chartreuse-olive primary against pure white so the color reads as sunlit foliage, pairing it with a deep umber accent for the dry-stone contrast." },
|
||||
{ id: "seed-176", oklch: [0.300, 0.071, 120.0],
|
||||
mood: "moss-darkened apothecary jar — herbal, shadowed, mid-19th-century botanical study",
|
||||
strategy: "Seed is a deep desaturated olive-green that reads as preserved botanical pigment; I anchor it on pure white so the dim moss-green primary feels like ink on a herbarium page, with a warm ochre accent supplying the aged-paper counterpoint." },
|
||||
{ id: "seed-155", oklch: [0.550, 0.142, 130.0],
|
||||
mood: "moss-bed forest floor at noon — chlorophyll, lichen, sunlit fern",
|
||||
strategy: "Seed is a confident mid-olive green with strong chroma; mood is daylight botanical, so I let the brand greens do the work on a pure paper-white bg and pair with a warm umber accent for fern-against-bark contrast." },
|
||||
{ id: "seed-119", oklch: [0.600, 0.154, 130.0],
|
||||
mood: "moss garden at Saihō-ji — damp stone, filtered green light through old cedar",
|
||||
strategy: "Pure near-black bg lets the seed's mossy green glow like wet lichen under low light; accent shifts to a pale ochre-gold like sun catching through canopy." },
|
||||
{ id: "seed-179", oklch: [0.300, 0.096, 140.0],
|
||||
mood: "moss on wet stone — forest floor at dusk, deep botanical hush",
|
||||
strategy: "Kept the seed's deep moss green as primary against a near-black surface so the green reads as living shadow, with a pale lichen accent providing the single point of light." },
|
||||
{ id: "seed-180", oklch: [0.350, 0.110, 140.0],
|
||||
mood: "moss-darkened apothecary — herbal tinctures in amber glass, pressed botanicals, the deep green of a conservatory at dusk",
|
||||
strategy: "Near-black bg with a whisper of green undertone lets the seed's deep moss read as luminous foliage; a warm parchment accent provides the apothecary-label counterpoint without breaking the herbal register." },
|
||||
{ id: "seed-120", oklch: [0.650, 0.100, 140.0],
|
||||
mood: "moss on weathered stone — quiet botanical garden conservatory at midday",
|
||||
strategy: "Pure white bg lets the muted sage-green primary read as a considered botanical mark, with a deeper terracotta accent providing earthen counterpoint without breaking the gallery-like restraint." },
|
||||
{ id: "seed-121", oklch: [0.750, 0.090, 140.0],
|
||||
mood: "moss garden at Saihō-ji — diffuse green light filtered through wet stone and lichen",
|
||||
strategy: "Pure near-black bg lets the muted sage-green primary glow like lichen under low light; a warm pale-bone accent acts as the single ray of sun cutting through canopy." },
|
||||
{ id: "seed-182", oklch: [0.400, 0.106, 150.0],
|
||||
mood: "moss garden at Saiho-ji — deep cultivated green under wet stone shadow, contemplative and damp",
|
||||
strategy: "Near-black bg with the faintest cool-green undertone evokes shaded stone; primary holds the seed's moss tone while accent shifts to a lichen-yellow for organic counterpoint without breaking the hush." },
|
||||
{ id: "seed-157", oklch: [0.550, 0.145, 150.0],
|
||||
mood: "moss garden at Saiho-ji — damp stone, filtered green light through cedar canopy",
|
||||
strategy: "Near-black bg with a faint green undertone evokes deep forest shadow; primary holds the seed's verdant register while accent shifts to a pale lichen-cream to mimic light catching moss." },
|
||||
{ id: "seed-122", oklch: [0.600, 0.158, 150.0],
|
||||
mood: "forest floor at first light — moss, lichen, and clean morning air",
|
||||
strategy: "Seed reads as a living, daylight green; surface stays pure white so the green carries the freshness, with a cool teal accent pulling it toward dew rather than earth." },
|
||||
{ id: "seed-195", oklch: [0.650, 0.150, 145.0],
|
||||
mood: "Considered horticulture brand — botanical research lab, the green of a healthy stem photographed in clean daylight",
|
||||
strategy: "Pure white surface lets the seed's vegetal green carry the entire brand voice, paired with a deep forest ink and a warm clay accent for editorial contrast." },
|
||||
{ id: "seed-183", oklch: [0.350, 0.077, 160.0],
|
||||
mood: "moss-stained apothecary — deep forest glass, herbal tinctures shelved in low candlelight",
|
||||
strategy: "Anchored the seed as primary and built a near-black dark surface with whisper-tinted green to evoke aged apothecary glass, letting the green glow rather than shout." },
|
||||
{ id: "seed-184", oklch: [0.400, 0.087, 160.0],
|
||||
mood: "deep forest apothecary — moss, bottle glass, and herbal tincture under afternoon light",
|
||||
strategy: "Seed becomes a botanical-bottle-green primary on pure white, paired with a warm clove-amber accent to evoke herbal pharmacy contrast without tinting the surface." },
|
||||
{ id: "seed-158", oklch: [0.550, 0.119, 160.0],
|
||||
mood: "moss on wet stone — forest floor after rain, mineral and quiet",
|
||||
strategy: "Pure white surface lets the deep mossy green carry the entire mood; accent shifts to a damp slate-teal to sit beside primary like lichen on stone without competing." },
|
||||
{ id: "seed-159", oklch: [0.600, 0.130, 160.0],
|
||||
mood: "moss-covered forest apothecary — herbal tinctures in amber glass, eucalyptus shadow",
|
||||
strategy: "Anchored the green seed in a near-black backdrop so it reads like botanical glassware lit from within, with a warm amber accent pulled across the wheel to evoke tincture bottles against dark wood." },
|
||||
{ id: "seed-185", oklch: [0.450, 0.086, 170.0],
|
||||
mood: "weathered copper patina on a Pacific Northwest greenhouse — oxidized teal, glass light, botanical hush",
|
||||
strategy: "Seed sits as a deep oxidized-teal primary against pure white so the patina reads as pigment, not atmosphere; a rust-copper accent completes the verdigris/oxidation story across the warm-cool axis." },
|
||||
{ id: "seed-124", oklch: [0.750, 0.080, 170.0],
|
||||
mood: "sea-glass on a foggy Pacific shoreline — weathered, mineral, quietly oxidized",
|
||||
strategy: "Seed is a soft desaturated teal-green; pairing it on pure white lets the mineral primary read as patinated copper-glass, with a deeper kelp-toned primary and a rusted coral accent to spark the muted teal against its complement." },
|
||||
{ id: "seed-160", oklch: [0.550, 0.095, 180.0],
|
||||
mood: "weathered copper patina on a museum bronze — oxidized teal, conservatorial quiet",
|
||||
strategy: "Pure near-black gallery surround lets the patina-teal primary glow like a lit artifact, with a warm verdigris-adjacent accent providing the oxidation contrast against the cool seed." },
|
||||
{ id: "seed-161", oklch: [0.720, 0.100, 188.0],
|
||||
mood: "climate-tech dashboard — calm verdigris on plain paper, the quiet confidence of an instrument that just works",
|
||||
strategy: "Seed teal carries the entire mood as a single considered brand color on pure white, with a desaturated copper accent providing warm signal against the cool primary without competing for attention." },
|
||||
{ id: "seed-186", oklch: [0.450, 0.074, 200.0],
|
||||
mood: "deep hydrothermal vent — mineral teal under pressure, the cold blue-green of oxidized copper in submerged light",
|
||||
strategy: "Near-black surface lets the mineral teal glow as if lit from within; accent shifts toward verdigris-copper to suggest patina on submerged metal, while ink stays cool-neutral to keep the register austere rather than aquatic-cute." },
|
||||
{ id: "seed-125", oklch: [0.650, 0.100, 200.0],
|
||||
mood: "climate-tech dashboard — calm operational teal, the color of clean water data and atmospheric sensors",
|
||||
strategy: "Pure white surface lets a single muted-teal primary do all the brand work, with a deeper marine accent providing hierarchy without competing chroma." },
|
||||
{ id: "seed-126", oklch: [0.750, 0.080, 200.0],
|
||||
mood: "climate-tech product brand — quiet competence, dashboards for hard infrastructure problems",
|
||||
strategy: "Hold the seed's muted teal as primary, pair with a sharper cyan-leaning accent for interactive lift, and let a pure white surface do the disappearing act so the brand reads as a tool, not an atmosphere." },
|
||||
{ id: "seed-162", oklch: [0.550, 0.091, 210.0],
|
||||
mood: "weathered nautical instrument — patinated brass on oxidized steel, the cool blue-grey of a ship's chronometer at dawn",
|
||||
strategy: "Pure white surface lets the muted teal-steel primary read as a precise instrument mark, with a warm brass accent providing the single point of patina against clinical white." },
|
||||
{ id: "seed-163", oklch: [0.450, 0.086, 230.0],
|
||||
mood: "deep harbor at dusk — weathered nautical instruments, brass dials on oxidized steel",
|
||||
strategy: "Near-black background with subtle cool tint evokes the marine dusk; primary holds the seed's teal-blue while a warm brass accent creates the instrument-on-steel tension." },
|
||||
{ id: "seed-164", oklch: [0.550, 0.105, 230.0],
|
||||
mood: "deep harbor at dawn — cold steel water, fog-muted light, the quiet before the boats leave",
|
||||
strategy: "Pure near-black bg lets the seed's cold marine blue read as a luminous beacon, while a pale frost-cyan accent evokes diffused dawn light cutting through fog." },
|
||||
{ id: "seed-127", oklch: [0.650, 0.100, 230.0],
|
||||
mood: "climate-tech dashboard — atmospheric sensor blue, calm operational clarity",
|
||||
strategy: "Anchor the seed as a confident mid-blue primary on pure white so the brand color carries all the atmospheric feeling, with a deep navy accent for hierarchy and a soft slate muted for body text." },
|
||||
{ id: "seed-128", oklch: [0.750, 0.080, 230.0],
|
||||
mood: "climate-tech dashboard — calm atmospheric data, considered sky-blue",
|
||||
strategy: "Pure white surface lets the muted sky-blue primary carry the meteorological calm, with a deep-navy accent providing readable weight against the soft primary." },
|
||||
{ id: "seed-187", oklch: [0.350, 0.078, 240.0],
|
||||
mood: "deep harbor at blue hour — wet stone, cold steel, the quiet before night fully lands",
|
||||
strategy: "Near-black architectural bg with a hint of marine chroma lets the seed read as ambient atmosphere rather than UI chrome; a cooler steel accent sits opposite the warmer-shifted primary for navigational clarity." },
|
||||
{ id: "seed-077", oklch: [0.578, 0.130, 241.7],
|
||||
mood: "pre-dawn signal tower — cold blue solitude, instruments glowing against the dark",
|
||||
strategy: "Pure near-black bg lets the seed's cold tower-light blue glow as the sole emotional source, with a frost-cyan accent acting as a secondary indicator light." },
|
||||
{ id: "seed-188", oklch: [0.400, 0.110, 250.0],
|
||||
mood: "Linear's considered indigo — the calm authority of a well-built developer tool, blueprint ink on a clean page",
|
||||
strategy: "Held the seed as a deep indigo primary against pure white so the brand color carries all the gravity; accent shifts to a cooler, brighter cyan-blue to create a crisp hierarchy pair without warming the surface." },
|
||||
{ id: "seed-165", oklch: [0.450, 0.123, 250.0],
|
||||
mood: "blueprint room at dusk — drafting table, graphite, civic-engineering blue",
|
||||
strategy: "Seed is a mid-deep architectural blue with real chroma and no environmental cue, so I stay out of the way with a pure white surface and let the primary do all the talking, pairing it with a burnt-ochre accent for drafting-pencil contrast." },
|
||||
{ id: "seed-079", oklch: [0.478, 0.136, 251.8],
|
||||
mood: "twilight cartography — the blue of deep dusk over open water, precise and navigational",
|
||||
strategy: "Pure white surface lets the seed's oceanic blue act as a single navigational anchor, with a warm amber accent struck across it like a lighthouse beam at dusk." },
|
||||
{ id: "seed-080", oklch: [0.541, 0.122, 248.2],
|
||||
mood: "Linear-style considered tool blue — the calm, exact register of a modern engineering app where every pixel is intentional",
|
||||
strategy: "Pure white surface lets the considered indigo-blue primary carry the entire brand; a deeper navy accent provides hierarchy without warmth, keeping the palette in a single cool family for that focused-software feel" },
|
||||
{ id: "seed-166", oklch: [0.550, 0.149, 250.0],
|
||||
mood: "pre-dawn flight deck — instrument glow against deep cobalt sky, precise and quietly intense",
|
||||
strategy: "Near-black bg with the faintest cool tint reads like a darkened cockpit; the seed becomes a luminous instrument-blue primary, paired with a warm amber accent that mimics avionics readouts for unmistakable signal contrast." },
|
||||
{ id: "seed-081", oklch: [0.650, 0.160, 250.0],
|
||||
mood: "deep-sea research vessel at dawn — instrument glow against cold steel light",
|
||||
strategy: "Pure near-white bg keeps the palette technical and instrument-like; the seed blue holds as primary while a desaturated steel-cyan accent reads like signal readouts on glass." },
|
||||
{ id: "seed-082", oklch: [0.742, 0.140, 247.4],
|
||||
mood: "high-altitude flight deck at dawn — cold cabin instruments glowing against a sky still holding night",
|
||||
strategy: "Near-black cockpit ground with a faint blue cast lets the seed read as an illuminated instrument; primary holds the seed, accent shifts to cyan for signal/indicator contrast." },
|
||||
{ id: "seed-210", oklch: [0.360, 0.140, 260.0],
|
||||
mood: "Linear-style considered tool indigo — late-night focused work, the deep blue of a code editor at 2am where everything else falls away",
|
||||
strategy: "Pure black bg lets the indigo primary carry all the cognitive-focus weight, with a slightly brighter periwinkle accent for interactive lift — the surface disappears so the tool feels weightless." },
|
||||
{ id: "seed-189", oklch: [0.400, 0.130, 260.0],
|
||||
mood: "pre-dawn observatory — cold instrument blue, star-chart precision",
|
||||
strategy: "Seed becomes the primary on pure black so the deep instrument-blue glows like a calibration light, with a faint cyan accent reading as starlight against the void." },
|
||||
{ id: "seed-211", oklch: [0.420, 0.161, 260.0],
|
||||
mood: "Linear's considered indigo — the tool-for-thought blue of focused product work, calm authority without coldness",
|
||||
strategy: "Hold the seed as a deep indigo primary against pure white, then pair with a slightly warmer, lighter periwinkle accent to create gentle hue separation without breaking the disciplined tool-brand register." },
|
||||
{ id: "seed-129", oklch: [0.450, 0.150, 260.0],
|
||||
mood: "pre-dawn observatory — deep cobalt sky just before astronomical twilight, instruments cool to the touch",
|
||||
strategy: "Near-black surface lets the cobalt seed read as luminous starlight; a single warm amber accent acts as the calibration lamp against the cold blue field." },
|
||||
{ id: "seed-084", oklch: [0.476, 0.207, 261.2],
|
||||
mood: "pre-dawn flight deck — instrument glow against deep cobalt sky, precise and awake",
|
||||
strategy: "Default B black bg lets the cobalt primary read as a luminous instrument signal, with a cyan accent striking the analogous 'cockpit display' relationship." },
|
||||
{ id: "seed-085", oklch: [0.681, 0.132, 258.4],
|
||||
mood: "pre-dawn flight deck — instrument glow against deep cobalt sky",
|
||||
strategy: "Anchored the seed as a luminous primary against a near-black architectural ground, with a warm amber accent acting as the single instrument light cutting through cold blue." },
|
||||
{ id: "seed-086", oklch: [0.767, 0.106, 255.9],
|
||||
mood: "Scandinavian winter morning — quiet light through frost, pale sky over snow",
|
||||
strategy: "Anchored a pure white editorial stage so the seed's cool sky-blue reads as crisp polar light, with a deeper navy primary providing the only saturated weight — like a single dark pine against snow." },
|
||||
{ id: "seed-083", oklch: [0.340, 0.159, 262.4],
|
||||
mood: "deep cobalt twilight — the moment after sunset when the sky goes electric blue and city windows start to glow",
|
||||
strategy: "Pure black stage lets the cobalt seed act as a luminous neon-window glow, with a warm amber accent across the wheel for the lit-window contrast." },
|
||||
{ id: "seed-212", oklch: [0.360, 0.219, 270.0],
|
||||
mood: "Linear-grade tooling indigo — considered software for people who care about craft",
|
||||
strategy: "Anchored the deep indigo seed as primary on a pure white surface so the brand color carries all the weight, with a slightly cooler violet-blue accent for hierarchy without competing chroma." },
|
||||
{ id: "seed-130", oklch: [0.400, 0.150, 270.0],
|
||||
mood: "Linear-grade indigo — considered productivity tool, ink on paper, no theatrics",
|
||||
strategy: "Pure white surface lets a deep cool indigo carry all the brand weight, paired with a slightly warmer violet-blue accent for hierarchy without acid." },
|
||||
{ id: "seed-213", oklch: [0.411, 0.241, 267.9],
|
||||
mood: "Linear-style indigo — considered tool surface, the kind of blue-violet that sits behind a developer's keyboard at 11pm without shouting",
|
||||
strategy: "Pure black canvas lets a saturated indigo primary do all the brand work, with a cooler cyan-violet accent providing UI signal without competing." },
|
||||
{ id: "seed-131", oklch: [0.450, 0.180, 270.0],
|
||||
mood: "monastic indigo dusk — vespers light through stained glass, contemplative and severe",
|
||||
strategy: "Seed becomes a deep indigo primary against pure near-black so the violet reads as luminous stained-glass against architectural shadow, with a cooler iris accent for tonal lift." },
|
||||
{ id: "seed-088", oklch: [0.476, 0.158, 268.5],
|
||||
mood: "pre-dawn astronomer's notebook — deep indigo sky just before the stars fade, ink and graphite",
|
||||
strategy: "Near-black bg with the faintest cool tint to evoke night sky without theatrics; primary holds the seed's indigo, accent shifts to a paler periwinkle for stellar contrast, keeping the palette monochromatic-cool and observational." },
|
||||
{ id: "seed-196", oklch: [0.530, 0.130, 268.0],
|
||||
mood: "Linear-style considered tool indigo — the deep-focus blue-violet of a thoughtfully built productivity surface, the color of a well-typeset keyboard shortcut",
|
||||
strategy: "Pure white bg lets the indigo seed do all the brand work as primary, with a slightly darker, more saturated violet-shifted accent for hierarchy and interactive states — the surface disappears so the brand color reads as the entire identity." },
|
||||
{ id: "seed-132", oklch: [0.700, 0.120, 270.0],
|
||||
mood: "Linear-style considered tool indigo — the quiet violet of a focused product workspace, late-afternoon thinking",
|
||||
strategy: "Pure white surface lets a muted indigo-violet primary and a slightly cooler accent do all the brand work, keeping the register calm and software-like rather than theatrical." },
|
||||
{ id: "seed-090", oklch: [0.445, 0.206, 279.1],
|
||||
mood: "Linear-style considered tool indigo — the violet of a focused product surface, not a nightclub",
|
||||
strategy: "Anchor the seed as a confident product primary on pure white, with a cooler indigo-shift accent that reads as a sibling tool color, so the brand violet does all the emotional work." },
|
||||
{ id: "seed-133", oklch: [0.500, 0.160, 280.0],
|
||||
mood: "Linear-adjacent indigo — considered productivity tool, the violet of a thinking workspace",
|
||||
strategy: "Seed becomes a measured indigo primary on pure white; accent shifts to a cooler blue-violet to create hierarchy without nightclub saturation, letting the brand color do all the emotional work." },
|
||||
{ id: "seed-094", oklch: [0.533, 0.125, 294.3],
|
||||
mood: "Linear-style considered tool indigo — the violet of a focused product surface, calm authority for a creative workspace",
|
||||
strategy: "Pure white canvas lets the indigo-violet primary carry the entire brand voice; accent shifts hue slightly toward blue for a cool, tool-like duotone rather than warm decorative pairing." },
|
||||
{ id: "seed-137", oklch: [0.700, 0.120, 290.0],
|
||||
mood: "Linear-adjacent indigo — the considered tool, late-evening focus mode, software made for people who care about craft",
|
||||
strategy: "Pure black surface lets a single restrained indigo-violet carry the brand, with a cooler periwinkle accent providing UI hierarchy without competing — Vercel/Linear dark-mode discipline." },
|
||||
{ id: "seed-100", oklch: [0.450, 0.150, 330.0],
|
||||
mood: "velvet boudoir at last call — bruised orchid and lipstick traces under low lamplight",
|
||||
strategy: "Pure near-black surface lets a deep magenta-rose primary smolder while a warm peach accent acts like skin-lit lamplight — drama lives in the brand pair, not the room." },
|
||||
{ id: "seed-103", oklch: [0.650, 0.160, 330.0],
|
||||
mood: "1980s Memphis boudoir — powder-pink neon humming against lacquered black, lipstick and lacquer",
|
||||
strategy: "Near-black gallery surface lets the magenta-pink seed read as lit neon; accent shifts to warm coral to create cinematic dichromatic tension without competing chroma." },
|
||||
{ id: "seed-228", oklch: [0.360, 0.147, 340.0],
|
||||
mood: "Figma-era creative tool plum — considered productivity software for designers, the inky violet of a serif wordmark on a marketing site",
|
||||
strategy: "Held the seed as a deep plum primary against pure white so the brand color does the emotional work; paired with a muted rose accent for warmth without breaking the productivity-tool restraint." },
|
||||
{ id: "seed-107", oklch: [0.500, 0.200, 340.0],
|
||||
mood: "Figma plum — creative-tool confidence, considered magenta for a modern design product",
|
||||
strategy: "Pure white surface lets a saturated magenta-plum primary carry all the brand voice, paired with a cooler violet-leaning accent for hierarchy without competing." },
|
||||
{ id: "seed-198", oklch: [0.600, 0.210, 340.0],
|
||||
mood: "Figma-era creative tool plum — confident, considered, made for makers",
|
||||
strategy: "Anchor a saturated plum primary against pure white so the brand color does all the emotional work, with a deeper magenta-rose accent for hierarchy." },
|
||||
{ id: "seed-112", oklch: [0.754, 0.193, 343.4],
|
||||
mood: "Figma-era creative tool — confident pink primary doing the brand work on a clean canvas, the way Linear uses indigo or Stripe uses violet",
|
||||
strategy: "Anchor the seed pink as a saturated brand primary on pure white so the color carries all the personality; pair with a cooler plum accent to give the pink something to push against without competing." },
|
||||
{ id: "seed-229", oklch: [0.420, 0.163, 350.0],
|
||||
mood: "considered fintech rose — the deep magenta of a modern product brand (think Stripe-adjacent, but rotated toward berry), confident and current",
|
||||
strategy: "pure white surface lets a single deep berry-rose primary do all the brand work, paired with a cooler indigo accent for the contrast move you see in modern product marketing" },
|
||||
{ id: "seed-113", oklch: [0.470, 0.173, 354.8],
|
||||
mood: "1960s velvet rope nightclub — crushed magenta, low light, cigarette smoke catching a spotlight",
|
||||
strategy: "Pure black stage so the seed's smoky magenta reads as a single hot spotlight, paired with a cooler violet accent for the second light cue." },
|
||||
{ id: "seed-114", oklch: [0.570, 0.158, 353.3],
|
||||
mood: "fin-de-siècle Parisian rose — velvet curtain, theatre program, lipstick blotted on linen",
|
||||
strategy: "Drop bg to true black so the dusty-rose primary reads as stage-lit silk; accent shifts to a warmer coral-mauve at higher lightness to create gentle hue rotation without breaking the romance." },
|
||||
{ id: "seed-199", oklch: [0.650, 0.180, 350.0],
|
||||
mood: "modern fintech rose — the considered pink of a Series B brand mark, confident and current without nostalgia",
|
||||
strategy: "Pure white surface lets a saturated rose primary do the brand work, paired with a deep plum accent for hierarchy — the Stripe move applied to a pink hue." },
|
||||
{ id: "seed-115", oklch: [0.636, 0.218, 355.3],
|
||||
mood: "backstage at a cabaret — velvet rope, lipstick mark on a champagne glass",
|
||||
strategy: "Seed reads as a saturated stage-light magenta-red; I push it into pure black so the primary glows like a neon sign and the accent (a cold pearl-pink) acts as the spotlight rim — the room is dark, the color does the singing." },
|
||||
{ id: "seed-230", oklch: [0.650, 0.249, 354.5],
|
||||
mood: "Modern fintech rose — the considered pink of a contemporary payments brand: confident, alive, and clear-headed",
|
||||
strategy: "Pure white bg lets a saturated rose-magenta primary carry all the brand energy, paired with a cooler indigo accent for trustworthy contrast — the Stripe move applied to a pink hue." },
|
||||
{ id: "seed-231", oklch: [0.682, 0.241, 353.2],
|
||||
mood: "Figma-era creative tool — a confident pink-magenta product brand, the kind a modern design platform uses to feel alive without shouting",
|
||||
strategy: "Default A pure white bg lets the saturated pink-magenta primary do all the brand work, with a near-complementary cool teal accent for tool-like clarity and a neutral ink for editorial calm" },
|
||||
{ id: "seed-116", oklch: [0.734, 0.183, 356.8],
|
||||
mood: "modern beauty brand DTC — Glossier-adjacent pink, confident and current without being saccharine",
|
||||
strategy: "Pure white surface so the rose-pink primary carries all the brand warmth, paired with a near-black ink and a desaturated mauve accent for editorial restraint." },
|
||||
];
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = { id: null, from: null };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === '--id' && argv[i + 1]) { args.id = argv[++i]; }
|
||||
else if (a === '--from' && argv[i + 1]) { args.from = argv[++i]; }
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
// Hash a key into a stable float in [0, 1) for deterministic weighted picks.
|
||||
function hashUnit(key) {
|
||||
const h = crypto.createHash('sha256').update(key).digest();
|
||||
return h.readUInt32BE(0) / 0x100000000;
|
||||
}
|
||||
|
||||
// The curated library is hue-skewed (more reds/oranges than teals/magentas)
|
||||
// because that's where the source material + taste landed. Left uniform, a
|
||||
// random pick would land on red ~1/3 of the time. Inverse-frequency weighting
|
||||
// gives each seed a weight of 1/(count in its 30° hue bucket), so each hue
|
||||
// ZONE is roughly equally likely to be chosen regardless of how many seeds it
|
||||
// holds — fair rainbow exposure across runs without pruning the library.
|
||||
function buildWeights(seeds) {
|
||||
const bucketCount = {};
|
||||
const bucketOf = (s) => Math.floor(((s.oklch[2] % 360) + 360) % 360 / 30);
|
||||
for (const s of seeds) { const b = bucketOf(s); bucketCount[b] = (bucketCount[b] || 0) + 1; }
|
||||
const weights = seeds.map((s) => 1 / bucketCount[bucketOf(s)]);
|
||||
const total = weights.reduce((a, b) => a + b, 0);
|
||||
return { weights, total };
|
||||
}
|
||||
|
||||
function weightedPick(seeds, unit) {
|
||||
const { weights, total } = buildWeights(seeds);
|
||||
let target = unit * total;
|
||||
for (let i = 0; i < seeds.length; i++) {
|
||||
target -= weights[i];
|
||||
if (target < 0) return seeds[i];
|
||||
}
|
||||
return seeds[seeds.length - 1];
|
||||
}
|
||||
|
||||
function pickSeed(seeds, { id, from }) {
|
||||
if (id) {
|
||||
const found = seeds.find(s => s.id === id);
|
||||
if (!found) { console.error(`no seed with id "${id}"`); process.exit(2); }
|
||||
return found;
|
||||
}
|
||||
const envFrom = process.env.IMPECCABLE_PALETTE_SEED;
|
||||
const key = from || envFrom;
|
||||
const unit = key ? hashUnit(key) : Math.random();
|
||||
return weightedPick(seeds, unit);
|
||||
}
|
||||
|
||||
function fmtOklch([L, C, H]) {
|
||||
return `oklch(${L.toFixed(3)} ${C.toFixed(3)} ${H.toFixed(1)})`;
|
||||
}
|
||||
|
||||
function hueWord(H) {
|
||||
if (H < 15 || H >= 345) return 'pure red';
|
||||
if (H < 35) return 'warm red / crimson';
|
||||
if (H < 55) return 'warm coral / burnt orange';
|
||||
if (H < 80) return 'orange / honey';
|
||||
if (H < 105) return 'warm amber / honey-gold';
|
||||
if (H < 135) return 'yellow-green / olive';
|
||||
if (H < 170) return 'green';
|
||||
if (H < 200) return 'teal';
|
||||
if (H < 230) return 'sky blue';
|
||||
if (H < 265) return 'cobalt / indigo';
|
||||
if (H < 295) return 'violet / purple';
|
||||
if (H < 330) return 'magenta / pink';
|
||||
return 'deep pink / rose';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const seed = pickSeed(SEEDS, args);
|
||||
const [L, C, H] = seed.oklch;
|
||||
|
||||
// The mood + strategy on each seed were derived by the model that
|
||||
// originally judged it. We surface them as *hints*, not commands —
|
||||
// the brief should still drive what the seed becomes.
|
||||
const moodHint = seed.mood ? ` (one read: "${seed.mood}")` : '';
|
||||
const strategyHint = seed.strategy ? `\n - one example strategy: ${seed.strategy}` : '';
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// Fat tool-exit response — what the model sees on stdout.
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
process.stdout.write(`BRAND SEED · ${seed.id}
|
||||
|
||||
Seed color (anchor for your primary brand color):
|
||||
${fmtOklch(seed.oklch)} — ${hueWord(H)}${moodHint}
|
||||
|
||||
This is the brand's anchor — a single beautiful color. Compose the rest of
|
||||
the palette around it using YOUR judgment, the brief (PRODUCT.md /
|
||||
DESIGN.md / the user's prompt), and the color-strategy guidance already in
|
||||
SKILL.md.
|
||||
|
||||
How to use:
|
||||
|
||||
1. Read the brief. Write one specific phrase describing the mood this
|
||||
product calls for. Be granular. Good: "1970s travel poster — sun-baked
|
||||
warmth, considered", "midnight jazz club — smoky brass, saxophone
|
||||
light", "Scandinavian winter morning — quiet light through frost". Bad:
|
||||
"modern and clean", "warm and inviting". The first lets you compose; the
|
||||
second is generic and will produce generic palettes.
|
||||
|
||||
2. The seed's hue (${H.toFixed(0)}°) anchors your primary brand color. You
|
||||
choose L and C to match the mood. The same hue can be deep-and-velvet,
|
||||
bright-and-confident, or pale-and-faded — pick the one the mood demands.
|
||||
Primary's hue should stay within ±10° of the seed.${strategyHint}
|
||||
|
||||
3. Now compose the full palette in OKLCH (5 more roles):
|
||||
• bg — the most important architectural choice.
|
||||
CORE PRINCIPLE: the mood lives in the BRAND COLORS
|
||||
(primary + accent) and typography, NOT in the surface.
|
||||
Stripe is warm — its purple does that, bg is pure
|
||||
white. Linear is cool — its blue does that, bg is
|
||||
pure. Notion is warm — its accents do that, bg is
|
||||
near-pure-white. Putting warmth in BOTH primary AND
|
||||
bg is the AI cliché.
|
||||
|
||||
DEFAULT A — PURE white: exactly oklch(1.000 0.000 0).
|
||||
Not 0.99, not chroma 0.002. Stripe / Notion / Apple
|
||||
use literal #ffffff. Don't add hidden warmth.
|
||||
Refs: Stripe, Notion, Linear (light), Apple.com,
|
||||
Vercel docs, Figma marketing, Loom, Substack.
|
||||
|
||||
DEFAULT B — PURE black/near-black: L 0.04-0.12,
|
||||
chroma exactly 0.000. No hue tint. Vercel is
|
||||
roughly oklch(0.08 0 0). Pick L for mood; C is 0.
|
||||
Refs: Vercel, A24, Acne, Apple dark, MUBI.
|
||||
|
||||
ALT 2 — TINTED: chroma 0.015-0.05.
|
||||
Use ONLY when:
|
||||
(a) the mood is EXPLICITLY environmental — the surface
|
||||
IS part of the brand (1920s lacquered interior,
|
||||
leather library, ceramic studio, hotel lobby), or
|
||||
(b) the seed itself is desaturated (chroma < 0.10) and
|
||||
needs a tinted surface to read as a brand.
|
||||
NOT for "feels warm" / "modern + warm" / "moody". If
|
||||
your mood says "warm" but doesn't name a specific
|
||||
environment, use PURE white and let primary carry
|
||||
the warmth.
|
||||
|
||||
HEURISTIC: if seed chroma > 0.10 AND mood is product-
|
||||
focused (not environment-focused), it's almost always
|
||||
PURE white. Target distribution across many palettes:
|
||||
~50% pure white, ~25% pure black, ~25% tinted.
|
||||
• surface — bg pulled slightly toward ink (10-15% mix). Same hue
|
||||
family as bg. Used for cards, panels, sections.
|
||||
• ink — body text color. Must reach ≥7:1 contrast vs bg.
|
||||
Can carry the brand hue at low chroma in light mode
|
||||
(slight warmth or coolness toward the brand).
|
||||
• accent — a SECOND brand color, distinct from primary in BOTH
|
||||
hue AND lightness. Picked to complement the mood (not
|
||||
default-complementary across the wheel). Used for
|
||||
badges, status pills, links, accent rules.
|
||||
• muted — secondary text. Ink pulled 40% toward bg, keeping ink's
|
||||
hue. Must reach ≥3.5:1 contrast vs bg.
|
||||
|
||||
4. Pick a color STRATEGY (the four steps from SKILL.md):
|
||||
• Restrained: tinted neutrals + accent ≤10% — product default
|
||||
• Committed: one saturated color carries 30-60% — identity-driven
|
||||
• Full palette: 3-4 named roles each used deliberately — brand work
|
||||
• Drenched: the surface IS the color — campaign, hero, statement
|
||||
The brief picks the strategy. A startup dashboard ≠ a perfume brand.
|
||||
|
||||
Hard rules (already in SKILL.md, recapped because the seed step is where
|
||||
they actually bite):
|
||||
|
||||
- OKLCH only — never hex. Never #RRGGBB.
|
||||
- ink-vs-bg WCAG contrast ≥ 7 (body text must be readable)
|
||||
- primary chroma ≤ 0.23 (above this, primary glows perceptually and
|
||||
no text on it is readable — acid-bright is a UI failure)
|
||||
- if primary L > 0.78, primary chroma ≤ 0.18 (the fluorescent zone)
|
||||
- primary-vs-accent contrast ≥ 1.7 (they must be visually distinct,
|
||||
not two variants of the same hue at similar lightness)
|
||||
- accent must carry readable text on a filled badge/pill: EITHER
|
||||
saturated (chroma ≥ 0.10) OR clearly light (L ≥ 0.85) OR clearly
|
||||
dark (L ≤ 0.30). Never a muddy mid-tone (L 0.45-0.72 + chroma < 0.10)
|
||||
— taupe/mushroom/dusty-grey accents read as weak and can't hold text
|
||||
either way. Saturate it or push its lightness to a clear light/dark.
|
||||
- avoid the saturated AI attractor zones: claude-beige (warm-cream bg
|
||||
+ dusty brown primary), forest-green-on-cream, AI-purple-on-white,
|
||||
navy-cream-with-orange-accent
|
||||
|
||||
TEXT-ON-COLOR FILLS — pick by perceptual contrast, not just WCAG. The
|
||||
rule applies to ANY element where text sits on a saturated color fill:
|
||||
primary buttons, accent buttons, badges, status pills, tag highlights,
|
||||
filled callouts. Don't only think "primary button" — apply consistently.
|
||||
|
||||
For any saturated mid-luminance color (L between 0.42 and 0.78, chroma ≥
|
||||
0.08), use WHITE text (or near-white from your bg), not dark text — even
|
||||
if WCAG says dark technically passes. The Helmholtz-Kohlrausch effect
|
||||
makes saturated colors appear brighter than their luminance suggests,
|
||||
and dark text on a warm-or-cool-saturated fill reads as muddy.
|
||||
|
||||
Convention: Stripe orange CTAs, McDonald's red, every fintech orange
|
||||
button, Vercel's filled badges, Linear's status pills — all use white
|
||||
text on saturated bg fills.
|
||||
|
||||
Dark text is correct only on PALE fills (L > 0.85) or PURE-NEUTRAL fills
|
||||
(chroma near 0). Everything else: white text.
|
||||
|
||||
Return your composed palette in CSS custom properties using OKLCH, then
|
||||
build with it. The seed is the start, not the recipe.
|
||||
`);
|
||||
@@ -27,7 +27,7 @@ const HARNESS_DIRS = [
|
||||
|
||||
// Valid sub-command names
|
||||
const VALID_COMMANDS = [
|
||||
'craft', 'teach', 'extract', 'document', 'shape',
|
||||
'craft', 'init', 'extract', 'document', 'shape',
|
||||
'critique', 'audit',
|
||||
'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
|
||||
'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
{
|
||||
"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.1.1",
|
||||
"version": "3.5.0",
|
||||
"author": {
|
||||
"name": "Paul Bakaus",
|
||||
"email": "paul@paulbakaus.com"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"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.1.1",
|
||||
"version": "3.5.0",
|
||||
"author": {
|
||||
"name": "Paul Bakaus",
|
||||
"email": "paul@paulbakaus.com"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
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.1.1
|
||||
version: 3.5.0
|
||||
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.
|
||||
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · init|document|extract|live] [target]"
|
||||
license: Apache 2.0
|
||||
allowed-tools:
|
||||
- Bash(npx impeccable *)
|
||||
---
|
||||
@@ -13,85 +13,80 @@ Designs and iterates production-grade frontend interfaces. Real working code, co
|
||||
|
||||
## Setup
|
||||
|
||||
Before any design work or file edits:
|
||||
You MUST do these steps before proceeding:
|
||||
|
||||
1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
|
||||
2. Identify the register and load the matching register reference (brand.md or product.md).
|
||||
3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
|
||||
1. Run `node .claude/skills/impeccable/scripts/context.mjs` once per session. If you've already seen its output in this conversation, do not re-run it. The script either prints the project's PRODUCT.md (and DESIGN.md when present) as a markdown block, or tells you it's missing. Follow whatever it prints. **If it reports `NO_PRODUCT_MD`, stop and follow `reference/init.md` before doing anything else.** If the output ends with an `UPDATE_AVAILABLE` directive, follow it (ask the user once about updating, then continue). It never blocks the current task.
|
||||
2. If the user invoked a sub-command (`craft`, `shape`, `audit`, `polish`, ...), you MUST read `reference/<command>.md` next. Non-optional. The reference defines the command's flow; without it you will skip steps the user expects.
|
||||
3. Familiarize yourself with any existing design system, conventions, and components in the code. Read at least one project file (CSS / tokens / theme / a representative component or page). **Required even when you've loaded a sub-command reference in step 2.** Don't reinvent the wheel; use what's there when it works, branch out when the UX wins.
|
||||
4. Read the matching register reference. **This is non-optional; skipping it produces generic output.** If the project is marketing, a landing page, a campaign, long-form content, or a portfolio (design IS the product), read `reference/brand.md`. If it is app UI, admin, a dashboard, or a tool (design SERVES the product), read `reference/product.md`. Pick by first match: (1) task cue ("landing page" vs "dashboard"); (2) surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md.
|
||||
5. **If the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .claude/skills/impeccable/scripts/palette.mjs` to receive a brand seed color and composition guidance. This is the anchor for your primary brand color. Compose the rest of the palette (bg, surface, ink, accent, muted) around it per the script's instructions. Use OKLCH throughout. **Skip this step only if step 3 found committed brand colors in existing tokens; in that case identity-preservation wins.**
|
||||
|
||||
Skipping these produces generic output that ignores the project.
|
||||
## Design guidance
|
||||
|
||||
### 1. Context gathering
|
||||
Produce ready-to-ship, production-grade code, not prototypes or starting points. Take no shortcuts unless the user asks for them (when in doubt, ask). Don't stop until arriving at a complete implementation (beautiful, responsive, fast, precise, bug-free, on brand). You take attention to detail seriously: every page, section or component crafted is battle tested using the tools available to you (browser screenshotting, computer use, etc). Claude is capable of extraordinary work. Don't hold back.
|
||||
|
||||
Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
|
||||
### General rules
|
||||
|
||||
- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
|
||||
- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
|
||||
#### Color
|
||||
|
||||
Load both in one call:
|
||||
- **Verify contrast.** Body text must hit ≥4.5:1 against its background; large text (≥18px or bold ≥14px) needs ≥3:1. Placeholder text needs the same 4.5:1, not the muted-gray default. The most common failure: muted gray body text on a tinted near-white. If the contrast is even close, bump the body color toward the ink end of the ramp; light gray "for elegance" is the single biggest reason AI designs feel hard to read.
|
||||
- Gray text on a colored background looks washed out. Use a darker shade of the background's own hue, or a transparency of the text color.
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/load-context.mjs
|
||||
```
|
||||
#### Typography
|
||||
|
||||
Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
|
||||
- Cap body line length at 65–75ch.
|
||||
- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
|
||||
- Cap font-family count at 3 (display + body + optional mono). More than 3 reads as indecision, not richness. One well-tuned family with weight contrast usually beats three competing typefaces.
|
||||
- Don't pair fonts that are similar but not identical (two geometric sans-serifs, two humanist sans-serifs). Pair on a contrast axis (serif + sans, geometric + humanist) or use one family in multiple weights.
|
||||
- No all-caps body copy. Reserve uppercase for short labels (≤4 words), section eyebrows (used sparingly per the Absolute bans), and badges. Sentences in ALL CAPS are unreadable at body sizes.
|
||||
- Hero / display heading ceiling: clamp() max ≤ 6rem (~96px). Above that the page is shouting, not designing.
|
||||
- Display heading letter-spacing floor: ≥ -0.04em. Anything tighter and letters touch; cramped, not "designed".
|
||||
- Use `text-wrap: balance` on h1–h3 for even line lengths; `text-wrap: pretty` on long prose to reduce orphans.
|
||||
|
||||
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.
|
||||
#### Layout
|
||||
|
||||
`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
|
||||
- Vary spacing for rhythm.
|
||||
- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
|
||||
- Flexbox for 1D, Grid for 2D. Don't default to Grid when `flex-wrap` would be simpler.
|
||||
- For responsive grids without breakpoints: `repeat(auto-fit, minmax(280px, 1fr))`.
|
||||
- Build a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip). Never arbitrary values like 999 or 9999.
|
||||
|
||||
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 the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
|
||||
#### Motion
|
||||
- Motion should be intentional, and not be an afterthought. consider it as part of the build.
|
||||
- Don't animate CSS layout properties unless truly needed.
|
||||
- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
|
||||
- Use libraries for more advanced motion needs (e.g. motion, gsap, anime.js, lenis etc)
|
||||
- Reduced motion is not optional. Every animation needs a `@media (prefers-reduced-motion: reduce)` alternative: typically a crossfade or instant transition.
|
||||
- Staggering the items within one list is legitimate. The tell is the uniform reflex (one identical entrance applied to every section), not motion itself; each reveal should fit what it reveals. Suppressing the reflex is never a reason to ship a page with no motion at all.
|
||||
- Reveal animations must enhance an already-visible default. Don't gate content visibility on a class-triggered transition; transitions pause on hidden tabs and headless renderers, so the reveal never fires and the section ships blank.
|
||||
- Premium motion materials are not just transform/opacity. Blur, backdrop-filter, clip-path, mask, and shadow/glow are part of the palette when they materially improve the effect and stay smooth.
|
||||
|
||||
If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
|
||||
#### Interaction
|
||||
|
||||
### 2. Register
|
||||
- Dropdowns rendered with `position: absolute` inside an `overflow: hidden` or `overflow: auto` container will be clipped. Use the native `<dialog>` / popover API, `position: fixed`, or a portal to escape the stacking context.
|
||||
|
||||
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).
|
||||
### Copy
|
||||
|
||||
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.
|
||||
- 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 `--`.
|
||||
- **No aphoristic-cadence body copy as a default voice.** Don't fall into the rhythm of "serious statement, then punchy short negation" as the page's recurring voice. If three or more section copy blocks on the page land on a short rebuttal-shaped sentence, rewrite. Specific, not aphoristic.
|
||||
- **No marketing buzzwords.** The streamline / empower / supercharge / leverage / unleash / transform / seamless / world-class / enterprise-grade / next-generation / cutting-edge / game-changer / mission-critical family of phrases. Pick a specific noun and a verb that describes what the product literally does.
|
||||
- Button labels: verb + object. "Save changes" beats "OK"; "Delete project" beats "Yes". The label should say what will happen.
|
||||
- Link text needs standalone meaning. "View pricing plans" beats "Click here"; screen readers announce links out of context.
|
||||
|
||||
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.
|
||||
### New projects only (when no prior work exists)
|
||||
|
||||
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.
|
||||
#### Color & Theme
|
||||
|
||||
## 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).
|
||||
- Use OKLCH.
|
||||
- **The cream / sand / beige body bg is the saturated AI default of 2026.** The whole warm-neutral band (OKLCH L 0.84-0.97, C < 0.06, hue 40-100) reads as cream/sand/paper/parchment regardless of what you call it. Token names like `--paper`, `--cream`, `--sand`, `--bone`, `--flour`, `--linen`, `--parchment`, `--wheat`, `--biscuit`, `--ivory` are tells in themselves. If the brief is "warm, traditional, family-coastal-Italian" or "magazine-warm" or "editorial-restraint", DO NOT translate that into a near-white warm-tinted bg; that's the AI move. Pick: (a) a saturated brand color as the body (terracotta, oxblood, deep ochre, near-black), (b) a true off-white at chroma 0 (or chroma toward the brand's own hue, not toward warmth-by-default), or (c) a darker mid-tone tinted neutral that's clearly the brand's own. "Warmth" in the brand is carried by accent + typography + imagery, not by body bg.
|
||||
- Tinted neutrals: add 0.005–0.015 chroma toward the brand's hue. Don't default-tint toward warm or cool "because the brand feels that way"; that's the cross-project monoculture move.
|
||||
- When picking a 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.
|
||||
- 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
|
||||
|
||||
@@ -102,12 +97,9 @@ Match-and-refuse. If you're about to write any of these, rewrite the element wit
|
||||
- **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 `--`.
|
||||
- **Tiny uppercase tracked eyebrow above every section.** The 2023-era kicker (small all-caps text with wide tracking, "ABOUT" "PROCESS" "PRICING" above each heading) is now the saturated AI scaffold; it appears on 55-95% of generations regardless of brief, which is the definition of a tell. One named kicker as a deliberate brand system is voice; an eyebrow on every section is AI grammar. Choose a different cadence.
|
||||
- **Numbered section markers as default scaffolding (01 / 02 / 03).** Putting `01 · About / 02 · Process / 03 · Pricing` above every section is the eyebrow trope one tier deeper: reach for it because "landing pages do this" and you're scaffolding by reflex. Numbers earn their place when the section actually IS a sequence (a real 3-step process, an ordered flow, a typed timeline) and the order carries information the reader needs. One deliberate numbered sequence on one page is voice; numbered eyebrows on every section across the site is AI grammar.
|
||||
- **Text that overflows its container.** Long heading words plus large clamp scales plus narrow grids cause headline overflow on tablet/mobile. Test the heading copy at every breakpoint; if it overflows, reduce the clamp max or rewrite the copy. The viewport is part of the design.
|
||||
|
||||
### The AI slop test
|
||||
|
||||
@@ -115,7 +107,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
|
||||
|
||||
**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
|
||||
|
||||
- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
|
||||
- **First-order:** if someone could guess the theme + palette from the category alone, it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
|
||||
- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
|
||||
|
||||
## Commands
|
||||
@@ -124,7 +116,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
|
||||
|---|---|---|---|
|
||||
| `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) |
|
||||
| `init` | Build | Set up project context: PRODUCT.md, DESIGN.md, live config, next steps | [reference/init.md](reference/init.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) |
|
||||
@@ -152,11 +144,14 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
|
||||
|
||||
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.
|
||||
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
|
||||
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, 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`.
|
||||
|
||||
If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
|
||||
If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `init` as a blocker, finish init, refresh context, then resume the original command and target.
|
||||
|
||||
`teach` is a deprecated alias for `init`: if the user types it, load [reference/init.md](reference/init.md) and proceed as if they ran `init`.
|
||||
|
||||
## Pin / Unpin
|
||||
|
||||
|
||||
@@ -188,3 +188,124 @@ Test thoroughly across contexts:
|
||||
- **Slow connections**: Test on throttled network
|
||||
|
||||
When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously `responsive-design.md` and live inline now so the adapt flow has its deep responsive reference in one place.
|
||||
|
||||
### Responsive Design
|
||||
|
||||
#### Mobile-First: Write It Right
|
||||
|
||||
Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
|
||||
|
||||
#### Breakpoints: Content-Driven
|
||||
|
||||
Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
|
||||
|
||||
#### Detect Input Method, Not Just Screen Size
|
||||
|
||||
**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
|
||||
|
||||
```css
|
||||
/* Fine pointer (mouse, trackpad) */
|
||||
@media (pointer: fine) {
|
||||
.button { padding: 8px 16px; }
|
||||
}
|
||||
|
||||
/* Coarse pointer (touch, stylus) */
|
||||
@media (pointer: coarse) {
|
||||
.button { padding: 12px 20px; } /* Larger touch target */
|
||||
}
|
||||
|
||||
/* Device supports hover */
|
||||
@media (hover: hover) {
|
||||
.card:hover { transform: translateY(-2px); }
|
||||
}
|
||||
|
||||
/* Device doesn't support hover (touch) */
|
||||
@media (hover: none) {
|
||||
.card { /* No hover state - use active instead */ }
|
||||
}
|
||||
```
|
||||
|
||||
**Critical**: Don't rely on hover for functionality. Touch users can't hover.
|
||||
|
||||
#### Safe Areas: Handle the Notch
|
||||
|
||||
Modern phones have notches, rounded corners, and home indicators. Use `env()`:
|
||||
|
||||
```css
|
||||
body {
|
||||
padding-top: env(safe-area-inset-top);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
padding-left: env(safe-area-inset-left);
|
||||
padding-right: env(safe-area-inset-right);
|
||||
}
|
||||
|
||||
/* With fallback */
|
||||
.footer {
|
||||
padding-bottom: max(1rem, env(safe-area-inset-bottom));
|
||||
}
|
||||
```
|
||||
|
||||
**Enable viewport-fit** in your meta tag:
|
||||
```html
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
```
|
||||
|
||||
#### Responsive Images: Get It Right
|
||||
|
||||
##### srcset with Width Descriptors
|
||||
|
||||
```html
|
||||
<img
|
||||
src="hero-800.jpg"
|
||||
srcset="
|
||||
hero-400.jpg 400w,
|
||||
hero-800.jpg 800w,
|
||||
hero-1200.jpg 1200w
|
||||
"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
alt="Hero image"
|
||||
>
|
||||
```
|
||||
|
||||
**How it works**:
|
||||
- `srcset` lists available images with their actual widths (`w` descriptors)
|
||||
- `sizes` tells the browser how wide the image will display
|
||||
- Browser picks the best file based on viewport width AND device pixel ratio
|
||||
|
||||
##### Picture Element for Art Direction
|
||||
|
||||
When you need different crops/compositions (not just resolutions):
|
||||
|
||||
```html
|
||||
<picture>
|
||||
<source media="(min-width: 768px)" srcset="wide.jpg">
|
||||
<source media="(max-width: 767px)" srcset="tall.jpg">
|
||||
<img src="fallback.jpg" alt="...">
|
||||
</picture>
|
||||
```
|
||||
|
||||
#### Layout Adaptation Patterns
|
||||
|
||||
**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
|
||||
|
||||
#### Testing: Don't Trust DevTools Alone
|
||||
|
||||
DevTools device emulation is useful for layout but misses:
|
||||
|
||||
- Actual touch interactions
|
||||
- Real CPU/memory constraints
|
||||
- Network latency patterns
|
||||
- Font rendering differences
|
||||
- Browser chrome/keyboard appearances
|
||||
|
||||
**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
|
||||
|
||||
@@ -6,7 +6,7 @@ Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut moti
|
||||
|
||||
## 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.
|
||||
Brand: motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions. The saturated AI default is fade-and-rise reveals on every scrolled section; that's a tell, not a choreography. Reserve scroll-triggered motion for moments that earn it.
|
||||
|
||||
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.
|
||||
|
||||
@@ -49,10 +49,11 @@ Create a purposeful animation plan:
|
||||
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
|
||||
- **List rhythm**: Sibling stagger is legitimate for cards-in-a-grid or list-items-appearing. Whole-section fade-on-scroll is not a list and is not legitimate. Cap total stagger time: 10 items at 50ms each = 500ms total. For more items, reduce per-item delay or cap the staggered count.
|
||||
|
||||
Use CSS custom properties for clean stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"`, `style="--i: 1"`, etc. on each item.
|
||||
|
||||
### Micro-interactions
|
||||
- **Button feedback**:
|
||||
@@ -97,11 +98,14 @@ 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)
|
||||
**Duration: the 100/300/500 rule.** Timing matters more than easing for "feels right":
|
||||
|
||||
| Duration | Use Case | Examples |
|
||||
|----------|----------|----------|
|
||||
| **100–150ms** | Instant feedback | Button press, toggle, color change |
|
||||
| **200–300ms** | State changes | Menu open, tooltip, hover state |
|
||||
| **300–500ms** | Layout changes | Accordion, modal, drawer |
|
||||
| **500–800ms** | Entrance animations | Page load, hero reveal |
|
||||
|
||||
**Easing curves (use these, not CSS defaults):**
|
||||
```css
|
||||
@@ -134,13 +138,35 @@ Use appropriate techniques for each animation:
|
||||
- GSAP for complex sequences
|
||||
```
|
||||
|
||||
### Motion Materials
|
||||
|
||||
Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties. Match material to effect:
|
||||
|
||||
- **Transform / opacity**: movement, press feedback, simple reveals, list choreography
|
||||
- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances
|
||||
- **Clip-path / masks**: wipes, reveals, editorial cropping, product-like transitions
|
||||
- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state
|
||||
- **Grid-template-rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly
|
||||
|
||||
The hard rule isn't "transform and opacity only." It's: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify smoothness in-browser on target viewports.
|
||||
|
||||
### Performance
|
||||
- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
|
||||
- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
|
||||
- **will-change**: Add sparingly for known expensive animations
|
||||
- **will-change**: Add sparingly for known expensive animations only (e.g. on `:hover` or an `.animating` class), never preemptively across the whole page
|
||||
- **Scroll triggers**: Use Intersection Observer instead of scroll event listeners; unobserve after the animation fires once
|
||||
- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
|
||||
- **Monitor FPS**: Ensure 60fps on target devices
|
||||
|
||||
### Perceived Performance
|
||||
|
||||
Nobody cares how fast your site *is*, only how fast it feels. The 80ms threshold: anything under ~80ms feels instant because our brains buffer sensory input for that long to synchronize perception. Target this for micro-interactions.
|
||||
|
||||
- **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 (progressive images, streaming HTML, skeleton fade-ins).
|
||||
- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Use for low-stakes actions (likes, follows). 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.
|
||||
- **Caution**: Too-fast responses can decrease perceived value for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
|
||||
|
||||
### Accessibility
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
@@ -50,7 +50,7 @@ Create a strategy to increase impact while maintaining coherence:
|
||||
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)
|
||||
- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and the [Reference Material section of typeset.md](typeset.md#reference-material) 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)
|
||||
@@ -78,10 +78,10 @@ Systematically increase impact across these dimensions:
|
||||
- **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, which cheapen the effect)
|
||||
- **Hero moment**: One signature entrance, once. Not on every visit and not on every section.
|
||||
- **Micro-interactions**: Satisfying hover effects, click feedback, state changes.
|
||||
- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect).
|
||||
- **Bolder ≠ scroll-fade-rise on every section.** That's the saturated AI default, the opposite of bold.
|
||||
|
||||
### Composition Boldness
|
||||
- **Hero moments**: Create clear focal points with dramatic treatment
|
||||
|
||||
@@ -43,17 +43,10 @@ The reflex-reject lists apply to **new design choices**. When the existing brand
|
||||
|
||||
### 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.
|
||||
Distinctive + refined is the goal. The specific shape depends on the brand, not on the brand's category. A category ("restaurant", "dev tool", "magazine", "fintech") is not a recipe; treating it as one is the first-order reflex SKILL.md warns against.
|
||||
|
||||
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.
|
||||
@@ -74,8 +67,7 @@ Brand surfaces have permission for Committed, Full palette, and Drenched strateg
|
||||
|
||||
- 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.
|
||||
- For image-led briefs (hotels, restaurants, magazines, photography), full-bleed hero imagery with overlaid menu and centered headline is a canonical move; let the photograph be the design.
|
||||
- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
|
||||
|
||||
## Imagery
|
||||
@@ -93,8 +85,7 @@ Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landin
|
||||
|
||||
## 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`.
|
||||
- One well-orchestrated page-load beats scattered micro-interactions, when the brand invites it. Some brands skip entrance motion entirely; the restraint is the voice.
|
||||
|
||||
## Brand bans (on top of the shared absolute bans)
|
||||
|
||||
@@ -111,8 +102,7 @@ Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landin
|
||||
|
||||
Brand can afford things product can't. Take them.
|
||||
|
||||
- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
|
||||
- Ambitious first-load motion. Reveals and typographic choreography that earn their place; not fade-on-scroll for every section.
|
||||
- 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.
|
||||
|
||||
@@ -172,3 +172,117 @@ Test that copy improvements work:
|
||||
- **Tone**: Is it appropriate for the situation?
|
||||
|
||||
When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously `ux-writing.md` and live inline now so the clarify flow has its deep UX-writing reference in one place.
|
||||
|
||||
### UX Writing
|
||||
|
||||
#### The Button Label Problem
|
||||
|
||||
**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
|
||||
|
||||
| Bad | Good | Why |
|
||||
|-----|------|-----|
|
||||
| OK | Save changes | Says what will happen |
|
||||
| Submit | Create account | Outcome-focused |
|
||||
| Yes | Delete message | Confirms the action |
|
||||
| Cancel | Keep editing | Clarifies what "cancel" means |
|
||||
| Click here | Download PDF | Describes the destination |
|
||||
|
||||
**For destructive actions**, name the destruction:
|
||||
- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
|
||||
- "Delete 5 items" not "Delete selected" (show the count)
|
||||
|
||||
#### Error Messages: The Formula
|
||||
|
||||
Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
|
||||
|
||||
##### Error Message Templates
|
||||
|
||||
| Situation | Template |
|
||||
|-----------|----------|
|
||||
| **Format error** | "[Field] needs to be [format]. Example: [example]" |
|
||||
| **Missing required** | "Please enter [what's missing]" |
|
||||
| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
|
||||
| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
|
||||
| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
|
||||
|
||||
##### Don't Blame the User
|
||||
|
||||
Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
|
||||
|
||||
#### Empty States Are Opportunities
|
||||
|
||||
Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
|
||||
|
||||
#### Voice vs Tone
|
||||
|
||||
**Voice** is your brand's personality, consistent everywhere.
|
||||
**Tone** adapts to the moment.
|
||||
|
||||
| Moment | Tone Shift |
|
||||
|--------|------------|
|
||||
| Success | Celebratory, brief: "Done! Your changes are live." |
|
||||
| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
|
||||
| Loading | Reassuring: "Saving your work..." |
|
||||
| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
|
||||
|
||||
**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
|
||||
|
||||
#### Writing for Accessibility
|
||||
|
||||
**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
|
||||
|
||||
#### Writing for Translation
|
||||
|
||||
##### Plan for Expansion
|
||||
|
||||
German text is ~30% longer than English. Allocate space:
|
||||
|
||||
| Language | Expansion |
|
||||
|----------|-----------|
|
||||
| German | +30% |
|
||||
| French | +20% |
|
||||
| Finnish | +30-40% |
|
||||
| Chinese | -30% (fewer chars, but same width) |
|
||||
|
||||
##### Translation-Friendly Patterns
|
||||
|
||||
Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
|
||||
|
||||
#### Consistency: The Terminology Problem
|
||||
|
||||
Pick one term and stick with it:
|
||||
|
||||
| Inconsistent | Consistent |
|
||||
|--------------|------------|
|
||||
| Delete / Remove / Trash | Delete |
|
||||
| Settings / Preferences / Options | Settings |
|
||||
| Sign in / Log in / Enter | Sign in |
|
||||
| Create / Add / New | Create |
|
||||
|
||||
Build a terminology glossary and enforce it. Variety creates confusion.
|
||||
|
||||
#### Avoid Redundant Copy
|
||||
|
||||
If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
|
||||
|
||||
#### Loading States
|
||||
|
||||
Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
|
||||
|
||||
#### Confirmation Dialogs: Use Sparingly
|
||||
|
||||
Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
|
||||
|
||||
#### Form Instructions
|
||||
|
||||
Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
|
||||
|
||||
@@ -23,8 +23,8 @@ Before generating anything, run a brief direction conversation grounded in the s
|
||||
|
||||
Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
|
||||
|
||||
- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
|
||||
- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
|
||||
- "Brief says 'specimen-page restraint.' Are we closer to a quiet typographic page or a wider editorial spread with hero imagery?"
|
||||
- "Palette strategy from shape was 'Committed.' Which one color carries the surface (a brand-driven pick rather than a default warm-or-cool framing)? (And no, the answer isn't a cream/sand body bg; that's the saturated AI default.)"
|
||||
|
||||
**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
|
||||
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,105 +0,0 @@
|
||||
# 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).
|
||||
@@ -68,10 +68,10 @@ Add color systematically across these dimensions:
|
||||
- **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)`)
|
||||
- **Tinted backgrounds**: If you replace pure gray, tint toward the brand hue, not toward a generic-warm-or-cool pair. The default-warm-tint (`oklch(97% 0.01 60)` and its neighbors) is now the AI cream/sand giveaway. Be specific to the brand or stay neutral.
|
||||
- **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
|
||||
- **Cards & surfaces**: Tint cards or surfaces toward the brand, not "for warmth" by reflex
|
||||
|
||||
**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
|
||||
|
||||
@@ -124,8 +124,6 @@ Ensure color addition improves rather than overwhelms:
|
||||
- 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 depth
|
||||
- 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)
|
||||
@@ -152,3 +150,108 @@ When invoked from live mode, each variant MUST declare a `color-amount` param so
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously `color-and-contrast.md` and live inline now so the colorize flow has its deep color reference in one place.
|
||||
|
||||
### 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 |
|
||||
|
||||
##### Dangerous Color Combinations
|
||||
|
||||
These commonly fail contrast or cause readability issues:
|
||||
|
||||
- Light gray text on white (the #1 accessibility fail)
|
||||
- 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)
|
||||
|
||||
##### 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 | Either pure black or a deep surface that fits the brand (a brand-tinted near-black at oklch 12-18% works too) |
|
||||
|
||||
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. Skipping color blindness testing (8% of men affected).
|
||||
|
||||
@@ -56,15 +56,15 @@ If the harness has native image generation (Codex), a compact shape's "confirm o
|
||||
|
||||
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
|
||||
- [layout.md](layout.md) for layout, spacing, grid, container queries, optical adjustments
|
||||
- [typeset.md](typeset.md) for type hierarchy, font selection, web font loading, OpenType features (Reference Material section)
|
||||
|
||||
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)
|
||||
- Animation or transitions? Consult [animate.md](animate.md) (Reference Material covers motion materials, durations, easing, perceived performance)
|
||||
- Color-heavy or themed? Consult [colorize.md](colorize.md) (Reference Material covers OKLCH, palette structure, dark mode, contrast)
|
||||
- Responsive requirements? Consult [adapt.md](adapt.md) (Reference Material covers breakpoints, input methods, safe areas, responsive images)
|
||||
- Heavy on copy, labels, or errors? Consult [clarify.md](clarify.md) (Reference Material covers button labels, error formula, voice/tone, translation)
|
||||
|
||||
## Step 3: Visual Direction & Assets (Harness-Gated)
|
||||
|
||||
|
||||
@@ -38,9 +38,9 @@ Read relevant source files and visually inspect the live page when browser autom
|
||||
Evaluate:
|
||||
- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
|
||||
- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
|
||||
- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
|
||||
- **Cognitive load**: consult the [Cognitive Load Assessment](#cognitive-load-assessment) section below; report checklist failures and decision points with >4 visible options.
|
||||
- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
|
||||
- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
|
||||
- **Nielsen heuristics**: consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below; score all 10 heuristics 0-4.
|
||||
|
||||
Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
|
||||
|
||||
@@ -80,7 +80,7 @@ The chat response is the primary user-facing deliverable. Present the full struc
|
||||
Structure your feedback as a design director would:
|
||||
|
||||
#### Design Health Score
|
||||
> *Consult [heuristics-scoring](heuristics-scoring.md)*
|
||||
> *Consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below.*
|
||||
|
||||
Present the Nielsen's 10 heuristics scores as a table:
|
||||
|
||||
@@ -119,16 +119,16 @@ 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):
|
||||
For each issue, tag with **P0-P3 severity** (see [Issue Severity below](#issue-severity-p0p3) for 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)*
|
||||
> *Consult the [Personas reference](#persona-based-design-testing) below.*
|
||||
|
||||
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.
|
||||
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 init`, 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:
|
||||
|
||||
@@ -234,3 +234,534 @@ 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.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously separate reference files (`cognitive-load.md`, `heuristics-scoring.md`, `personas.md`). They live inline now so the critique flow has all its deep context in one place.
|
||||
|
||||
### 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.
|
||||
|
||||
---
|
||||
|
||||
### 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.
|
||||
|
||||
---
|
||||
|
||||
### 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 use 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 init`), 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.
|
||||
|
||||
@@ -45,7 +45,7 @@ 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.
|
||||
- **Scale keys are open-ended.** Use whatever names the project already uses (`oxblood-deep`, `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)
|
||||
@@ -61,7 +61,7 @@ Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] P
|
||||
|
||||
## When to run
|
||||
|
||||
- The user just ran `/impeccable teach` and needs the visual side documented.
|
||||
- The user just ran `/impeccable init` 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.
|
||||
@@ -71,7 +71,7 @@ If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user
|
||||
## 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.
|
||||
- **Seed mode**: the project is pre-implementation (fresh init, 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.
|
||||
|
||||
@@ -103,7 +103,7 @@ Build a structured draft from the discovered tokens. For each token class:
|
||||
|
||||
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.
|
||||
- **Colors**: one entry per extracted color. Key = descriptive slug (`oxblood-deep`, `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.
|
||||
@@ -253,7 +253,7 @@ Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user onl
|
||||
"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": ["...", "...", "..."] }
|
||||
"cool-paper": { "role": "neutral", "displayName": "Cool Paper", "canonical": "oklch(96% 0.005 230)", "tonalRamp": ["...", "...", "..."] }
|
||||
},
|
||||
"typographyMeta": {
|
||||
"display": { "displayName": "Display", "purpose": "Hero headlines only." }
|
||||
@@ -328,12 +328,13 @@ Pull directly from the DESIGN.md you just wrote:
|
||||
|
||||
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
|
||||
### Step 5: Confirm and refine
|
||||
|
||||
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 `.impeccable/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.
|
||||
|
||||
Your own write is the freshest source; subsequent commands in this session don't need a reload.
|
||||
|
||||
## Seed mode
|
||||
|
||||
@@ -394,11 +395,12 @@ Per-section guidance in seed mode:
|
||||
|
||||
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 `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
|
||||
|
||||
### Step 4: Confirm and refresh session cache
|
||||
### Step 4: Confirm
|
||||
|
||||
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.
|
||||
|
||||
Your own write is the freshest source; no reload needed.
|
||||
|
||||
## Style guidelines
|
||||
|
||||
|
||||
@@ -1,234 +0,0 @@
|
||||
# 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.
|
||||
+38
-22
@@ -1,21 +1,16 @@
|
||||
# Teach Flow
|
||||
# Init Flow
|
||||
|
||||
Gathers design context for a project and writes two complementary files at the project root:
|
||||
The setup command for a project. One codebase crawl feeds everything it writes:
|
||||
|
||||
- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
|
||||
- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
|
||||
- **`.impeccable/live/config.json`** (live mode): pre-configured so `/impeccable live` boots straight into variant mode with no first-time detour.
|
||||
|
||||
Every other impeccable command reads these files before doing any work.
|
||||
It closes by pointing the user at the best command to run next. Every other impeccable command reads PRODUCT.md and DESIGN.md before doing any work.
|
||||
|
||||
## Step 1: Load current state
|
||||
|
||||
Run the shared loader first so you know what already exists:
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/load-context.mjs
|
||||
```
|
||||
|
||||
The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
|
||||
Check what already exists. PRODUCT.md and DESIGN.md live at the project root, or under `.agents/context/` or `docs/` (case-insensitive). Read whichever are present with your native file tool. Also note whether `.impeccable/live/config.json` already exists (Step 6 leaves it untouched if so).
|
||||
|
||||
Decision tree:
|
||||
- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
|
||||
@@ -26,14 +21,14 @@ Decision tree:
|
||||
|
||||
Never silently overwrite an existing file. Always confirm first.
|
||||
|
||||
If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
|
||||
If init was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete init, then resume the original command. Your own writes are the freshest source; no reload needed. For craft, resume into shape next; init creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
|
||||
|
||||
## Step 2: Explore the codebase
|
||||
|
||||
Before asking questions, thoroughly scan the project to discover what you can:
|
||||
Before asking questions, thoroughly scan the project to discover what you can. This single crawl feeds PRODUCT.md, DESIGN.md, **and** the live-mode framework detection in Step 6, so be thorough once rather than re-scanning later:
|
||||
|
||||
- **README and docs**: Project purpose, target audience, any stated goals
|
||||
- **Package.json / config files**: Tech stack, dependencies, existing design libraries
|
||||
- **Package.json / config files**: Tech stack, dependencies, existing design libraries, **and the framework** (Vite/SPA, Next.js, Nuxt, SvelteKit, Astro, multi-page static) plus the HTML entry the browser actually loads
|
||||
- **Existing components**: Current design patterns, spacing, typography in use
|
||||
- **Brand assets**: Logos, favicons, color values already defined
|
||||
- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
|
||||
@@ -46,7 +41,7 @@ Also form a **register hypothesis** from what you find:
|
||||
|
||||
Register is a hypothesis at this point, not a decision; Step 3 confirms it.
|
||||
|
||||
Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
|
||||
Note what you've learned and what remains unclear. Also note any rough edges worth a follow-up command (thin hierarchy, flat or gray palette, missing error/empty states, dull copy); Step 7 turns these into concrete recommendations without re-analyzing.
|
||||
|
||||
## Step 3: Ask strategic questions (for PRODUCT.md)
|
||||
|
||||
@@ -84,8 +79,7 @@ If the signal is genuinely split (e.g. a product with a big marketing landing),
|
||||
### Brand & Personality
|
||||
- How would you describe the brand personality in 3 words?
|
||||
- Reference sites or apps that capture the right feel? What specifically about them?
|
||||
- For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
|
||||
- For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
|
||||
- Push for specific named references with the *specific* thing about them that fits this brand, not generic "modern" adjectives or category-bucket lanes.
|
||||
- What should this explicitly NOT look like? Any anti-references?
|
||||
|
||||
### Accessibility & Inclusion
|
||||
@@ -141,16 +135,38 @@ If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs
|
||||
|
||||
If the user prefers to skip, mention they can run `/impeccable document` any time later.
|
||||
|
||||
## Step 6: Confirm and wrap up
|
||||
## Step 6: Configure live mode (when code exists)
|
||||
|
||||
Summarize:
|
||||
If the project has code with HTML entries and a dev server (the same "code exists" condition that puts `/impeccable document` in scan mode), pre-configure live mode now. You already identified the framework and the served HTML entry in Step 2, so this is nearly free, and it spares the user the first-time setup detour when they later run `/impeccable live`.
|
||||
|
||||
**Skip this step for empty / pre-implementation projects** (nothing to inject into yet). Tell the user live mode will configure itself the first time they run it once there's code.
|
||||
|
||||
**If `.impeccable/live/config.json` already exists, leave it untouched** and note that live mode is already configured.
|
||||
|
||||
Otherwise:
|
||||
|
||||
1. Write `.impeccable/live/config.json`. Choose `files` (the HTML entries the browser actually loads), `insertBefore`, and `commentSyntax` from the framework table in [live.md](live.md)'s **First-time setup** section, using the framework you found in Step 2. That table is canonical; do not restate it here. For multi-page static sites, prefer a glob (`["public/**/*.html"]`) over a literal list.
|
||||
2. Run `node .claude/skills/impeccable/scripts/detect-csp.mjs`. If it reports a patchable shape (`append-arrays` / `append-string`), use the **consent prompt template** from live.md before editing any source file. On decline, skip the patch. For `middleware` / `meta-tag` shapes, surface the detected files and ask the user to add `http://localhost:8400` to `script-src` and `connect-src` manually. For `null`, there's nothing to do.
|
||||
3. Set `cspChecked: true` in the config once CSP is handled (patched, declined, manual, or not needed). The schema and per-shape patch details live in live.md's First-time setup; follow it rather than duplicating.
|
||||
|
||||
Writing the config file is harmless and needs no consent; only the CSP **source-file patch** requires a yes.
|
||||
|
||||
## Step 7: Recommend starting points, then wrap up
|
||||
|
||||
Summarize tersely:
|
||||
- Register captured (brand / product)
|
||||
- What was written (PRODUCT.md, DESIGN.md, or both)
|
||||
- What was written (PRODUCT.md, DESIGN.md, live config, or a subset)
|
||||
- The 3-5 strategic principles from PRODUCT.md that will guide future work
|
||||
- If DESIGN.md is pending, remind the user how to generate it later
|
||||
- If DESIGN.md or live config is pending, one line on how to set it up later
|
||||
|
||||
**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .claude/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
|
||||
Then recommend the **best commands to run next**, drawn from what your Step 2 crawl already surfaced. Do not run a fresh analysis here; surface observations you already have. Tailor to register and to what you saw, offer the 2-4 most relevant (not a menu dump), and give the exact command to type. Group by intent:
|
||||
|
||||
If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
|
||||
- **Build something new**: `/impeccable craft <feature>` (shape, then build end-to-end) or `/impeccable shape <feature>` (plan first). Lead with this for empty or early-stage projects.
|
||||
- **Improve what's there**: name the specific surface. `/impeccable critique <page>` for a scored UX review; `/impeccable audit <area>` for a11y / perf / responsive checks; `/impeccable polish <component>` for a pre-ship pass. When the crawl flagged a specific weakness, point the matching command at it: thin hierarchy or spacing → `layout`, flat or gray palette → `colorize`, missing error / empty states → `harden` or `onboard`, dull or unclear copy → `clarify`.
|
||||
- **Iterate visually**: `/impeccable live` (configured in Step 6) to pick elements in the browser and generate variants in place.
|
||||
|
||||
The full command menu is one bare `/impeccable` away; keep this list short and pointed.
|
||||
|
||||
If init was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now. Your own writes are the freshest source; no reload needed.
|
||||
|
||||
Optionally STOP and call the AskUserQuestion tool to clarify. Ask whether they'd like a brief summary of PRODUCT.md appended to CLAUDE.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
|
||||
@@ -150,12 +150,6 @@ For browsers without anchor positioning support, `position: fixed` with manual c
|
||||
|
||||
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.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
|
||||
Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids) and fix the structure, not the surface.
|
||||
|
||||
---
|
||||
|
||||
@@ -27,7 +27,6 @@ Analyze what's weak about the current spatial design:
|
||||
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)
|
||||
@@ -43,8 +42,6 @@ Analyze what's weak about the current spatial design:
|
||||
|
||||
## 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 (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
|
||||
@@ -57,6 +54,7 @@ Create a systematic plan:
|
||||
### Establish a Spacing System
|
||||
|
||||
- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
|
||||
- Prefer a 4pt base scale (4, 8, 12, 16, 24, 32, 48, 64, 96px) over 8pt; 8pt is too coarse and you'll frequently need 12px between 8 and 16.
|
||||
- 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
|
||||
@@ -66,15 +64,22 @@ Create a systematic plan:
|
||||
- **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
|
||||
- **Asymmetric compositions**: a deliberate choice when the content invites it (not a default to chase).
|
||||
|
||||
### 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 Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals.
|
||||
- **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.
|
||||
- Use **container queries** for components, viewport queries for page layouts. A card in a narrow sidebar can stay compact while the same card in a main content area expands automatically:
|
||||
|
||||
```css
|
||||
.card-container { container-type: inline-size; }
|
||||
.card { display: grid; gap: var(--space-md); }
|
||||
@container (min-width: 400px) {
|
||||
.card { grid-template-columns: 120px 1fr; }
|
||||
}
|
||||
```
|
||||
|
||||
### Break Card Grid Monotony
|
||||
|
||||
@@ -85,18 +90,36 @@ Create a systematic plan:
|
||||
### 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 polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
|
||||
- The best hierarchy combines 2–3 dimensions at once. A heading that's larger, bolder, AND has more space above it reads as primary without trying:
|
||||
|
||||
| Tool | Strong Hierarchy | Weak Hierarchy |
|
||||
|------|------------------|----------------|
|
||||
| **Size** | 3:1 ratio or more | <2:1 ratio |
|
||||
| **Weight** | Bold vs Regular | Medium vs Regular |
|
||||
| **Color** | High contrast | Similar tones |
|
||||
| **Position** | Top/left (primary) | Bottom/right |
|
||||
| **Space** | Surrounded by white space | Crowded |
|
||||
|
||||
- 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.
|
||||
- Text at `margin-left: 0` looks slightly indented because of letterform whitespace; a negative margin (`-0.05em`) optically aligns it. Geometrically centered glyphs often look off-center (play icons need to shift right, arrows shift toward their direction).
|
||||
- Touch targets must be 44×44px minimum even when the visual element is smaller. Expand the hit area with padding or a pseudo-element:
|
||||
|
||||
```css
|
||||
.icon-button { width: 24px; height: 24px; position: relative; }
|
||||
.icon-button::before {
|
||||
content: ''; position: absolute; inset: -10px;
|
||||
}
|
||||
```
|
||||
|
||||
**NEVER**:
|
||||
- Use arbitrary spacing values outside your scale
|
||||
@@ -104,10 +127,7 @@ Create a systematic plan:
|
||||
- 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
|
||||
|
||||
|
||||
@@ -9,18 +9,21 @@ A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR
|
||||
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.
|
||||
2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.
|
||||
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=`.
|
||||
|
||||
The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.
|
||||
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 runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
|
||||
6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
|
||||
7. On `exit`: run the cleanup at the bottom.
|
||||
5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.
|
||||
6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
|
||||
7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
|
||||
8. 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.
|
||||
- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).
|
||||
- **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.
|
||||
- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.
|
||||
|
||||
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.
|
||||
|
||||
@@ -30,7 +33,7 @@ Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodi
|
||||
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.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. 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.
|
||||
Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath }`. `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.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt.
|
||||
|
||||
`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).
|
||||
|
||||
@@ -38,12 +41,15 @@ If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`,
|
||||
|
||||
## Poll loop
|
||||
|
||||
**Default (portable, all harnesses):**
|
||||
|
||||
```
|
||||
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
|
||||
"steer" → Handle Steer; reply steer_done; LOOP
|
||||
"accept" → Handle Accept; complete carbonize cleanup if required; LOOP
|
||||
"discard" → Handle Discard; LOOP
|
||||
"prefetch" → Handle Prefetch; LOOP
|
||||
@@ -51,6 +57,16 @@ LOOP:
|
||||
"exit" → break → Cleanup
|
||||
```
|
||||
|
||||
**Stream mode (experimental, not for Cursor):**
|
||||
|
||||
```
|
||||
node .claude/skills/impeccable/scripts/live-poll.mjs --stream # stays running; one JSON line per event
|
||||
Handle event; run --reply in a separate command
|
||||
Repeat until "exit" line → Cleanup
|
||||
```
|
||||
|
||||
Stream keeps one process alive and waits for `--reply` ack before polling again. Useful only when the harness reads incremental stdout reliably and quickly. **Cursor is not one of those:** background pattern notify on a long-running shell was ~5s to pick up events vs sub-second for one-shot exit notify. Default to one-shot everywhere unless you have measured otherwise.
|
||||
|
||||
## Recovery commands
|
||||
|
||||
The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
|
||||
@@ -71,9 +87,32 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues
|
||||
|
||||
## Handle `generate`
|
||||
|
||||
Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
|
||||
**Replace mode** (default): `{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.
|
||||
**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.
|
||||
|
||||
Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.
|
||||
|
||||
### Insert mode branch
|
||||
|
||||
When `event.mode === "insert"`:
|
||||
|
||||
1. Read the screenshot if `event.screenshotPath` is present (annotations only).
|
||||
2. Run the insert helper instead of wrap:
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \
|
||||
--element-id "ANCHOR_ID" --classes "class1,class2" --tag "section" --text "ANCHOR_TEXT"
|
||||
```
|
||||
|
||||
- `--position` ← `event.insert.position` (`before` | `after`)
|
||||
- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)
|
||||
|
||||
The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.
|
||||
|
||||
On accept/discard, `live-accept.mjs` removes the wrapper block; the anchor element is untouched.
|
||||
|
||||
### Replace mode (default)
|
||||
|
||||
### 1. Read the screenshot (if present)
|
||||
|
||||
@@ -424,6 +463,28 @@ A background agent may be used for the rewrite, but the current thread is respon
|
||||
|
||||
Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
|
||||
|
||||
## Handle `steer`
|
||||
|
||||
Event: `{id, message, pageUrl}`. The user typed or spoke into the global bar **Steer** control: page-level direction without picking an element or launching variant generation.
|
||||
|
||||
The mic button uses the browser **Web Speech API** (MVP): click to start, speak, stop automatically when the utterance ends, then the transcript submits as a steer event. Click again while listening to cancel without submitting.
|
||||
|
||||
This is lighter than `generate`: no screenshot, no element context, no variant cycling. Read `message` and inspect the live page or project files as needed, then either make edits or answer in prose.
|
||||
|
||||
When finished:
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID steer_done ["Optional short note for a browser toast"]
|
||||
```
|
||||
|
||||
On failure:
|
||||
|
||||
```bash
|
||||
node .claude/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
|
||||
```
|
||||
|
||||
Then poll again immediately. Do not send a separate "picked up" reply. The Steer bar stays locked until `steer_done` or `error` arrives over SSE.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
# 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.
|
||||
|
||||
## Premium Motion Materials
|
||||
|
||||
Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
|
||||
|
||||
Use the right material for the effect:
|
||||
|
||||
- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
|
||||
- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
|
||||
- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
|
||||
- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
|
||||
- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
|
||||
|
||||
The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
|
||||
|
||||
## 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.
|
||||
@@ -1,179 +0,0 @@
|
||||
# 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 use 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.
|
||||
@@ -91,7 +91,6 @@ Visual polish on a misshapen flow is wasted work. Match the *shape* of the exper
|
||||
- **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
|
||||
|
||||
@@ -10,7 +10,6 @@ Product UI's failure mode isn't flatness, it's strangeness without purpose: over
|
||||
|
||||
## Typography
|
||||
|
||||
- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
|
||||
- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
|
||||
- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
|
||||
- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
|
||||
@@ -26,8 +25,6 @@ Product defaults to Restrained. A single surface can earn Committed (a dashboard
|
||||
|
||||
## Layout
|
||||
|
||||
- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
|
||||
- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
|
||||
- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
|
||||
|
||||
## Components
|
||||
@@ -51,6 +48,7 @@ Every interactive component has: default, hover, focus, active, disabled, loadin
|
||||
- Display fonts in UI labels, buttons, data.
|
||||
- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
|
||||
- Heavy color or full-saturation accents on inactive states.
|
||||
- Modal as first thought. Modals are usually laziness. Exhaust inline / progressive alternatives first.
|
||||
|
||||
## Product permissions
|
||||
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
# Responsive Design
|
||||
|
||||
## Mobile-First: Write It Right
|
||||
|
||||
Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
|
||||
|
||||
## Breakpoints: Content-Driven
|
||||
|
||||
Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
|
||||
|
||||
## Detect Input Method, Not Just Screen Size
|
||||
|
||||
**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
|
||||
|
||||
```css
|
||||
/* Fine pointer (mouse, trackpad) */
|
||||
@media (pointer: fine) {
|
||||
.button { padding: 8px 16px; }
|
||||
}
|
||||
|
||||
/* Coarse pointer (touch, stylus) */
|
||||
@media (pointer: coarse) {
|
||||
.button { padding: 12px 20px; } /* Larger touch target */
|
||||
}
|
||||
|
||||
/* Device supports hover */
|
||||
@media (hover: hover) {
|
||||
.card:hover { transform: translateY(-2px); }
|
||||
}
|
||||
|
||||
/* Device doesn't support hover (touch) */
|
||||
@media (hover: none) {
|
||||
.card { /* No hover state - use active instead */ }
|
||||
}
|
||||
```
|
||||
|
||||
**Critical**: Don't rely on hover for functionality. Touch users can't hover.
|
||||
|
||||
## Safe Areas: Handle the Notch
|
||||
|
||||
Modern phones have notches, rounded corners, and home indicators. Use `env()`:
|
||||
|
||||
```css
|
||||
body {
|
||||
padding-top: env(safe-area-inset-top);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
padding-left: env(safe-area-inset-left);
|
||||
padding-right: env(safe-area-inset-right);
|
||||
}
|
||||
|
||||
/* With fallback */
|
||||
.footer {
|
||||
padding-bottom: max(1rem, env(safe-area-inset-bottom));
|
||||
}
|
||||
```
|
||||
|
||||
**Enable viewport-fit** in your meta tag:
|
||||
```html
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
```
|
||||
|
||||
## Responsive Images: Get It Right
|
||||
|
||||
### srcset with Width Descriptors
|
||||
|
||||
```html
|
||||
<img
|
||||
src="hero-800.jpg"
|
||||
srcset="
|
||||
hero-400.jpg 400w,
|
||||
hero-800.jpg 800w,
|
||||
hero-1200.jpg 1200w
|
||||
"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
alt="Hero image"
|
||||
>
|
||||
```
|
||||
|
||||
**How it works**:
|
||||
- `srcset` lists available images with their actual widths (`w` descriptors)
|
||||
- `sizes` tells the browser how wide the image will display
|
||||
- Browser picks the best file based on viewport width AND device pixel ratio
|
||||
|
||||
### Picture Element for Art Direction
|
||||
|
||||
When you need different crops/compositions (not just resolutions):
|
||||
|
||||
```html
|
||||
<picture>
|
||||
<source media="(min-width: 768px)" srcset="wide.jpg">
|
||||
<source media="(max-width: 767px)" srcset="tall.jpg">
|
||||
<img src="fallback.jpg" alt="...">
|
||||
</picture>
|
||||
```
|
||||
|
||||
## Layout Adaptation Patterns
|
||||
|
||||
**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
|
||||
|
||||
## Testing: Don't Trust DevTools Alone
|
||||
|
||||
DevTools device emulation is useful for layout but misses:
|
||||
|
||||
- Actual touch interactions
|
||||
- Real CPU/memory constraints
|
||||
- Network latency patterns
|
||||
- Font rendering differences
|
||||
- Browser chrome/keyboard appearances
|
||||
|
||||
**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
|
||||
@@ -151,7 +151,7 @@ How users interact with this feature. What happens on click, hover, scroll? What
|
||||
What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
|
||||
|
||||
**9. Recommended References**
|
||||
Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
|
||||
Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., layout.md for complex layouts, animate.md for animated features, interaction-design.md for form-heavy features, typeset.md for typography-driven pages, colorize.md for color-led brands).
|
||||
|
||||
**10. Open Questions**
|
||||
Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
# Spatial Design
|
||||
|
||||
## Spacing Systems
|
||||
|
||||
### Use 4pt Base, Not 8pt
|
||||
|
||||
8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
|
||||
|
||||
### Name Tokens Semantically
|
||||
|
||||
Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
|
||||
|
||||
## Grid Systems
|
||||
|
||||
### The Self-Adjusting Grid
|
||||
|
||||
Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
|
||||
|
||||
## Visual Hierarchy
|
||||
|
||||
### The Squint Test
|
||||
|
||||
Blur your eyes (or screenshot and blur). Can you still identify:
|
||||
- The most important element?
|
||||
- The second most important?
|
||||
- Clear groupings?
|
||||
|
||||
If everything looks the same weight blurred, you have a hierarchy problem.
|
||||
|
||||
### Hierarchy Through Multiple Dimensions
|
||||
|
||||
Don't rely on size alone. Combine:
|
||||
|
||||
| Tool | Strong Hierarchy | Weak Hierarchy |
|
||||
|------|------------------|----------------|
|
||||
| **Size** | 3:1 ratio or more | <2:1 ratio |
|
||||
| **Weight** | Bold vs Regular | Medium vs Regular |
|
||||
| **Color** | High contrast | Similar tones |
|
||||
| **Position** | Top/left (primary) | Bottom/right |
|
||||
| **Space** | Surrounded by white space | Crowded |
|
||||
|
||||
**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
|
||||
|
||||
### Cards Are Not Required
|
||||
|
||||
Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
|
||||
|
||||
## Container Queries
|
||||
|
||||
Viewport queries are for page layouts. **Container queries are for components**:
|
||||
|
||||
```css
|
||||
.card-container {
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: grid;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
|
||||
/* Card layout changes based on its container, not viewport */
|
||||
@container (min-width: 400px) {
|
||||
.card {
|
||||
grid-template-columns: 120px 1fr;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
|
||||
|
||||
## Optical Adjustments
|
||||
|
||||
Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
|
||||
|
||||
### Touch Targets vs Visual Size
|
||||
|
||||
Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
|
||||
|
||||
```css
|
||||
.icon-button {
|
||||
width: 24px; /* Visual size */
|
||||
height: 24px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.icon-button::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: -10px; /* Expand tap target to 44px */
|
||||
}
|
||||
```
|
||||
|
||||
## Depth & Elevation
|
||||
|
||||
Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
|
||||
@@ -4,7 +4,7 @@ Typography carries most of the information on the page. Replace generic defaults
|
||||
|
||||
## Register
|
||||
|
||||
Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
|
||||
Brand: run the font selection procedure in [brand.md](brand.md). Fluid `clamp()` scale, ≥1.25 ratio between steps.
|
||||
|
||||
Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
|
||||
|
||||
@@ -43,7 +43,7 @@ Analyze what's weak or generic about the current type:
|
||||
|
||||
## Plan Typography Improvements
|
||||
|
||||
Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
|
||||
Consult the [Reference Material](#reference-material) section below for detailed guidance on scales, pairing, and loading strategies.
|
||||
|
||||
Create a systematic plan:
|
||||
|
||||
@@ -122,3 +122,158 @@ Each variant MUST declare a `scale` param controlling the hierarchy ratio. Expre
|
||||
Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
|
||||
|
||||
See `reference/live.md` for the full params contract.
|
||||
|
||||
---
|
||||
|
||||
## Reference Material
|
||||
|
||||
The sections below were previously `typography.md` and live inline now so the typeset flow has its deep typography reference in one place. `bolder.md` also references this section.
|
||||
|
||||
### Typography
|
||||
|
||||
#### Classic Typography Principles
|
||||
|
||||
##### Vertical Rhythm
|
||||
|
||||
Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
|
||||
|
||||
##### Modular Scale & Hierarchy
|
||||
|
||||
The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
|
||||
|
||||
**Use fewer sizes with more contrast.** A 5-size system covers most needs:
|
||||
|
||||
| Role | Typical Ratio | Use Case |
|
||||
|------|---------------|----------|
|
||||
| xs | 0.75rem | Captions, legal |
|
||||
| sm | 0.875rem | Secondary UI, metadata |
|
||||
| base | 1rem | Body text |
|
||||
| lg | 1.25-1.5rem | Subheadings, lead text |
|
||||
| xl+ | 2-4rem | Headlines, hero text |
|
||||
|
||||
Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
|
||||
|
||||
##### Readability & Measure
|
||||
|
||||
Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
|
||||
|
||||
**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
|
||||
|
||||
**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
|
||||
|
||||
#### Font Selection & Pairing
|
||||
|
||||
The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
|
||||
|
||||
##### Anti-reflexes worth defending against
|
||||
|
||||
- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
|
||||
- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
|
||||
- A children's product does NOT need a rounded display font. Kids' books use real type.
|
||||
- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
|
||||
|
||||
**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
|
||||
|
||||
##### Pairing Principles
|
||||
|
||||
**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
|
||||
|
||||
When pairing, contrast on multiple axes:
|
||||
- Serif + Sans (structure contrast)
|
||||
- Geometric + Humanist (personality contrast)
|
||||
- Condensed display + Wide body (proportion contrast)
|
||||
|
||||
##### Web Font Loading
|
||||
|
||||
The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
|
||||
|
||||
```css
|
||||
/* 1. Use font-display: swap for visibility */
|
||||
@font-face {
|
||||
font-family: 'CustomFont';
|
||||
src: url('font.woff2') format('woff2');
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* 2. Match fallback metrics to minimize shift */
|
||||
@font-face {
|
||||
font-family: 'CustomFont-Fallback';
|
||||
src: local('Arial');
|
||||
size-adjust: 105%; /* Scale to match x-height */
|
||||
ascent-override: 90%; /* Match ascender height */
|
||||
descent-override: 20%; /* Match descender depth */
|
||||
line-gap-override: 10%; /* Match line spacing */
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
|
||||
}
|
||||
```
|
||||
|
||||
Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
|
||||
|
||||
**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
|
||||
|
||||
**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
|
||||
|
||||
**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
|
||||
|
||||
#### Modern Web Typography
|
||||
|
||||
##### Fluid Type
|
||||
|
||||
Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
|
||||
|
||||
**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
|
||||
|
||||
**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
|
||||
|
||||
**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
|
||||
|
||||
**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
|
||||
|
||||
##### OpenType Features
|
||||
|
||||
Most developers don't know these exist. Use them for polish:
|
||||
|
||||
```css
|
||||
/* Proper fractions */
|
||||
.recipe-amount { font-variant-numeric: diagonal-fractions; }
|
||||
|
||||
/* Small caps for abbreviations */
|
||||
abbr { font-variant-caps: all-small-caps; }
|
||||
|
||||
/* Disable ligatures in code */
|
||||
code { font-variant-ligatures: none; }
|
||||
|
||||
/* Enable kerning (usually on by default, but be explicit) */
|
||||
body { font-kerning: normal; }
|
||||
```
|
||||
|
||||
Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
|
||||
|
||||
##### Rendering polish
|
||||
|
||||
```css
|
||||
/* Variable fonts: pick the right optical-size master automatically */
|
||||
body { font-optical-sizing: auto; }
|
||||
```
|
||||
|
||||
**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
|
||||
|
||||
#### Typography System Architecture
|
||||
|
||||
Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
|
||||
|
||||
#### Accessibility Considerations
|
||||
|
||||
Beyond contrast ratios (which are well-documented), consider:
|
||||
|
||||
- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
|
||||
- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
|
||||
- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
|
||||
- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
# Typography
|
||||
|
||||
## Classic Typography Principles
|
||||
|
||||
### Vertical Rhythm
|
||||
|
||||
Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
|
||||
|
||||
### Modular Scale & Hierarchy
|
||||
|
||||
The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
|
||||
|
||||
**Use fewer sizes with more contrast.** A 5-size system covers most needs:
|
||||
|
||||
| Role | Typical Ratio | Use Case |
|
||||
|------|---------------|----------|
|
||||
| xs | 0.75rem | Captions, legal |
|
||||
| sm | 0.875rem | Secondary UI, metadata |
|
||||
| base | 1rem | Body text |
|
||||
| lg | 1.25-1.5rem | Subheadings, lead text |
|
||||
| xl+ | 2-4rem | Headlines, hero text |
|
||||
|
||||
Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
|
||||
|
||||
### Readability & Measure
|
||||
|
||||
Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
|
||||
|
||||
**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
|
||||
|
||||
**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
|
||||
|
||||
## Font Selection & Pairing
|
||||
|
||||
The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
|
||||
|
||||
### Anti-reflexes worth defending against
|
||||
|
||||
- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
|
||||
- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
|
||||
- A children's product does NOT need a rounded display font. Kids' books use real type.
|
||||
- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
|
||||
|
||||
**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
|
||||
|
||||
### Pairing Principles
|
||||
|
||||
**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
|
||||
|
||||
When pairing, contrast on multiple axes:
|
||||
- Serif + Sans (structure contrast)
|
||||
- Geometric + Humanist (personality contrast)
|
||||
- Condensed display + Wide body (proportion contrast)
|
||||
|
||||
**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
|
||||
|
||||
### Web Font Loading
|
||||
|
||||
The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
|
||||
|
||||
```css
|
||||
/* 1. Use font-display: swap for visibility */
|
||||
@font-face {
|
||||
font-family: 'CustomFont';
|
||||
src: url('font.woff2') format('woff2');
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* 2. Match fallback metrics to minimize shift */
|
||||
@font-face {
|
||||
font-family: 'CustomFont-Fallback';
|
||||
src: local('Arial');
|
||||
size-adjust: 105%; /* Scale to match x-height */
|
||||
ascent-override: 90%; /* Match ascender height */
|
||||
descent-override: 20%; /* Match descender depth */
|
||||
line-gap-override: 10%; /* Match line spacing */
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
|
||||
}
|
||||
```
|
||||
|
||||
Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
|
||||
|
||||
**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
|
||||
|
||||
**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
|
||||
|
||||
**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
|
||||
|
||||
## Modern Web Typography
|
||||
|
||||
### Fluid Type
|
||||
|
||||
Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
|
||||
|
||||
**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
|
||||
|
||||
**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
|
||||
|
||||
**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
|
||||
|
||||
**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
|
||||
|
||||
### OpenType Features
|
||||
|
||||
Most developers don't know these exist. Use them for polish:
|
||||
|
||||
```css
|
||||
/* Tabular numbers for data alignment */
|
||||
.data-table { font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* Proper fractions */
|
||||
.recipe-amount { font-variant-numeric: diagonal-fractions; }
|
||||
|
||||
/* Small caps for abbreviations */
|
||||
abbr { font-variant-caps: all-small-caps; }
|
||||
|
||||
/* Disable ligatures in code */
|
||||
code { font-variant-ligatures: none; }
|
||||
|
||||
/* Enable kerning (usually on by default, but be explicit) */
|
||||
body { font-kerning: normal; }
|
||||
```
|
||||
|
||||
Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
|
||||
|
||||
### Rendering polish
|
||||
|
||||
```css
|
||||
/* Even out heading line lengths (browser picks better break points) */
|
||||
h1, h2, h3 { text-wrap: balance; }
|
||||
|
||||
/* Reduce orphans and ragged endings in long prose */
|
||||
article p { text-wrap: pretty; }
|
||||
|
||||
/* Variable fonts: pick the right optical-size master automatically */
|
||||
body { font-optical-sizing: auto; }
|
||||
```
|
||||
|
||||
**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
|
||||
|
||||
## Typography System Architecture
|
||||
|
||||
Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
|
||||
|
||||
## Accessibility Considerations
|
||||
|
||||
Beyond contrast ratios (which are well-documented), consider:
|
||||
|
||||
- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
|
||||
- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
|
||||
- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
|
||||
- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
|
||||
@@ -1,107 +0,0 @@
|
||||
# UX Writing
|
||||
|
||||
## The Button Label Problem
|
||||
|
||||
**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
|
||||
|
||||
| Bad | Good | Why |
|
||||
|-----|------|-----|
|
||||
| OK | Save changes | Says what will happen |
|
||||
| Submit | Create account | Outcome-focused |
|
||||
| Yes | Delete message | Confirms the action |
|
||||
| Cancel | Keep editing | Clarifies what "cancel" means |
|
||||
| Click here | Download PDF | Describes the destination |
|
||||
|
||||
**For destructive actions**, name the destruction:
|
||||
- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
|
||||
- "Delete 5 items" not "Delete selected" (show the count)
|
||||
|
||||
## Error Messages: The Formula
|
||||
|
||||
Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
|
||||
|
||||
### Error Message Templates
|
||||
|
||||
| Situation | Template |
|
||||
|-----------|----------|
|
||||
| **Format error** | "[Field] needs to be [format]. Example: [example]" |
|
||||
| **Missing required** | "Please enter [what's missing]" |
|
||||
| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
|
||||
| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
|
||||
| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
|
||||
|
||||
### Don't Blame the User
|
||||
|
||||
Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
|
||||
|
||||
## Empty States Are Opportunities
|
||||
|
||||
Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
|
||||
|
||||
## Voice vs Tone
|
||||
|
||||
**Voice** is your brand's personality, consistent everywhere.
|
||||
**Tone** adapts to the moment.
|
||||
|
||||
| Moment | Tone Shift |
|
||||
|--------|------------|
|
||||
| Success | Celebratory, brief: "Done! Your changes are live." |
|
||||
| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
|
||||
| Loading | Reassuring: "Saving your work..." |
|
||||
| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
|
||||
|
||||
**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
|
||||
|
||||
## Writing for Accessibility
|
||||
|
||||
**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
|
||||
|
||||
## Writing for Translation
|
||||
|
||||
### Plan for Expansion
|
||||
|
||||
German text is ~30% longer than English. Allocate space:
|
||||
|
||||
| Language | Expansion |
|
||||
|----------|-----------|
|
||||
| German | +30% |
|
||||
| French | +20% |
|
||||
| Finnish | +30-40% |
|
||||
| Chinese | -30% (fewer chars, but same width) |
|
||||
|
||||
### Translation-Friendly Patterns
|
||||
|
||||
Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
|
||||
|
||||
## Consistency: The Terminology Problem
|
||||
|
||||
Pick one term and stick with it:
|
||||
|
||||
| Inconsistent | Consistent |
|
||||
|--------------|------------|
|
||||
| Delete / Remove / Trash | Delete |
|
||||
| Settings / Preferences / Options | Settings |
|
||||
| Sign in / Log in / Enter | Sign in |
|
||||
| Create / Add / New | Create |
|
||||
|
||||
Build a terminology glossary and enforce it. Variety creates confusion.
|
||||
|
||||
## Avoid Redundant Copy
|
||||
|
||||
If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
|
||||
|
||||
## Loading States
|
||||
|
||||
Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
|
||||
|
||||
## Confirmation Dialogs: Use Sparingly
|
||||
|
||||
Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
|
||||
|
||||
## Form Instructions
|
||||
|
||||
Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
|
||||
|
||||
---
|
||||
|
||||
**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
|
||||
@@ -25,7 +25,7 @@ import { join, resolve } from 'node:path';
|
||||
const DEPRECATED_NAMES = [
|
||||
// v2.0 renames
|
||||
'frontend-design', // renamed to impeccable
|
||||
'teach-impeccable', // folded into /impeccable teach
|
||||
'teach-impeccable', // folded into /impeccable init
|
||||
// v2.1 merges
|
||||
'arrange', // renamed to layout
|
||||
'normalize', // merged into polish
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
"description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
|
||||
"argumentHint": "[feature description]"
|
||||
},
|
||||
"teach": {
|
||||
"description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
|
||||
"init": {
|
||||
"description": "Sets up a project for impeccable. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles); offers DESIGN.md (visual: colors, typography, components) when code exists; pre-configures live mode; then recommends the best commands to run next. Every other command reads these files before doing work. Use once per project.",
|
||||
"argumentHint": ""
|
||||
},
|
||||
"document": {
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Context loader: prints PRODUCT.md (and DESIGN.md if present) as one
|
||||
* markdown block on stdout, or exits with empty stdout when no PRODUCT.md
|
||||
* is found anywhere. The skill keys off "empty stdout" to branch into the
|
||||
* init flow.
|
||||
*
|
||||
* Path resolution (first match wins):
|
||||
* 1. cwd, if PRODUCT.md or DESIGN.md is there
|
||||
* 2. .agents/context/ then docs/
|
||||
* 3. $IMPECCABLE_CONTEXT_DIR (absolute or cwd-relative) — power-user
|
||||
* escape hatch, only consulted when defaults are empty
|
||||
* 4. cwd as a "nothing found" default
|
||||
*
|
||||
* `resolveContextDir()` and `loadContext()` are also exported for the
|
||||
* server-side scripts (live.mjs, live-server.mjs) that need the structured
|
||||
* shape rather than the markdown block.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
|
||||
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
|
||||
const FALLBACK_DIRS = ['.agents/context', 'docs'];
|
||||
|
||||
// ─── Update check ──────────────────────────────────────────────────────────
|
||||
// Piggyback a lightweight skill-version check on the once-per-session boot.
|
||||
// When a newer skill ships, append an UPDATE_AVAILABLE directive so the agent
|
||||
// can offer `npx impeccable skills update`. Everything here is best-effort and
|
||||
// silent on failure: a network problem, sandbox, or missing cache must never
|
||||
// block context output or print an error.
|
||||
|
||||
const UPDATE_HOST = (process.env.IMPECCABLE_UPDATE_HOST || 'https://impeccable.style').replace(/\/$/, '');
|
||||
const UPDATE_CACHE_PATH =
|
||||
process.env.IMPECCABLE_UPDATE_CACHE || path.join(os.homedir(), '.impeccable', 'update-check.json');
|
||||
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // throttle the network poll to once a day
|
||||
const RENOTIFY_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; // don't re-surface the same version for a week
|
||||
const FETCH_TIMEOUT_MS = 1200;
|
||||
|
||||
export function resolveContextDir(cwd = process.cwd()) {
|
||||
if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
|
||||
return cwd;
|
||||
}
|
||||
for (const rel of FALLBACK_DIRS) {
|
||||
const candidate = path.resolve(cwd, rel);
|
||||
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
|
||||
if (envDir && envDir.trim()) {
|
||||
const trimmed = envDir.trim();
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
return cwd;
|
||||
}
|
||||
|
||||
export function loadContext(cwd = process.cwd()) {
|
||||
const contextDir = resolveContextDir(cwd);
|
||||
const productPath = firstExisting(contextDir, PRODUCT_NAMES);
|
||||
const designPath = firstExisting(contextDir, DESIGN_NAMES);
|
||||
const product = productPath ? safeRead(productPath) : null;
|
||||
const design = designPath ? safeRead(designPath) : null;
|
||||
return {
|
||||
hasProduct: !!product,
|
||||
product,
|
||||
productPath: productPath ? path.relative(cwd, productPath) : null,
|
||||
hasDesign: !!design,
|
||||
design,
|
||||
designPath: designPath ? path.relative(cwd, designPath) : null,
|
||||
contextDir,
|
||||
};
|
||||
}
|
||||
|
||||
function firstExisting(dir, names) {
|
||||
for (const name of names) {
|
||||
const abs = path.join(dir, name);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function safeRead(p) {
|
||||
try {
|
||||
return fs.readFileSync(p, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull the register (`brand` or `product`) out of PRODUCT.md by looking
|
||||
* for a `## Register` section and reading the first non-empty line that
|
||||
* follows it. Returns null when the file is legacy / register-less.
|
||||
*/
|
||||
function extractRegister(product) {
|
||||
if (!product) return null;
|
||||
const lines = product.split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (/^##\s+Register\b/i.test(lines[i].trim())) {
|
||||
for (let j = i + 1; j < lines.length; j++) {
|
||||
const next = lines[j].trim();
|
||||
if (!next) continue;
|
||||
const word = next.toLowerCase();
|
||||
if (word === 'brand' || word === 'product') return word;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the installed skill's own version from the sibling SKILL.md frontmatter
|
||||
* (this file lives at `<skill>/scripts/context.mjs`). Returns null when the
|
||||
* frontmatter is missing or unreadable.
|
||||
*/
|
||||
function readLocalSkillVersion() {
|
||||
try {
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const skillMd = path.join(here, '..', 'SKILL.md');
|
||||
const content = fs.readFileSync(skillMd, 'utf-8');
|
||||
const match = content.match(/^version:\s*(.+)$/m);
|
||||
return match ? match[1].trim().replace(/^["']|["']$/g, '') : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readUpdateCache() {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(UPDATE_CACHE_PATH, 'utf-8'));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeUpdateCache(cache) {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(UPDATE_CACHE_PATH), { recursive: true });
|
||||
fs.writeFileSync(UPDATE_CACHE_PATH, JSON.stringify(cache));
|
||||
} catch {
|
||||
// Best-effort: a read-only home dir just means we re-poll next session.
|
||||
}
|
||||
}
|
||||
|
||||
/** Compare dotted numeric versions. Returns >0 when a is newer than b. */
|
||||
function compareSemver(a, b) {
|
||||
const pa = String(a).split('.').map(n => parseInt(n, 10) || 0);
|
||||
const pb = String(b).split('.').map(n => parseInt(n, 10) || 0);
|
||||
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
||||
const diff = (pa[i] || 0) - (pb[i] || 0);
|
||||
if (diff !== 0) return diff;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function fetchLatestSkillVersion() {
|
||||
try {
|
||||
const res = await fetch(`${UPDATE_HOST}/api/version`, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
return typeof data?.skills === 'string' ? data.skills : null;
|
||||
} catch {
|
||||
return null; // offline, sandboxed, timed out, or bad JSON: all non-fatal
|
||||
}
|
||||
}
|
||||
|
||||
function buildUpdateDirective(localVersion, latestVersion) {
|
||||
return (
|
||||
`UPDATE_AVAILABLE: A newer Impeccable skill is available ` +
|
||||
`(installed v${localVersion}, latest v${latestVersion}). ` +
|
||||
`Before continuing, ask the user once: "A newer Impeccable (v${latestVersion}) is available. ` +
|
||||
`Update now? It runs \`npx impeccable skills update\`." ` +
|
||||
`If they agree, run \`npx impeccable skills update\` (the update applies to the next session, not this one). ` +
|
||||
`Either way, continue the current task without waiting, and do not raise this again.`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort update directive for the boot output. Returns a string to append
|
||||
* or null. Polls the version endpoint at most once per day (cached globally in
|
||||
* the user's home dir) and re-surfaces a given version at most once per week so
|
||||
* the agent never nags. Opt out entirely with IMPECCABLE_NO_UPDATE_CHECK=1.
|
||||
*/
|
||||
async function computeUpdateDirective(now = Date.now()) {
|
||||
try {
|
||||
if (process.env.IMPECCABLE_NO_UPDATE_CHECK) return null;
|
||||
const localVersion = readLocalSkillVersion();
|
||||
if (!localVersion) return null;
|
||||
|
||||
const cache = readUpdateCache();
|
||||
|
||||
// Poll the network only when the throttle window has elapsed. Stamp
|
||||
// lastCheck even on failure so an offline machine doesn't poll every boot.
|
||||
if (!cache.lastCheck || now - cache.lastCheck > CHECK_INTERVAL_MS) {
|
||||
const latest = await fetchLatestSkillVersion();
|
||||
cache.lastCheck = now;
|
||||
if (latest) cache.latestVersion = latest;
|
||||
writeUpdateCache(cache);
|
||||
}
|
||||
|
||||
const latest = cache.latestVersion;
|
||||
if (!latest || compareSemver(latest, localVersion) <= 0) return null;
|
||||
|
||||
// Anti-nag: surface a given version at most once per RENOTIFY window.
|
||||
if (cache.notifiedVersion === latest && cache.notifiedAt && now - cache.notifiedAt < RENOTIFY_INTERVAL_MS) {
|
||||
return null;
|
||||
}
|
||||
cache.notifiedVersion = latest;
|
||||
cache.notifiedAt = now;
|
||||
writeUpdateCache(cache);
|
||||
|
||||
return buildUpdateDirective(localVersion, latest);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function cli() {
|
||||
const ctx = loadContext(process.cwd());
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
// Direct stdout message instead of relying on empty output as a signal
|
||||
// — cheap models miss the empty case more often than the explicit one.
|
||||
const parts = [
|
||||
'NO_PRODUCT_MD: This project has no PRODUCT.md yet. ' +
|
||||
'Stop the current task, load reference/init.md, and follow its ' +
|
||||
'instructions to write PRODUCT.md before resuming.',
|
||||
];
|
||||
if (updateDirective) parts.push(updateDirective);
|
||||
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const parts = [`# PRODUCT.md\n\n${ctx.product.trim()}`];
|
||||
if (ctx.hasDesign) {
|
||||
parts.push(`# DESIGN.md\n\n${ctx.design.trim()}`);
|
||||
}
|
||||
const register = extractRegister(ctx.product);
|
||||
const next = register
|
||||
? `NEXT STEP: This project's register is \`${register}\`. You MUST now read \`reference/${register}.md\` before producing any design output.`
|
||||
: `NEXT STEP: You MUST now read the matching register reference (\`reference/brand.md\` or \`reference/product.md\`) before producing any design output. Pick based on PRODUCT.md above.`;
|
||||
parts.push(next);
|
||||
if (updateDirective) parts.push(updateDirective);
|
||||
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
|
||||
}
|
||||
|
||||
const _running = process.argv[1];
|
||||
if (_running?.endsWith('context.mjs') || _running?.endsWith('context.mjs/')) {
|
||||
cli();
|
||||
}
|
||||
@@ -63,7 +63,7 @@ function parseYamlSubset(yaml) {
|
||||
}
|
||||
|
||||
const key = content.slice(0, colonIdx).trim();
|
||||
const rest = content.slice(colonIdx + 1).trim();
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
@@ -93,6 +93,21 @@ function findTopLevelColon(s) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
|
||||
@@ -9,8 +9,21 @@ if (IS_BROWSER) {
|
||||
const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
|
||||
|| document.documentElement.dataset.impeccableExtension === 'true';
|
||||
|
||||
const BRAND_COLOR = 'oklch(55% 0.25 350)';
|
||||
const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
|
||||
// Kinpaku gold — pinned to the site's brand token (see
|
||||
// site/styles/kinpaku-tokens.css --ks-kinpaku). Keep this in sync with
|
||||
// the picker's C.brand in skill/scripts/live-browser.js and the kit's
|
||||
// picker section in site/styles/kinpaku-kit.css.
|
||||
//
|
||||
// One color across both light and dark host pages. The outline is a
|
||||
// 2px gesture pointing at an element + a labeled tag — it's a marker,
|
||||
// not body text, so it doesn't need WCAG AA against the page. The
|
||||
// label text inside the gold tag is dark (LABEL_INK) which has ~16:1
|
||||
// against the leaf gold, so reading the rule name is solid in both
|
||||
// modes. Hover deepens the gold (preserves chroma — never drops it,
|
||||
// dropping chroma washes the gold into a sand/olive tone).
|
||||
const BRAND_COLOR = 'oklch(84% 0.19 80.46)';
|
||||
const BRAND_COLOR_HOVER = 'oklch(74% 0.18 80)';
|
||||
const LABEL_INK = 'oklch(4% 0.004 95)';
|
||||
const LABEL_BG = BRAND_COLOR;
|
||||
const OUTLINE_COLOR = BRAND_COLOR;
|
||||
|
||||
@@ -278,7 +291,7 @@ if (IS_BROWSER) {
|
||||
display: 'flex', alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
|
||||
color: 'white', lineHeight: '14px',
|
||||
color: LABEL_INK, lineHeight: '14px',
|
||||
background: LABEL_BG,
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
borderRadius: '4px 4px 0 0',
|
||||
@@ -398,7 +411,7 @@ if (IS_BROWSER) {
|
||||
banner.className = 'impeccable-overlay impeccable-banner';
|
||||
Object.assign(banner.style, {
|
||||
position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
|
||||
background: LABEL_BG, color: 'white',
|
||||
background: LABEL_BG, color: LABEL_INK,
|
||||
fontFamily: 'system-ui, sans-serif', fontSize: '13px',
|
||||
display: 'flex', alignItems: 'center', pointerEvents: 'auto',
|
||||
height: '36px', overflow: 'hidden', maxWidth: '100vw',
|
||||
@@ -1223,12 +1236,12 @@ if (IS_BROWSER) {
|
||||
}
|
||||
console.group(
|
||||
`%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
|
||||
'color: oklch(60% 0.25 350); font-weight: bold'
|
||||
'color: oklch(84% 0.19 80.46); font-weight: bold'
|
||||
);
|
||||
for (const { el, findings } of allFindings) {
|
||||
for (const f of findings) {
|
||||
console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
|
||||
'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
|
||||
'color: oklch(84% 0.19 80.46); font-weight: bold', 'color: inherit', el);
|
||||
}
|
||||
}
|
||||
console.groupEnd();
|
||||
@@ -1249,6 +1262,10 @@ if (IS_BROWSER) {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
// output concern, applied in the Node engines' detect* return paths.
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
// Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
|
||||
@@ -1270,11 +1287,23 @@ if (IS_BROWSER) {
|
||||
...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementOversizedH1DOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
|
||||
// Hero eyebrow: the offending element is the eyebrow above the heading,
|
||||
// not the heading itself — highlight the previous sibling instead.
|
||||
const eyebrowFindings = checkElementHeroEyebrowDOM(el)
|
||||
.map(f => ({ type: f.id, detail: f.snippet }))
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (eyebrowFindings.length > 0 && el.previousElementSibling) {
|
||||
addBrowserFindings(groupMap, el.previousElementSibling, eyebrowFindings);
|
||||
}
|
||||
}
|
||||
|
||||
const pageLevelFindings = [];
|
||||
@@ -1306,6 +1335,14 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, qualityFindings);
|
||||
}
|
||||
|
||||
const creamFindings = checkCreamPalette(document)
|
||||
.map(f => ({ type: f.id, detail: f.snippet }))
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (creamFindings.length > 0) {
|
||||
pageLevelFindings.push(...creamFindings);
|
||||
addBrowserFindings(groupMap, document.body, creamFindings);
|
||||
}
|
||||
|
||||
// Regex-on-HTML checks (shared with Node)
|
||||
// Clone the document and strip impeccable-live overlay nodes before the
|
||||
// regex scan, so the inspector's own inline styles (transitions on top/
|
||||
|
||||
@@ -41,7 +41,7 @@ function formatFindings(findings, jsonMode) {
|
||||
// Stdin handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function handleStdin() {
|
||||
async function handleStdin(options = {}) {
|
||||
const chunks = [];
|
||||
for await (const chunk of process.stdin) chunks.push(chunk);
|
||||
const input = Buffer.concat(chunks).toString('utf-8');
|
||||
@@ -50,10 +50,10 @@ async function handleStdin() {
|
||||
const fp = parsed?.tool_input?.file_path;
|
||||
if (fp && fs.existsSync(fp)) {
|
||||
return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
|
||||
? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
|
||||
? detectHtml(fp, options) : detectText(fs.readFileSync(fp, 'utf-8'), fp, options);
|
||||
}
|
||||
} catch { /* not JSON */ }
|
||||
return detectText(input, '<stdin>');
|
||||
return detectText(input, '<stdin>', options);
|
||||
}
|
||||
|
||||
|
||||
@@ -81,6 +81,8 @@ Scan files or URLs for UI anti-patterns and design quality issues.
|
||||
Options:
|
||||
--fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
|
||||
--json Output results as JSON
|
||||
--gpt Also report GPT-specific provider tells (off by default)
|
||||
--gemini Also report Gemini-specific provider tells (off by default)
|
||||
--help Show this help message
|
||||
|
||||
Detection modes:
|
||||
@@ -106,6 +108,10 @@ async function detectCli() {
|
||||
const jsonMode = args.includes('--json');
|
||||
const helpMode = args.includes('--help');
|
||||
const fastMode = args.includes('--fast');
|
||||
const providers = [];
|
||||
if (args.includes('--gpt')) providers.push('gpt');
|
||||
if (args.includes('--gemini')) providers.push('gemini');
|
||||
const scanOptions = { providers };
|
||||
const targets = args.filter(a => !a.startsWith('--'));
|
||||
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
@@ -113,7 +119,7 @@ async function detectCli() {
|
||||
let allFindings = [];
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin();
|
||||
allFindings = await handleStdin(scanOptions);
|
||||
} else {
|
||||
const paths = targets.length > 0 ? targets : [process.cwd()];
|
||||
const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
|
||||
@@ -124,8 +130,8 @@ async function detectCli() {
|
||||
if (/^https?:\/\//i.test(target)) {
|
||||
try {
|
||||
const scanner = browserDetector
|
||||
? (url) => browserDetector.detectUrl(url)
|
||||
: (url) => detectUrl(url);
|
||||
? (url) => browserDetector.detectUrl(url, scanOptions)
|
||||
: (url) => detectUrl(url, scanOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
continue;
|
||||
@@ -192,9 +198,9 @@ async function detectCli() {
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
let fileFindings;
|
||||
if (!fastMode && HTML_EXTENSIONS.has(ext)) {
|
||||
fileFindings = await detectHtml(file);
|
||||
fileFindings = await detectHtml(file, scanOptions);
|
||||
} else {
|
||||
fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
|
||||
fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file, scanOptions);
|
||||
}
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
@@ -209,9 +215,9 @@ async function detectCli() {
|
||||
} else if (stat.isFile()) {
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
if (!fastMode && HTML_EXTENSIONS.has(ext)) {
|
||||
allFindings.push(...await detectHtml(resolved));
|
||||
allFindings.push(...await detectHtml(resolved, scanOptions));
|
||||
} else {
|
||||
allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
|
||||
allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved, scanOptions));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ const OVERUSED_FONTS = new Set([
|
||||
// Older monoculture (still ubiquitous):
|
||||
'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
|
||||
// Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
|
||||
'fraunces', 'instrument sans',
|
||||
'fraunces', 'instrument sans', 'instrument serif',
|
||||
'geist', 'geist sans', 'geist mono',
|
||||
'mona sans',
|
||||
'plus jakarta sans', 'space grotesk', 'recoleta',
|
||||
@@ -165,6 +165,15 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'AI color palette',
|
||||
},
|
||||
{
|
||||
id: 'cream-palette',
|
||||
category: 'slop',
|
||||
name: 'Cream / beige palette',
|
||||
description:
|
||||
'A warm cream or beige page background has become the default "tasteful" AI surface, reached for by reflex. Choose a background that comes from a deliberate palette, not the safe warm off-white.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'cream and beige as the default surface',
|
||||
},
|
||||
{
|
||||
id: 'nested-cards',
|
||||
category: 'slop',
|
||||
@@ -183,15 +192,6 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'same spacing everywhere',
|
||||
},
|
||||
{
|
||||
id: 'everything-centered',
|
||||
category: 'slop',
|
||||
name: 'Everything centered',
|
||||
description:
|
||||
'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'Center everything',
|
||||
},
|
||||
{
|
||||
id: 'bounce-easing',
|
||||
category: 'slop',
|
||||
@@ -247,17 +247,72 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
|
||||
},
|
||||
{
|
||||
id: 'numbered-section-markers',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
name: 'Numbered section markers (01 / 02 / 03)',
|
||||
description:
|
||||
'Numbered display markers as section labels (01, 02, 03) are the AI editorial scaffold one tier deeper than tracked eyebrow chips. If you find yourself reaching for them, choose a different section cadence.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'numbered section markers',
|
||||
},
|
||||
{
|
||||
id: 'em-dash-overuse',
|
||||
category: 'slop',
|
||||
name: 'Em-dash overuse',
|
||||
description:
|
||||
'More than two em-dashes (— or --) in body copy is an AI cadence tell. Use commas, colons, periods, or parentheses instead.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'no em dashes',
|
||||
},
|
||||
{
|
||||
id: 'marketing-buzzword',
|
||||
category: 'slop',
|
||||
name: 'Marketing buzzword',
|
||||
description:
|
||||
'Generic SaaS phrases (streamline / empower / supercharge / world-class / enterprise-grade / next-generation / cutting-edge / etc) are instant AI tells. Pick a specific verb and noun that says what the product literally does.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'marketing buzzwords',
|
||||
},
|
||||
{
|
||||
id: 'aphoristic-cadence',
|
||||
category: 'slop',
|
||||
name: 'Aphoristic-cadence copy',
|
||||
description:
|
||||
'Three or more sections landing on a short rebuttal sentence ("X. No Y." / "X. Just Y.") or a manufactured-contrast aphorism ("Not a feature. A platform.") reads as AI cadence, not voice. Once is fine; the pattern is the tell.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'aphoristic cadence',
|
||||
},
|
||||
{
|
||||
id: 'oversized-h1',
|
||||
category: 'slop',
|
||||
name: 'Oversized hero headline',
|
||||
description:
|
||||
'A full-sentence headline set at display size ends up dominating the viewport, leaving no room for anything else above the fold. A punchy one- or two-word headline at that size is fine — the problem is a long headline blown up too large. Set long headlines smaller, or tighten the copy.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'long headline set at display size',
|
||||
},
|
||||
{
|
||||
id: 'extreme-negative-tracking',
|
||||
category: 'slop',
|
||||
name: 'Crushed letter spacing',
|
||||
description:
|
||||
'Letter-spacing pulled tighter than the point where characters keep their own shapes costs legibility. Tighten display type optically, not destructively.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'letter spacing crushed past legibility',
|
||||
},
|
||||
{
|
||||
id: 'broken-image',
|
||||
category: 'quality',
|
||||
name: 'Broken or placeholder image',
|
||||
description:
|
||||
'<img> tags with empty src, missing src, or placeholder values ship as broken-image boxes. Use real images, generated assets, or remove the tag.',
|
||||
skillSection: 'Imagery',
|
||||
skillGuideline: 'broken image references',
|
||||
},
|
||||
|
||||
// ── Quality: general design and accessibility issues ──
|
||||
{
|
||||
id: 'pure-black-white',
|
||||
category: 'quality',
|
||||
name: 'Pure black background',
|
||||
description:
|
||||
'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'pure black (#000)',
|
||||
},
|
||||
{
|
||||
id: 'gray-on-color',
|
||||
category: 'quality',
|
||||
@@ -297,7 +352,9 @@ const ANTIPATTERNS = [
|
||||
category: 'quality',
|
||||
name: 'Cramped padding',
|
||||
description:
|
||||
'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
|
||||
'Text is too close to the edge of its container. Two shapes: (1) an element with its own text where the padding is too low for the font size, and (2) a wrapper with text-bearing children and near-zero padding against a visible boundary (border, outline, or non-transparent background) — children land flush against the boundary line. Add at least 8px (ideally 12–16px) of padding inside bordered, outlined, or colored containers.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'inside bordered or colored containers',
|
||||
},
|
||||
{
|
||||
id: 'body-text-viewport-edge',
|
||||
@@ -350,6 +407,70 @@ const ANTIPATTERNS = [
|
||||
description:
|
||||
'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
|
||||
},
|
||||
{
|
||||
id: 'text-overflow',
|
||||
category: 'quality',
|
||||
name: 'Content overflowing its container',
|
||||
description:
|
||||
'Content renders wider than its container, spilling out or forcing a horizontal scrollbar. Let text wrap, constrain widths, or give the region a deliberate scroll affordance.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'content wider than its container',
|
||||
},
|
||||
{
|
||||
id: 'clipped-overflow-container',
|
||||
category: 'quality',
|
||||
name: 'Positioned child clipped by overflow container',
|
||||
description:
|
||||
'A clipping container (overflow hidden or clip) wrapping an absolutely-positioned child cuts off tooltips, menus, and popovers that need to escape. Let the overflow be visible, or move the positioned layer out of the clip.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
id: 'gpt-thin-border-wide-shadow',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Hairline border with wide shadow',
|
||||
description:
|
||||
'A hairline border paired with a wide, diffuse shadow is a recurring generated-UI signature. Commit to one — a defined edge or a soft elevation — rather than both at once.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'hairline border plus wide diffuse shadow',
|
||||
},
|
||||
{
|
||||
id: 'repeating-stripes-gradient',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Repeating-gradient stripes',
|
||||
description:
|
||||
'Repeating-gradient stripes used as surface decoration are a recurring generated-UI signature. Reach for a deliberate texture or leave the surface plain.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'repeating-gradient decorative stripes',
|
||||
},
|
||||
{
|
||||
id: 'theater-slop-phrase',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Theater framing copy',
|
||||
description:
|
||||
'Dismissing something as "theater" is a recurring generated-copy tic. Say plainly what the thing does or does not do.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'theater framing copy',
|
||||
},
|
||||
{
|
||||
id: 'image-hover-transform',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gemini',
|
||||
name: 'Image hover transform',
|
||||
description:
|
||||
'Scaling or rotating an image on hover is a recurring generated-UI signature. Let imagery sit still, or use a subtler, purposeful interaction.',
|
||||
skillSection: 'Motion',
|
||||
skillGuideline: 'image scale or rotate on hover',
|
||||
},
|
||||
];
|
||||
|
||||
// --- cli/engine/shared/color.mjs ---
|
||||
@@ -527,11 +648,6 @@ function checkColors(opts) {
|
||||
}
|
||||
const findings = [];
|
||||
|
||||
// Pure black background (only solid or near-solid, not semi-transparent overlays)
|
||||
if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
|
||||
findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
|
||||
}
|
||||
|
||||
if (hasDirectText && textColor && !isEmojiOnly) {
|
||||
// Run background-dependent checks against either a solid bg or, if the
|
||||
// ancestor is a gradient, against every gradient stop (use the worst case).
|
||||
@@ -587,9 +703,6 @@ function checkColors(opts) {
|
||||
// Tailwind class checks
|
||||
if (classList) {
|
||||
const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
|
||||
if (/\bbg-black\b(?!\/)/.test(classStr)) {
|
||||
findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
|
||||
}
|
||||
|
||||
const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
|
||||
const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
|
||||
@@ -905,12 +1018,6 @@ function checkHtmlPatterns(html) {
|
||||
|
||||
// --- Color ---
|
||||
|
||||
// Pure black background
|
||||
const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
|
||||
if (pureBlackBgRe.test(html)) {
|
||||
findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
|
||||
}
|
||||
|
||||
// AI color palette: purple/violet
|
||||
const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
|
||||
if (purpleHexRe.test(html)) {
|
||||
@@ -1027,6 +1134,39 @@ function checkHtmlPatterns(html) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): repeating-gradient stripes (GPT) ---
|
||||
if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(html)) {
|
||||
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
|
||||
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
|
||||
// runs in the bundled browser path too, not just the CLI/static path.
|
||||
{
|
||||
const bodyText = html
|
||||
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<[^>]+>/g, ' ');
|
||||
const tm = /\b(\w+)\s+theater\b/i.exec(bodyText);
|
||||
if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` });
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): image hover transform (Gemini) ---
|
||||
// A CSS `img...:hover { transform: ... }` rule, or a Tailwind hover:scale /
|
||||
// hover:rotate / hover:translate utility on an <img>. Each distinct
|
||||
// mechanism is its own finding.
|
||||
const imgHoverCss = /\bimg\b[^,{}]*:hover\b[^{}]*\{[^}]*\btransform\s*:\s*(?:scale|rotate|translate|matrix|skew)/i;
|
||||
if (imgHoverCss.test(html)) {
|
||||
findings.push({ id: 'image-hover-transform', snippet: 'img:hover { transform } rule' });
|
||||
}
|
||||
const imgTagRe = /<img\b[^>]*\bclass\s*=\s*"([^"]*)"/gi;
|
||||
let im;
|
||||
while ((im = imgTagRe.exec(html)) !== null) {
|
||||
if (/\bhover:(?:scale|rotate|translate|skew)-/.test(im[1])) {
|
||||
findings.push({ id: 'image-hover-transform', snippet: 'Tailwind hover transform on <img>' });
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
@@ -1673,7 +1813,7 @@ function resolveLengthPx(value, fontSizePx) {
|
||||
// Both adapters resolve font-size, line-height and letter-spacing to pixels
|
||||
// before calling this so the pure function only deals with numbers.
|
||||
function checkQuality(opts) {
|
||||
const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
|
||||
const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0, win = null } = opts;
|
||||
const findings = [];
|
||||
// Skip browser extension injected elements
|
||||
const elId = el.id || '';
|
||||
@@ -1724,6 +1864,155 @@ function checkQuality(opts) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flush against a visible boundary ---
|
||||
// Fires when a container has a visible boundary (border, outline, OR a
|
||||
// non-transparent background) AND near-zero padding on the bounded
|
||||
// side(s) AND text-bearing children land flush against the boundary.
|
||||
//
|
||||
// Distinct from cramped-padding: that rule needs the element itself to
|
||||
// have direct text (hasDirectText). This rule targets the OPPOSITE
|
||||
// shape — a container with NO direct text, only children — which is
|
||||
// exactly what cramped-padding misses (a section wrapping a label +
|
||||
// list lands a free pass).
|
||||
//
|
||||
// The classic shape: agent writes `padding: 28px 0 0` shorthand on a
|
||||
// section that also has a border, zeroing horizontal padding so the
|
||||
// text-bearing children touch the side borders. Background and
|
||||
// outline count too: a colored card with zero padding has the same
|
||||
// visual failure mode.
|
||||
{
|
||||
const FLUSH_SKIP_TAGS = new Set(['HTML', 'BODY', 'MAIN', 'HEADER', 'FOOTER', 'NAV', 'ARTICLE', 'ASIDE', 'BUTTON', 'A', 'LABEL', 'SUMMARY', 'CODE', 'PRE', 'INPUT', 'TEXTAREA', 'SELECT', 'FORM', 'FIGURE', 'TABLE', 'TBODY', 'THEAD', 'TR', 'TD', 'TH']);
|
||||
const upperTag = tag ? tag.toUpperCase() : '';
|
||||
const elPosition = style.position || '';
|
||||
if (
|
||||
!FLUSH_SKIP_TAGS.has(upperTag) &&
|
||||
!hasDirectText &&
|
||||
!['fixed', 'absolute'].includes(elPosition) &&
|
||||
el.children && el.children.length > 0
|
||||
) {
|
||||
const isTransparent = (c) =>
|
||||
!c || c === 'transparent' || c === 'rgba(0, 0, 0, 0)' ||
|
||||
/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0(?:\.0+)?\s*\)$/.test(c);
|
||||
|
||||
const borderW = {
|
||||
top: parseFloat(style.borderTopWidth) || 0,
|
||||
right: parseFloat(style.borderRightWidth) || 0,
|
||||
bottom: parseFloat(style.borderBottomWidth) || 0,
|
||||
left: parseFloat(style.borderLeftWidth) || 0,
|
||||
};
|
||||
const borderVisible = {
|
||||
top: borderW.top > 0 && !isTransparent(style.borderTopColor),
|
||||
right: borderW.right > 0 && !isTransparent(style.borderRightColor),
|
||||
bottom: borderW.bottom > 0 && !isTransparent(style.borderBottomColor),
|
||||
left: borderW.left > 0 && !isTransparent(style.borderLeftColor),
|
||||
};
|
||||
// Outline detection. jsdom decomposes `border` shorthand into
|
||||
// border{Top,…}Width/Color but does NOT decompose `outline` —
|
||||
// the longhands come back empty when the value was set via the
|
||||
// shorthand. Fall back to parsing `style.outline` ourselves.
|
||||
let outlineW = parseFloat(style.outlineWidth) || 0;
|
||||
let outlineStyleVal = style.outlineStyle || '';
|
||||
let outlineColorVal = style.outlineColor || '';
|
||||
if (!outlineW && style.outline) {
|
||||
const wMatch = style.outline.match(/(\d+(?:\.\d+)?)\s*px/);
|
||||
if (wMatch) outlineW = parseFloat(wMatch[1]) || 0;
|
||||
if (!outlineStyleVal) {
|
||||
outlineStyleVal = /\b(solid|dashed|dotted|double|groove|ridge|inset|outset)\b/.test(style.outline) ? 'solid' : '';
|
||||
}
|
||||
if (!outlineColorVal) {
|
||||
const cMatch = style.outline.match(/(rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}|[a-zA-Z]+)\s*$/);
|
||||
if (cMatch) outlineColorVal = cMatch[1];
|
||||
}
|
||||
}
|
||||
const outlineVisible = outlineW > 0 && !isTransparent(outlineColorVal) && outlineStyleVal && outlineStyleVal !== 'none';
|
||||
const bgVisible = !isTransparent(style.backgroundColor);
|
||||
|
||||
const anyVisible = borderVisible.top || borderVisible.right || borderVisible.bottom || borderVisible.left || outlineVisible || bgVisible;
|
||||
if (anyVisible) {
|
||||
// Resolve padding to px (jsdom returns raw "1.5rem" etc., not the
|
||||
// computed px value; parseFloat would strip the unit and treat
|
||||
// 1.5rem as 1.5px, false-flagging legitimate insets).
|
||||
const pad = {
|
||||
top: resolveLengthPx(style.paddingTop, fontSize) ?? 0,
|
||||
right: resolveLengthPx(style.paddingRight, fontSize) ?? 0,
|
||||
bottom: resolveLengthPx(style.paddingBottom, fontSize) ?? 0,
|
||||
left: resolveLengthPx(style.paddingLeft, fontSize) ?? 0,
|
||||
};
|
||||
const PAD_THRESHOLD = 2;
|
||||
// Children-insulate-this-side: a side is insulated if ANY direct
|
||||
// child has its own padding ≥ 4px on that side. Rationale: in
|
||||
// typical flow, only the first/last (or leftmost/rightmost)
|
||||
// children actually sit at the parent's edges. If even one of
|
||||
// them has its own padding, the visual flush is broken on that
|
||||
// side. Classic example: a column-flow card frame where the
|
||||
// top child (header) has padding-top:12 and the bottom child
|
||||
// (footer) has padding-bottom:8 — the parent's padding:0 doesn't
|
||||
// matter; nothing is actually flush. The `any-child-insulates`
|
||||
// heuristic accepts some false negatives (a card with one heavily
|
||||
// padded middle child won't flag) for far fewer false positives.
|
||||
const CHILD_INSULATE_THRESHOLD = 4;
|
||||
const childrenInsulate = { top: false, right: false, bottom: false, left: false };
|
||||
for (const child of el.children) {
|
||||
let childStyle = null;
|
||||
if (win && typeof win.getComputedStyle === 'function') {
|
||||
try { childStyle = win.getComputedStyle(child); } catch {}
|
||||
}
|
||||
if (!childStyle && typeof getComputedStyle === 'function') {
|
||||
try { childStyle = getComputedStyle(child); } catch {}
|
||||
}
|
||||
if (!childStyle) continue;
|
||||
const childPad = {
|
||||
top: resolveLengthPx(childStyle.paddingTop, fontSize) ?? 0,
|
||||
right: resolveLengthPx(childStyle.paddingRight, fontSize) ?? 0,
|
||||
bottom: resolveLengthPx(childStyle.paddingBottom, fontSize) ?? 0,
|
||||
left: resolveLengthPx(childStyle.paddingLeft, fontSize) ?? 0,
|
||||
};
|
||||
for (const s of ['top', 'right', 'bottom', 'left']) {
|
||||
if (childPad[s] >= CHILD_INSULATE_THRESHOLD) childrenInsulate[s] = true;
|
||||
}
|
||||
}
|
||||
|
||||
const flushSides = [];
|
||||
for (const side of ['top', 'right', 'bottom', 'left']) {
|
||||
const sideBounded = borderVisible[side] || outlineVisible || bgVisible;
|
||||
if (sideBounded && pad[side] <= PAD_THRESHOLD && !childrenInsulate[side]) {
|
||||
flushSides.push(side);
|
||||
}
|
||||
}
|
||||
|
||||
if (flushSides.length > 0) {
|
||||
// Confirm at least one direct child has substantial text content
|
||||
// (> 4 chars). Without this, the flush is harmless: e.g. an
|
||||
// image-only card.
|
||||
let hasTextChild = false;
|
||||
for (const child of el.children) {
|
||||
const childText = (child.textContent || '').trim();
|
||||
if (childText.length > 4) { hasTextChild = true; break; }
|
||||
}
|
||||
if (hasTextChild) {
|
||||
const cls = (typeof el.className === 'string' && el.className.trim())
|
||||
? el.className.trim().split(/\s+/)[0]
|
||||
: '';
|
||||
const boundaryParts = [];
|
||||
const borderSidesVisible = ['top', 'right', 'bottom', 'left'].filter(s => borderVisible[s]);
|
||||
if (borderSidesVisible.length === 4) boundaryParts.push('border');
|
||||
else if (borderSidesVisible.length > 0) boundaryParts.push(`border-${borderSidesVisible.join('/')}`);
|
||||
if (outlineVisible) boundaryParts.push('outline');
|
||||
if (bgVisible) boundaryParts.push('bg');
|
||||
const sidesLabel = flushSides.length === 4 ? 'all sides' : flushSides.join('/');
|
||||
const ident = cls
|
||||
? `<${tag.toLowerCase()}> "${cls}"`
|
||||
: `<${tag.toLowerCase()}>`;
|
||||
findings.push({
|
||||
id: 'cramped-padding',
|
||||
snippet: `${ident}: children flush against ${boundaryParts.join('+')} on ${sidesLabel} (no inset)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Body text touching viewport edge --- (browser-only: needs rect)
|
||||
// Catches the failure mode where the agent ships body paragraphs
|
||||
// with NO container providing horizontal padding — text bleeds
|
||||
@@ -1804,6 +2093,20 @@ function checkQuality(opts) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Crushed letter spacing (mirror of wide-tracking) ---
|
||||
// Tracking pulled tighter than ~-0.05em crushes characters into each other.
|
||||
// Optical tightening that display type legitimately wants (around -0.02em)
|
||||
// stays well above this floor.
|
||||
if (hasDirectText && textLen > 20 && fontSize > 0) {
|
||||
if (letterSpacingPx != null && letterSpacingPx < 0) {
|
||||
const trackingEm = letterSpacingPx / fontSize;
|
||||
if (trackingEm <= -0.05) {
|
||||
const excerpt = (el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 40);
|
||||
findings.push({ id: 'extreme-negative-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em — "${excerpt}"` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
@@ -1820,7 +2123,7 @@ function checkElementQualityDOM(el) {
|
||||
const rect = el.getBoundingClientRect();
|
||||
const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
|
||||
const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth, win: typeof window !== 'undefined' ? window : null });
|
||||
}
|
||||
|
||||
// Pure page-level skipped-heading walk. Takes a Document so it works in both
|
||||
@@ -1862,7 +2165,7 @@ function checkElementQuality(el, style, tag, window) {
|
||||
const fontSize = resolveFontSizePx(el, window);
|
||||
const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
|
||||
const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null, win: window });
|
||||
}
|
||||
|
||||
function checkElementBorders(tag, style, overrides, resolvedRadius) {
|
||||
@@ -2303,40 +2606,213 @@ function checkPageLayout(doc, win) {
|
||||
}
|
||||
}
|
||||
|
||||
// Everything centered
|
||||
const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
|
||||
let centeredCount = 0;
|
||||
let totalText = 0;
|
||||
for (const el of textEls) {
|
||||
const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
|
||||
if (!hasDirectText) continue;
|
||||
totalText++;
|
||||
|
||||
let cur = el;
|
||||
let isCentered = false;
|
||||
while (cur && cur.nodeType === 1) {
|
||||
const rawStyle = cur.getAttribute?.('style') || '';
|
||||
const cls = cur.getAttribute?.('class') || '';
|
||||
if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
|
||||
isCentered = true;
|
||||
break;
|
||||
}
|
||||
if (cur.tagName === 'BODY') break;
|
||||
cur = cur.parentElement;
|
||||
}
|
||||
if (isCentered) centeredCount++;
|
||||
}
|
||||
|
||||
if (totalText >= 5 && centeredCount / totalText > 0.7) {
|
||||
findings.push({
|
||||
id: 'everything-centered',
|
||||
snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
|
||||
});
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Cream / beige palette (the default "tasteful" AI surface) ────────────────
|
||||
// A warm, lightly-tinted off-white page background — light, with R≥G≥B and a
|
||||
// small warm tint (not white, not a strong color). The current reflex surface.
|
||||
function isCreamColor(rgb) {
|
||||
if (!rgb) return false;
|
||||
const { r, g, b } = rgb;
|
||||
if (Math.min(r, g, b) < 209) return false; // must be light
|
||||
if (!(r >= g && g >= b)) return false; // warm ordering
|
||||
const warmth = r - b;
|
||||
return warmth >= 6 && warmth <= 48; // tinted, not white, not strong
|
||||
}
|
||||
|
||||
// Tailwind background utilities that render as a warm off-white surface. The
|
||||
// static engine doesn't fetch Tailwind's CSS, so a `bg-amber-50` on <body>
|
||||
// resolves to nothing in computed style — catch it from the class list
|
||||
// instead. Candidate tokens map to their actual Tailwind hex and are still
|
||||
// filtered through isCreamColor, so neutral grays (stone) and over-saturated
|
||||
// shades drop out on their own.
|
||||
const TAILWIND_BG_HEX = {
|
||||
'bg-amber-50': '#fffbeb', 'bg-amber-100': '#fef3c7',
|
||||
'bg-orange-50': '#fff7ed', 'bg-orange-100': '#ffedd5',
|
||||
'bg-yellow-50': '#fefce8',
|
||||
'bg-stone-50': '#fafaf9', 'bg-stone-100': '#f5f5f4', 'bg-stone-200': '#e7e5e4',
|
||||
};
|
||||
|
||||
function creamFromClassList(cls) {
|
||||
if (!cls) return null;
|
||||
// Arbitrary value: bg-[#f5f0e6] / bg-[rgb(245_240_230)] (underscores = spaces).
|
||||
const arb = cls.match(/\bbg-\[([^\]]+)\]/);
|
||||
if (arb && isCreamColor(parseAnyColor(arb[1].replace(/_/g, ' ')))) return `bg-[${arb[1]}]`;
|
||||
// Named warm-light utilities.
|
||||
for (const [tok, hex] of Object.entries(TAILWIND_BG_HEX)) {
|
||||
if (new RegExp(`(^|\\s)${tok}($|\\s)`).test(cls) && isCreamColor(parseAnyColor(hex))) return tok;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkCreamPalette(doc, win) {
|
||||
const findings = [];
|
||||
const body = doc.body || (doc.querySelector ? doc.querySelector('body') : null);
|
||||
if (!body) return findings;
|
||||
const html = doc.documentElement;
|
||||
const getCS = (el) => (win ? win.getComputedStyle(el) : getComputedStyle(el));
|
||||
|
||||
// 1. Computed background — covers inline / <style> / linked CSS, and Tailwind
|
||||
// once it's actually rendered (browser path).
|
||||
let bg = readOwnBackgroundColor(body, getCS(body));
|
||||
if (!bg || bg.a === 0) {
|
||||
if (html) bg = readOwnBackgroundColor(html, getCS(html));
|
||||
}
|
||||
if (isCreamColor(bg)) {
|
||||
findings.push({ id: 'cream-palette', snippet: `cream/beige page background rgb(${bg.r}, ${bg.g}, ${bg.b})` });
|
||||
return findings;
|
||||
}
|
||||
|
||||
// 2. Tailwind class fallback — for the static path, where utility classes
|
||||
// never resolve to computed CSS.
|
||||
for (const el of [body, html]) {
|
||||
const tok = creamFromClassList(el && el.getAttribute ? el.getAttribute('class') : '');
|
||||
if (tok) {
|
||||
findings.push({ id: 'cream-palette', snippet: `cream/beige page background (Tailwind ${tok})` });
|
||||
break;
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Oversized hero headline ────────────────────────────────────────────────
|
||||
// Fires when a *long* headline is set at display size, so a full sentence ends
|
||||
// up dominating the viewport. A punchy one- or two-word headline at the same
|
||||
// size is a legitimate stylistic choice and must pass — length, not size
|
||||
// alone, is the tell.
|
||||
const OVERSIZED_H1_FONT_PX = 72;
|
||||
const OVERSIZED_H1_MIN_CHARS = 40;
|
||||
function checkOversizedH1({ tag, fontSize, headingText }) {
|
||||
if (tag !== 'h1') return [];
|
||||
const textLen = headingText.length;
|
||||
if (fontSize >= OVERSIZED_H1_FONT_PX && textLen >= OVERSIZED_H1_MIN_CHARS) {
|
||||
return [{ id: 'oversized-h1', snippet: `${Math.round(fontSize)}px h1, ${textLen} chars "${headingText.slice(0, 60)}"` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function checkElementOversizedH1(el, style, tag, window) {
|
||||
if (tag !== 'h1') return [];
|
||||
const fontSize = resolveFontSizePx(el, window);
|
||||
const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
|
||||
return checkOversizedH1({ tag, fontSize, headingText });
|
||||
}
|
||||
|
||||
function checkElementOversizedH1DOM(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (tag !== 'h1') return [];
|
||||
const style = getComputedStyle(el);
|
||||
const fontSize = parseFloat(style.fontSize) || 0;
|
||||
const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
|
||||
return checkOversizedH1({ tag, fontSize, headingText });
|
||||
}
|
||||
|
||||
// ─── GPT tell: hairline border + wide diffuse shadow (gated --gpt) ────────────
|
||||
function shadowMaxBlurPx(boxShadow) {
|
||||
if (!boxShadow || boxShadow === 'none') return 0;
|
||||
let maxBlur = 0;
|
||||
// Split into layers on commas not inside parentheses (rgba(...) etc.).
|
||||
for (const layer of boxShadow.split(/,(?![^()]*\))/)) {
|
||||
// Strip colors and keywords (rgba()/hsl()/hex/named/inset/px), leaving the
|
||||
// ordered length tokens: offsetX offsetY blur [spread]. Static jsdom keeps
|
||||
// unitless zeros ("0 0 24px"); browsers normalize to px ("0px 0px 24px") —
|
||||
// both reduce to the same numbers here.
|
||||
const cleaned = layer.replace(/rgba?\([^)]*\)|hsla?\([^)]*\)|#[0-9a-f]+|\b[a-z]+\b/gi, ' ');
|
||||
const nums = [...cleaned.matchAll(/-?\d*\.?\d+/g)].map(m => parseFloat(m[0]));
|
||||
if (nums.length >= 3) maxBlur = Math.max(maxBlur, nums[2]);
|
||||
}
|
||||
return maxBlur;
|
||||
}
|
||||
|
||||
function checkGptThinBorderWideShadow({ borderWidths, boxShadow }) {
|
||||
const maxBorder = Math.max(0, ...borderWidths);
|
||||
const hasThinBorder = maxBorder > 0 && maxBorder <= 1.5;
|
||||
const blur = shadowMaxBlurPx(boxShadow);
|
||||
if (hasThinBorder && blur >= 16) {
|
||||
return [{ id: 'gpt-thin-border-wide-shadow', snippet: `${maxBorder}px border + ${Math.round(blur)}px shadow blur` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function borderWidthsFromStyle(style) {
|
||||
return [
|
||||
parseFloat(style.borderTopWidth) || 0,
|
||||
parseFloat(style.borderRightWidth) || 0,
|
||||
parseFloat(style.borderBottomWidth) || 0,
|
||||
parseFloat(style.borderLeftWidth) || 0,
|
||||
];
|
||||
}
|
||||
|
||||
function checkElementGptBorderShadow(el, style) {
|
||||
return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
|
||||
}
|
||||
|
||||
function checkElementGptBorderShadowDOM(el) {
|
||||
const style = getComputedStyle(el);
|
||||
return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
|
||||
}
|
||||
|
||||
// ─── Clipped overflow container ───────────────────────────────────────────────
|
||||
// A clipping container (overflow hidden/clip, not a scroll region) wrapping an
|
||||
// absolutely/fixed-positioned descendant clips popovers/menus that must escape.
|
||||
function classSelector(el) {
|
||||
const cls = (el.getAttribute ? el.getAttribute('class') : el.className) || '';
|
||||
const tokens = String(cls).trim().split(/\s+/).filter(Boolean);
|
||||
const tag = el.tagName ? el.tagName.toLowerCase() : 'el';
|
||||
return tokens.length ? `${tag}.${tokens.join('.')}` : tag;
|
||||
}
|
||||
|
||||
function checkClippedOverflow(el, style, getStyle) {
|
||||
const clips = (v) => v === 'hidden' || v === 'clip';
|
||||
const scrolls = (v) => v === 'auto' || v === 'scroll';
|
||||
const ox = style.overflowX || '', oy = style.overflowY || '', ov = style.overflow || '';
|
||||
const anyClip = clips(ox) || clips(oy) || clips(ov);
|
||||
const anyScroll = scrolls(ox) || scrolls(oy) || scrolls(ov);
|
||||
if (!anyClip || anyScroll) return [];
|
||||
if (!el.querySelectorAll) return [];
|
||||
for (const child of el.querySelectorAll('*')) {
|
||||
const pos = (getStyle(child).position) || '';
|
||||
if (pos === 'absolute' || pos === 'fixed') {
|
||||
return [{ id: 'clipped-overflow-container', snippet: `${classSelector(el)} clips a positioned child` }];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function checkElementClippedOverflow(el, style, tag, window) {
|
||||
return checkClippedOverflow(el, style, (n) => window.getComputedStyle(n));
|
||||
}
|
||||
|
||||
function checkElementClippedOverflowDOM(el) {
|
||||
const style = getComputedStyle(el);
|
||||
return checkClippedOverflow(el, style, (n) => getComputedStyle(n));
|
||||
}
|
||||
|
||||
// ─── Text overflow (browser-only: needs scrollWidth/clientWidth) ──────────────
|
||||
const TEXT_OVERFLOW_SKIP_TAGS = new Set(['pre', 'code', 'textarea', 'svg', 'canvas', 'select', 'option', 'marquee']);
|
||||
|
||||
function checkElementTextOverflowDOM(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (TEXT_OVERFLOW_SKIP_TAGS.has(tag)) return [];
|
||||
// Only the element that actually owns overflowing text — not its ancestors,
|
||||
// which inherit a wider scrollWidth from the spilling descendant.
|
||||
const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
|
||||
if (!hasDirectText) return [];
|
||||
const style = getComputedStyle(el);
|
||||
const isScrollRegion = (s) => /(auto|scroll)/.test(s.overflowX || '') || /(auto|scroll)/.test(s.overflow || '');
|
||||
if (isScrollRegion(style)) return [];
|
||||
// A scrollable ancestor means this overflow is intentional and scrollable.
|
||||
for (let p = el.parentElement; p; p = p.parentElement) {
|
||||
if (isScrollRegion(getComputedStyle(p))) return [];
|
||||
}
|
||||
const delta = el.scrollWidth - el.clientWidth;
|
||||
if (el.clientWidth > 0 && delta >= 16) {
|
||||
return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its box by ${Math.round(delta)}px` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// --- cli/engine/browser/injected/index.mjs ---
|
||||
const IS_BROWSER = typeof window !== 'undefined';
|
||||
|
||||
@@ -2349,8 +2825,21 @@ if (IS_BROWSER) {
|
||||
const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
|
||||
|| document.documentElement.dataset.impeccableExtension === 'true';
|
||||
|
||||
const BRAND_COLOR = 'oklch(55% 0.25 350)';
|
||||
const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
|
||||
// Kinpaku gold — pinned to the site's brand token (see
|
||||
// site/styles/kinpaku-tokens.css --ks-kinpaku). Keep this in sync with
|
||||
// the picker's C.brand in skill/scripts/live-browser.js and the kit's
|
||||
// picker section in site/styles/kinpaku-kit.css.
|
||||
//
|
||||
// One color across both light and dark host pages. The outline is a
|
||||
// 2px gesture pointing at an element + a labeled tag — it's a marker,
|
||||
// not body text, so it doesn't need WCAG AA against the page. The
|
||||
// label text inside the gold tag is dark (LABEL_INK) which has ~16:1
|
||||
// against the leaf gold, so reading the rule name is solid in both
|
||||
// modes. Hover deepens the gold (preserves chroma — never drops it,
|
||||
// dropping chroma washes the gold into a sand/olive tone).
|
||||
const BRAND_COLOR = 'oklch(84% 0.19 80.46)';
|
||||
const BRAND_COLOR_HOVER = 'oklch(74% 0.18 80)';
|
||||
const LABEL_INK = 'oklch(4% 0.004 95)';
|
||||
const LABEL_BG = BRAND_COLOR;
|
||||
const OUTLINE_COLOR = BRAND_COLOR;
|
||||
|
||||
@@ -2618,7 +3107,7 @@ if (IS_BROWSER) {
|
||||
display: 'flex', alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
|
||||
color: 'white', lineHeight: '14px',
|
||||
color: LABEL_INK, lineHeight: '14px',
|
||||
background: LABEL_BG,
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
borderRadius: '4px 4px 0 0',
|
||||
@@ -2738,7 +3227,7 @@ if (IS_BROWSER) {
|
||||
banner.className = 'impeccable-overlay impeccable-banner';
|
||||
Object.assign(banner.style, {
|
||||
position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
|
||||
background: LABEL_BG, color: 'white',
|
||||
background: LABEL_BG, color: LABEL_INK,
|
||||
fontFamily: 'system-ui, sans-serif', fontSize: '13px',
|
||||
display: 'flex', alignItems: 'center', pointerEvents: 'auto',
|
||||
height: '36px', overflow: 'hidden', maxWidth: '100vw',
|
||||
@@ -3563,12 +4052,12 @@ if (IS_BROWSER) {
|
||||
}
|
||||
console.group(
|
||||
`%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
|
||||
'color: oklch(60% 0.25 350); font-weight: bold'
|
||||
'color: oklch(84% 0.19 80.46); font-weight: bold'
|
||||
);
|
||||
for (const { el, findings } of allFindings) {
|
||||
for (const f of findings) {
|
||||
console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
|
||||
'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
|
||||
'color: oklch(84% 0.19 80.46); font-weight: bold', 'color: inherit', el);
|
||||
}
|
||||
}
|
||||
console.groupEnd();
|
||||
@@ -3589,6 +4078,10 @@ if (IS_BROWSER) {
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
|
||||
// real browser env (detector page, live overlay, extension) running every
|
||||
// check is free, so we always surface them; the gating is purely a CLI
|
||||
// output concern, applied in the Node engines' detect* return paths.
|
||||
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
// Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
|
||||
@@ -3610,11 +4103,23 @@ if (IS_BROWSER) {
|
||||
...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementOversizedH1DOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
|
||||
].filter(f => _ruleOk(f.type));
|
||||
|
||||
addBrowserFindings(groupMap, el, findings);
|
||||
|
||||
// Hero eyebrow: the offending element is the eyebrow above the heading,
|
||||
// not the heading itself — highlight the previous sibling instead.
|
||||
const eyebrowFindings = checkElementHeroEyebrowDOM(el)
|
||||
.map(f => ({ type: f.id, detail: f.snippet }))
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (eyebrowFindings.length > 0 && el.previousElementSibling) {
|
||||
addBrowserFindings(groupMap, el.previousElementSibling, eyebrowFindings);
|
||||
}
|
||||
}
|
||||
|
||||
const pageLevelFindings = [];
|
||||
@@ -3646,6 +4151,14 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, qualityFindings);
|
||||
}
|
||||
|
||||
const creamFindings = checkCreamPalette(document)
|
||||
.map(f => ({ type: f.id, detail: f.snippet }))
|
||||
.filter(f => _ruleOk(f.type));
|
||||
if (creamFindings.length > 0) {
|
||||
pageLevelFindings.push(...creamFindings);
|
||||
addBrowserFindings(groupMap, document.body, creamFindings);
|
||||
}
|
||||
|
||||
// Regex-on-HTML checks (shared with Node)
|
||||
// Clone the document and strip impeccable-live overlay nodes before the
|
||||
// regex scan, so the inspector's own inline styles (transitions on top/
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
|
||||
|
||||
@@ -212,7 +213,7 @@ async function detectUrl(url, options = {}) {
|
||||
}, () => browser.close());
|
||||
}
|
||||
}
|
||||
return results.map(f => finding(f.id, url, f.snippet));
|
||||
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
|
||||
}
|
||||
|
||||
async function createBrowserDetector(options = {}) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { GENERIC_FONTS } from '../../shared/constants.mjs';
|
||||
import { isFullPage } from '../../shared/page.mjs';
|
||||
import { finding } from '../../findings.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { profileFindings, profileStep } from '../../profile/profiler.mjs';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -11,6 +12,17 @@ const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
|
||||
const hasBorderRadius = (line) => /border-radius/i.test(line);
|
||||
const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
|
||||
|
||||
/** Strip HTML to plain text — drops script/style/comments/tags so
|
||||
* content-text analyzers don't false-positive on code or CSS. */
|
||||
function stripHtmlToText(html) {
|
||||
return html
|
||||
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<!--[\s\S]*?-->/g, ' ')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function isNeutralBorderColor(str) {
|
||||
const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
|
||||
if (!m) return false;
|
||||
@@ -57,16 +69,12 @@ const REGEX_MATCHERS = [
|
||||
test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
|
||||
fmt: (m) => m[0] },
|
||||
// --- Overused font ---
|
||||
{ id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
|
||||
{ id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans|Instrument Serif)\b/gi,
|
||||
test: () => true,
|
||||
fmt: (m) => m[0] },
|
||||
{ id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
|
||||
{ id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Instrument\+Serif|Mona\+Sans|Geist)\b/gi,
|
||||
test: () => true,
|
||||
fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
|
||||
// --- Pure black background ---
|
||||
{ id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
|
||||
test: () => true,
|
||||
fmt: (m) => m[0] },
|
||||
// --- Gradient text ---
|
||||
{ id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
|
||||
test: (m, line) => /gradient/i.test(line),
|
||||
@@ -75,10 +83,6 @@ const REGEX_MATCHERS = [
|
||||
{ id: 'gradient-text', regex: /\bbg-clip-text\b/g,
|
||||
test: (m, line) => /\bbg-gradient-to-/i.test(line),
|
||||
fmt: () => 'bg-clip-text + bg-gradient' },
|
||||
// --- Tailwind pure black background ---
|
||||
{ id: 'pure-black-white', regex: /\bbg-black\b/g,
|
||||
test: () => true,
|
||||
fmt: (m) => m[0] },
|
||||
// --- Tailwind gray on colored bg ---
|
||||
{ id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
|
||||
test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
|
||||
@@ -124,6 +128,14 @@ const REGEX_MATCHERS = [
|
||||
const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
|
||||
return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
|
||||
} },
|
||||
// --- Broken image: src="" or src="#" or src=" " ---
|
||||
{ id: 'broken-image', regex: /<img\b[^>]*?\bsrc\s*=\s*(?:""|''|"\s+"|'\s+'|"#"|'#')/gi,
|
||||
test: () => true,
|
||||
fmt: (m) => m[0].slice(0, 100) },
|
||||
// --- Broken image: <img> with no src attribute at all ---
|
||||
{ id: 'broken-image', regex: /<img\b(?:(?!\bsrc\s*=)[^>])*>/gi,
|
||||
test: (m) => !/\bsrc\s*=/i.test(m[0]),
|
||||
fmt: (m) => m[0].slice(0, 100) },
|
||||
];
|
||||
|
||||
const REGEX_ANALYZERS = [
|
||||
@@ -197,18 +209,86 @@ const REGEX_ANALYZERS = [
|
||||
const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
|
||||
return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
|
||||
},
|
||||
// Everything centered (regex)
|
||||
// Em-dash overuse: 5+ em-dashes or "--" in body text content
|
||||
// (occasional em-dash use in prose is fine; the pattern fires only
|
||||
// when count crosses into AI-cadence territory).
|
||||
(content, filePath) => {
|
||||
const lines = content.split('\n');
|
||||
let centered = 0, total = 0;
|
||||
for (const line of lines) {
|
||||
if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
|
||||
total++;
|
||||
if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
|
||||
const text = stripHtmlToText(content);
|
||||
let count = 0;
|
||||
const re = /[—]|--(?=\S)/g;
|
||||
while (re.exec(text) !== null) count++;
|
||||
if (count < 5) return [];
|
||||
return [finding('em-dash-overuse', filePath, `${count} em-dashes in body text`)];
|
||||
},
|
||||
// Marketing buzzwords: SaaS phrase list
|
||||
(content, filePath) => {
|
||||
const text = stripHtmlToText(content);
|
||||
const lower = text.toLowerCase();
|
||||
const BUZZWORDS = [
|
||||
'streamline your', 'empower your', 'supercharge your',
|
||||
'unleash your', 'unleash the power', 'leverage the power',
|
||||
'built for the modern', 'trusted by leading', 'trusted by the world',
|
||||
'best-in-class', 'industry-leading', 'world-class', 'enterprise-grade',
|
||||
'next-generation', 'cutting-edge', 'transform your business',
|
||||
'revolutionize', 'game-changer', 'game changing',
|
||||
'mission-critical', 'best of breed', 'future-proof', 'future proof',
|
||||
'seamless experience', 'seamlessly integrate',
|
||||
'drive engagement', 'drive growth', 'drive results',
|
||||
'harness the power',
|
||||
];
|
||||
let count = 0;
|
||||
let firstSample = '';
|
||||
for (const phrase of BUZZWORDS) {
|
||||
let from = 0;
|
||||
while (true) {
|
||||
const idx = lower.indexOf(phrase, from);
|
||||
if (idx === -1) break;
|
||||
count++;
|
||||
if (!firstSample) {
|
||||
firstSample = text.slice(Math.max(0, idx - 12), Math.min(text.length, idx + phrase.length + 12)).trim();
|
||||
}
|
||||
from = idx + phrase.length;
|
||||
}
|
||||
}
|
||||
if (total < 5 || centered / total <= 0.7) return [];
|
||||
return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
|
||||
if (count === 0) return [];
|
||||
return [finding('marketing-buzzword', filePath, `${count} buzzword phrase${count === 1 ? '' : 's'}: "${firstSample}"`)];
|
||||
},
|
||||
// Numbered section markers (01 / 02 / 03 ...)
|
||||
(content, filePath) => {
|
||||
const text = stripHtmlToText(content);
|
||||
const re = /\b(0[1-9]|1[0-2])\b/g;
|
||||
const seen = new Set();
|
||||
let m;
|
||||
while ((m = re.exec(text)) !== null) seen.add(m[1]);
|
||||
if (seen.size < 3) return [];
|
||||
const sorted = [...seen].sort();
|
||||
let sequential = 0;
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
if (parseInt(sorted[i], 10) === parseInt(sorted[i - 1], 10) + 1) sequential++;
|
||||
}
|
||||
if (sequential < 2) return [];
|
||||
return [finding('numbered-section-markers', filePath, `Sequence: ${sorted.slice(0, 6).join(', ')}`)];
|
||||
},
|
||||
// Aphoristic cadence: manufactured-contrast + short-rebuttal
|
||||
(content, filePath) => {
|
||||
const text = stripHtmlToText(content);
|
||||
const NOT_A_RE = /\bNot an? [a-z][^.!?]{1,40}[.!]\s+[A-Z][^.!?]{1,60}[.!]/g;
|
||||
const SHORT_REBUTTAL_RE = /\b[A-Z][^.!?]{4,80}[.!]\s+(No|Just)\s+[a-z][^.!?]{2,60}[.!]/g;
|
||||
let count = 0;
|
||||
let firstSample = '';
|
||||
let m;
|
||||
NOT_A_RE.lastIndex = 0;
|
||||
while ((m = NOT_A_RE.exec(text)) !== null) {
|
||||
count++;
|
||||
if (!firstSample) firstSample = m[0].trim().slice(0, 80);
|
||||
}
|
||||
SHORT_REBUTTAL_RE.lastIndex = 0;
|
||||
while ((m = SHORT_REBUTTAL_RE.exec(text)) !== null) {
|
||||
count++;
|
||||
if (!firstSample) firstSample = m[0].trim().slice(0, 80);
|
||||
}
|
||||
if (count < 3) return [];
|
||||
return [finding('aphoristic-cadence', filePath, `${count} aphoristic constructions: "${firstSample}"`)];
|
||||
},
|
||||
// Dark glow (page-level: dark bg + colored box-shadow with blur)
|
||||
(content, filePath) => {
|
||||
@@ -328,6 +408,36 @@ function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null,
|
||||
return findings;
|
||||
}
|
||||
|
||||
/** Page-level analyzers that scan rendered text content (em-dash use,
|
||||
* buzzword phrases, numbered section markers, aphoristic cadence).
|
||||
* These are detector-agnostic — they work on any HTML/text source
|
||||
* and don't need a parsed DOM. Exported so detectHtml can call them
|
||||
* for `.html` files (which otherwise skip the regex engine). */
|
||||
const TEXT_CONTENT_ANALYZER_IDS = [
|
||||
'em-dash-overuse',
|
||||
'marketing-buzzword',
|
||||
'numbered-section-markers',
|
||||
'aphoristic-cadence',
|
||||
];
|
||||
|
||||
function runTextContentAnalyzers(content, filePath, options = {}) {
|
||||
const profile = options?.profile;
|
||||
if (!isFullPage(content)) return [];
|
||||
// The 4 text-content analyzers are at indices 3-6 in REGEX_ANALYZERS.
|
||||
const findings = [];
|
||||
for (let i = 0; i < TEXT_CONTENT_ANALYZER_IDS.length; i++) {
|
||||
const analyzer = REGEX_ANALYZERS[3 + i];
|
||||
const ruleId = TEXT_CONTENT_ANALYZER_IDS[i];
|
||||
findings.push(...profileFindings(profile, {
|
||||
engine: 'regex',
|
||||
phase: 'text-content',
|
||||
ruleId,
|
||||
target: filePath,
|
||||
}, () => analyzer(content, filePath)));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
function detectText(content, filePath, options = {}) {
|
||||
const profile = options?.profile;
|
||||
const findings = [];
|
||||
@@ -393,7 +503,10 @@ function detectText(content, filePath, options = {}) {
|
||||
'single-font',
|
||||
'flat-type-hierarchy',
|
||||
'monotonous-spacing',
|
||||
'everything-centered',
|
||||
'em-dash-overuse',
|
||||
'marketing-buzzword',
|
||||
'numbered-section-markers',
|
||||
'aphoristic-cadence',
|
||||
'dark-glow',
|
||||
];
|
||||
for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
|
||||
@@ -407,14 +520,16 @@ function detectText(content, filePath, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
return deduped;
|
||||
return filterByProviders(deduped, options?.providers);
|
||||
}
|
||||
|
||||
export {
|
||||
REGEX_MATCHERS,
|
||||
REGEX_ANALYZERS,
|
||||
TEXT_CONTENT_ANALYZER_IDS,
|
||||
extractStyleBlocks,
|
||||
extractCSSinJS,
|
||||
runRegexMatchers,
|
||||
runTextContentAnalyzers,
|
||||
detectText,
|
||||
};
|
||||
|
||||
@@ -241,6 +241,9 @@ const STATIC_DEFAULT_STYLE = {
|
||||
borderBottomColor: 'rgb(0, 0, 0)',
|
||||
borderLeftColor: 'rgb(0, 0, 0)',
|
||||
borderRadius: '0px',
|
||||
outlineWidth: '0px',
|
||||
outlineColor: 'rgb(0, 0, 0)',
|
||||
outlineStyle: 'none',
|
||||
boxShadow: 'none',
|
||||
fontFamily: '',
|
||||
fontSize: '16px',
|
||||
@@ -266,6 +269,9 @@ const STATIC_DEFAULT_STYLE = {
|
||||
paddingLeft: '0px',
|
||||
position: 'static',
|
||||
display: '',
|
||||
overflow: 'visible',
|
||||
overflowX: 'visible',
|
||||
overflowY: 'visible',
|
||||
};
|
||||
|
||||
const STATIC_PROP_MAP = {
|
||||
@@ -282,6 +288,9 @@ const STATIC_PROP_MAP = {
|
||||
'border-right-color': 'borderRightColor',
|
||||
'border-bottom-color': 'borderBottomColor',
|
||||
'border-left-color': 'borderLeftColor',
|
||||
'outline-width': 'outlineWidth',
|
||||
'outline-color': 'outlineColor',
|
||||
'outline-style': 'outlineStyle',
|
||||
'box-shadow': 'boxShadow',
|
||||
'font-family': 'fontFamily',
|
||||
'font-size': 'fontSize',
|
||||
@@ -305,6 +314,9 @@ const STATIC_PROP_MAP = {
|
||||
'padding-left': 'paddingLeft',
|
||||
'position': 'position',
|
||||
'display': 'display',
|
||||
'overflow': 'overflow',
|
||||
'overflow-x': 'overflowX',
|
||||
'overflow-y': 'overflowY',
|
||||
};
|
||||
|
||||
const STATIC_NAMED_COLORS = {
|
||||
@@ -511,6 +523,26 @@ function expandStaticDeclaration(prop, value) {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (p === 'outline') {
|
||||
// `outline` shorthand: width | style | color, in any order. Reuse the
|
||||
// border parser for width + color, then sniff a style keyword from the
|
||||
// tokens (solid|dashed|...). `outline: 0` (single-token zero) zeros
|
||||
// the width and effectively hides the outline.
|
||||
const tokens = splitCssTokens(v);
|
||||
const parsed = parseStaticBorder(v);
|
||||
const styleToken = tokens.find(t =>
|
||||
/^(none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/i.test(t)
|
||||
);
|
||||
const out = [];
|
||||
if (parsed.width) out.push(['outlineWidth', parsed.width]);
|
||||
if (parsed.color) out.push(['outlineColor', parsed.color]);
|
||||
if (styleToken) out.push(['outlineStyle', styleToken.toLowerCase()]);
|
||||
// `outline: 0` with no other tokens: explicit zero width.
|
||||
if (!parsed.width && /^0(?:px|rem|em|%)?$/.test(v.trim())) {
|
||||
out.push(['outlineWidth', '0px']);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
|
||||
if (sideMatch) {
|
||||
const parsed = parseStaticBorder(v);
|
||||
|
||||
@@ -7,13 +7,17 @@ import { finding } from '../../findings.mjs';
|
||||
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
|
||||
import {
|
||||
checkElementBorders,
|
||||
checkElementClippedOverflow,
|
||||
checkElementColors,
|
||||
checkElementGlow,
|
||||
checkElementGptBorderShadow,
|
||||
checkElementHeroEyebrow,
|
||||
checkElementIconTile,
|
||||
checkElementItalicSerif,
|
||||
checkElementMotion,
|
||||
checkElementOversizedH1,
|
||||
checkElementQuality,
|
||||
checkCreamPalette,
|
||||
checkHtmlPatterns,
|
||||
checkPageLayout,
|
||||
checkPageQualityFromDoc,
|
||||
@@ -21,7 +25,8 @@ import {
|
||||
resolveBackground,
|
||||
resolveBorderRadiusPx,
|
||||
} from '../../rules/checks.mjs';
|
||||
import { detectText } from '../regex/detect-text.mjs';
|
||||
import { filterByProviders } from '../../registry/antipatterns.mjs';
|
||||
import { detectText, runTextContentAnalyzers } from '../regex/detect-text.mjs';
|
||||
import {
|
||||
StaticDocument,
|
||||
buildStaticStyleMap,
|
||||
@@ -64,6 +69,20 @@ function checkStaticPageTypography(document, window) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
function checkElementBrokenImage(el) {
|
||||
const src = (el.getAttribute && el.getAttribute('src')) ?? el.attribs?.src;
|
||||
// Missing src attribute entirely
|
||||
if (src === undefined || src === null) {
|
||||
return [{ id: 'broken-image', snippet: '<img> with no src attribute' }];
|
||||
}
|
||||
const trimmed = String(src).trim();
|
||||
// Empty or placeholder-only src values
|
||||
if (trimmed === '' || trimmed === '#') {
|
||||
return [{ id: 'broken-image', snippet: `<img src="${src}">` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
const STATIC_ELEMENT_RULES = [
|
||||
{ id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
|
||||
{ id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
|
||||
@@ -72,7 +91,11 @@ const STATIC_ELEMENT_RULES = [
|
||||
{ id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
|
||||
{ id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
|
||||
{ id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
|
||||
{ id: 'broken-image', selector: 'img', run: (el) => checkElementBrokenImage(el) },
|
||||
{ id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
|
||||
{ id: 'oversized-h1', selector: 'h1', run: (el, tag, style, window) => checkElementOversizedH1(el, style, tag, window) },
|
||||
{ id: 'clipped-overflow-container', selector: '*', run: (el, tag, style, window) => checkElementClippedOverflow(el, style, tag, window) },
|
||||
{ id: 'gpt-thin-border-wide-shadow', selector: '*', run: (el, tag, style) => checkElementGptBorderShadow(el, style) },
|
||||
];
|
||||
|
||||
async function detectHtml(filePath, options = {}) {
|
||||
@@ -158,6 +181,9 @@ async function detectHtml(filePath, options = {}) {
|
||||
for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
for (const f of runPageCheck('cream-palette', () => checkCreamPalette(document, window))) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
@@ -166,9 +192,17 @@ async function detectHtml(filePath, options = {}) {
|
||||
))) {
|
||||
findings.push(finding(f.id, filePath, f.snippet));
|
||||
}
|
||||
// Text-content analyzers (em-dash overuse, marketing buzzwords,
|
||||
// numbered section markers, aphoristic cadence) live in the regex
|
||||
// engine. Call them from here so .html files get the same coverage
|
||||
// as .css/.tsx files. These are scoped to text content only and
|
||||
// don't overlap with static-html's element/page rules.
|
||||
for (const f of runPageCheck('text-content', () => runTextContentAnalyzers(html, filePath, options))) {
|
||||
findings.push(finding(f.antipattern, filePath, f.snippet));
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
return filterByProviders(findings, options.providers);
|
||||
}
|
||||
|
||||
export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
|
||||
|
||||
@@ -63,6 +63,15 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'AI color palette',
|
||||
},
|
||||
{
|
||||
id: 'cream-palette',
|
||||
category: 'slop',
|
||||
name: 'Cream / beige palette',
|
||||
description:
|
||||
'A warm cream or beige page background has become the default "tasteful" AI surface, reached for by reflex. Choose a background that comes from a deliberate palette, not the safe warm off-white.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'cream and beige as the default surface',
|
||||
},
|
||||
{
|
||||
id: 'nested-cards',
|
||||
category: 'slop',
|
||||
@@ -81,15 +90,6 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'same spacing everywhere',
|
||||
},
|
||||
{
|
||||
id: 'everything-centered',
|
||||
category: 'slop',
|
||||
name: 'Everything centered',
|
||||
description:
|
||||
'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'Center everything',
|
||||
},
|
||||
{
|
||||
id: 'bounce-easing',
|
||||
category: 'slop',
|
||||
@@ -145,17 +145,72 @@ const ANTIPATTERNS = [
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
|
||||
},
|
||||
{
|
||||
id: 'numbered-section-markers',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
name: 'Numbered section markers (01 / 02 / 03)',
|
||||
description:
|
||||
'Numbered display markers as section labels (01, 02, 03) are the AI editorial scaffold one tier deeper than tracked eyebrow chips. If you find yourself reaching for them, choose a different section cadence.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'numbered section markers',
|
||||
},
|
||||
{
|
||||
id: 'em-dash-overuse',
|
||||
category: 'slop',
|
||||
name: 'Em-dash overuse',
|
||||
description:
|
||||
'More than two em-dashes (— or --) in body copy is an AI cadence tell. Use commas, colons, periods, or parentheses instead.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'no em dashes',
|
||||
},
|
||||
{
|
||||
id: 'marketing-buzzword',
|
||||
category: 'slop',
|
||||
name: 'Marketing buzzword',
|
||||
description:
|
||||
'Generic SaaS phrases (streamline / empower / supercharge / world-class / enterprise-grade / next-generation / cutting-edge / etc) are instant AI tells. Pick a specific verb and noun that says what the product literally does.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'marketing buzzwords',
|
||||
},
|
||||
{
|
||||
id: 'aphoristic-cadence',
|
||||
category: 'slop',
|
||||
name: 'Aphoristic-cadence copy',
|
||||
description:
|
||||
'Three or more sections landing on a short rebuttal sentence ("X. No Y." / "X. Just Y.") or a manufactured-contrast aphorism ("Not a feature. A platform.") reads as AI cadence, not voice. Once is fine; the pattern is the tell.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'aphoristic cadence',
|
||||
},
|
||||
{
|
||||
id: 'oversized-h1',
|
||||
category: 'slop',
|
||||
name: 'Oversized hero headline',
|
||||
description:
|
||||
'A full-sentence headline set at display size ends up dominating the viewport, leaving no room for anything else above the fold. A punchy one- or two-word headline at that size is fine — the problem is a long headline blown up too large. Set long headlines smaller, or tighten the copy.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'long headline set at display size',
|
||||
},
|
||||
{
|
||||
id: 'extreme-negative-tracking',
|
||||
category: 'slop',
|
||||
name: 'Crushed letter spacing',
|
||||
description:
|
||||
'Letter-spacing pulled tighter than the point where characters keep their own shapes costs legibility. Tighten display type optically, not destructively.',
|
||||
skillSection: 'Typography',
|
||||
skillGuideline: 'letter spacing crushed past legibility',
|
||||
},
|
||||
{
|
||||
id: 'broken-image',
|
||||
category: 'quality',
|
||||
name: 'Broken or placeholder image',
|
||||
description:
|
||||
'<img> tags with empty src, missing src, or placeholder values ship as broken-image boxes. Use real images, generated assets, or remove the tag.',
|
||||
skillSection: 'Imagery',
|
||||
skillGuideline: 'broken image references',
|
||||
},
|
||||
|
||||
// ── Quality: general design and accessibility issues ──
|
||||
{
|
||||
id: 'pure-black-white',
|
||||
category: 'quality',
|
||||
name: 'Pure black background',
|
||||
description:
|
||||
'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
|
||||
skillSection: 'Color & Contrast',
|
||||
skillGuideline: 'pure black (#000)',
|
||||
},
|
||||
{
|
||||
id: 'gray-on-color',
|
||||
category: 'quality',
|
||||
@@ -195,7 +250,9 @@ const ANTIPATTERNS = [
|
||||
category: 'quality',
|
||||
name: 'Cramped padding',
|
||||
description:
|
||||
'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
|
||||
'Text is too close to the edge of its container. Two shapes: (1) an element with its own text where the padding is too low for the font size, and (2) a wrapper with text-bearing children and near-zero padding against a visible boundary (border, outline, or non-transparent background) — children land flush against the boundary line. Add at least 8px (ideally 12–16px) of padding inside bordered, outlined, or colored containers.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'inside bordered or colored containers',
|
||||
},
|
||||
{
|
||||
id: 'body-text-viewport-edge',
|
||||
@@ -248,6 +305,70 @@ const ANTIPATTERNS = [
|
||||
description:
|
||||
'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
|
||||
},
|
||||
{
|
||||
id: 'text-overflow',
|
||||
category: 'quality',
|
||||
name: 'Content overflowing its container',
|
||||
description:
|
||||
'Content renders wider than its container, spilling out or forcing a horizontal scrollbar. Let text wrap, constrain widths, or give the region a deliberate scroll affordance.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'content wider than its container',
|
||||
},
|
||||
{
|
||||
id: 'clipped-overflow-container',
|
||||
category: 'quality',
|
||||
name: 'Positioned child clipped by overflow container',
|
||||
description:
|
||||
'A clipping container (overflow hidden or clip) wrapping an absolutely-positioned child cuts off tooltips, menus, and popovers that need to escape. Let the overflow be visible, or move the positioned layer out of the clip.',
|
||||
skillSection: 'Layout & Space',
|
||||
skillGuideline: 'overflow container clipping positioned children',
|
||||
},
|
||||
|
||||
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
|
||||
{
|
||||
id: 'gpt-thin-border-wide-shadow',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Hairline border with wide shadow',
|
||||
description:
|
||||
'A hairline border paired with a wide, diffuse shadow is a recurring generated-UI signature. Commit to one — a defined edge or a soft elevation — rather than both at once.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'hairline border plus wide diffuse shadow',
|
||||
},
|
||||
{
|
||||
id: 'repeating-stripes-gradient',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Repeating-gradient stripes',
|
||||
description:
|
||||
'Repeating-gradient stripes used as surface decoration are a recurring generated-UI signature. Reach for a deliberate texture or leave the surface plain.',
|
||||
skillSection: 'Visual Details',
|
||||
skillGuideline: 'repeating-gradient decorative stripes',
|
||||
},
|
||||
{
|
||||
id: 'theater-slop-phrase',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gpt',
|
||||
name: 'Theater framing copy',
|
||||
description:
|
||||
'Dismissing something as "theater" is a recurring generated-copy tic. Say plainly what the thing does or does not do.',
|
||||
skillSection: 'Copy',
|
||||
skillGuideline: 'theater framing copy',
|
||||
},
|
||||
{
|
||||
id: 'image-hover-transform',
|
||||
category: 'slop',
|
||||
severity: 'advisory',
|
||||
gated: 'gemini',
|
||||
name: 'Image hover transform',
|
||||
description:
|
||||
'Scaling or rotating an image on hover is a recurring generated-UI signature. Let imagery sit still, or use a subtler, purposeful interaction.',
|
||||
skillSection: 'Motion',
|
||||
skillGuideline: 'image scale or rotate on hover',
|
||||
},
|
||||
];
|
||||
|
||||
const RULE_ENGINE_SUPPORT = {
|
||||
@@ -269,10 +390,30 @@ function getRuleEngineSupport(engine) {
|
||||
return RULE_ENGINE_SUPPORT[engine] || new Set();
|
||||
}
|
||||
|
||||
// Set of provider tags that gate rules off by default (e.g. 'gpt', 'gemini').
|
||||
const GATED_PROVIDERS = new Set(
|
||||
ANTIPATTERNS.map(rule => rule.gated).filter(Boolean),
|
||||
);
|
||||
|
||||
// Drop findings for rules gated behind a provider tag unless that provider
|
||||
// was explicitly enabled (CLI --gpt / --gemini). Non-gated findings always
|
||||
// pass through. `findings` carry the rule id on `.antipattern`.
|
||||
function filterByProviders(findings, providers = []) {
|
||||
const enabled = new Set(providers || []);
|
||||
if (!GATED_PROVIDERS.size) return findings;
|
||||
return findings.filter(f => {
|
||||
const rule = getAntipattern(f.antipattern);
|
||||
if (!rule || !rule.gated) return true;
|
||||
return enabled.has(rule.gated);
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
ANTIPATTERNS,
|
||||
RULE_ENGINE_SUPPORT,
|
||||
GATED_PROVIDERS,
|
||||
getAntipattern,
|
||||
getRulesForCategory,
|
||||
getRuleEngineSupport,
|
||||
filterByProviders,
|
||||
};
|
||||
|
||||
@@ -78,11 +78,6 @@ function checkColors(opts) {
|
||||
}
|
||||
const findings = [];
|
||||
|
||||
// Pure black background (only solid or near-solid, not semi-transparent overlays)
|
||||
if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
|
||||
findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
|
||||
}
|
||||
|
||||
if (hasDirectText && textColor && !isEmojiOnly) {
|
||||
// Run background-dependent checks against either a solid bg or, if the
|
||||
// ancestor is a gradient, against every gradient stop (use the worst case).
|
||||
@@ -138,9 +133,6 @@ function checkColors(opts) {
|
||||
// Tailwind class checks
|
||||
if (classList) {
|
||||
const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
|
||||
if (/\bbg-black\b(?!\/)/.test(classStr)) {
|
||||
findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
|
||||
}
|
||||
|
||||
const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
|
||||
const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
|
||||
@@ -456,12 +448,6 @@ function checkHtmlPatterns(html) {
|
||||
|
||||
// --- Color ---
|
||||
|
||||
// Pure black background
|
||||
const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
|
||||
if (pureBlackBgRe.test(html)) {
|
||||
findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
|
||||
}
|
||||
|
||||
// AI color palette: purple/violet
|
||||
const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
|
||||
if (purpleHexRe.test(html)) {
|
||||
@@ -578,6 +564,39 @@ function checkHtmlPatterns(html) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): repeating-gradient stripes (GPT) ---
|
||||
if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(html)) {
|
||||
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
|
||||
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
|
||||
// runs in the bundled browser path too, not just the CLI/static path.
|
||||
{
|
||||
const bodyText = html
|
||||
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<[^>]+>/g, ' ');
|
||||
const tm = /\b(\w+)\s+theater\b/i.exec(bodyText);
|
||||
if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` });
|
||||
}
|
||||
|
||||
// --- Provider tells (gated): image hover transform (Gemini) ---
|
||||
// A CSS `img...:hover { transform: ... }` rule, or a Tailwind hover:scale /
|
||||
// hover:rotate / hover:translate utility on an <img>. Each distinct
|
||||
// mechanism is its own finding.
|
||||
const imgHoverCss = /\bimg\b[^,{}]*:hover\b[^{}]*\{[^}]*\btransform\s*:\s*(?:scale|rotate|translate|matrix|skew)/i;
|
||||
if (imgHoverCss.test(html)) {
|
||||
findings.push({ id: 'image-hover-transform', snippet: 'img:hover { transform } rule' });
|
||||
}
|
||||
const imgTagRe = /<img\b[^>]*\bclass\s*=\s*"([^"]*)"/gi;
|
||||
let im;
|
||||
while ((im = imgTagRe.exec(html)) !== null) {
|
||||
if (/\bhover:(?:scale|rotate|translate|skew)-/.test(im[1])) {
|
||||
findings.push({ id: 'image-hover-transform', snippet: 'Tailwind hover transform on <img>' });
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
@@ -1224,7 +1243,7 @@ function resolveLengthPx(value, fontSizePx) {
|
||||
// Both adapters resolve font-size, line-height and letter-spacing to pixels
|
||||
// before calling this so the pure function only deals with numbers.
|
||||
function checkQuality(opts) {
|
||||
const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
|
||||
const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0, win = null } = opts;
|
||||
const findings = [];
|
||||
// Skip browser extension injected elements
|
||||
const elId = el.id || '';
|
||||
@@ -1275,6 +1294,155 @@ function checkQuality(opts) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flush against a visible boundary ---
|
||||
// Fires when a container has a visible boundary (border, outline, OR a
|
||||
// non-transparent background) AND near-zero padding on the bounded
|
||||
// side(s) AND text-bearing children land flush against the boundary.
|
||||
//
|
||||
// Distinct from cramped-padding: that rule needs the element itself to
|
||||
// have direct text (hasDirectText). This rule targets the OPPOSITE
|
||||
// shape — a container with NO direct text, only children — which is
|
||||
// exactly what cramped-padding misses (a section wrapping a label +
|
||||
// list lands a free pass).
|
||||
//
|
||||
// The classic shape: agent writes `padding: 28px 0 0` shorthand on a
|
||||
// section that also has a border, zeroing horizontal padding so the
|
||||
// text-bearing children touch the side borders. Background and
|
||||
// outline count too: a colored card with zero padding has the same
|
||||
// visual failure mode.
|
||||
{
|
||||
const FLUSH_SKIP_TAGS = new Set(['HTML', 'BODY', 'MAIN', 'HEADER', 'FOOTER', 'NAV', 'ARTICLE', 'ASIDE', 'BUTTON', 'A', 'LABEL', 'SUMMARY', 'CODE', 'PRE', 'INPUT', 'TEXTAREA', 'SELECT', 'FORM', 'FIGURE', 'TABLE', 'TBODY', 'THEAD', 'TR', 'TD', 'TH']);
|
||||
const upperTag = tag ? tag.toUpperCase() : '';
|
||||
const elPosition = style.position || '';
|
||||
if (
|
||||
!FLUSH_SKIP_TAGS.has(upperTag) &&
|
||||
!hasDirectText &&
|
||||
!['fixed', 'absolute'].includes(elPosition) &&
|
||||
el.children && el.children.length > 0
|
||||
) {
|
||||
const isTransparent = (c) =>
|
||||
!c || c === 'transparent' || c === 'rgba(0, 0, 0, 0)' ||
|
||||
/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0(?:\.0+)?\s*\)$/.test(c);
|
||||
|
||||
const borderW = {
|
||||
top: parseFloat(style.borderTopWidth) || 0,
|
||||
right: parseFloat(style.borderRightWidth) || 0,
|
||||
bottom: parseFloat(style.borderBottomWidth) || 0,
|
||||
left: parseFloat(style.borderLeftWidth) || 0,
|
||||
};
|
||||
const borderVisible = {
|
||||
top: borderW.top > 0 && !isTransparent(style.borderTopColor),
|
||||
right: borderW.right > 0 && !isTransparent(style.borderRightColor),
|
||||
bottom: borderW.bottom > 0 && !isTransparent(style.borderBottomColor),
|
||||
left: borderW.left > 0 && !isTransparent(style.borderLeftColor),
|
||||
};
|
||||
// Outline detection. jsdom decomposes `border` shorthand into
|
||||
// border{Top,…}Width/Color but does NOT decompose `outline` —
|
||||
// the longhands come back empty when the value was set via the
|
||||
// shorthand. Fall back to parsing `style.outline` ourselves.
|
||||
let outlineW = parseFloat(style.outlineWidth) || 0;
|
||||
let outlineStyleVal = style.outlineStyle || '';
|
||||
let outlineColorVal = style.outlineColor || '';
|
||||
if (!outlineW && style.outline) {
|
||||
const wMatch = style.outline.match(/(\d+(?:\.\d+)?)\s*px/);
|
||||
if (wMatch) outlineW = parseFloat(wMatch[1]) || 0;
|
||||
if (!outlineStyleVal) {
|
||||
outlineStyleVal = /\b(solid|dashed|dotted|double|groove|ridge|inset|outset)\b/.test(style.outline) ? 'solid' : '';
|
||||
}
|
||||
if (!outlineColorVal) {
|
||||
const cMatch = style.outline.match(/(rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}|[a-zA-Z]+)\s*$/);
|
||||
if (cMatch) outlineColorVal = cMatch[1];
|
||||
}
|
||||
}
|
||||
const outlineVisible = outlineW > 0 && !isTransparent(outlineColorVal) && outlineStyleVal && outlineStyleVal !== 'none';
|
||||
const bgVisible = !isTransparent(style.backgroundColor);
|
||||
|
||||
const anyVisible = borderVisible.top || borderVisible.right || borderVisible.bottom || borderVisible.left || outlineVisible || bgVisible;
|
||||
if (anyVisible) {
|
||||
// Resolve padding to px (jsdom returns raw "1.5rem" etc., not the
|
||||
// computed px value; parseFloat would strip the unit and treat
|
||||
// 1.5rem as 1.5px, false-flagging legitimate insets).
|
||||
const pad = {
|
||||
top: resolveLengthPx(style.paddingTop, fontSize) ?? 0,
|
||||
right: resolveLengthPx(style.paddingRight, fontSize) ?? 0,
|
||||
bottom: resolveLengthPx(style.paddingBottom, fontSize) ?? 0,
|
||||
left: resolveLengthPx(style.paddingLeft, fontSize) ?? 0,
|
||||
};
|
||||
const PAD_THRESHOLD = 2;
|
||||
// Children-insulate-this-side: a side is insulated if ANY direct
|
||||
// child has its own padding ≥ 4px on that side. Rationale: in
|
||||
// typical flow, only the first/last (or leftmost/rightmost)
|
||||
// children actually sit at the parent's edges. If even one of
|
||||
// them has its own padding, the visual flush is broken on that
|
||||
// side. Classic example: a column-flow card frame where the
|
||||
// top child (header) has padding-top:12 and the bottom child
|
||||
// (footer) has padding-bottom:8 — the parent's padding:0 doesn't
|
||||
// matter; nothing is actually flush. The `any-child-insulates`
|
||||
// heuristic accepts some false negatives (a card with one heavily
|
||||
// padded middle child won't flag) for far fewer false positives.
|
||||
const CHILD_INSULATE_THRESHOLD = 4;
|
||||
const childrenInsulate = { top: false, right: false, bottom: false, left: false };
|
||||
for (const child of el.children) {
|
||||
let childStyle = null;
|
||||
if (win && typeof win.getComputedStyle === 'function') {
|
||||
try { childStyle = win.getComputedStyle(child); } catch {}
|
||||
}
|
||||
if (!childStyle && typeof getComputedStyle === 'function') {
|
||||
try { childStyle = getComputedStyle(child); } catch {}
|
||||
}
|
||||
if (!childStyle) continue;
|
||||
const childPad = {
|
||||
top: resolveLengthPx(childStyle.paddingTop, fontSize) ?? 0,
|
||||
right: resolveLengthPx(childStyle.paddingRight, fontSize) ?? 0,
|
||||
bottom: resolveLengthPx(childStyle.paddingBottom, fontSize) ?? 0,
|
||||
left: resolveLengthPx(childStyle.paddingLeft, fontSize) ?? 0,
|
||||
};
|
||||
for (const s of ['top', 'right', 'bottom', 'left']) {
|
||||
if (childPad[s] >= CHILD_INSULATE_THRESHOLD) childrenInsulate[s] = true;
|
||||
}
|
||||
}
|
||||
|
||||
const flushSides = [];
|
||||
for (const side of ['top', 'right', 'bottom', 'left']) {
|
||||
const sideBounded = borderVisible[side] || outlineVisible || bgVisible;
|
||||
if (sideBounded && pad[side] <= PAD_THRESHOLD && !childrenInsulate[side]) {
|
||||
flushSides.push(side);
|
||||
}
|
||||
}
|
||||
|
||||
if (flushSides.length > 0) {
|
||||
// Confirm at least one direct child has substantial text content
|
||||
// (> 4 chars). Without this, the flush is harmless: e.g. an
|
||||
// image-only card.
|
||||
let hasTextChild = false;
|
||||
for (const child of el.children) {
|
||||
const childText = (child.textContent || '').trim();
|
||||
if (childText.length > 4) { hasTextChild = true; break; }
|
||||
}
|
||||
if (hasTextChild) {
|
||||
const cls = (typeof el.className === 'string' && el.className.trim())
|
||||
? el.className.trim().split(/\s+/)[0]
|
||||
: '';
|
||||
const boundaryParts = [];
|
||||
const borderSidesVisible = ['top', 'right', 'bottom', 'left'].filter(s => borderVisible[s]);
|
||||
if (borderSidesVisible.length === 4) boundaryParts.push('border');
|
||||
else if (borderSidesVisible.length > 0) boundaryParts.push(`border-${borderSidesVisible.join('/')}`);
|
||||
if (outlineVisible) boundaryParts.push('outline');
|
||||
if (bgVisible) boundaryParts.push('bg');
|
||||
const sidesLabel = flushSides.length === 4 ? 'all sides' : flushSides.join('/');
|
||||
const ident = cls
|
||||
? `<${tag.toLowerCase()}> "${cls}"`
|
||||
: `<${tag.toLowerCase()}>`;
|
||||
findings.push({
|
||||
id: 'cramped-padding',
|
||||
snippet: `${ident}: children flush against ${boundaryParts.join('+')} on ${sidesLabel} (no inset)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Body text touching viewport edge --- (browser-only: needs rect)
|
||||
// Catches the failure mode where the agent ships body paragraphs
|
||||
// with NO container providing horizontal padding — text bleeds
|
||||
@@ -1355,6 +1523,20 @@ function checkQuality(opts) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Crushed letter spacing (mirror of wide-tracking) ---
|
||||
// Tracking pulled tighter than ~-0.05em crushes characters into each other.
|
||||
// Optical tightening that display type legitimately wants (around -0.02em)
|
||||
// stays well above this floor.
|
||||
if (hasDirectText && textLen > 20 && fontSize > 0) {
|
||||
if (letterSpacingPx != null && letterSpacingPx < 0) {
|
||||
const trackingEm = letterSpacingPx / fontSize;
|
||||
if (trackingEm <= -0.05) {
|
||||
const excerpt = (el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 40);
|
||||
findings.push({ id: 'extreme-negative-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em — "${excerpt}"` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
@@ -1371,7 +1553,7 @@ function checkElementQualityDOM(el) {
|
||||
const rect = el.getBoundingClientRect();
|
||||
const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
|
||||
const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth, win: typeof window !== 'undefined' ? window : null });
|
||||
}
|
||||
|
||||
// Pure page-level skipped-heading walk. Takes a Document so it works in both
|
||||
@@ -1413,7 +1595,7 @@ function checkElementQuality(el, style, tag, window) {
|
||||
const fontSize = resolveFontSizePx(el, window);
|
||||
const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
|
||||
const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
|
||||
return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null, win: window });
|
||||
}
|
||||
|
||||
function checkElementBorders(tag, style, overrides, resolvedRadius) {
|
||||
@@ -1854,40 +2036,213 @@ function checkPageLayout(doc, win) {
|
||||
}
|
||||
}
|
||||
|
||||
// Everything centered
|
||||
const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
|
||||
let centeredCount = 0;
|
||||
let totalText = 0;
|
||||
for (const el of textEls) {
|
||||
const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
|
||||
if (!hasDirectText) continue;
|
||||
totalText++;
|
||||
|
||||
let cur = el;
|
||||
let isCentered = false;
|
||||
while (cur && cur.nodeType === 1) {
|
||||
const rawStyle = cur.getAttribute?.('style') || '';
|
||||
const cls = cur.getAttribute?.('class') || '';
|
||||
if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
|
||||
isCentered = true;
|
||||
break;
|
||||
}
|
||||
if (cur.tagName === 'BODY') break;
|
||||
cur = cur.parentElement;
|
||||
}
|
||||
if (isCentered) centeredCount++;
|
||||
}
|
||||
|
||||
if (totalText >= 5 && centeredCount / totalText > 0.7) {
|
||||
findings.push({
|
||||
id: 'everything-centered',
|
||||
snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
|
||||
});
|
||||
}
|
||||
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Cream / beige palette (the default "tasteful" AI surface) ────────────────
|
||||
// A warm, lightly-tinted off-white page background — light, with R≥G≥B and a
|
||||
// small warm tint (not white, not a strong color). The current reflex surface.
|
||||
function isCreamColor(rgb) {
|
||||
if (!rgb) return false;
|
||||
const { r, g, b } = rgb;
|
||||
if (Math.min(r, g, b) < 209) return false; // must be light
|
||||
if (!(r >= g && g >= b)) return false; // warm ordering
|
||||
const warmth = r - b;
|
||||
return warmth >= 6 && warmth <= 48; // tinted, not white, not strong
|
||||
}
|
||||
|
||||
// Tailwind background utilities that render as a warm off-white surface. The
|
||||
// static engine doesn't fetch Tailwind's CSS, so a `bg-amber-50` on <body>
|
||||
// resolves to nothing in computed style — catch it from the class list
|
||||
// instead. Candidate tokens map to their actual Tailwind hex and are still
|
||||
// filtered through isCreamColor, so neutral grays (stone) and over-saturated
|
||||
// shades drop out on their own.
|
||||
const TAILWIND_BG_HEX = {
|
||||
'bg-amber-50': '#fffbeb', 'bg-amber-100': '#fef3c7',
|
||||
'bg-orange-50': '#fff7ed', 'bg-orange-100': '#ffedd5',
|
||||
'bg-yellow-50': '#fefce8',
|
||||
'bg-stone-50': '#fafaf9', 'bg-stone-100': '#f5f5f4', 'bg-stone-200': '#e7e5e4',
|
||||
};
|
||||
|
||||
function creamFromClassList(cls) {
|
||||
if (!cls) return null;
|
||||
// Arbitrary value: bg-[#f5f0e6] / bg-[rgb(245_240_230)] (underscores = spaces).
|
||||
const arb = cls.match(/\bbg-\[([^\]]+)\]/);
|
||||
if (arb && isCreamColor(parseAnyColor(arb[1].replace(/_/g, ' ')))) return `bg-[${arb[1]}]`;
|
||||
// Named warm-light utilities.
|
||||
for (const [tok, hex] of Object.entries(TAILWIND_BG_HEX)) {
|
||||
if (new RegExp(`(^|\\s)${tok}($|\\s)`).test(cls) && isCreamColor(parseAnyColor(hex))) return tok;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkCreamPalette(doc, win) {
|
||||
const findings = [];
|
||||
const body = doc.body || (doc.querySelector ? doc.querySelector('body') : null);
|
||||
if (!body) return findings;
|
||||
const html = doc.documentElement;
|
||||
const getCS = (el) => (win ? win.getComputedStyle(el) : getComputedStyle(el));
|
||||
|
||||
// 1. Computed background — covers inline / <style> / linked CSS, and Tailwind
|
||||
// once it's actually rendered (browser path).
|
||||
let bg = readOwnBackgroundColor(body, getCS(body));
|
||||
if (!bg || bg.a === 0) {
|
||||
if (html) bg = readOwnBackgroundColor(html, getCS(html));
|
||||
}
|
||||
if (isCreamColor(bg)) {
|
||||
findings.push({ id: 'cream-palette', snippet: `cream/beige page background rgb(${bg.r}, ${bg.g}, ${bg.b})` });
|
||||
return findings;
|
||||
}
|
||||
|
||||
// 2. Tailwind class fallback — for the static path, where utility classes
|
||||
// never resolve to computed CSS.
|
||||
for (const el of [body, html]) {
|
||||
const tok = creamFromClassList(el && el.getAttribute ? el.getAttribute('class') : '');
|
||||
if (tok) {
|
||||
findings.push({ id: 'cream-palette', snippet: `cream/beige page background (Tailwind ${tok})` });
|
||||
break;
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Oversized hero headline ────────────────────────────────────────────────
|
||||
// Fires when a *long* headline is set at display size, so a full sentence ends
|
||||
// up dominating the viewport. A punchy one- or two-word headline at the same
|
||||
// size is a legitimate stylistic choice and must pass — length, not size
|
||||
// alone, is the tell.
|
||||
const OVERSIZED_H1_FONT_PX = 72;
|
||||
const OVERSIZED_H1_MIN_CHARS = 40;
|
||||
function checkOversizedH1({ tag, fontSize, headingText }) {
|
||||
if (tag !== 'h1') return [];
|
||||
const textLen = headingText.length;
|
||||
if (fontSize >= OVERSIZED_H1_FONT_PX && textLen >= OVERSIZED_H1_MIN_CHARS) {
|
||||
return [{ id: 'oversized-h1', snippet: `${Math.round(fontSize)}px h1, ${textLen} chars "${headingText.slice(0, 60)}"` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function checkElementOversizedH1(el, style, tag, window) {
|
||||
if (tag !== 'h1') return [];
|
||||
const fontSize = resolveFontSizePx(el, window);
|
||||
const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
|
||||
return checkOversizedH1({ tag, fontSize, headingText });
|
||||
}
|
||||
|
||||
function checkElementOversizedH1DOM(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (tag !== 'h1') return [];
|
||||
const style = getComputedStyle(el);
|
||||
const fontSize = parseFloat(style.fontSize) || 0;
|
||||
const headingText = (el.textContent || '').trim().replace(/\s+/g, ' ');
|
||||
return checkOversizedH1({ tag, fontSize, headingText });
|
||||
}
|
||||
|
||||
// ─── GPT tell: hairline border + wide diffuse shadow (gated --gpt) ────────────
|
||||
function shadowMaxBlurPx(boxShadow) {
|
||||
if (!boxShadow || boxShadow === 'none') return 0;
|
||||
let maxBlur = 0;
|
||||
// Split into layers on commas not inside parentheses (rgba(...) etc.).
|
||||
for (const layer of boxShadow.split(/,(?![^()]*\))/)) {
|
||||
// Strip colors and keywords (rgba()/hsl()/hex/named/inset/px), leaving the
|
||||
// ordered length tokens: offsetX offsetY blur [spread]. Static jsdom keeps
|
||||
// unitless zeros ("0 0 24px"); browsers normalize to px ("0px 0px 24px") —
|
||||
// both reduce to the same numbers here.
|
||||
const cleaned = layer.replace(/rgba?\([^)]*\)|hsla?\([^)]*\)|#[0-9a-f]+|\b[a-z]+\b/gi, ' ');
|
||||
const nums = [...cleaned.matchAll(/-?\d*\.?\d+/g)].map(m => parseFloat(m[0]));
|
||||
if (nums.length >= 3) maxBlur = Math.max(maxBlur, nums[2]);
|
||||
}
|
||||
return maxBlur;
|
||||
}
|
||||
|
||||
function checkGptThinBorderWideShadow({ borderWidths, boxShadow }) {
|
||||
const maxBorder = Math.max(0, ...borderWidths);
|
||||
const hasThinBorder = maxBorder > 0 && maxBorder <= 1.5;
|
||||
const blur = shadowMaxBlurPx(boxShadow);
|
||||
if (hasThinBorder && blur >= 16) {
|
||||
return [{ id: 'gpt-thin-border-wide-shadow', snippet: `${maxBorder}px border + ${Math.round(blur)}px shadow blur` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function borderWidthsFromStyle(style) {
|
||||
return [
|
||||
parseFloat(style.borderTopWidth) || 0,
|
||||
parseFloat(style.borderRightWidth) || 0,
|
||||
parseFloat(style.borderBottomWidth) || 0,
|
||||
parseFloat(style.borderLeftWidth) || 0,
|
||||
];
|
||||
}
|
||||
|
||||
function checkElementGptBorderShadow(el, style) {
|
||||
return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
|
||||
}
|
||||
|
||||
function checkElementGptBorderShadowDOM(el) {
|
||||
const style = getComputedStyle(el);
|
||||
return checkGptThinBorderWideShadow({ borderWidths: borderWidthsFromStyle(style), boxShadow: style.boxShadow || '' });
|
||||
}
|
||||
|
||||
// ─── Clipped overflow container ───────────────────────────────────────────────
|
||||
// A clipping container (overflow hidden/clip, not a scroll region) wrapping an
|
||||
// absolutely/fixed-positioned descendant clips popovers/menus that must escape.
|
||||
function classSelector(el) {
|
||||
const cls = (el.getAttribute ? el.getAttribute('class') : el.className) || '';
|
||||
const tokens = String(cls).trim().split(/\s+/).filter(Boolean);
|
||||
const tag = el.tagName ? el.tagName.toLowerCase() : 'el';
|
||||
return tokens.length ? `${tag}.${tokens.join('.')}` : tag;
|
||||
}
|
||||
|
||||
function checkClippedOverflow(el, style, getStyle) {
|
||||
const clips = (v) => v === 'hidden' || v === 'clip';
|
||||
const scrolls = (v) => v === 'auto' || v === 'scroll';
|
||||
const ox = style.overflowX || '', oy = style.overflowY || '', ov = style.overflow || '';
|
||||
const anyClip = clips(ox) || clips(oy) || clips(ov);
|
||||
const anyScroll = scrolls(ox) || scrolls(oy) || scrolls(ov);
|
||||
if (!anyClip || anyScroll) return [];
|
||||
if (!el.querySelectorAll) return [];
|
||||
for (const child of el.querySelectorAll('*')) {
|
||||
const pos = (getStyle(child).position) || '';
|
||||
if (pos === 'absolute' || pos === 'fixed') {
|
||||
return [{ id: 'clipped-overflow-container', snippet: `${classSelector(el)} clips a positioned child` }];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function checkElementClippedOverflow(el, style, tag, window) {
|
||||
return checkClippedOverflow(el, style, (n) => window.getComputedStyle(n));
|
||||
}
|
||||
|
||||
function checkElementClippedOverflowDOM(el) {
|
||||
const style = getComputedStyle(el);
|
||||
return checkClippedOverflow(el, style, (n) => getComputedStyle(n));
|
||||
}
|
||||
|
||||
// ─── Text overflow (browser-only: needs scrollWidth/clientWidth) ──────────────
|
||||
const TEXT_OVERFLOW_SKIP_TAGS = new Set(['pre', 'code', 'textarea', 'svg', 'canvas', 'select', 'option', 'marquee']);
|
||||
|
||||
function checkElementTextOverflowDOM(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (TEXT_OVERFLOW_SKIP_TAGS.has(tag)) return [];
|
||||
// Only the element that actually owns overflowing text — not its ancestors,
|
||||
// which inherit a wider scrollWidth from the spilling descendant.
|
||||
const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
|
||||
if (!hasDirectText) return [];
|
||||
const style = getComputedStyle(el);
|
||||
const isScrollRegion = (s) => /(auto|scroll)/.test(s.overflowX || '') || /(auto|scroll)/.test(s.overflow || '');
|
||||
if (isScrollRegion(style)) return [];
|
||||
// A scrollable ancestor means this overflow is intentional and scrollable.
|
||||
for (let p = el.parentElement; p; p = p.parentElement) {
|
||||
if (isScrollRegion(getComputedStyle(p))) return [];
|
||||
}
|
||||
const delta = el.scrollWidth - el.clientWidth;
|
||||
if (el.clientWidth > 0 && delta >= 16) {
|
||||
return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its box by ${Math.round(delta)}px` }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export {
|
||||
checkBorders,
|
||||
isEmojiOnlyText,
|
||||
@@ -1945,4 +2300,17 @@ export {
|
||||
checkPageTypography,
|
||||
isCardLike,
|
||||
checkPageLayout,
|
||||
isCreamColor,
|
||||
checkCreamPalette,
|
||||
checkOversizedH1,
|
||||
checkElementOversizedH1,
|
||||
checkElementOversizedH1DOM,
|
||||
shadowMaxBlurPx,
|
||||
checkGptThinBorderWideShadow,
|
||||
checkElementGptBorderShadow,
|
||||
checkElementGptBorderShadowDOM,
|
||||
checkClippedOverflow,
|
||||
checkElementClippedOverflow,
|
||||
checkElementClippedOverflowDOM,
|
||||
checkElementTextOverflowDOM,
|
||||
};
|
||||
|
||||
@@ -24,7 +24,7 @@ const OVERUSED_FONTS = new Set([
|
||||
// Older monoculture (still ubiquitous):
|
||||
'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
|
||||
// Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
|
||||
'fraunces', 'instrument sans',
|
||||
'fraunces', 'instrument sans', 'instrument serif',
|
||||
'geist', 'geist sans', 'geist mono',
|
||||
'mona sans',
|
||||
'plus jakarta sans', 'space grotesk', 'recoleta',
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user