Component preview

From civitai/civitai · View interactive version

Component preview is an AI agent skill from the GitHub repository civitai/civitai. Preview React components with real Mantine + Tailwind styling using Ladle. Use when modifying UI components, fixing visual bugs, or when the user asks to see what a component looks like. Creates Ladle stories, captures screenshots in dark/light mode, and presents them for review. Use proactively aft

How to use this skill

Skill file

Component Preview

Preview React components in isolation using Ladle (lightweight Storybook alternative) with real Mantine v7 + Tailwind styling. No dev server needed.

When to Use

Prerequisites

Ladle is configured in the project root:

If these don't exist in the current worktree, copy them from main or create them. See Setup Reference below.

Workflow

1. Create/Update the Story

Create a .stories.tsx file near the component being previewed:

src/components/MyComponent/MyComponent.stories.tsx
src/pages/challenges/EligibleModels.stories.tsx

Story structure:

import { /* Mantine components */ } from '@mantine/core';
// Import the component or recreate the relevant JSX

// Mock data that represents realistic API responses
const mockData = [ ... ];

// Render the component with different states
function Preview({ data }) {
  return (
    <div style={{ width: 320 }}> {/* Constrain to realistic width */}
      <MyComponent data={data} />
    </div>
  );
}

/** Default state */
export const Default = () => <Preview data={mockData} />;

/** Empty state */
export const Empty = () => <Preview data={[]} />;

/** Loading or edge case states */
export const LongList = () => <Preview data={longMockData} />;

Important patterns:

2. Start Ladle

# Check if Ladle is already running
curl -s -o /dev/null -w "%{http_code}" http://localhost:61111/

# If not running, start it (from project root or worktree root), logging to a file
cd <worktree-path>
npx ladle serve --port 61111 > <scratch-dir>/ladle.log 2>&1 &
# Wait for it to be ready (~3-5 seconds)

Ladle auto-discovers stories matching src/**/*.stories.tsx.

Warm the cache before capturing. Without node_modules/.vite (a fresh worktree, or after an

install), Vite pre-bundles dependencies on the first request, and a story that imports the generator

graph takes 25–30s to reach load, close enough to Playwright's 30s default page.goto timeout

to exceed it on a busy machine. Vite then logs

optimized dependencies changed. reloading and reloads the page. Don't work around the timeout with

waitUntil: 'commit': that captures the page mid-reload, where transient errors such as

Cannot access '<x>' before initialization appear that a warm load doesn't have. Instead, open each

story you will capture once in the browser session (step 3) with a long goto timeout, then wait until

ladle.log stops growing for ~10s (it usually ends with optimized dependencies changed. reloading).

A story whose imports no earlier story pulled in can trigger another optimize-and-reload, so warming

with one story doesn't cover unrelated ones. A curl doesn't warm anything — Vite optimizes on the

browser's module requests. Once warm, loads take well under a second.

3. Capture Screenshots

Use the browser-automation skill to capture cropped, padded screenshots:

# Start the server and create a browser session on Ladle
node .claude/skills/browser-automation/server.mjs &
curl -X POST http://localhost:9222/sessions -d '{"name": "ladle", "url": "http://localhost:61111"}'

Put the capture code in a scratch file, e.g. <scratch-dir>/capture.js:

const stories = [
  { name: 'default', path: 'my-component--default' },
  { name: 'empty', path: 'my-component--empty' },
];
const themes = ['dark', 'light'];
const dir = '<absolute-output-dir>';

for (const theme of themes) {
  for (const story of stories) {
    // Run the warm-up in step 2 first: a cold load can reload mid-capture. The long timeout is a safety net.
    await page.goto('http://localhost:61111/?story=' + story.path + '&theme=' + theme + '&mode=preview', {
      timeout: 120_000,
    });
    const wrapper = page.locator('.ladle-story-wrapper');
    await wrapper.waitFor({ timeout: 60_000 });
    await page.waitForTimeout(800);
    await wrapper.screenshot({ path: dir + '/crop-' + theme + '-' + story.name + '.png' });
  }
}

Then run it as a chunk:

node -e "fetch('http://localhost:9222/chunk?session=ladle', { method: 'POST', body: JSON.stringify({ label: 'Component preview screenshots', code: require('fs').readFileSync(process.argv[1], 'utf8') }) }).then((r) => r.text()).then(console.log)" "<scratch-dir>/capture.js"

Story path format: The story path is derived from the file name and export name:

Pattern: kebab-case filename + -- + kebab-case export name.

4. Present to User

  1. Show screenshots inline using the Read tool on the PNG files
  2. Open for the user if they want to see them in their image viewer:

```bash

start "" "<path-to-screenshot>"

```

  1. Ask for feedback — "Does this look right? Want me to adjust anything?"
  2. Iterate — if they want changes, modify the component, re-capture, re-present

Handling Complex Components

Some components depend heavily on app context. When this happens:

Easy (just do it)

Medium (mock the data)

Hard (raise to user)

When encountering hard cases, tell the user:

"This component depends on [auth/router/tRPC context]. I can either:

1. Mock out the dependencies (more setup, more accurate)

2. Extract just the visual parts into the story (faster, close enough)

3. Skip the preview and we can check it on the dev server instead

What would you prefer?"

Setup Reference

If Ladle isn't configured in the worktree, create these files:

`.ladle/components.tsx`

import { MantineProvider, createTheme, Modal } from '@mantine/core';
import type { GlobalProvider } from '@ladle/react';

import '@mantine/core/styles.layer.css';
import '../src/styles/globals.css';

// Theme subset from src/providers/ThemeProvider.tsx
const theme = createTheme({
  components: {
    Badge: {
      styles: { leftSection: { lineHeight: 1 } },
      defaultProps: { radius: 'sm', variant: 'light' },
    },
    ActionIcon: {
      defaultProps: { color: 'gray', variant: 'subtle' },
    },
    Tooltip: {
      defaultProps: { withArrow: true },
    },
  },
  colors: {
    dark: ['#C1C2C5','#A6A7AB','#8c8fa3','#5C5F66','#373A40','#2C2E33','#25262B','#1A1B1E','#141517','#101113'],
    blue: ['#E7F5FF','#D0EBFF','#A5D8FF','#74C0FC','#4DABF7','#339AF0','#228BE6','#1C7ED6','#1971C2','#1864AB'],
  },
  white: '#fefefe',
  black: '#222',
});

export const Provider: GlobalProvider = ({ children, globalState }) => (
  <MantineProvider
    theme={theme}
    defaultColorScheme={globalState.theme === 'dark' ? 'dark' : 'light'}
    forceColorScheme={globalState.theme === 'dark' ? 'dark' : 'light'}
  >
    <div className="ladle-story-wrapper" style={{ padding: 24, width: 'fit-content' }}>
      {children}
    </div>
  </MantineProvider>
);

`.ladle/config.mjs`

/** @type {import('@ladle/react').UserConfig} */
export default {
  stories: 'src/**/*.stories.tsx',
  defaultStory: '',
  viteConfig: '.ladle/vite.config.ts',
};

`.ladle/vite.config.ts`

import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  resolve: {
    alias: { '~': path.resolve(__dirname, '../src') },
  },
  css: {
    postcss: path.resolve(__dirname, '..'),
  },
});

Ensure Ladle is installed

pnpm add -D @ladle/react

Tips

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.