Claude Skill

react-frontend

React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, or reviewing React code. For visual design and aesthetic direction, use frontend-design instead

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download iliaal-ai-skills-skills_react-frontend-7b0520a.zip · 29 KB
Part of iliaal/ai-skills — 26 skills

Install

skills CLI npx skills add https://github.com/iliaal/ai-skills/tree/master/skills/react-frontend
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install iliaal-ai-skills@llmmart
Git git clone https://github.com/iliaal/ai-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole iliaal/ai-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

React Frontend

Verify before implementing: For App Router patterns, React 19 APIs, or version-specific behavior, look up current docs (Context7 query-docs if available, else the framework's official docs via web search) before writing code. Training data may lag current releases.

Working rules

  • Keep derived state in render and user actions in event handlers; use effects for external synchronization.
  • Give async work a lifecycle and cancellation policy; represent failure separately from pending and empty data.
  • Preserve focus when hiding interactive regions and exercise keyboard navigation in a real browser.
  • Validate and authorize every public server action; send only needed fields across server/client boundaries.
  • Measure performance changes and test user-visible behavior, not type-checking alone.

Effects Decision Tree

Effects are escape hatches; most logic should NOT use effects.

Need Solution
Derived value from props/state Calculate during render (useMemo if expensive)
Reset state on prop change key prop on component
Respond to user event Event handler
Notify parent of state change Call onChange in event handler, or fully controlled component
Chain of state updates Calculate all next state in one event handler
Sync with external system Effect with cleanup

Effect rules:

  • Never suppress the linter; fix the code instead
  • Use updater functions (setItems(prev => [...prev, item])) to remove state dependencies
  • Move objects/functions inside effects to stabilize dependencies
  • useEffectEvent for non-reactive values (e.g., theme in a connection effect)
  • Always return cleanup for subscriptions, connections, listeners
  • Data fetching cancellation (pick by situation): AbortController for fetch; ignore flag for non-cancellable promises; React Query handles both automatically

Discipline

  • Simplicity first: every change as simple as possible, impact minimal code
  • Only touch what's necessary; avoid introducing unrelated changes
  • No hacky workarounds: if a fix feels wrong, step back and implement the clean solution
  • Before adding a new abstraction, verify it appears in 3+ places

References

Verify

  • TypeScript compiles with zero errors
  • No suppressed lint rules (eslint-disable, @ts-ignore) in new code
  • useEffect dependency arrays not manually overridden
  • No forwardRef usage in React 19+ projects (use ref prop directly)

Task-specific references

Read the relevant reference before implementing or reviewing the matching behavior:

  • For component types, state ownership, async races, focus, or cached query behavior: components-and-state.md.
  • For performance, React APIs, Next.js boundaries, or caching: rendering-and-frameworks.md.
  • For Tailwind CSS: utilities, @theme tokens, CVA/tailwind-variants, dark mode, v3-to-v4 migration, or overflow and hidden pitfalls: tailwind.md.
  • For component, hook, browser, or integration test changes: test-selection.md.

Existing specialized references, when the corresponding topic applies:

Files (ai-skills)
  • references
    • components-and-state.md 9 KB
      # Components, state, and interaction
      
      ## Component TypeScript
      
      - Extend native elements with `ComponentPropsWithoutRef<'button'>`, add custom props via intersection
      - Use `React.ReactNode` for children, `React.ReactElement` for single element, render prop `(data: T) => ReactNode`
      - Discriminated unions for variant props; TypeScript narrows automatically in branches
      - Generic components: `<T>` with `keyof T` for column keys, `T extends { id: string }` for constraints
      - Event types: `React.MouseEvent<HTMLButtonElement>`, `FormEvent<HTMLFormElement>`, `ChangeEvent<HTMLInputElement>`
      - `as const` for custom hook tuple returns
      - `useRef<HTMLInputElement>(null)` for DOM (use `?.`), `useRef<number>(0)` for mutable values
      - Explicit `useState<User | null>(null)` for unions/null
      - useReducer actions as discriminated unions: `{ type: 'set'; payload: number } | { type: 'reset' }`
      - useContext null guard: throw in custom `useX()` hook if context is null
      - **A parameter type whose properties are all optional is a weak type, and a mismatched argument fails to compile rather than passing `undefined`.** TypeScript requires the argument to share at least one property with a weak type, so `(record: { newField?: boolean })` rejects a generated type that does not yet carry `newField` with `TS2559: Type 'X' has no properties in common with type 'Y'`. Intersect with the base type instead (`T & { newField?: boolean }`); the shim then deletes cleanly once the field lands upstream
      
      
      ## Concurrency & Race Classes
      
      Five race classes survive type-checking and unit tests; hunt each one during review (cleanup/cancellation mechanics: Effect rules above):
      
      | Class | Production signal | Fix |
      |-------|-------------------|-----|
      | Lifecycle cleanup gap | "state update on unmounted component" warnings, leaks under rapid navigation | Return cleanup from every effect that registers a listener/timer/observer |
      | Remount-timing mistake | Async callback mutates state/DOM after route change/unmount (`fetch().then(setData)` resolves post-navigation) | Cancel per the cancellation hierarchy |
      | Boolean-as-state for non-binary UI | Contradictory combos (`isLoading: true, error: Error`) | State constant (`'idle' \| 'loading' \| 'success' \| 'error'`) + transition function; invalid states unreachable |
      | Stale promise/timer, no cancel path | Promise chain or `setTimeout` holds `setState` after the component moved on | Bind every async op to a cancel mechanism; test the cleanup path |
      | Per-element handlers on large lists | N closures/subscriptions per row, stale-closure bugs on rapid re-renders | Delegate: one parent handler + `event.target.closest(...)` when >~50 items or frequent updates |
      | Gate keyed on a child's success-only callback | Parent's submit stays locked behind "still loading, try again in a moment" copy that never resolves; only a page reload escapes | Report failures up (`onLoadError`) as well as successes, and split the flag into loading / loaded / failed; a boolean cannot carry a terminal state. Keep the action blocked in both if proceeding on unknown data is unsafe; the fix is honest copy plus a real in-place retry, not unblocking |
      | `inert` toggled from a blur-managed flag | First `Tab` *inside* the subtree sends focus to `<body>`; the next `Tab` restarts at the top of the document and skips the (now inert) subtree entirely | React maps `onBlur` to native `focusout`, which fires on intra-subtree moves, and `focusin`/`focusout` are `DiscreteEventPriority`, so React commits `inert` synchronously *between* the two events, landing it on the already-focused incoming control. Stand down only when focus truly leaves: `if (e.currentTarget.contains(e.relatedTarget)) return;` |
      
      **Focus-ownership rules:**
      - Never toggle `inert` on a subtree that currently holds focus. The blunt version has no guard at all: a scroll-driven `inert={!isVisible}` on a sticky bar, drawer, or collapsing panel strands the user on a control that is invisible, inert, and unactivatable. Hand focus to the equivalent visible control before hiding, and pass `focus({ preventScroll: true })` when the handoff fires from a scroll handler, or `focus()` scrolls its target into view and fights the scroll the user is performing. If the handoff target carries the same focus listeners that feed the guard, `focus()` arms the flag as a side effect of doing its job and the subtree never goes inert again; make the handoff symmetric (two effects guarding opposite values of one flag) rather than adding an exception to the guard. `aria-hidden` without `inert` fixes double announcement but leaves the duplicate tab stops. Assert on what the user can *do* (does the handler fire, where does `Tab` go), not on `document.activeElement`; Chromium resolves the unfocusing steps lazily and it reads back inconsistently
      - A blur-managed "focus is inside" flag cannot be cleared by a blur that never fires. Headless popover primitives restore focus to the element that *opened* the content on close; when the popover is anchored to an input with no trigger element, that restore no-ops, the library preventDefaults the focus-scope restore, and focus lands on `document.body`. The input never receives another `blur`, so the flag sticks `true` for the component's lifetime and anything gated on it (a "re-seed local text from `props.value`" effect, for instance) is silently dead. Clear it explicitly in the select handler and on close when `document.activeElement` is not the input. The same design usually adds `onOpenAutoFocus={e => e.preventDefault()}` to avoid stealing typing focus, which leaves the content pointer-only: no trigger to Tab to and no auto-focus in. Add an explicit affordance plus `aria-haspopup`/`aria-expanded`. Browser-dependent: Chromium and Firefox blur the input on `mousedown`, Safari does not, so "works on my machine" from Safari proves nothing
      
      
      ## State Management
      
      ```
      Local UI state       → useState, useReducer
      Shared client state  → Zustand (simple) | Redux Toolkit (complex)
      Atomic/granular      → Jotai
      Server/remote data   → React Query (TanStack Query)
      URL state            → nuqs, router search params
      Form state           → React Hook Form
      ```
      
      **Key patterns:**
      - Zustand: `create<State>()(devtools(persist((set) => ({...}))))`; use slices for scale, selective subscriptions to prevent re-renders
      - React Query: query keys factory (`['users', 'detail', id] as const`), `staleTime`/`gcTime`, optimistic updates with `onMutate`/`onError` rollback
      - React Query `isError` means *a fetch failed*, not *there is no data*: a failed refetch sets `status: 'error'` while retaining the last successful payload, so the usual `isLoading ? spinner : isError ? errorPanel : content` ladder routes a working, fully cached list into the error panel. The defaults compose into it: `refetchOnMount: true` + `staleTime: 0` refetch on every mount, `retry: false` makes one blip terminal, and `gcTime: 5min` keeps the cache alive across a modal's unmount/remount. Gate the branch on data-absence: `isLoadingError` (`isError && !hasData`), or `isError && derived.length === 0` when the suite mocks the hook and leaves `isLoadingError` undefined. Audit the side effects with it: `useEffect(() => { if (isError) toast(...) }, [isError])` fires over the live list too
      - The mirror case has the same tell: under `retry: false` a first load that fails leaves `data` `undefined` forever, so a branch gated on `data !== undefined` folds *failed* into *pending* and renders "Loading…" permanently. Whether it is recoverable is decided by mount topology, not by open/closed state: a component rendered unconditionally inside a ref-driven popup is mounted for the life of the page, so `refetchOnMount` never fires again. Any remedy that adds a branch on `isError` must itself be gated on data-absence, or it re-introduces the previous bullet. Enumerate all four states before writing either gate (`isLoading` for first load with no data yet, `isFetching` for any fetch in flight including a background refetch over a warm cache, `isError` for last fetch failed with cache possibly still present, and loaded-and-genuinely-empty) and state the action in each: `!isFetching` misses the error state, `!isFetching && !isError` mishandles a background refetch of a legitimately empty result. The write path has the same shape, inverted: a fail-closed save gate keyed on `isError` blocks a valid submit whenever cached data is present
      - A mutate-scoped `onSuccess` survives an unmount that the mutation itself caused, so "the success toast is dropped on promote/archive/delete" is usually a false finding. The mutation dispatches success on the microtask after the hook-level `onSuccess` await resolves, while query-observer notifications (the ones that re-render the list and unmount the row) flush on a zero-delay timer; that is an ordering guarantee, not a race. The documented "callbacks do not fire on unmount" caveat describes a different unmount (navigation, closing a drawer). Read the scheduler and run a known-bad control (remove the observer before dispatch) before accepting the finding
      - Never duplicate server data (React Query) in a client store (Zustand)
      - Colocate state close to where it's used
      
    • e2e-testing.md 6.2 KB
      # E2E Testing with Playwright
      
      > When to read: when authoring Playwright end-to-end tests: directory layout, fixtures, page objects, network mocking, CI integration.
      
      ## Directory Structure
      
      ```
      e2e/
      ├── playwright.config.ts
      ├── fixtures/
      │   ├── auth.fixture.ts
      │   └── test-data.fixture.ts
      ├── pages/
      │   ├── base.page.ts
      │   └── <page-name>.page.ts
      ├── tests/
      │   ├── auth/
      │   │   └── login.spec.ts
      │   └── smoke/
      │       └── critical-paths.spec.ts
      └── utils/
          └── api-helpers.ts
      ```
      
      Naming: tests `<feature>.spec.ts`, page objects `<page>.page.ts`, fixtures `<concern>.fixture.ts`.
      
      ## Configuration
      
      ```typescript
      import { defineConfig, devices } from '@playwright/test';
      
      export default defineConfig({
        testDir: './e2e/tests',
        fullyParallel: true,
        forbidOnly: !!process.env.CI,
        retries: process.env.CI ? 2 : 0,
        workers: process.env.CI ? 1 : undefined,
        reporter: 'html',
        use: {
          baseURL: 'http://localhost:5173',
          trace: 'on-first-retry',
          screenshot: 'only-on-failure',
        },
        projects: [
          { name: 'setup', testDir: './e2e/fixtures', testMatch: 'auth.fixture.ts' },
          {
            name: 'chromium',
            use: { ...devices['Desktop Chrome'], storageState: 'e2e/.auth/user.json' },
            dependencies: ['setup'],
          },
        ],
        webServer: {
          command: 'npm run dev',
          url: 'http://localhost:5173',
          reuseExistingServer: !process.env.CI,
        },
      });
      ```
      
      ## Page Object Model
      
      Tests never use selectors directly; page objects encapsulate all locators and actions.
      
      ```typescript
      // e2e/pages/base.page.ts
      import { type Page, type Locator } from '@playwright/test';
      
      export abstract class BasePage {
        constructor(protected readonly page: Page) {}
        abstract goto(): Promise<void>;
        abstract readonly ready: Locator;
        async waitForLoad() { await this.ready.waitFor(); }
        get toast(): Locator { return this.page.getByRole('alert'); }
      }
      
      // e2e/pages/users.page.ts
      export class UsersPage extends BasePage {
        readonly ready: Locator;
        readonly createButton: Locator;
        readonly searchInput: Locator;
      
        constructor(page: Page) {
          super(page);
          this.ready = page.getByRole('heading', { name: /users/i });
          this.createButton = page.getByRole('button', { name: /create/i });
          this.searchInput = page.getByRole('searchbox', { name: /search/i });
        }
      
        async goto() {
          await this.page.goto('/users');
          await this.waitForLoad();
        }
      
        async searchFor(query: string) {
          const resp = this.page.waitForResponse('**/api/users?*');
          await this.searchInput.fill(query);
          await resp;
        }
      }
      ```
      
      Rules: locators as public readonly properties, actions as async methods with internal waits, no assertions in page objects, one PO per page.
      
      ## Selector Priority
      
      | Priority | Method | Use when |
      |----------|--------|----------|
      | 1 | `getByRole` | Buttons, links, headings, inputs |
      | 2 | `getByLabel` | Form inputs with labels |
      | 3 | `getByPlaceholder` | Search inputs |
      | 4 | `getByText` | Static text content |
      | 5 | `getByTestId` | No accessible selector available |
      
      Never use CSS selectors, XPath, or DOM structure selectors. When adding `data-testid`, use `<action>-<entity>-<type>` pattern: `create-user-btn`.
      
      ## Filling Inputs
      
      Prefer `locator.fill(value)` to `page.keyboard.type()`. Synthesised keystrokes drop characters intermittently under a browser-attached session (CDP against an already-running browser), and the driver reports the full string as typed while the DOM holds a short value, so the assertion that would catch it is the one nobody writes. Rich-text editors whose state lives outside the element's `value` (ProseMirror, Slate, TipTap) ignore programmatic writes and still need `type()`; there, assert `input_value()` (or the editor's own serialized content) after typing and retry on a short read.
      
      ## Wait Strategies
      
      Never use `waitForTimeout` or `setTimeout`. Do not use `waitForLoadState('networkidle')` as a readiness signal; Playwright's API docs mark it discouraged for testing and point to web assertions instead. Start a `waitForResponse` before the action that triggers the request, or a fast response is missed. Use explicit conditions:
      
      ```typescript
      await page.getByRole('heading', { name: 'Dashboard' }).waitFor();
      await page.waitForURL('/dashboard');
      const resp = page.waitForResponse(
        (r) => r.url().includes('/api/users') && r.status() === 200,
      );
      await page.getByRole('button', { name: /load/i }).click();
      await resp;
      await page.getByTestId('spinner').waitFor({ state: 'hidden' });
      ```
      
      ## Auth State Reuse
      
      Save auth state once, reuse across all tests:
      
      ```typescript
      // e2e/fixtures/auth.fixture.ts
      import { test as setup } from '@playwright/test';
      
      setup('authenticate', async ({ page }) => {
        await page.goto('/login');
        await page.getByLabel('Email').fill('testuser@example.com');
        await page.getByLabel('Password').fill('TestPassword123!');
        await page.getByRole('button', { name: /sign in/i }).click();
        await page.waitForURL('/dashboard');
        await page.context().storageState({ path: 'e2e/.auth/user.json' });
      });
      ```
      
      Tests receive auth state via `storageState` in config projects.
      
      ## Test Data & Network
      
      - Tests create own data via API helpers (faster than UI), clean up in `finally` blocks
      - Mock responses with `page.route('**/api/path', route => route.fulfill({ ... }))`
      - Simulate errors with `route.abort('failed')`
      
      ## Flaky Test Fixes
      
      | Cause | Fix |
      |-------|-----|
      | Hardcoded waits | Explicit wait conditions |
      | Shared test data | Each test creates its own |
      | Animations | `animations: 'disabled'` in config |
      | Race conditions | Wait for API responses before assertions |
      
      **Quarantine workflow**: confirm flakiness before quarantining:
      ```bash
      npx playwright test --repeat-each=10 path/to/test.spec.ts  # Confirm flakiness
      npx playwright test --retries=3 path/to/test.spec.ts       # Check if retries help
      ```
      
      Mark confirmed flaky tests with an issue reference:
      ```typescript
      test.fixme(true, 'Flaky - Issue #123');                       // Always skip
      test.skip(!!process.env.CI, 'Flaky in CI only - Issue #123'); // Skip in CI only
      ```
      
      ```bash
      npx playwright test --headed --debug  # Debug mode
      npx playwright show-trace trace.zip   # Trace viewer
      npx playwright test --ui              # Interactive UI
      ```
      
    • rendering-and-frameworks.md 6.1 KB
      # Rendering and framework patterns
      
      ## Performance
      
      **Critical: eliminate waterfalls:**
      - `Promise.all()` for independent async operations
      - Move `await` into branches where actually needed
      - Suspense boundaries to stream slow content
      
      **Critical: bundle size:**
      - Import directly from modules, avoid barrel files (`index.ts` re-exports)
      - `next/dynamic` or `React.lazy()` for heavy components
      - Defer third-party scripts (analytics, logging) until after hydration
      - Preload on hover/focus for perceived speed
      - `content-visibility: auto` + `contain-intrinsic-size` on long lists skips off-screen layout/paint
      
      **Re-render optimization:**
      - Never define a component inside another component. Each parent render creates a new function identity, and React compares element *types* to decide whether to update or replace: a new type means the whole subtree unmounts and remounts, so local state is lost, effects re-run, and DOM nodes are recreated. Symptoms are behavioral, not slow: an input loses focus on every keystroke, animations restart, scroll position resets. Hoist the component to module scope and pass what it needed via props. The React Compiler does not save this one; the type identity changes before memoization applies
      - Derive state during render, not in effects
      - Subscribe to derived booleans, not raw objects (`state.items.length > 0` not `state.items`)
      - Functional setState for stable callbacks: `setCount(c => c + 1)`
      - Lazy state init: `useState(() => expensiveComputation())`
      - `useTransition` for non-urgent updates (search filtering)
      - `useDeferredValue` for expensive derived UI
      - Don't subscribe to searchParams/state read only in callbacks; read on demand
      - Use ternary (`condition ? <A /> : <B />`), not `&&` for conditionals
      - `React.memo` only for expensive subtrees with stable props
      - Hoist static JSX outside components
      
      **React Compiler** (React 19): auto-memoizes, so write idiomatic React and remove manual `useMemo`/`useCallback`/`memo`. Enable via `reactCompiler: true` in next.config (non-framework: `babel-plugin-react-compiler`). Keep components pure.
      
      
      ## React 19
      
      - **ref as prop**: `forwardRef` deprecated. Accept `ref?: React.Ref<HTMLElement>` as regular prop
      - **useActionState**: replaces `useFormState`: `const [state, formAction, isPending] = useActionState(action, initialState)`
      - **use()**: unwrap Promise or Context during render (not in callbacks/effects). Enables conditional context reads
      - **useOptimistic**: `const [optimistic, addOptimistic] = useOptimistic(state, mergeFn)` for instant UI feedback
      - **useFormStatus**: `const { pending } = useFormStatus()` in child of `<form action={...}>`
      - **Server Components**: default in App Router. Async, access DB/secrets directly. No hooks, no event handlers
      - **Server Actions**: `'use server'` directive. Validate inputs (Zod), `revalidateTag`/`revalidatePath` after mutations. **Server Actions are public endpoints**; always verify auth/authz inside each action, not just in middleware or layout guards
      - **`<Activity mode='visible'|'hidden'>`** preserves state/DOM for toggled components (experimental)
      
      
      ## Next.js App Router
      
      **File conventions:** `page.tsx` (route UI), `layout.tsx` (shared wrapper), `template.tsx` (re-mounted on navigation, unlike layout), `loading.tsx` (Suspense), `error.tsx` (error boundary), `not-found.tsx` (404), `default.tsx` (parallel route fallback), `route.ts` (API endpoint)
      
      **Rendering modes:** Server Components (default) | Client (`'use client'`) | Static (build) | Dynamic (request) | Streaming (progressive)
      
      **Decision:** Server Component unless it needs hooks, event handlers, or browser APIs. Split: server parent + client child. Isolate interactive components as `'use client'` leaf components; keep server components static with no global state or event handlers.
      
      **Server → client boundary:** pass only the fields a client component actually uses, not whole ORM rows or fetch objects. Every prop crossing the `'use client'` boundary is serialized into the payload, so a 50-field `user` object read for one field still ships all 50.
      
      **Client-only state that drives first paint** (theme, locale, feature flag, auth hint): reading `localStorage` during render breaks SSR, and reading it in `useEffect` paints the default first, so the correct value arrives one frame later as a visible flash. Set the value on the document with a small synchronous inline script that runs before hydration, typically writing a `class` or `data-` attribute on `<html>` that CSS already keys on. The script is developer-authored and must never interpolate user, request, or database data; it is the one place `dangerouslySetInnerHTML` is warranted, and only for a literal string.
      
      **Routing patterns:**
      - Route groups `(name)`: organize without affecting URL
      - Parallel routes `@slot`: independent loading states in same layout
      - Intercepting routes `(.)`: modal overlays with full-page fallback
      
      **Caching:**
      - `fetch(url, { cache: 'force-cache' })`: static
      - `fetch(url, { next: { revalidate: 60 } })`: ISR
      - `fetch(url, { cache: 'no-store' })`: dynamic
      - Tag-based: `fetch(url, { next: { tags: ['products'] } })` then `revalidateTag('products')`
      
      **Data fetching:**
      - Fetch in Server Components where data is used
      - Use Suspense boundaries for slow queries
      - `React.cache()` for per-request dedup
      - `generateStaticParams` for static generation
      - `generateMetadata` for dynamic SEO
      - Static metadata with `title: { default: 'App', template: '%s | App' }` for cascading page titles
      - `after()` for non-blocking side effects (logging, analytics); runs after response is sent
      - Hoist static I/O (fonts, config) to module level; runs once, not per request
      - Never hold request-scoped or user data in module-level mutable state: server renders run concurrently in one process, so shared module state leaks across requests (one user's data surfacing in another's response). Hoist only immutable static I/O; keep request data local to the render tree (pass as props)
      
      
      ## Tailwind Integration
      
      For Tailwind v4 configuration, utility patterns, dark mode, and component variants, see [tailwind.md](./tailwind.md).
      
      **Class sorting in JSX**: keep Tailwind classes in canonical order (enforce via `eslint-plugin-better-tailwindcss`).
      
    • tailwind-class-composition.md 3.5 KB
      # Class generation and composition
      
      ## ESLint Integration
      
      Use `eslint-plugin-better-tailwindcss` for automated class validation:
      - `no-conflicting-classes`: catches `text-red-500 text-blue-500`
      - `no-unknown-classes`: flags typos
      - `enforce-canonical-classes`: normalizes shorthand
      - `no-duplicate-classes`: removes redundant entries
      - `no-deprecated-classes`: catches v3 classes removed in v4
      - `useSortedClasses`: enforces canonical class order; configure `attributes: ["classList"]` and `functions: ["clsx", "cva", "cn", "tv", "tw"]` to cover JSX utility functions
      
      
      ## Class Merging
      
      Use `cn()` combining `clsx` + `tailwind-merge` for conditional/dynamic classes. Use plain strings for static `className` attributes.
      
      ```typescript
      import { type ClassValue, clsx } from "clsx";
      import { twMerge } from "tailwind-merge";
      export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }
      ```
      
      ```typescript
      // Static: plain string
      <button className="rounded-lg px-4 py-2 font-medium bg-blue-600">
      
      // Conditional: use cn()
      <button className={cn("rounded-lg px-4 py-2", isActive ? "bg-blue-600" : "bg-gray-700")} />
      ```
      
      **Keep class names whole in the source.** The example above works because both branches are complete literals. Tailwind's scanner does literal string matching over source text and never evaluates JavaScript, so a class assembled by interpolation is invisible to it and the utility is simply never generated. The failure is silent: no error, no warning, just missing styles.
      
      ```typescript
      // Broken: `bg-red-500` never appears in the source, so it is never generated
      <div className={`bg-${color}-500`} />
      
      // Works: every candidate class is a complete literal the scanner can see
      const BG = { red: "bg-red-500", blue: "bg-blue-500" } as const;
      
      function Swatch({ color }: { color: keyof typeof BG }) {
        return <div className={BG[color]} />;
      }
      ```
      
      The same applies to classes built in a non-scanned location (a string in a database, a CMS field, or a file outside the configured `@source` paths). Confirm the source actually gets scanned before assuming a literal is enough.
      
      `@source` directives resolve relative to the file they appear in, so a shared token package pulling in a sibling (`@source '../../ui/src/**/*.{ts,tsx}'`) is what makes a `libs/ui`-only utility generate in every consuming app. The real generation risk is a utility with **no** prior usage anywhere, and it fails invisibly rather than loudly: an SVG whose root carries `fill="none"` and whose paths swap `fill="#355BF5"` for `className="fill-primary-500"` renders *invisible*, not mis-colored. Grep the compiled CSS of every consuming app, not one.
      
      Verify by building, not by reading: when class names or scanned sources changed, run the real Tailwind build and grep the output CSS for the expected utilities. Reviewing the `className` attribute proves the string is right, not that the rule exists.
      
      
      ## Component Variants
      
      Use `tailwind-variants` (`tv()`) for type-safe variant components. Alternative: `class-variance-authority` (`cva()`).
      
      ```typescript
      import { tv } from "tailwind-variants";
      const button = tv({
        base: "rounded-lg px-4 py-2 font-medium transition-colors",
        variants: {
          color: { primary: "bg-blue-600 text-white", secondary: "bg-gray-200 text-gray-800" },
          size: { sm: "text-sm px-3 py-1", md: "text-base", lg: "text-lg px-6 py-3" },
        },
        defaultVariants: { color: "primary", size: "md" },
      });
      ```
      
      See [tailwind-variants patterns](./tailwind-component-patterns.md) for slots, composition, and responsive variants.
      
    • tailwind-component-patterns.md 3.3 KB
      # Component Patterns
      
      ## tailwind-variants (tv)
      
      Type-safe component variants with slots, composition, and responsive support.
      
      ### Slots API
      
      ```typescript
      import { tv } from "tailwind-variants";
      
      const card = tv({
        slots: {
          base: "rounded-lg border shadow-sm",
          header: "flex flex-col space-y-1.5 p-6",
          title: "text-2xl font-semibold leading-none tracking-tight",
          content: "p-6 pt-0",
          footer: "flex items-center p-6 pt-0",
        },
        variants: {
          elevated: { true: { base: "shadow-lg border-0" } },
        },
      });
      
      const { base, header, title, content, footer } = card({ elevated: true });
      ```
      
      ### Composition
      
      ```typescript
      const baseButton = tv({ base: "rounded-lg font-medium transition-colors" });
      
      const iconButton = tv({
        extend: baseButton,
        base: "inline-flex items-center justify-center",
        variants: {
          size: { sm: "size-8", md: "size-10", lg: "size-12" },
        },
      });
      ```
      
      ### Responsive Variants
      
      ```typescript
      const grid = tv({
        base: "grid gap-4",
        variants: {
          cols: { 1: "grid-cols-1", 2: "grid-cols-2", 3: "grid-cols-3", 4: "grid-cols-4" },
        },
        responsiveVariants: ["sm", "md", "lg"],
      });
      
      // Usage: <div className={grid({ cols: { initial: 1, sm: 2, lg: 4 } })} />
      ```
      
      ## CVA (class-variance-authority)
      
      Alternative to tailwind-variants: simpler API, no slots.
      
      ```typescript
      import { cva, type VariantProps } from "class-variance-authority";
      
      const buttonVariants = cva(
        "inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50",
        {
          variants: {
            variant: {
              default: "bg-primary text-primary-foreground hover:bg-primary/90",
              outline: "border border-border bg-background hover:bg-accent",
              ghost: "hover:bg-accent hover:text-accent-foreground",
            },
            size: {
              sm: "h-9 rounded-md px-3",
              default: "h-10 px-4 py-2",
              lg: "h-11 rounded-md px-8",
              icon: "size-10",
            },
          },
          defaultVariants: { variant: "default", size: "default" },
        }
      );
      
      export interface ButtonProps
        extends React.ButtonHTMLAttributes<HTMLButtonElement>,
          VariantProps<typeof buttonVariants> {}
      
      export function Button({ className, variant, size, ...props }: ButtonProps) {
        return <button className={cn(buttonVariants({ variant, size, className }))} {...props} />;
      }
      ```
      
      ## Compound Components (React 19)
      
      React 19 passes ref as a regular prop; no `forwardRef` needed.
      
      ```typescript
      export function Card({ className, ref, ...props }: React.HTMLAttributes<HTMLDivElement> & { ref?: React.Ref<HTMLDivElement> }) {
        return <div ref={ref} className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)} {...props} />;
      }
      
      export function CardHeader({ className, ref, ...props }: React.HTMLAttributes<HTMLDivElement> & { ref?: React.Ref<HTMLDivElement> }) {
        return <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />;
      }
      ```
      
      ## ESLint Integration
      
      Use `eslint-plugin-better-tailwindcss` for v4 class validation:
      
      | Rule | Purpose |
      |------|---------|
      | `no-conflicting-classes` | Detect classes that override each other |
      | `no-unknown-classes` | Flag classes not registered with Tailwind |
      | `enforce-shorthand-classes` | `size-6` not `w-6 h-6`; `p-6` not `px-6 py-6` |
      | `no-deprecated-classes` | Catch v3 class names used in v4 projects |
      
    • tailwind-configuration.md 4.9 KB
      # Configuration and migration
      
      ## CSS-First Configuration
      
      v4 eliminates `tailwind.config.ts`. All configuration lives in CSS.
      
      | Directive | Purpose |
      |-----------|---------|
      | `@import "tailwindcss"` | Entry point (replaces `@tailwind base/components/utilities`) |
      | `@theme { }` | Define/extend design tokens; auto-generates utility classes |
      | `@theme inline { }` | Map CSS variables to Tailwind utilities without generating new vars |
      | `@theme static { }` | Emit all theme variables, including unused ones; utility generation still applies |
      | `@utility name { }` | Create custom utilities (replaces `@layer components` + `@apply`) |
      | `@custom-variant name (selector)` | Define custom variants |
      
      ```css
      @import "tailwindcss";
      
      @theme {
        --color-brand: oklch(0.72 0.11 178);
        --font-display: "Inter", sans-serif;
        --animate-fade-in: fade-in 0.2s ease-out;
        @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
      }
      
      @custom-variant dark (&:where(.dark, .dark *));
      ```
      
      Tokens defined with `@theme` become utilities automatically: `--color-brand` produces `bg-brand`, `text-brand`, `border-brand`. Define z-index as tokens (`--z-modal: 50`) and reference via `z-(--z-modal)` instead of arbitrary `z-50`. The `oklch()` form above matches how v4 defines its own default palette; lightness is perceptually uniform there, so a scale stepped by L reads evenly, and the `/N` opacity modifier mixes in the same space (`bg-brand/50` compiles to `color-mix(in oklab, var(--color-brand) 50%, transparent)`).
      
      - **Derive alpha variants from one token instead of hand-picking shades**: `--color-brand-soft: color-mix(in oklab, var(--color-brand) 10%, transparent);` inside `@theme` yields a named `bg-brand-soft` that tracks the base token; use it only when a named token must exist (design-system contract, shared across apps), since the `/N` modifier already covers one-off use.
      - **Clear a namespace for a strict design system**: `--color-*: initial;` as the first line of `@theme` removes the entire default palette (no `bg-red-500`, no emitted `--color-red-*` variables), so only the tokens declared after it exist; `--color-lime-*: initial;` drops a single default color, and `--*: initial;` resets every namespace (spacing, fonts, breakpoints) for a fully custom theme.
      
      For custom properties that should not define Tailwind utilities, declare them in ordinary CSS such as `:root`, outside `@theme`.
      
      **`@theme` tokens are tree-shaken.** v4 emits only the variables it can see used, so a token existing in a shared file says nothing about whether it reaches a given app's bundle. Measured on one shared token file feeding two apps: 20 of 59 `--color-*` emitted into one, 19 of 59 into the other. `@theme static` is the opt-out. A `var(--color-x)` reference inside your own hand-written CSS **counts as a use**, so pointing a custom property at a token (`--app-checkbox-border: var(--color-border-400)`) is self-sustaining, not fragile: Tailwind sees your CSS, not just your class names. Never rate a "this indirection depends on some unrelated utility still existing" concern on tree-shaking alone: delete the last utility usage in that app's scan set, rebuild, and read the compiled CSS. Assert the utility actually vanished as the applied control, or a build that silently no-opped (wrong package filter, stale `dist`) reads identically, producing the same false conclusion from nothing.
      
      **CSS Modules**: when using `.module.css` with Tailwind v4, add `@reference "#tailwind";` at the top of the module file to enable theme token access inside the module.
      
      **Animations (tw-animate-css)**: use `animate-in`/`animate-out` base classes combined with effect classes (`fade-in`, `slide-in-from-top`). Decimal spacing gotcha: use bracket notation `[0.625rem]` instead of fractional values like `2.5`.
      
      
      ## v3 to v4 Migration
      
      For projects upgrading from v3 to v4, see [tailwind-v3-to-v4.md](./tailwind-v3-to-v4.md) for the full breaking-change table and codemod guidance. For greenfield v4 work, current patterns are above.
      
      
      ## Common Errors
      
      | Symptom | Fix |
      |---------|-----|
      | `bg-primary` doesn't work | Add `@theme inline { --color-primary: var(--primary); }` |
      | Colors all black/white | Double `hsl()` wrapping; use `var(--color)` not `hsl(var(--color))` |
      | `@apply` fails on custom class | Use `@utility` instead of `@layer components` |
      | Build fails after migration | Delete `tailwind.config.ts` |
      | Animations broken | Replace `tailwindcss-animate` with `tw-animate-css` |
      | `.dark { @theme { } }` fails | v4 does not support nested `@theme`; use `:root`/`.dark` CSS vars mapped via `@theme inline` |
      
      
      ## Dark Mode (v4 Pattern)
      
      ```css
      :root { --background: hsl(0 0% 100%); --foreground: hsl(222 84% 4.9%); }
      .dark { --background: hsl(222 84% 4.9%); --foreground: hsl(210 40% 98%); }
      @theme inline { --color-background: var(--background); --color-foreground: var(--foreground); }
      ```
      
      Semantic classes (`bg-background`, `text-foreground`) auto-switch; no `dark:` variants needed for themed colors.
      
    • tailwind-layout-patterns.md 3.6 KB
      # Layout Patterns
      
      ## Grid Template Areas
      
      Define reusable grid areas with `@utility`:
      
      ```css
      @utility grid-areas-dashboard {
        grid-template-areas: "header header header" "nav main aside" "nav footer footer";
      }
      @utility area-header { grid-area: header; }
      @utility area-nav { grid-area: nav; }
      @utility area-main { grid-area: main; }
      ```
      
      ```html
      <div class="grid grid-areas-dashboard grid-cols-[200px_1fr_250px] grid-rows-[60px_1fr_40px]">
        <header class="area-header">Header</header>
        <nav class="area-nav">Nav</nav>
        <main class="area-main">Content</main>
      </div>
      ```
      
      ## Auto-Responsive Grids
      
      ```html
      <!-- Auto-fit: cards stretch to fill -->
      <div class="grid grid-cols-[repeat(auto-fit,minmax(280px,1fr))] gap-6">
      
      <!-- Auto-fill: maintains track size, leaves empty space -->
      <div class="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-4">
      
      <!-- Safe minimum (handles container < minmax min) -->
      <div class="grid grid-cols-[repeat(auto-fill,minmax(min(100%,300px),1fr))] gap-4">
      ```
      
      ## Z-Index Management
      
      Define a z-index scale in `@theme` tokens instead of arbitrary numbers:
      
      ```css
      @theme {
        --z-dropdown: 100;
        --z-sticky: 200;
        --z-fixed: 300;
        --z-modal-backdrop: 400;
        --z-modal: 500;
        --z-popover: 600;
        --z-tooltip: 700;
        --z-toast: 800;
      }
      ```
      
      Reference with `z-(--z-modal)` syntax; never use `z-[9999]`.
      
      ## Container Queries
      
      Component-level responsiveness independent of viewport.
      
      ```css
      @plugin "@tailwindcss/container-queries";
      ```
      
      ```html
      <article class="@container">
        <div class="flex flex-col @sm:flex-row gap-4">
          <img class="w-full @sm:w-32 @lg:w-48 aspect-video @sm:aspect-square object-cover" />
          <div class="flex-1 min-w-0">
            <h3 class="text-base @md:text-lg @lg:text-xl font-semibold truncate">Title</h3>
            <p class="text-sm @md:text-base line-clamp-2 @lg:line-clamp-3">Description</p>
          </div>
        </div>
      </article>
      ```
      
      | Use Container Queries | Use Viewport Queries |
      |----------------------|---------------------|
      | Reusable components | Page-level layouts |
      | Sidebar widgets | Navigation bars |
      | Card grids | Hero sections |
      | Embedded/CMS content | Full-width sections |
      
      Named containers scope queries: `@container/sidebar` with `@lg/sidebar:flex-row`.
      
      ## Fluid Typography
      
      Eliminate breakpoint jumps with `clamp()`:
      
      ```css
      @theme {
        --text-fluid-base: clamp(1rem, 0.9rem + 0.5vw, 1.125rem);
        --text-fluid-xl: clamp(1.25rem, 1rem + 1.25vw, 1.5rem);
        --text-fluid-3xl: clamp(1.875rem, 1.2rem + 3.375vw, 2.5rem);
      }
      ```
      
      Always combine `vw` with `rem`; pure `vw` breaks when users zoom (WCAG violation).
      
      ## Custom Utilities
      
      ```css
      @utility scrollbar-none {
        scrollbar-width: none;
        -ms-overflow-style: none;
      }
      
      @utility text-gradient {
        @apply bg-linear-to-r from-primary to-accent bg-clip-text text-transparent;
      }
      ```
      
      ## Native CSS Animations (v4)
      
      Define keyframes inside `@theme` and reference with `--animate-*` tokens:
      
      ```css
      @theme {
        --animate-slide-up: slide-up 0.3s ease-out;
        @keyframes slide-up {
          from { opacity: 0; transform: translateY(20px); }
          to { opacity: 1; transform: translateY(0); }
        }
      }
      ```
      
      Use `@starting-style` for entry animations on native popovers/dialogs:
      
      ```css
      [popover]:popover-open { opacity: 1; transform: scale(1); }
      @starting-style { [popover]:popover-open { opacity: 0; transform: scale(0.95); } }
      ```
      
      Respect motion preferences: `motion-safe:animate-bounce motion-reduce:animate-none`.
      
      ## Safe Area Handling (Notched Devices)
      
      ```css
      @utility safe-area-pt { padding-top: env(safe-area-inset-top); }
      @utility safe-area-pb { padding-bottom: env(safe-area-inset-bottom); }
      ```
      
      Apply to fixed headers/footers on mobile.
      
    • tailwind-v3-to-v4.md 1.5 KB
      # v3 to v4 Breaking Changes
      
      Reference for migrating an existing Tailwind v3 project to v4. For greenfield v4 work, [tailwind.md](./tailwind.md) covers current patterns directly.
      
      | v3 | v4 | Notes |
      |----|-----|-------|
      | `tailwind.config.ts` | `@theme` in CSS | Delete config file |
      | `@tailwind base/components/utilities` | `@import "tailwindcss"` | Single import |
      | `darkMode: "class"` | `@custom-variant dark (...)` | CSS-only |
      | `bg-gradient-to-r` | `bg-linear-to-r` | Also: `bg-radial`, `bg-conic` |
      | `bg-opacity-60` | `bg-red-500/60` | All `*-opacity-*` removed |
      | `rounded-sm` | `rounded-xs` | Radius scale shifted down one step |
      | `rounded` | `rounded-sm` | (run `@tailwindcss/upgrade` codemod) |
      | `rounded-md`, `rounded-lg`, `rounded-xl` | Unchanged | Default radii remain 6px, 8px, and 12px |
      | `min-h-screen` | `min-h-dvh` | `dvh` handles mobile browser chrome |
      | `w-6 h-6` | `size-6` | Size shorthand for equal w/h |
      | `space-x-4` | `gap-4` | Gap handles flex/grid wrapping correctly |
      | `text-base leading-7` | `text-base/7` | Inline line-height modifier |
      | `require("tailwindcss-animate")` | `tw-animate-css` | CSS-only animations |
      | display utility beats `[hidden]` | `[hidden]` beats display utilities | Preflight adds `[hidden]:where(:not([hidden="until-found"])) { display: none !important }`; remove the attribute instead of overriding it |
      
      Run `@tailwindcss/upgrade` codemod before hand-editing; it handles the mechanical class renames. Hand-fix `@theme` migration, custom variants, and any project-specific config patterns the codemod cannot infer.
      
    • tailwind.md 3.7 KB
      # Tailwind CSS v4
      
      **Verify before implementing**: For v4-specific syntax (`@theme`, `@variant`, CSS-first config), look up current docs via Context7 (`query-docs`) before writing code. Tailwind v4 changed significantly from v3 and training data may be stale.
      
      ## Working rules
      
      - Keep utility names as complete source literals and confirm their files are scanned.
      - Use shared design tokens and one consistent visibility mechanism.
      - Inspect generated CSS after source/configuration changes; JSX strings alone do not prove utilities exist.
      - Test scrolling, overlays, and focus behavior in a browser when layout containment changes.
      
      ## Coding Rules
      
      - **`gap` over `space-x`/`space-y`**: gap handles wrapping; space-* breaks on wrap
      - **`size-*` over `w-* h-*`** for equal dimensions
      - **`min-h-dvh` over `min-h-screen`**: dvh accounts for mobile browser chrome
      - **Opacity modifier** (`bg-black/50`): `*-opacity-*` utilities are removed in v4
      - **Design tokens over arbitrary values**: check `@theme` before using `[#hex]`
      - **Never construct classes dynamically**: `text-${color}-500` won't be detected; use complete class names
      - **`@utility` over `@apply` with `@layer`**: `@apply` on `@layer` classes fails in v4
      - **Parent padding over last-child margin**: use padding on containers instead of bottom margins on the last child
      - **`overflow-x-auto` makes a scroll container on BOTH axes**: the utility emits only `overflow-x: auto`, but CSS Overflow 3 computes a `visible` value on the other axis to `auto` once either axis is scrollable, so a wrapper added purely to allow horizontal panning silently clips or scrolls whatever overflows it vertically: a non-portalled dropdown, popover, tooltip, custom select, or focus ring. jsdom does no layout, so no unit test catches it; enumerate every component rendered inside the new wrapper and confirm each overlay-ish one escapes it. Portaling is opt-in, not automatic: Radix exposes it as a separate `*.Portal` part wrapping `*.Content`, so read the component rather than assuming a library handles it. Same computed-value rule read backwards: before blaming a page-level scrollbar, walk every ancestor's `overflow` and name the element that actually scrolls
      - **Never express visibility as the native `hidden` attribute plus a display utility**: the two resolve in opposite directions across versions. v4's Preflight ships `[hidden]:where(:not([hidden="until-found"])) { display: none !important }`, so the attribute wins and an element expected to be visible stays hidden; on v3, or wherever Preflight is disabled or not loaded, the author-origin utility (`block`, `flex`, `grid`) beats the UA-origin `[hidden]` rule regardless of specificity and the element stays on screen with `hidden` set. Toggle one mechanism: `clsx(base, open ? 'block' : 'hidden')`. Neither direction is visible to jsdom's `toBeInTheDocument`; only `toBeVisible` or a real browser engine catches it
      
      ## Verify
      
      - Build passes with zero errors (`npm run build` or equivalent)
      - No v3 class names remain in changed files (check with `@tailwindcss/upgrade --dry-run` if available)
      - No conflicting classes on the same element
      
      ## Task-specific references
      
      - For theme tokens, build configuration, dark mode, or missing styles: [tailwind-configuration.md](./tailwind-configuration.md).
      - For migrating an existing v3 project: [tailwind-v3-to-v4.md](./tailwind-v3-to-v4.md).
      - For class merging, scanning paths, variants, or lint integration: [tailwind-class-composition.md](./tailwind-class-composition.md).
      - For tailwind-variants slots, CVA, or compound components: [tailwind-component-patterns.md](./tailwind-component-patterns.md).
      - For grid areas, container queries, z-index management, or fluid typography: [tailwind-layout-patterns.md](./tailwind-layout-patterns.md).
      
    • test-selection.md 1.5 KB
      # Test selection
      
      ## Testing (Vitest + React Testing Library)
      
      - **Component tests**: Vitest + RTL, co-located `*.test.tsx`. Default for React components.
      - **Hook tests**: `renderHook` + `act`, co-located `*.test.ts`
      - **Unit tests**: Vitest for pure functions, utilities, services
      - **E2E**: Playwright for user flows and critical paths
      - **Query priority**: `getByRole` > `getByLabelText` > `getByPlaceholderText` > `getByText` > `getByTestId`
      - Mock API services and external providers; render child components real for integration confidence
      - One behavior per test with AAA structure. Name: `should <behavior> when <condition>`
      - Use `userEvent` over `fireEvent` for realistic interactions
      - `findBy*` for async elements, `waitFor` after state-triggering actions
      - `vi.clearAllMocks()` in `beforeEach` on Vitest 4 or with `clearMocks: false` (Vitest 5 clears by default). Recreate state per test.
      - Timing (`useLayoutEffect` vs `useEffect` report races), engine fidelity (jsdom/happy-dom vs a real browser engine for parser/layout-dependent behavior), interaction-mode pitfalls (`userEvent` delay, fake-timer incompatibility, `fireEvent` vs `userEvent` tradeoffs), and runner/environment failures (`vmThreads` OOM, happy-dom swallowing `console.*`): see [testing.md](./testing.md)
      General testing discipline (anti-patterns, rationalization resistance): see the `ia-writing-tests` skill.
      See [testing patterns and examples](./testing.md) for component, hook, and mocking examples.
      See [e2e testing](./e2e-testing.md) for Playwright patterns.
      
    • testing.md 7.8 KB
      # Testing React (Vitest + RTL)
      
      > When to read: when adding or fixing component tests with Vitest + React Testing Library: setup, queries, user-event, async assertions, mocking.
      
      ## Setup
      
      Vitest config: `environment: 'jsdom'`, `globals: true`, `setupFiles` pointing to a file that imports `@testing-library/jest-dom/vitest`. Use `@vitejs/plugin-react` and mirror path aliases from `tsconfig.json`.
      
      ## Component Test
      
      ```tsx
      import { render, screen, waitFor } from '@testing-library/react';
      import userEvent from '@testing-library/user-event';
      
      vi.mock('@/api/client');
      
      describe('UserForm', () => {
        beforeEach(() => { vi.clearAllMocks(); }); // redundant on Vitest 5 unless clearMocks: false
      
        it('should submit valid form data', async () => {
          const onSubmit = vi.fn();
          render(<UserForm onSubmit={onSubmit} />);
      
          await userEvent.type(screen.getByLabelText(/email/i), 'test@example.com');
          await userEvent.click(screen.getByRole('button', { name: /submit/i }));
      
          await waitFor(() => {
            expect(onSubmit).toHaveBeenCalledWith(
              expect.objectContaining({ email: 'test@example.com' }),
            );
          });
        });
      });
      ```
      
      ## Hook Test
      
      ```typescript
      import { renderHook, act } from '@testing-library/react';
      
      it('should debounce value updates', () => {
        vi.useFakeTimers();
        const { result, rerender } = renderHook(
          ({ value }) => useDebounce(value, 300),
          { initialProps: { value: 'initial' } },
        );
        rerender({ value: 'updated' });
        expect(result.current).toBe('initial');
        act(() => { vi.advanceTimersByTime(300); });
        expect(result.current).toBe('updated');
        vi.useRealTimers();
      });
      ```
      
      ## Mocking Patterns
      
      ```typescript
      // Service mock -- mock the module, not the transport layer
      vi.mock('@/server-api/me/me.service', () => ({
        MeService: { retrieveMe: vi.fn() },
      }));
      
      // QueryClient wrapper for components using TanStack Query
      const createWrapper = () => {
        const queryClient = new QueryClient({
          defaultOptions: { queries: { retry: false } },
        });
        return ({ children }: { children: React.ReactNode }) => (
          <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
        );
      };
      render(<Component />, { wrapper: createWrapper() });
      ```
      
      ## Test Classification
      
      | Type | Tool | Target | File pattern |
      |------|------|--------|-------------|
      | Unit | Vitest | Pure functions, utilities, services | Co-located `*.test.ts` |
      | Component | Vitest + RTL | React components | Co-located `*.test.tsx` |
      | Hook | Vitest + RTL | Custom hooks | Co-located `*.test.ts` |
      | E2E | Playwright | User flows, critical paths | Separate `e2e/` directory |
      
      ## Running Tests
      
      ```bash
      npx vitest                         # Watch mode
      npx vitest run                     # Single run (CI)
      npx vitest run src/features/       # Test specific directory
      npx vitest --coverage              # Coverage report
      ```
      
      ## Timing, Fidelity, and Interaction-Mode Pitfalls
      
      Report from `useLayoutEffect`, not `useEffect`, in a child stub whose report feeds a gate under test. A `useEffect` report lands a tick late: `render()` returns, the test queries and clicks before the report's `setState` has committed, and the click reads the pre-report state. RTL flushes layout effects *and their state updates* synchronously inside `render()`'s `act`. Awaiting a settled-state text papers over it only where there is a positive DOM signal; a gate-*unsatisfiable* case has none, so it flakes or silently asserts the wrong branch.
      
      jsdom and happy-dom are not evidence about a browser-rendered artifact. Where the behavior is decided by a parser, layout, or print engine (a serialized DOM re-parsed by Chromium, `inert`, `postMessage` across an opaque origin), execute it in the *sink's* engine (Playwright/Chromium against the repo's own dependency) and carry a known-bad control in the same batch. jsdom does not enforce the radio-group invariant on parse and does not enforce the opaque-origin `targetOrigin` check, so the natural regression test passes while the bug ships. Engine fidelity and path fidelity are separate requirements: load the committed artifact verbatim and drive it through its real entry point, because a hand-rebuilt reconstruction can invert the result while looking like executed evidence.
      
      Use `userEvent.setup({ delay: null })` in component tests. A bare `setup()` inserts a `setTimeout(0)` macrotask between every simulated keystroke and pointer event: pure idle time in a test DOM, and the single largest source of a slow suite's tail.
      
      `vi.useFakeTimers()` freezes `findBy`/`waitFor` polling **and** `userEvent` (v14 awaits real timers internally), so the two do not compose. Under fake timers drive with `fireEvent` plus an explicit settle (`await act(async () => { await vi.runOnlyPendingTimersAsync(); })`, or `advanceTimersByTimeAsync(N)` for a debounce window) and assert both sides of the boundary: not-called at N-1ms, called once at Nms. A one-sided assertion passes against an eager implementation.
      
      Fill forms with one `fireEvent.change` per field when typing is not the behavior under test. `user.type` into a `mode: 'onChange'` react-hook-form field pays a full-schema re-validation per keystroke, and it focuses the input, which mounts whatever popover is attached (a date field re-renders a 42-day calendar grid on every keystroke). Keep one keystroke-level test per form for validation coverage and convert the rest. `fireEvent` cannot drive components that need a real pointer sequence (a combobox opening on input click, a menu opening on `pointerdown`); those keep `userEvent`.
      
      ## Runner and Environment Failures
      
      Under `pool: 'vmThreads'` a worker's RSS grows monotonically across files, and the recycler's default threshold is a share of `os.totalmem()` (the *host's* RAM, not the container's cgroup limit), so in CI the kernel OOM-kills the worker before Vitest decides to recycle it. Fingerprint: `Worker exited unexpectedly` late in the run, every test that ran reporting green, and **no `Test Files ... | Tests ...` summary line at all**. Set `test.vmMemoryLimit` in the Vitest config (512MB is a sane starting point) on every app using a VM pool; it is a recycle threshold rather than a hard cap, and it is inert on non-VM pools, so it is safe to set repo-wide.
      
      happy-dom installs a virtual console that swallows `console.*`, so debug output written from a test never reaches the runner and a diagnostic that prints nothing looks like a code path that never ran. Write diagnostics through `process.stdout.write`. Any console-reporting safety net (a setup file that fails the suite on an unexpected `console.error`, for instance) must write to stdout the same way, and must throw when the environment hook it depends on is missing rather than silently reporting nothing.
      
      ## Vitest 5 Upgrade: Changes That Stay Green
      
      These 5.0 changes alter what a suite checks or emits without a loud failure. Audit them on upgrade (source: the official Vitest migration guide):
      
      - `clearMocks` defaults to `true`: mock call history is cleared before every test, so calls recorded in `beforeAll` or at module scope are gone when the test body runs. A `not.toHaveBeenCalled()` over them passes vacuously, and a `vi.clearAllMocks()` in `beforeEach` becomes redundant. Set `clearMocks: false` to keep the v4 behavior.
      - `-t` / `testNamePattern` matches the full name, with suite and test titles joined by `' > '`, so an existing filter can select a different set of tests.
      - Config files are no longer found in parent directories; running `vitest` from a subdirectory needs `--config <path>` or it runs without the parent config.
      - The `json` and `junit` reporters write to `.vitest/json/output.json` and `.vitest/junit/output.xml` by default instead of stdout, so a CI step parsing stdout reads nothing.
      - Coverage `include`/`exclude` patterns match paths relative to the project root, and a pattern with no wildcard matches a whole directory, so coverage totals can shift.
      - `toThrow('')` matches any error message; assert an empty message with `/^$/`.
      
  • SKILL.md 4.2 KB
    ---
    name: react-frontend
    class: language
    description: >-
      React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when
      working with React component structure, state management, Next.js routing,
      Vitest, React Testing Library, or reviewing React code. For visual design and
      aesthetic direction, use frontend-design instead.
    paths: "**/*.tsx,**/*.jsx,**/*.ts,**/*.css,**/tailwind.config.*,**/*.html,**/*.vue,**/*.blade.php"
    ---
    
    # React Frontend
    
    **Verify before implementing**: For App Router patterns, React 19 APIs, or version-specific behavior, look up current docs (Context7 `query-docs` if available, else the framework's official docs via web search) before writing code. Training data may lag current releases.
    
    ## Working rules
    
    - Keep derived state in render and user actions in event handlers; use effects for external synchronization.
    - Give async work a lifecycle and cancellation policy; represent failure separately from pending and empty data.
    - Preserve focus when hiding interactive regions and exercise keyboard navigation in a real browser.
    - Validate and authorize every public server action; send only needed fields across server/client boundaries.
    - Measure performance changes and test user-visible behavior, not type-checking alone.
    
    ## Effects Decision Tree
    
    Effects are escape hatches; most logic should NOT use effects.
    
    | Need | Solution |
    |------|----------|
    | Derived value from props/state | Calculate during render (useMemo if expensive) |
    | Reset state on prop change | `key` prop on component |
    | Respond to user event | Event handler |
    | Notify parent of state change | Call onChange in event handler, or fully controlled component |
    | Chain of state updates | Calculate all next state in one event handler |
    | Sync with external system | Effect with cleanup |
    
    **Effect rules:**
    - Never suppress the linter; fix the code instead
    - Use updater functions (`setItems(prev => [...prev, item])`) to remove state dependencies
    - Move objects/functions inside effects to stabilize dependencies
    - `useEffectEvent` for non-reactive values (e.g., theme in a connection effect)
    - Always return cleanup for subscriptions, connections, listeners
    - Data fetching cancellation (pick by situation): `AbortController` for fetch; `ignore` flag for non-cancellable promises; React Query handles both automatically
    
    
    ## Discipline
    
    - Simplicity first: every change as simple as possible, impact minimal code
    - Only touch what's necessary; avoid introducing unrelated changes
    - No hacky workarounds: if a fix feels wrong, step back and implement the clean solution
    - Before adding a new abstraction, verify it appears in 3+ places
    
    
    ## References
    
    - [testing.md](./references/testing.md): Component, hook, and mocking test examples
    - [e2e-testing.md](./references/e2e-testing.md): Playwright E2E patterns
    
    
    ## Verify
    
    - TypeScript compiles with zero errors
    - No suppressed lint rules (`eslint-disable`, `@ts-ignore`) in new code
    - `useEffect` dependency arrays not manually overridden
    - No `forwardRef` usage in React 19+ projects (use `ref` prop directly)
    
    ## Task-specific references
    
    Read the relevant reference before implementing or reviewing the matching behavior:
    
    - For component types, state ownership, async races, focus, or cached query behavior: [components-and-state.md](./references/components-and-state.md).
    - For performance, React APIs, Next.js boundaries, or caching: [rendering-and-frameworks.md](./references/rendering-and-frameworks.md).
    - For Tailwind CSS: utilities, `@theme` tokens, CVA/tailwind-variants, dark mode, v3-to-v4 migration, or overflow and `hidden` pitfalls: [tailwind.md](./references/tailwind.md).
    - For component, hook, browser, or integration test changes: [test-selection.md](./references/test-selection.md).
    
    Existing specialized references, when the corresponding topic applies:
    
    - Tailwind details behind [tailwind.md](./references/tailwind.md): [tailwind-configuration.md](./references/tailwind-configuration.md), [tailwind-v3-to-v4.md](./references/tailwind-v3-to-v4.md), [tailwind-class-composition.md](./references/tailwind-class-composition.md), [tailwind-component-patterns.md](./references/tailwind-component-patterns.md), [tailwind-layout-patterns.md](./references/tailwind-layout-patterns.md).
    
  • SPEC.md 4.4 KB
    # ia-react-frontend Specification
    
    ## Intent
    
    `ia-react-frontend` is a `language`-class skill (stack-specific patterns and idioms). React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, or reviewing React code. For visual design and aesthetic direction, use frontend-design instead.
    
    ## Scope
    
    In scope:
    - Behaviors described in `SKILL.md` and routed via the should_trigger phrasings in `distillery/tests/fixtures/triggers/ia-react-frontend.jsonl`.
    - Updates to runtime behavior, structure, trigger precision, references, and validation.
    
    Out of scope:
    - Acting as the runtime instructions themselves (those live in `SKILL.md`).
    - Trigger phrasings already covered by adjacent `ia-*` skills (`validate-plugin` flags >70% description overlap as DUPLICATE_TRIGGER).
    - <!-- to fill in: domain-specific exclusions when the skill drifts -->
    
    ## Trigger Context
    
    - Class: `language`
    - Hook regex: `plugins/whetstone/hooks/skill-patterns.sh` -> `SKILL_PATTERNS[ia-react-frontend]`
    - Common requests (from fixture should_trigger):
      - "create a React component with state management"
      - "create a React hook for form validation"
      - "fix the Next.js routing issue"
    - Should not trigger for (from fixture should_not_trigger):
      - "write a Laravel migration for the orders table"
      - "optimize the database indexes"
      - "write a bash script for deployment"
    
    ## Source And Evidence Model
    
    Authoritative sources:
    
    - `SKILL.md`: runtime instructions and reference routing.
    - `references/*.md`: bundled supplementary content (5 file(s)).
    - `distillery/tests/fixtures/triggers/ia-react-frontend.jsonl`: positive and negative trigger phrasings under regression test.
    - `plugins/whetstone/hooks/skill-patterns.sh`: regex pattern that fires this skill.
    - `distillery/.eval-data/ia-react-frontend/`: harvested session examples (when present).
    
    Data that must not be stored in this skill or its references:
    
    - Secrets, credentials, tokens.
    - Machine-specific filesystem paths (`/home/...`, `/Users/...`, `~/ai/...`). The validator (`MACHINE_PATH_LEAK`) flags these as HIGH.
    - Private URLs, customer data, or unredacted personal information.
    
    ### Coverage matrix
    
    | Dimension | Status | Evidence |
    |---|---|---|
    | Trigger fixtures | complete | distillery/tests/fixtures/triggers/ia-react-frontend.jsonl (>=5 should_trigger, >=5 should_not_trigger) |
    | Hook regex pattern | complete | plugins/whetstone/hooks/skill-patterns.sh (`SKILL_PATTERNS[ia-react-frontend]`) |
    | Reference architecture | complete | 5 file(s) under references/ |
    | Real-usage signal | <!-- populated by harvest-sessions when sessions exist --> | distillery/.eval-data/ia-react-frontend/ (created by harvest-sessions) |
    
    ## Evaluation
    
    Lightweight (run on every change):
    
    ```bash
    python3 distillery/scripts/distiller.py validate-plugin --component ia-react-frontend
    python3 distillery/scripts/distiller.py test-triggers --skill ia-react-frontend
    ```
    
    Deeper (when behavior risk warrants):
    
    ```bash
    python3 distillery/scripts/distiller.py dspy-eval ia-react-frontend
    python3 distillery/scripts/distiller.py diagnose-negatives ia-react-frontend
    ```
    
    Acceptance gates:
    - `validate-plugin --component ia-react-frontend` returns 0 HIGH findings.
    - `test-triggers --skill ia-react-frontend` returns F1 = 1.0 with floors of 5 should_trigger and 5 should_not_trigger.
    - For dspy-eval, the composite score does not regress against the most recent saved baseline (see `distillery/.eval-data/ia-react-frontend/history.json`).
    
    ## Known Limitations
    
    <!-- to fill in over time as drift surfaces. Default rule: any time diagnose-negatives
         surfaces a recurring failure pattern, document it here so future maintainers
         understand the trade-off the current implementation accepts. -->
    
    ## Maintenance Notes
    
    - Update `SKILL.md` when the runtime workflow, branch conditions, or output contract changes.
    - Update this `SPEC.md` when intent, scope, evidence model, evaluation gates, or maintenance expectations change.
    - Update the trigger fixture when adding new positive phrasings, removing stale ones, or expanding scope (the 5/5 floor is a hard validator gate).
    - Update the hook regex in `skill-patterns.sh` whenever fixture positives expose a missed phrasing; verify F1 = 1.0 with `eval-triggers` before committing.
    - Run the full release pipeline via `/release`; never bump versions or update CHANGELOG.md from a per-skill edit.
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related