### Full setup with npm Source: https://ladle.dev/docs/setup A complete set of commands to initialize a new project, add Ladle and its dependencies, create a story, and start the development server using npm. ```bash mkdir my-ladle cd my-ladle npm init --yes npm install @ladle/react react react-dom mkdir src echo "export const World = () =>

Hey

;" > src/hello.stories.tsx npx ladle serve ``` -------------------------------- ### Full setup with pnpm Source: https://ladle.dev/docs/setup A complete set of commands to initialize a new project, add Ladle and its dependencies, create a story, and start the development server using pnpm. ```bash mkdir my-ladle cd my-ladle pnpm init pnpm add @ladle/react react react-dom mkdir src echo "export const World = () =>

Hey

;" > src/hello.stories.tsx pnpm ladle serve ``` -------------------------------- ### Full setup with yarn Source: https://ladle.dev/docs/setup A complete set of commands to initialize a new project, add Ladle and its dependencies, create a story, and start the development server using yarn. ```bash mkdir my-ladle cd my-ladle yarn init --yes yarn add @ladle/react react react-dom mkdir src echo "export const World = () =>

Hey

;" > src/hello.stories.tsx yarn ladle serve ``` -------------------------------- ### Import Ladle's MSW Node Setup Source: https://ladle.dev/docs/msw Use Ladle's re-exported `setupServer` from `@ladle/react/msw-node` for Node.js environment setup. ```typescript import { setupServer } from "@ladle/react/msw-node"; ``` -------------------------------- ### serve Source: https://ladle.dev/docs/programmatic Starts a development server for Ladle. Accepts an optional configuration object. ```APIDOC ## serve ### Description Starts a development server for Ladle. ### Method JavaScript API call ### Parameters #### Request Body - **config** (object) - Optional - Configuration object for Ladle. ### Request Example ```javascript import serve from "@ladle/react/serve"; await serve({ // config: {} }); ``` ### Response This function does not return a value directly but starts a server process. ``` -------------------------------- ### Import MSW Node Setup Source: https://ladle.dev/docs/msw Import the `setupServer` function from MSW's node environment. ```typescript import { setupServer } from 'msw/node' ``` -------------------------------- ### Emotion Setup with Vite Source: https://ladle.dev/docs/css Integrate Emotion with Ladle by adding necessary dependencies and configuring Vite. This setup enables Emotion's features like `css` prop and styled components. ```bash pnpm add @emotion/react @swc/plugin-emotion @vitejs/plugin-react-swc ``` ```javascript import react from "@vitejs/plugin-react-swc"; export default { plugins: [ react({ jsxImportSource: "@emotion/react", plugins: [["@swc/plugin-emotion", {}]], }), ], }; ``` -------------------------------- ### Install mkcert and Generate Localhost Certificate Source: https://ladle.dev/docs/http2 Install mkcert using Homebrew and then generate a certificate for localhost. This process creates a new local certificate authority and a certificate file for your local development environment. ```bash brew install mkcert #assuming you have homebrew installed mkcert -install #creates a new local certificate authority mkcert localhost #creates a new certificate for localhost ``` -------------------------------- ### Serve Ladle project with pnpm Source: https://ladle.dev/docs/setup Starts the Ladle development server and opens your browser. This command is ideal for component development. ```bash pnpm ladle serve ``` -------------------------------- ### Styled-components Setup with Vite Source: https://ladle.dev/docs/css Configure Vite to work with styled-components, optionally including the SWC plugin for performance. Install the necessary packages and update `vite.config.js`. ```bash pnpm add styled-components @swc/plugin-styled-components @vitejs/plugin-react-swc ``` ```javascript import react from "@vitejs/plugin-react-swc"; export default { plugins: [ react({ plugins: [["@swc/plugin-styled-components", {}]], }), ], }; ``` -------------------------------- ### Serve Ladle project with npx Source: https://ladle.dev/docs/setup Starts the Ladle development server using npx. This command is ideal for component development. ```bash npx ladle serve ``` -------------------------------- ### Serve Ladle project with yarn Source: https://ladle.dev/docs/setup Starts the Ladle development server using yarn. This command is ideal for component development. ```bash yarn ladle serve ``` -------------------------------- ### Ladle Serve Command Options Source: https://ladle.dev/docs/cli Options for the 'serve' command to start the development server. Customize host, port, story discovery, theme, and configuration. ```bash Usage: ladle serve|dev [options] start developing Options: -h, --host [string] host to serve the application -p, --port [number] port to serve the application --stories [string] glob to find stories --theme [string] theme light, dark or auto --config [string] folder where config is located, default .ladle --viteConfig [string] file with Vite configuration --base [string] base URL path for build output --mode [string] Vite mode --noWatch [string] disable file system watcher -h, --help display help for command ``` -------------------------------- ### Install Playwright Test Runner Source: https://ladle.dev/docs/visual-snapshots Install the Playwright test runner as a development dependency. ```bash pnpm install @playwright/test ``` -------------------------------- ### Build and Preview Ladle, Run Playwright Tests Source: https://ladle.dev/docs/visual-snapshots Commands to build Ladle, start a preview server, and execute Playwright tests. The first test run will create baseline screenshots. ```bash pnpm ladle build pnpm ladle preview -p 61000 pnpm exec playwright test ``` -------------------------------- ### Install Ladle with yarn Source: https://ladle.dev/docs/setup Use this command to add the Ladle package to your project when using yarn. ```bash yarn add @ladle/react ``` -------------------------------- ### Install Ladle with npm Source: https://ladle.dev/docs/setup Use this command to add the Ladle package to your project when using npm. ```bash npm install @ladle/react ``` -------------------------------- ### Playwright Test Run Output Example Source: https://ladle.dev/docs/visual-snapshots Example output from running Playwright tests, showing passed and skipped tests. The initial run may show skipped tests as it generates baseline screenshots. ```bash Running 2 tests using 1 worker ✓ tests/snapshot.spec.ts:23:3 › abc--first - compare snapshots (259ms) - tests/snapshot.spec.ts:23:3 › abc--second - compare snapshots 1 skipped 1 passed (952ms) ``` -------------------------------- ### PostCSS Configuration Source: https://ladle.dev/docs/css Ladle automatically applies PostCSS transformations if a valid PostCSS configuration file is present. This example shows a typical `postcss.config.js` setup. ```javascript module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, }; ``` -------------------------------- ### Install Ladle with pnpm Source: https://ladle.dev/docs/setup Use this command to add the Ladle package to your project when using pnpm. ```bash pnpm add @ladle/react ``` -------------------------------- ### CSS Modules Example Source: https://ladle.dev/docs/css Use CSS Modules by naming your CSS file with a `.module.css` extension. Importing it returns a module object for scoped class names. ```css /* example.module.css */ .red { color: red; } ``` ```javascript import type { Story } from "@ladle/react"; import classes from "./example.module.css"; export const MyStory: Story = () => { return

Red Header

; }; ``` -------------------------------- ### Create a simple story Source: https://ladle.dev/docs/setup This is an example of a basic story component that Ladle will render. Ensure your story files match the glob pattern `src/**/*.stories.{js,jsx,ts,tsx,mdx}`. ```tsx export const World = () =>

Hey!

; ``` -------------------------------- ### Global Story Decorator - Ladle Source: https://ladle.dev/docs/decorators Apply a decorator to all stories in a file by defining it in the default export. This example adds a margin to each story. ```typescript import type { StoryDefault } from "@ladle/react"; export default { decorators: [ (Component) => (
), ], } satisfies StoryDefault; ``` -------------------------------- ### Configure Vite to Use Babel Source: https://ladle.dev/docs/babel Install and configure @vitejs/plugin-react in your vite.config.js to use Babel instead of SWC. Ladle will automatically detect and use this configuration. ```javascript import react from "@vitejs/plugin-react"; export default { plugins: [react()], }; ``` -------------------------------- ### Set default story in .ladle/config.mjs Source: https://ladle.dev/docs/config Configure the `defaultStory` parameter to specify which story is loaded when Ladle starts. This value is used in the URL query parameter `?story=`. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { defaultStory: "a11y--welcome", }; ``` -------------------------------- ### Specific Story Decorator - Ladle Source: https://ladle.dev/docs/decorators Apply a decorator to a single story by assigning it to the story's `decorators` property. This example adds a margin to 'MyStory'. ```typescript import type { Story } from "@ladle/react"; export const MyStory: Story = () =>
My Story
; MyStory.decorators = [ (Component) => (
), ]; ``` -------------------------------- ### Customizing Story Title in MDX Source: https://ladle.dev/docs/mdx Customize the title displayed in the side navigation by using the `` component. This example sets the title to 'Documentation/Welcome'. ```mdx import { Meta } from "@ladle/react"; # Customized This is a paragraph. ``` -------------------------------- ### Utilize Exported Types for Story Development Source: https://ladle.dev/docs/typescript Import types like `StoryDefault` and `Story` from `@ladle/react` to improve type safety and autocompletion when defining stories. This example demonstrates defining props and a basic story component. ```typescript import type { StoryDefault, Story } from "@ladle/react"; type Props = { label: string }; export default { title: "New title", } satisfies StoryDefault; const Card: Story = ({ label }) =>

Label: {label}

; Card.args = { label: "Hello", }; ``` -------------------------------- ### Context-Aware Decorator - Ladle Source: https://ladle.dev/docs/decorators Access Ladle's context within a decorator to control story aspects like controls and addons. This example displays the value of a control named 'label'. ```typescript import type { StoryDefault, Story } from "@ladle/react"; type Props = { label: string }; export default { decorators: [ (Component, context) => (
{context.globalState.control.label.value}
), ], } satisfies StoryDefault; const Card: Story = ({ label }) =>

Label: {label}

; Card.args = { label: "Hello", }; ``` -------------------------------- ### Ladle Preview Command Options Source: https://ladle.dev/docs/cli Options for the 'preview' command to serve the built application. Configure output directory, host, port, and other build-related settings. ```bash Usage: ladle preview [options] start a server to preview the build in outDir Options: -o, --outDir output directory -h, --host [string] host to serve the application -p, --port [number] port to serve the application --config [string] folder where config is located, default .ladle --viteConfig [string] file with Vite configuration --base [string] base URL path for build output --mode [string] Vite mode -h, --help display help for command ``` -------------------------------- ### Ladle Build Command Options Source: https://ladle.dev/docs/cli Options for the 'build' command to create a static production application. Specify output directory, story glob, theme, and configuration. ```bash Usage: ladle build [options] build static production app Options: -o, --outDir output directory --stories [string] glob to find stories --theme [string] theme light, dark or auto --config [string] folder where config is located, default .ladle --viteConfig [string] file with Vite configuration --base [string] base URL path for build output --mode [string] Vite mode -h, --help display help for command ``` -------------------------------- ### Serve, Build, and Preview with Ladle API Source: https://ladle.dev/docs/programmatic Use the `serve`, `build`, and `preview` functions from the `@ladle/react` package to programmatically control Ladle's operations. Configuration options can be passed within the respective function calls. ```javascript import serve from "@ladle/react/serve"; import build from "@ladle/react/build"; import preview from "@ladle/react/preview"; await serve({ // config: {} }); await build({ // config: {} }); await preview({ // config: {} }); ``` -------------------------------- ### Build Ladle project with pnpm Source: https://ladle.dev/docs/setup Creates a production-ready build of your Ladle project in the `build` folder. The output is optimized and minified for deployment or testing. ```bash pnpm ladle build ``` -------------------------------- ### Preview Ladle build with pnpm Source: https://ladle.dev/docs/setup Serves the production build of your Ladle project. This command is used after running `ladle build` to test the deployed assets. ```bash pnpm ladle preview ``` -------------------------------- ### Preview Ladle build with npx Source: https://ladle.dev/docs/setup Serves the production build of your Ladle project using npx. This command is used after running `ladle build` to test the deployed assets. ```bash npx ladle preview ``` -------------------------------- ### Specify preview server host in .ladle/config.mjs Source: https://ladle.dev/docs/config Configure the `previewHost` parameter to set the preview server's host address. Use '0.0.0.0' to allow connections from any IP address. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { previewHost: "0.0.0.0", }; ``` -------------------------------- ### preview Source: https://ladle.dev/docs/programmatic Generates a preview build of the Ladle project. Accepts an optional configuration object. ```APIDOC ## preview ### Description Generates a preview build of the Ladle project. ### Method JavaScript API call ### Parameters #### Request Body - **config** (object) - Optional - Configuration object for Ladle. ### Request Example ```javascript import preview from "@ladle/react/preview"; await preview({ // config: {} }); ``` ### Response This function does not return a value directly but generates preview assets. ``` -------------------------------- ### Build Ladle project with npx Source: https://ladle.dev/docs/setup Creates a production-ready build of your Ladle project using npx. The output is optimized and minified for deployment or testing. ```bash npx ladle build ``` -------------------------------- ### build Source: https://ladle.dev/docs/programmatic Builds the Ladle project for production. Accepts an optional configuration object. ```APIDOC ## build ### Description Builds the Ladle project for production. ### Method JavaScript API call ### Parameters #### Request Body - **config** (object) - Optional - Configuration object for Ladle. ### Request Example ```javascript import build from "@ladle/react/build"; await build({ // config: {} }); ``` ### Response This function does not return a value directly but generates production assets. ``` -------------------------------- ### Preview Ladle build with yarn Source: https://ladle.dev/docs/setup Serves the production build of your Ladle project using yarn. This command is used after running `ladle build` to test the deployed assets. ```bash yarn ladle preview ``` -------------------------------- ### Build Ladle project with yarn Source: https://ladle.dev/docs/setup Creates a production-ready build of your Ladle project using yarn. The output is optimized and minified for deployment or testing. ```bash yarn ladle build ``` -------------------------------- ### Ladle CLI Usage Source: https://ladle.dev/docs/cli This is the main usage command for the Ladle CLI. It outlines the available commands: serve, build, and preview. ```bash Usage: ladle [options] [command] Options: -h, --help display help for command Commands: serve|dev [options] start developing build [options] build static production app preview [options] start a server to preview the build in outDir help [command] display help for command ``` -------------------------------- ### Global Level Args and ArgTypes Configuration Source: https://ladle.dev/docs/controls Demonstrates how to define global `args` and `argTypes` in `.ladle/components.tsx` to apply them to all stories across the project. ```typescript export const args = { label: "Hello world", }; export const argTypes = { cities: { options: ["Prague", "NYC"], control: { type: "check" }, }, }; ``` -------------------------------- ### File-Level Args and ArgTypes Configuration Source: https://ladle.dev/docs/controls Shows how to set default `args` and `argTypes` for all stories within a single file using `export default`. ```typescript export default { args: { label: "Hello world", }, argTypes: { cities: { options: ["Prague", "NYC"], control: { type: "check" }, }, }, }; ``` -------------------------------- ### Creating Multiple Stories with Different Args Source: https://ladle.dev/docs/controls Illustrates how to create distinct stories from a single component by assigning different default `args` values. ```typescript import type { Story } from "@ladle/react"; const Card: Story<{ label: string; }> = ({ label }) =>

Label: {label}

; export const CardHello = Card.bind({}); CardHello.args = { label: "Hello", }; export const CardWorld = Card.bind({}); CardWorld.args = { label: "World", }; ``` -------------------------------- ### Specify preview server port in .ladle/config.mjs Source: https://ladle.dev/docs/config Configure the `previewPort` parameter to set the preview server's port. Ensure this port does not conflict with other services. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { previewPort: 8080, }; ``` -------------------------------- ### Basic Controls with Args and ArgTypes Source: https://ladle.dev/docs/controls Demonstrates defining primitive types via `args` and enums via `argTypes` for component parametrization. Supports various control types like radio, select, range, and checkboxes. ```typescript import type { Story } from "@ladle/react"; export const Controls: Story<{ label: string; disabled: boolean; count: number; range: number; colors: string[]; variant: string; size: string; airports: string[]; }> = ({ count, range, disabled, label, colors, variant, size, airports }) => ( <>

Count: {count}

Range: {range}

Disabled: {disabled ? "yes" : "no"}

Label: {label}

Colors: {colors.join(",")}

Variant: {variant}

Size: {size}

Airports: {airports.join(",")}

); Controls.args = { label: "Hello world", disabled: false, count: 2, colors: ["Red", "Blue"], }; Controls.argTypes = { variant: { options: ["primary", "secondary"], control: { type: "radio" }, // or type: inline-radio defaultValue: "primary", }, size: { options: ["small", "medium", "big", "huuuuge"], control: { type: "select" }, // or type: multi-select }, airports: { name: "International Airports", // custom label options: ["sfo", "slc", "prg"], // custom option labels labels: { sfo: "San Francisco", slc: "Salt Lake City", prg: "Prague", }, control: { type: "check" }, // or type: inline-check }, range: { control: { type: "range", min: 1, max: 10, step: 0.5 }, defaultValue: 5, }, }; ``` -------------------------------- ### Specify output directory in .ladle/config.mjs Source: https://ladle.dev/docs/config Configure the `outDir` parameter to set the output directory for the build, relative to the project root. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { outDir: "build", }; ``` -------------------------------- ### Set Base Path for Build Output Source: https://ladle.dev/docs/config Define the base path for the build output. This is useful for hosting projects on platforms like GitHub Pages. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { base: "/my-project/", }; ``` -------------------------------- ### Specify dev server host in .ladle/config.mjs Source: https://ladle.dev/docs/config Configure the `host` parameter to set the development server's host address. Use '0.0.0.0' to allow connections from any IP address. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { host: "0.0.0.0", }; ``` -------------------------------- ### BaseWeb and Styletron Global Provider Source: https://ladle.dev/docs/css Set up a global provider in `.ladle/components.tsx` to integrate BaseWeb and Styletron. This allows for theme management (dark/light, RTL) and global styling. ```bash pnpm add baseui styletron-react styletron-engine-monolithic ``` ```typescript import { Provider as StyletronProvider } from "styletron-react"; import { Client as Styletron } from "styletron-engine-monolithic"; import { LightTheme, DarkTheme, BaseProvider } from "baseui"; import type { GlobalProvider } from "@ladle/react"; const engine = new Styletron(); export const Provider: GlobalProvider = ({ children, globalState }) => ( {children} ); ``` -------------------------------- ### Enable MSW in Ladle Config Source: https://ladle.dev/docs/msw Enable MSW addon in your `.ladle/config.mjs` file to activate API mocking. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { addons: { msw: { enabled: true, }, }, }; ``` -------------------------------- ### Configure Global Background Control Source: https://ladle.dev/docs/background Set up the global background control in '.ladle/components.tsx'. This makes the background control accessible to all stories with predefined options and a default value. ```typescript export const argTypes = { background: { control: { type: "background" }, options: ["purple", "blue", "white", "pink"], defaultValue: "purple", }, }; ``` -------------------------------- ### Customize Story Source Theme with Prism React Renderer Source: https://ladle.dev/docs/source Configure the source code highlighting theme in `.ladle/config.mjs` using `prism-react-renderer` themes. You can define custom themes or use provided ones like `themes.github`. ```javascript import { themes } from "prism-react-renderer"; const customDarkTheme = { plain: { color: "salmon", backgroundColor: "#1E1E1E", }, }; /** @type {import('@ladle/react').UserConfig} */ export default { addons: { source: { themeLight: themes.github, themeDark: customDarkTheme, }, }, }; ``` -------------------------------- ### Configure Ladle stories search pattern in .ladle/config.mjs Source: https://ladle.dev/docs/config Use the `stories` parameter to specify the glob pattern for finding story files. Supports a single string or an array of strings. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { stories: "src/**/*.stories.{js,jsx,ts,tsx,mdx}", }; ``` ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { stories: ["src/**/control.stories.{js,jsx,ts,tsx}", "src/stories.custom.tsx"], }; ``` -------------------------------- ### Enable Verbose Output in Browser Console Source: https://ladle.dev/docs/troubleshooting Add an item to local storage to enable verbose debugging in the browser console. Set the 'debug' key to 'ladle*' to activate Ladle's debug logs within the browser. ```javascript localStorage.debug = 'ladle*' ``` -------------------------------- ### Expand Story Tree by Default Source: https://ladle.dev/docs/config Configure Ladle to expand the story tree by default when the application loads. This makes all stories visible initially. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { expandStoryTree: true, }; ``` -------------------------------- ### Configure Ladle Addons Source: https://ladle.dev/docs/config Enable, disable, or set the default state for Ladle addons. This controls the visibility and initial behavior of the buttons in the bottom-left corner. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { addons: { a11y: { enabled: false, }, action: { enabled: false, defaultState: [], }, control: { enabled: true, defaultState: {}, }, ladle: { enabled: true, }, mode: { enabled: true, defaultState: "full", }, msw: { enabled: false, }, rtl: { enabled: true, defaultState: false, }, source: { enabled: true, defaultState: false, }, theme: { enabled: true, defaultState: "light", }, width: { enabled: true, options: { xsmall: 414, small: 640, medium: 768, large: 1024, }, defaultState: 0, }, }, }; ``` -------------------------------- ### Basic MDX Structure Source: https://ladle.dev/docs/mdx This is a basic MDX structure that will be displayed in the side navigation as 'Basic' > 'Readme'. ```mdx # Header > Some quote: Suspendisse at tempor velit. **Fusce** a fermentum arcu, > vitae semper mi. Nunc placerat, mauris ac volutpat tempus, arcu eros > accumsan nisi, in congue risus turpis in ligula. Some [example](https://example.com) link. 1. One 2. Two 3. Three ``` -------------------------------- ### Global Provider for next/navigation Context Source: https://ladle.dev/docs/nextjs Provides the AppRouterContext to all stories globally. This resolves the 'invariant expected app router to be mounted' error when using 'useRouter()' from 'next/navigation' in Ladle. ```typescript import { GlobalProvider } from "@ladle/react"; import { AppRouterContext } from "next/dist/shared/lib/app-router-context.shared-runtime"; export const Provider: GlobalProvider = ({ children }) => { return ( { // Do nothing }, forward: () => { // Do nothing }, prefetch: () => { // Do nothing }, push: () => { // Do nothing }, refresh: () => { // Do nothing }, replace: () => { // Do nothing }, }} > {children} ); }; ``` -------------------------------- ### Default Viewport Widths (px) Source: https://ladle.dev/docs/width These are the default viewport widths provided by Ladle in pixels. They can be used directly or customized. ```json { "xsmall": 414, "small": 640, "medium": 768, "large": 1024, } ``` -------------------------------- ### Specify HMR host in .ladle/config.mjs Source: https://ladle.dev/docs/config Configure the `hmrHost` parameter to set the host for Hot Module Replacement. Use '0.0.0.0' to allow connections from any IP address. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { hmrHost: 0.0.0.0, }; ``` -------------------------------- ### Configure Custom Widths in .ladle/config.mjs Source: https://ladle.dev/docs/width Customize default viewport widths and enable/disable the width addon in your Ladle configuration file. You can also set a default state for the width. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { addons: { width: { options: { phone: 380, tablet: 720, large: 1200, }, enabled: true, // the addon can be disabled defaultState: 0, // default width in pixels (0 = no viewport is set) }, }, }; ``` -------------------------------- ### Set Vite Mode Source: https://ladle.dev/docs/config Configure the Vite mode. Defaults to 'development' for development and 'production' for builds. This setting also influences Vite's .env file loading. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { mode: "my-custom-mode", }; ``` -------------------------------- ### Specify dev server port in .ladle/config.mjs Source: https://ladle.dev/docs/config Configure the `port` parameter to set the development server's port. Ensure this port does not conflict with other services. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { port: 61000, }; ``` -------------------------------- ### Configure story order in .ladle/config.mjs Source: https://ladle.dev/docs/config Use the `storyOrder` parameter to control the order of stories in the navigation. It accepts an array of story IDs or a function that returns such an array. Stories not included in the array will not be visible. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { // note that alphabetically sorted stories are provided storyOrder: (stories) => stories, }; ``` ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { storyOrder: ["folder--story1", "folder--story2"], }; ``` ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { storyOrder: () => ["folder--story1", "folder--story2"], }; ``` -------------------------------- ### Ladle Meta JSON Structure Source: https://ladle.dev/docs/meta The meta.json file lists all stories and additional information. It is accessible at /meta.json in serve mode or output to the build folder in build mode. ```json { "about": { "homepage": "https://www.ladle.dev", "github": "https://github.com/tajo/ladle", "version": 1 }, "stories": { "control--first": { "name": "First", "levels": ["Control"], "locStart": 12, "locEnd": 12, "filePath": "src/control.stories.tsx", "meta": {} } } } ``` -------------------------------- ### Configure Vite for Next.js Environment Variables Source: https://ladle.dev/docs/nextjs Configure Vite to load and expose Next.js environment variables (prefixed with NEXT_PUBLIC_) to the browser. This ensures that frontend environment variables defined in .env files are accessible. ```typescript import { defineConfig, loadEnv } from "vite"; export default defineConfig(({ mode }) => ({ // resolve: {...}, define: { "process.env": loadEnv(mode, process.cwd(), "NEXT_PUBLIC_"), }, })); ``` -------------------------------- ### Configure tsconfig.json for React JSX Runtime Source: https://ladle.dev/docs/typescript Set the `jsx` compiler option to `react-jsx` in your `tsconfig.json` to enable Ladle's `jsx-runtime`. This avoids the need to import React in every module. ```json { "compilerOptions": { "jsx": "react-jsx" }, "include": ["src", ".ladle"] } ``` -------------------------------- ### Configure Vite for HTTPS with Local Certificates Source: https://ladle.dev/docs/http2 Configure your Vite project to use the generated SSL certificate and key for HTTPS. This involves reading the certificate files using Node.js 'fs' module and providing them to the Vite server configuration. ```typescript import { defineConfig } from "vite"; import fs from "fs"; export default defineConfig({ server: { https: { key: fs.readFileSync("./localhost-key.pem"), cert: fs.readFileSync("./localhost.pem"), }, }, }); ``` -------------------------------- ### Use useLadleContext to Change Theme in Story Source: https://ladle.dev/docs/providers This hook provides access to Ladle's `globalState` and a `dispatch` function. Use it to inspect and modify addon states like the theme. ```typescript import { useLadleContext, ActionType, ThemeState } from "@ladle/react"; export const StoryChangingTheTheme = () => { const { globalState, dispatch } = useLadleContext(); return ( <>

Active theme: {globalState.theme}

); }; ``` -------------------------------- ### Define Global Provider in .ladle/components.tsx Source: https://ladle.dev/docs/providers Use this to wrap all stories with global context. Access `globalState` and `storyMeta` for dynamic content. ```typescript import type { GlobalProvider } from "@ladle/react"; export const Provider: GlobalProvider = ({ children, globalState, storyMeta, }) => ( <>

Theme: {globalState.theme}

{storyMeta.customValue}

{children} ); ``` -------------------------------- ### Configure Per-Story Background Control Source: https://ladle.dev/docs/background Override or set the background control for an individual story in its respective file. This allows for story-specific background options and default values. ```typescript export const Story = () =>
Hello
; Story.argTypes = { background: { name: "Canvas background", control: { type: "background" }, options: ["green", "yellow", "pink"], defaultValue: "pink", }, }; ``` -------------------------------- ### Enable Verbose Output in Terminal Source: https://ladle.dev/docs/troubleshooting Use the DEBUG=ladle* environment variable with pnpm to enable verbose logging for Ladle commands in your terminal. This helps in diagnosing issues during serve or build processes. ```bash DEBUG=ladle* pnpm ladle serve DEBUG=ladle* pnpm ladle build ``` -------------------------------- ### Alias next/image and next/link in Vite Config Source: https://ladle.dev/docs/nextjs Configure Vite to alias 'next/image' and 'next/link' to custom unoptimized components. This is necessary because Ladle has its own build process that conflicts with Next.js's build-time transformations for these components. ```typescript import path from "path"; import { defineConfig } from "vite"; export default defineConfig({ resolve: { alias: { "next/image": path.resolve(__dirname, "./.ladle/UnoptimizedImage.tsx"), "next/link": path.resolve(__dirname, "./.ladle/UnoptimizedLink.tsx"), }, }, }); ``` -------------------------------- ### Basic Component Stories Source: https://ladle.dev/docs/stories Define stories for your components using the Story type from @ladle/react. These are automatically discovered by Ladle. ```jsx import type { Story } from "@ladle/react"; export const Button: Story = () => ; export const HeaderOne: Story = () =>

Header

; ``` ```jsx import type { Story } from "@ladle/react"; export const Simple: Story = () => (
  • Item 1
  • Item 2
); ``` -------------------------------- ### Customize Hotkeys Source: https://ladle.dev/docs/config Customize the default hotkeys for various actions in Ladle. Multiple hotkeys can be assigned to a single action, and an empty array disables a hotkey. 'meta' corresponds to 'cmd' on macOS and 'win' on Windows; 'alt' is 'option' on macOS. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { hotkeys: { search: ["/", "meta+p"], nextStory: ["alt+arrowright"], previousStory: ["alt+arrowleft"], nextComponent: ["alt+arrowdown"], previousComponent: ["alt+arrowup"], control: ["c"], darkMode: ["d"], fullscreen: ["f"], width: ["w"], rtl: ["r"], source: ["s"], a11y: ["a"], }, }; ``` -------------------------------- ### Enable a11y Addon in Ladle Config Source: https://ladle.dev/docs/a11y Enable the a11y addon in your `.ladle/config.mjs` file to integrate axe-core for accessibility testing within Ladle. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { addons: { a11y: { enabled: true, }, }, }; ``` -------------------------------- ### Updated Meta JSON with Annotations Source: https://ladle.dev/docs/meta This shows how the meta.json is updated to include the annotations defined in the story file. ```json { "stories": { "control--first": { "name": "First", "levels": ["Control"], "locStart": 8, "locEnd": 8, "filePath": "src/control.stories.tsx", "meta": { "baseweb": "test", "browsers": ["firefox"] } } } } ``` -------------------------------- ### Link to Another Story using `linkTo` Source: https://ladle.dev/docs/links Use the `linkTo` function from `@ladle/react` to navigate to a different story. The argument is the story's ID, which corresponds to the `?story=` parameter in the URL. ```typescript import * as React from "react"; import { linkTo } from "@ladle/react"; import type { Story } from "@ladle/react"; export const Link: Story = () => { return ; }; ``` -------------------------------- ### Setting Meta Parameters in MDX Source: https://ladle.dev/docs/mdx Set meta parameters for stories using the `` component. Individual stories can also override or add meta parameters using their own `` prop. ```mdx import { Story, Meta } from "@ladle/react"; This part will be rendered as a separate `Readme` story. ``` -------------------------------- ### Multiple Stories in a Single MDX File Source: https://ladle.dev/docs/mdx Define multiple stories within a single `*.stories.mdx` file using the `` component. Each `` tag creates a separate story. ```mdx import { Story } from "@ladle/react"; This part will be rendered as a separate `Readme` story. ``` -------------------------------- ### Mocking Date in a Ladle Story Source: https://ladle.dev/docs/mock-date Use the `meta.mockDate` parameter to set a specific date and time for `new Date()`. This is useful for ensuring consistent component rendering during tests. ```typescript import type { Story } from "@ladle/react"; export const DatePicker: Story = () => { const date = new Date(); return (

{date.toLocaleDateString("en-US")}

); }; DatePicker.meta = { mockDate: "1995-12-17T03:24:00", }; ``` -------------------------------- ### Dynamic Playwright Test for Ladle Stories Source: https://ladle.dev/docs/visual-snapshots This TypeScript file dynamically generates Playwright tests for each Ladle story. It fetches story data from `meta.json`, navigates to each story, and performs a visual snapshot comparison. Ensure Ladle is running on http://localhost:61000. ```typescript import { test, expect } from "@playwright/test"; // we can't create tests asynchronously, thus using the sync-fetch lib import fetch from "sync-fetch"; // URL where Ladle is served const url = "http://localhost:61000"; // fetch Ladle's meta file // https://ladle.dev/docs/meta const stories = fetch(`${url}/meta.json`).json().stories; // iterate through stories Object.keys(stories).forEach((storyKey) => { // create a test for each story test(`${storyKey} - compare snapshots`, async ({ page }) => { // navigate to the story await page.goto(`${url}/?story=${storyKey}&mode=preview`); // stories are code-splitted, wait for them to be loaded await page.waitForSelector("[data-storyloaded]"); // take a screenshot and compare it with the baseline await expect(page).toHaveScreenshot(`${storyKey}.png`); }); }); ``` -------------------------------- ### UnoptimizedLink Component for Ladle Source: https://ladle.dev/docs/nextjs A simple React component to replace 'next/link' when using Ladle. It renders a basic anchor tag, bypassing Next.js's specific link optimizations. ```typescript const UnoptimizedLink = (props: any) => { return ; }; export default UnoptimizedLink; ``` -------------------------------- ### Decorator for next/navigation Context in Stories Source: https://ladle.dev/docs/nextjs Applies the AppRouterContext to individual stories using decorators. This is an alternative to the global provider for resolving 'useRouter()' errors in Ladle. ```typescript import type { StoryDefault, Story } from "@ladle/react"; import { AppRouterContext } from "next/dist/shared/lib/app-router-context.shared-runtime"; import { useRouter } from "next/navigation"; export default { decorators: [ (Component) => { return ( { // Do nothing }, forward: () => { // Do nothing }, prefetch: () => { // Do nothing }, push: () => { // Do nothing }, refresh: () => { // Do nothing }, replace: () => { // Do nothing }, }} > ); }, ], } satisfies StoryDefault; export const Hello: Story = () => { const router = useRouter(); return ( <>

Hello Next.js App Router

); }; ``` -------------------------------- ### Specify HMR port in .ladle/config.mjs Source: https://ladle.dev/docs/config Configure the `hmrPort` parameter to set the port for Hot Module Replacement. Ensure this port does not conflict with other services. ```javascript /** @type {import('@ladle/react').UserConfig} */ export default { hmrPort: 24678, }; ``` -------------------------------- ### Import CSS File into Component Source: https://ladle.dev/docs/css Import CSS files directly into your components or stories. Ensure the CSS file is located relative to the component file. ```javascript import "./styles.css"; ``` -------------------------------- ### Tailwind CSS Configuration Source: https://ladle.dev/docs/css Configure Tailwind CSS by creating `tailwind.config.js`. This file specifies the content to scan for classes and theme/variant configurations. ```javascript module.exports = { content: ["./src/**/*.{js,ts,jsx,tsx}"], theme: {}, variants: {}, plugins: [], }; ``` -------------------------------- ### Importing Markdown into MDX Stories Source: https://ladle.dev/docs/mdx Import and render markdown files directly within your MDX stories. This allows you to include README content or other markdown documentation. ```mdx import Readme from "./README.md"; # Header ``` -------------------------------- ### Custom Title and Sublevels Source: https://ladle.dev/docs/stories Set a custom title for a story file and create navigation sublevels using the `title` property in `StoryDefault`. Use '/' to define hierarchy. ```jsx import type { StoryDefault, Story } from "@ladle/react"; export default { title: "Level / Sub level", } satisfies StoryDefault; export const Button: Story = () => ; ``` -------------------------------- ### UnoptimizedImage Component for Ladle Source: https://ladle.dev/docs/nextjs A React component to replace 'next/image' when using Ladle. It renders a standard img tag, handling the 'fill' prop for layout purposes without Next.js's image optimization. ```typescript import React from 'react'; interface UnoptimizedImageProps extends React.ImgHTMLAttributes { fill?: boolean; } const UnoptimizedImage: React.FC = ({ fill, ...props }) => { const style: React.CSSProperties = fill ? { position: 'absolute', inset: '0', width: '100%', height: '100%', } : {}; return ; }; export default UnoptimizedImage; ```