Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Ladle
https://github.com/tajo/ladle
Admin
🥄 Develop, test and document your React story components faster.
Tokens:
18,536
Snippets:
175
Trust Score:
8.9
License:
MIT
Update:
1 year ago
Context
Chat
Benchmark
71.64
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Developing and Building Ladle Example Project Source: https://github.com/tajo/ladle/blob/main/CONTRIBUTING.md Navigates into the example project directory and then runs `ladle serve` to start a development server and `ladle build` to create a production build, useful for testing changes in `@ladle/react`. ```sh cd packages/example pnpm ladle serve pnpm ladle build ``` -------------------------------- ### Complete Ladle Setup from Scratch Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/setup.mdx This comprehensive set of commands provides a full scratch setup for Ladle, including project initialization, dependency installation (Ladle, React), story file creation, and starting the development server. It demonstrates the complete workflow for different package managers. ```bash mkdir my-ladle cd my-ladle pnpm init pnpm add @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx pnpm ladle serve ``` ```bash mkdir my-ladle cd my-ladle yarn init --yes yarn add @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx yarn ladle serve ``` ```bash mkdir my-ladle cd my-ladle npm init --yes npm install @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx npx ladle serve ``` -------------------------------- ### Quick Start with pnpm - Ladle React Source: https://github.com/tajo/ladle/blob/main/packages/ladle/README.md This snippet provides a step-by-step guide to quickly set up a new Ladle project using pnpm. It initializes a new project, installs necessary React and Ladle dependencies, creates a source directory, adds a basic React component story, and starts the Ladle development server. ```bash mkdir my-ladle cd my-ladle pnpm init pnpm add @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx pnpm ladle serve ``` -------------------------------- ### Starting Ladle Documentation Website Source: https://github.com/tajo/ladle/blob/main/CONTRIBUTING.md Navigates to the website package directory and starts the documentation site, allowing contributors to preview and verify changes to `ladle.dev`. ```sh cd packages/website pnpm start ``` -------------------------------- ### Quick Start with npm for Ladle Source: https://github.com/tajo/ladle/blob/main/README.md This snippet details the process for a quick setup of a new Ladle project using npm. It initializes a new project, installs dependencies, creates a source directory, and generates a basic React story file, then serves the Ladle development environment. ```bash mkdir my-ladle cd my-ladle npm init --yes npm install @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx npx ladle serve ``` -------------------------------- ### Setting Up a New Ladle Project with PNPM Source: https://github.com/tajo/ladle/blob/main/packages/website/blog/2022-03-15-introducing-ladle.md This snippet provides a step-by-step guide to quickly set up a new Ladle project using PNPM. It initializes a new project, installs necessary dependencies like @ladle/react, react, and react-dom, creates a basic React component story, and then starts the Ladle development server to view the component. ```bash mkdir my-ladle cd my-ladle pnpm init pnpm add @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx pnpm ladle serve ``` -------------------------------- ### Quick Start with pnpm for Ladle Source: https://github.com/tajo/ladle/blob/main/README.md This snippet provides a quick start guide to set up a new Ladle project using pnpm. It initializes a new project, installs necessary dependencies, creates a source directory, and generates a basic React story file before serving the Ladle development environment. ```bash mkdir my-ladle cd my-ladle pnpm init pnpm add @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx pnpm ladle serve ``` -------------------------------- ### Running Ladle Development Server Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/setup.mdx These commands start the Ladle development server, which automatically opens your browser. This mode is optimized for rapid component development and provides live reloading capabilities. ```bash pnpm ladle serve ``` ```bash npx ladle serve ``` ```bash yarn ladle serve ``` -------------------------------- ### Quick Start with npm - Ladle React Source: https://github.com/tajo/ladle/blob/main/packages/ladle/README.md This snippet details the procedure for quickly setting up a Ladle project using npm. It initializes a new project, installs React and Ladle dependencies, creates a source directory, adds a basic React component story, and starts the Ladle development server. ```bash mkdir my-ladle cd my-ladle npm init --yes npm install @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx npx ladle serve ``` -------------------------------- ### Quick Start with yarn - Ladle React Source: https://github.com/tajo/ladle/blob/main/packages/ladle/README.md This snippet outlines the process for rapidly setting up a Ladle project using yarn. It initializes a new project, installs React and Ladle dependencies, creates a source directory, adds a simple React component story, and launches the Ladle development server. ```bash mkdir my-ladle cd my-ladle yarn init --yes yarn add @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx yarn ladle serve ``` -------------------------------- ### Importing setupServer from Ladle's MSW Node Re-export Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/msw.mdx This snippet demonstrates how to import `setupServer` from Ladle's re-exported MSW Node module, `@ladle/react/msw-node`. This allows developers to use Ladle's bundled version of MSW for Node.js environment setup without needing to install MSW separately. ```js import { setupServer } from "@ladle/react/msw-node"; ``` -------------------------------- ### Installing Project Dependencies with pnpm Source: https://github.com/tajo/ladle/blob/main/CONTRIBUTING.md Installs all project dependencies for the Ladle monorepo after cloning the repository, leveraging pnpm workspaces. ```sh pnpm install ``` -------------------------------- ### Quick Start with yarn for Ladle Source: https://github.com/tajo/ladle/blob/main/README.md This snippet outlines the steps to quickly set up a new Ladle project using yarn. It initializes a new project, adds required dependencies, creates a source directory, and generates a basic React story file, then starts the Ladle development server. ```bash mkdir my-ladle cd my-ladle yarn init --yes yarn add @ladle/react react react-dom mkdir src echo "export const World = () => <p>Hey</p>;" > src/hello.stories.tsx yarn ladle serve ``` -------------------------------- ### Installing Sync-Fetch Source: https://github.com/tajo/ladle/blob/main/packages/website/blog/2022-08-08-visual-snapshots.md Installs the `sync-fetch` library, which is used to synchronously fetch Ladle's `meta.json` file, as Playwright tests cannot be created asynchronously. ```sh pnpm install sync-fetch ``` -------------------------------- ### Installing Ladle Dependencies Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/setup.mdx These commands add the @ladle/react package to your project using different package managers. Ladle expects `react` and `react-dom` to be pre-installed as peer dependencies. ```bash pnpm add @ladle/react ``` ```bash npm install @ladle/react ``` ```bash yarn add @ladle/react ``` -------------------------------- ### Previewing Ladle Production Build Locally Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/setup.mdx After building, these commands allow you to serve the production-optimized Ladle assets locally via an HTTP server. This is useful for verifying the built output before deployment. ```bash pnpm ladle preview ``` ```bash npx ladle preview ``` ```bash yarn ladle preview ``` -------------------------------- ### Installing Project Dependencies with pnpm Source: https://github.com/tajo/ladle/blob/main/packages/website/README.md This command installs all required project dependencies using the pnpm package manager. It prepares the development environment by fetching and linking all necessary packages. ```Shell pnpm install ``` -------------------------------- ### Installing Project Dependencies with Yarn Source: https://github.com/tajo/ladle/blob/main/e2e/addons/src/README.md This command installs all required project dependencies listed in the `package.json` file using Yarn, preparing the development environment after cloning the repository. ```sh yarn install ``` -------------------------------- ### Installing Playwright Test Source: https://github.com/tajo/ladle/blob/main/packages/website/blog/2022-08-08-visual-snapshots.md Installs the Playwright test runner, a headless browser testing framework used for navigating Ladle and capturing screenshots. ```sh pnpm install @playwright/test ``` -------------------------------- ### Installing Project Dependencies with Yarn Source: https://github.com/tajo/ladle/blob/main/e2e/babel/src/README.md This command installs all necessary project dependencies using Yarn, ensuring that the development environment is properly set up after cloning the repository. ```shell $ yarn install ``` -------------------------------- ### Installing pnpm v9 Globally Source: https://github.com/tajo/ladle/blob/main/CONTRIBUTING.md Installs pnpm version 9 globally on the system, which is required for managing dependencies in the Ladle monorepo. ```sh npm install -g pnpm@9 ``` -------------------------------- ### Installing Playwright Dependencies Source: https://github.com/tajo/ladle/blob/main/CONTRIBUTING.md Installs the necessary Playwright browser dependencies used for running end-to-end tests within the Ladle project. ```sh pnpm exec playwright install ``` -------------------------------- ### Starting Local Development Server with pnpm Source: https://github.com/tajo/ladle/blob/main/packages/website/README.md This command launches a local development server and automatically opens the website in a browser. It provides a live-reloading experience, reflecting most code changes instantly without requiring a server restart. ```Shell pnpm start ``` -------------------------------- ### Installing Project Dependencies with Yarn Source: https://github.com/tajo/ladle/blob/main/packages/example/src/README.md This Yarn command installs all required project dependencies listed in the `package.json` file. It prepares the development environment for the React component by resolving all necessary packages. ```shell yarn install ``` -------------------------------- ### Installing and Configuring mkcert for SSL Certificates (macOS) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/http2.md This snippet provides bash commands for macOS users to install mkcert using Homebrew, install a local certificate authority, and generate a new SSL certificate for localhost. These certificates are essential for enabling HTTP/2. It assumes Homebrew is already installed. ```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 ``` -------------------------------- ### Building Ladle Production Assets Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/setup.mdx These commands generate an optimized and minified production build of your Ladle stories, outputting assets into a `build` folder. This build is suitable for deployment or testing environments. ```bash pnpm ladle build ``` ```bash npx ladle build ``` ```bash yarn ladle build ``` -------------------------------- ### Starting Ladle Development Server Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/cli.md This section details the `ladle serve` (or `ladle dev`) command, used to start a development server. It includes options for specifying the host, port, glob patterns for stories, theme, configuration folder, Vite configuration file, base URL, Vite mode, and disabling the file system watcher. ```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 ``` -------------------------------- ### Installing Styled-components Dependencies Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/css.md This `pnpm` command installs the recommended packages for integrating Styled-components with Ladle. It includes `styled-components` itself, and `@swc/plugin-styled-components` along with `@vitejs/plugin-react-swc` for enhanced performance. ```sh pnpm add styled-components @swc/plugin-styled-components @vitejs/plugin-react-swc ``` -------------------------------- ### Installing BaseWeb and Styletron Dependencies Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/css.md This `pnpm` command installs the necessary packages for integrating BaseWeb and Styletron into your Ladle project. These include `baseui`, `styletron-react`, and `styletron-engine-monolithic`. ```sh pnpm add baseui styletron-react styletron-engine-monolithic ``` -------------------------------- ### Installing React Test Component with jz Source: https://github.com/tajo/ladle/blob/main/packages/example/src/README.md This command installs the `@test/react-test` package using the `jz` package manager, making the React component available for use in a project. It's a prerequisite for integrating the component. ```shell jz add @test/react-test ``` -------------------------------- ### Installing Emotion Dependencies Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/css.md This `pnpm` command installs the required packages for integrating Emotion with Ladle. It includes `@emotion/react` for styling, and `@swc/plugin-emotion` along with `@vitejs/plugin-react-swc` for optimized compilation. ```sh pnpm add @emotion/react @swc/plugin-emotion @vitejs/plugin-react-swc ``` -------------------------------- ### Installing React Test Component using jz Source: https://github.com/tajo/ladle/blob/main/e2e/babel/src/README.md This command installs the `@test/react-test` component using the `jz` package manager, making it available for use in the project. ```shell $ jz add @test/react-test ``` -------------------------------- ### Installing Playwright for Visual Testing Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/visual-snapshots.md This command installs Playwright, a headless browser testing framework, as a development dependency using pnpm. It is a prerequisite for setting up visual snapshot testing with Ladle. ```sh pnpm install @playwright/test ``` -------------------------------- ### Installing React Test Component Source: https://github.com/tajo/ladle/blob/main/e2e/addons/src/README.md This command installs the `@test/react-test` package using the `jz` package manager, making the React component available for use in a project. ```sh jz add @test/react-test ``` -------------------------------- ### Defining Default MSW Handlers and Mocked Story in Ladle Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/msw.mdx This example demonstrates how to define default MSW handlers for all stories using `export default { msw: [...] }` and how to create a story that fetches data from a mocked API endpoint. It uses `msw.http.get` to intercept a GET request and return mock JSON data, showcasing API mocking within a Ladle story. ```tsx import type { Story } from "@ladle/react"; import { msw } from "@ladle/react"; import { useEffect, useState } from "react"; const FETCH_URL = "/api-url.json"; // Set default handlers for all stories export default { msw: [ msw.http.get(FETCH_URL, () => { return msw.HttpResponse.json([{ id: 1, title: "msw post default" }]); }), ], }; export const Mocked: Story = () => { const [posts, setPosts] = useState([]); useEffect(() => { fetchData(); async function fetchData() { try { const data = await fetch(FETCH_URL); const json = await data.json(); setPosts(json); } catch (e) { console.error(e); } }; }, []); return ( <> <h1>Posts</h1> <ul> {posts.map((post: { id: number; title: string }) => ( <li key={post.id}>{post.title}</li> ))} </ul> </> ); }; ``` -------------------------------- ### Previewing Ladle Build Output Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/cli.md This section details the `ladle preview` command, used to start a local server for previewing a previously built static application. Options include specifying the output directory (`--outDir`), host, port, configuration folder, Vite configuration file, base URL, and Vite mode. ```bash Usage: ladle preview [options] start a server to preview the build in outDir Options: -o, --outDir <path> 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 ``` -------------------------------- ### Playwright Configuration for Web Server Source: https://github.com/tajo/ladle/blob/main/packages/website/blog/2022-08-08-visual-snapshots.md Configures Playwright to start a web server before running tests. It conditionally runs either `ladle serve` for development or `ladle build` followed by `ladle preview` for production-like testing, based on the `TYPE` environment variable. ```ts export default { webServer: { command: process.env.TYPE === "dev" ? "pnpm serve" : "pnpm build", url: `http://127.0.0.1:61000` } }; ``` -------------------------------- ### Creating a Basic Ladle Story in TSX Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/setup.mdx This snippet demonstrates how to define a simple Ladle story in a `.tsx` file. Ladle automatically discovers stories matching the glob `src/**/*.stories.{js,jsx,ts,tsx,mdx}`. This story exports a React component named `World`. ```tsx export const World = () => <p>Hey!</p>; ``` -------------------------------- ### Running Visual Snapshot Tests with pnpm Source: https://github.com/tajo/ladle/blob/main/e2e/playwright/README.md This snippet provides the pnpm commands to set up, build, run, and update visual snapshot tests using Ladle and Playwright. It covers dependency installation, building the Ladle project, executing tests, and updating baseline snapshots. ```sh pnpm install pnpm build #build ladle pnpm test #run tests pnpm test:update #update snapshots if there are changes ``` -------------------------------- ### Importing Ladle Components and Markdown - TypeScript/JavaScript Source: https://github.com/tajo/ladle/blob/main/packages/ladle/tests/fixtures/meta.stories.mdx This snippet imports the `Meta` component from `@ladle/react` for defining documentation metadata and a local `README.md` file, likely for rendering its content directly. This is a common pattern for structuring documentation in Ladle. ```TypeScript import { Meta } from "@ladle/react"; import Readme from "./README.md"; ``` -------------------------------- ### Setting up Ladle Documentation Page (TypeScript/JSX) Source: https://github.com/tajo/ladle/blob/main/e2e/addons/src/docs.stories.mdx This snippet demonstrates how to configure a documentation page using Ladle, importing core components like `Meta`, `Description`, and `Story`, and integrating a Markdown file (`README.md`) for content. It defines the page's metadata and renders the imported Markdown as part of the documentation, serving as a foundational setup for a documentation entry. ```TypeScript import { Meta, Description, Story } from "@ladle/react"; import Readme from "./README.md"; <Meta title="Documentation" /> <Readme /> ``` -------------------------------- ### Configuring Vite for Emotion with SWC Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/css.md This `vite.config.js` setup enables Emotion support by configuring `@vitejs/plugin-react-swc`. It specifies `@emotion/react` as the JSX import source and includes the `@swc/plugin-emotion` for proper transpilation. ```js import react from "@vitejs/plugin-react-swc"; export default { plugins: [ react({ jsxImportSource: "@emotion/react", plugins: [["@swc/plugin-emotion", {}]], }), ], }; ``` -------------------------------- ### Playwright Dynamic Snapshot Test Setup Source: https://github.com/tajo/ladle/blob/main/packages/website/blog/2022-08-08-visual-snapshots.md This Playwright test file dynamically generates individual tests for each story listed in Ladle's `meta.json` file. It navigates to each story, waits for it to load, and then takes a screenshot, comparing it against a baseline. Stories with `meta.skip` are skipped. ```ts 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://127.0.0.1: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 }) => { // skip stories with `meta.skip` set to true test.skip(stories[storyKey].meta.skip, "meta.skip is true"); // 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`); }); }); ``` -------------------------------- ### Explicit React Import for JSX Components Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/setup.mdx When using `.js` files for React components with JSX, an explicit import of `React` is required. This ensures that JSX syntax is correctly transpiled and understood by the JavaScript runtime. ```jsx import * as React from "react"; ``` -------------------------------- ### Running Ladle and Playwright Visual Snapshot Tests Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/visual-snapshots.md These commands build the Ladle project, start a preview server on port 61000, and then execute the Playwright tests. The Playwright tests will capture visual snapshots of Ladle stories, creating baselines on the first run and comparing against them on subsequent runs. ```sh pnpm ladle build pnpm ladle preview -p 61000 pnpm exec playwright test ``` -------------------------------- ### Adding a Changeset for Ladle Source: https://github.com/tajo/ladle/blob/main/CONTRIBUTING.md Initiates the process of adding a new changeset, which is used by Ladle to manage changelogs and releases, prompting for scope, version, and a description of the change. ```sh pnpm changeset ``` -------------------------------- ### Creating React Story File in PowerShell for Ladle Source: https://github.com/tajo/ladle/blob/main/README.md This PowerShell snippet provides an alternative command for creating the `hello.stories.tsx` file, specifically for Windows users. It writes the React component story content to the specified file, ensuring proper encoding. ```powershell @"\nexport const World = () => <p>Hey</p>;\n"@ | out-file -encoding ASCII src/hello.stories.tsx ``` -------------------------------- ### Ladle `meta.json` Structure Example (JSON) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/meta.md This snippet illustrates the default structure of Ladle's `meta.json` file, which is automatically generated. It includes general project information under `about` and detailed entries for each story, such as `name`, `filePath`, and an initial empty `meta` object for custom annotations. ```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": {} } } } ``` -------------------------------- ### Debugging Playwright E2E Tests with test.only Source: https://github.com/tajo/ladle/blob/main/CONTRIBUTING.md Illustrates how to use `test.only` in Playwright to run a specific end-to-end test, which is useful for debugging individual test cases. ```diff -test("a11y addon works", async ({ page }) => { +test.only("a11y addon works", async ({ page }) => { ``` -------------------------------- ### Defining Global Default Args and ArgTypes in Ladle (TypeScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/controls.mdx This example demonstrates how to set global `args` and `argTypes` in `.ladle/components.tsx`, which will apply to all stories across the entire project. This establishes a project-wide baseline for controls, with per-story and file-level settings taking precedence. ```tsx export const args = { label: "Hello world", }; export const argTypes = { cities: { options: ["Prague", "NYC"], control: { type: "check" }, }, }; ``` -------------------------------- ### Defining a Basic Ladle Story - JSX Source: https://github.com/tajo/ladle/blob/main/e2e/addons/src/mdx.stories.mdx Defines a simple Ladle story named 'First' that renders an input field and a basic button. This example illustrates a minimal story definition without additional arguments. ```jsx <Story name="First"> <input /> <button>simple</button> </Story> ``` -------------------------------- ### Running Ladle Project Tests and Checks Source: https://github.com/tajo/ladle/blob/main/CONTRIBUTING.md Executes various checks and tests across the Ladle monorepo, including type checking, linting, building, and running unit/e2e tests, ensuring code quality before creating a pull request. ```sh # root pnpm typecheck pnpm lint # root or individual packages pnpm build pnpm test ``` -------------------------------- ### Setting Ladle Default Story (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Configures which story is loaded by default when Ladle starts, corresponding to the `?story=` URL parameter. An empty string loads the first story alphabetically. The `defaultStory` property accepts a string representing a story ID. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { defaultStory: "a11y--welcome" }; ``` -------------------------------- ### Using Ladle's Programmatic API for Serve, Build, and Preview in TypeScript Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/programmatic.md This snippet illustrates how to programmatically control Ladle's lifecycle using its JavaScript/TypeScript API. It imports and utilizes the `serve`, `build`, and `preview` functions from `@ladle/react`, enabling automated operations like starting a development server, creating a production build, or launching a preview server. Each function can accept an optional configuration object to customize its behavior. ```tsx 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: {} }); ``` -------------------------------- ### Defining Ladle Documentation Page Title - JSX Source: https://github.com/tajo/ladle/blob/main/packages/ladle/tests/fixtures/meta.stories.mdx This JSX snippet utilizes the imported `Meta` component to set the title for the current documentation page within Ladle. The `title` prop specifies the display name for the documentation entry in the Ladle UI. ```JSX <Meta title="Documentation" /> ``` -------------------------------- ### Defining a CSS Module in CSS Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/css.md This example shows the structure of a CSS module file, typically ending with `.module.css`. When imported, such a file returns a module object containing the defined class names. ```css /* example.module.css */ .red { color: red; } ``` -------------------------------- ### Creating Multiple Stories with Different Args in Ladle (TypeScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/controls.mdx This example illustrates how to generate multiple distinct stories from a single component by binding the component and assigning different `args` to each story. This allows for showcasing various states or configurations of the same component without duplicating the component's definition. ```tsx import type { Story } from "@ladle/react"; const Card: Story<{ label: string; }> = ({ label }) => <p>Label: {label}</p>; export const CardHello = Card.bind({}); CardHello.args = { label: "Hello", }; export const CardWorld = Card.bind({}); CardWorld.args = { label: "World", }; ``` -------------------------------- ### Configuring PostCSS for Tailwind CSS Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/css.md This `postcss.config.js` configuration enables Tailwind CSS and Autoprefixer for processing CSS files. Ladle automatically applies this PostCSS setup if a valid configuration file is present in the project. ```js module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, }; ``` -------------------------------- ### Updated `meta.json` with Custom Annotations (JSON) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/meta.md This `meta.json` snippet shows the result of applying custom metadata as demonstrated in the `control.stories.tsx` example. It highlights how the `meta` object for a specific story, `control--first`, is populated with the combined annotations, with story-level `meta` taking precedence. ```json { "stories": { "control--first": { "name": "First", "levels": ["Control"], "locStart": 8, "locEnd": 8, "filePath": "src/control.stories.tsx", "meta": { "baseweb": "test", "browsers": ["firefox"] } } } } ``` -------------------------------- ### Injecting Custom Styles into Ladle Head (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Allows injecting arbitrary HTML content directly into the `<head>` section of the Ladle application. This example demonstrates adding a simple `<style>` block to change the color of `<h1>` elements to pink, useful for quick UI customizations. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { appendToHead: "<style>h1 {color:pink}</style>" }; ``` -------------------------------- ### Customizing Ladle UI Margins (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Injects CSS into the `<head>` to modify Ladle's default UI styling. This specific example sets the `--ladle-main-padding` and `--ladle-main-padding-mobile` CSS variables to `0`, effectively removing margins around stories for a full-bleed layout. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { appendToHead: `<style> :root {--ladle-main-padding: 0; --ladle-main-padding-mobile: 0;} </style>` }; ``` -------------------------------- ### Changing Ladle Theme with useLadleContext Hook in React Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/providers.md This example illustrates the use of the experimental `useLadleContext` hook to access and modify Ladle's internal `globalState` and `dispatch` function. It shows how a story can inspect the current theme and toggle it between light and dark modes, demonstrating control over Ladle's addon state directly from within a component. ```TypeScript import { useLadleContext, ActionType, ThemeState } from "@ladle/react"; export const StoryChangingTheTheme = () => { const { globalState, dispatch } = useLadleContext(); return ( <> <p>Active theme: {globalState.theme}</p> <button onClick={() => dispatch({ type: ActionType.UpdateTheme, value: globalState.theme === ThemeState.Dark ? ThemeState.Light : ThemeState.Dark, }) } > Switch theme </button> </> ); }; ``` -------------------------------- ### Importing setupServer from msw/node Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/msw.mdx This snippet shows the standard way to import `setupServer` from the `msw/node` package. This import is typically used when setting up MSW in a Node.js environment for server-side mocking, allowing interception of network requests in a Node context. ```js import { setupServer } from 'msw/node' ``` -------------------------------- ### Configuring Global Background Control in Ladle (TypeScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/background.md This TypeScript snippet defines a global `background` control within `.ladle/components.tsx` for Ladle stories. It makes a set of predefined background color options available across all stories through the UI, with 'purple' as the default. This setup provides a consistent canvas background for the entire project. ```TypeScript export const argTypes = { background: { control: { type: "background" }, options: ["purple", "blue", "white", "pink"], defaultValue: "purple" } }; ``` -------------------------------- ### Building Static Website Content with pnpm Source: https://github.com/tajo/ladle/blob/main/packages/website/README.md This command generates the static assets for the website, compiling them into the `build` directory. The resulting content is ready to be served by any standard static content hosting service. ```Shell pnpm build ``` -------------------------------- ### Displaying Ladle CLI Help Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/cli.md This snippet shows the general usage of the `ladle` CLI, listing the main commands available: `serve` (or `dev`), `build`, and `preview`. It also indicates the `--help` option for displaying overall command help. ```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 ``` -------------------------------- ### Deploying Website to GitHub Pages with pnpm Source: https://github.com/tajo/ladle/blob/main/packages/website/README.md This command is a convenient utility for building the website and pushing the generated content to the `gh-pages` branch, specifically for hosting on GitHub Pages. It requires setting the `GIT_USER` environment variable and enabling SSH for deployment. ```Shell GIT_USER=<Your GitHub username> USE_SSH=true pnpm deploy ``` -------------------------------- ### Building Ladle Static Production App Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/cli.md This snippet describes the `ladle build` command, which compiles the application into a static production-ready output. Key options include defining the output directory (`--outDir`), specifying story glob patterns, theme, configuration folder, Vite configuration file, base URL, and Vite mode. ```bash Usage: ladle build [options] build static production app Options: -o, --outDir <path> 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 ``` -------------------------------- ### Package.json Scripts for Ladle and Playwright Source: https://github.com/tajo/ladle/blob/main/packages/website/blog/2022-08-08-visual-snapshots.md Defines npm scripts to streamline the Ladle build, serve, and Playwright test execution. Includes commands for development, production-like testing, and updating visual snapshots. ```json { "scripts": { "serve": "ladle serve", "build": "ladle build && ladle preview -p 61000", "test:dev": "TYPE=dev pnpm exec playwright test", "test": "pnpm exec playwright test", "test:update": "pnpm exec playwright test -u" } } ``` -------------------------------- ### Moving Ladle Side Navigation (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Injects CSS into the `<head>` to alter the layout of the Ladle UI. This example changes the `flex-direction` of the `.ladle-wrapper` to `row-reverse`, which effectively moves the side navigation from the right to the left side of the interface. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { appendToHead: `<style> .ladle-wrapper { flex-direction: row-reverse; } </style>` }; ``` -------------------------------- ### Setting Ladle Story Order (Default) (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Configures the default alphabetical sorting of stories in the navigation, prioritizing folders. This example shows the default behavior where stories are returned as-is. The `storyOrder` property accepts a function that receives the stories array. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { // note that alphabetically sorted stories are provided storyOrder: (stories) => stories }; ``` -------------------------------- ### Cloning Project Repository for Development Source: https://github.com/tajo/ladle/blob/main/packages/example/src/README.md This Git command clones the project repository from `gitolite@code.test`, allowing developers to obtain the source code for local development and contribution to the component. ```shell git clone gitolite@code.test ``` -------------------------------- ### Configuring Vite Path in Ladle (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Overrides the default path for the Vite configuration file. By default, Ladle checks `vite.config.{js|mjs|ts}` and `vite.config.ts` in the project root. This option allows specifying a custom path, useful for projects with non-standard Vite setups. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { viteConfig: process.cwd() + "/ladle-vite.config.ts" }; ``` -------------------------------- ### Cloning Project Repository Source: https://github.com/tajo/ladle/blob/main/e2e/babel/src/README.md This shell command clones the project repository from `gitolite@code.test`, which is the first step in setting up the development environment for the component. ```shell $ git clone gitolite@code.test ``` -------------------------------- ### Creating a Basic MDX Story in Ladle Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/mdx.mdx This snippet demonstrates how to create a simple MDX story file (`basic.stories.mdx`) in Ladle. It includes basic Markdown elements like headers, blockquotes, links, and ordered lists, which will be rendered as a 'Readme' story under 'Basic' in the navigation. ```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 ``` -------------------------------- ### Creating Basic Button Story - JSX Source: https://github.com/tajo/ladle/blob/main/packages/example/src/mdx.stories.mdx Defines a simple UI story named 'First' within Ladle, rendering an `<input>` element and a basic `<button>`. This demonstrates a straightforward component rendering without dynamic properties, suitable for initial component visualization. ```jsx <input />\n <button>simple</button> ``` -------------------------------- ### Adding Service with Yarn Source: https://github.com/tajo/ladle/blob/main/e2e/addons/src/README.md This command executes `yarn add-service`, which is likely used to add a new service or dependency within the project's development environment, possibly related to backend integration. ```sh yarn add-service ``` -------------------------------- ### Importing Markdown Readme - JavaScript Source: https://github.com/tajo/ladle/blob/main/packages/example/src/docs.stories.mdx This snippet imports a local Markdown file (`./README.md`) as a component. This allows the content of the Markdown file to be rendered directly within the Ladle documentation page, facilitating the reuse of existing documentation. ```JavaScript import Readme from "./README.md"; ``` -------------------------------- ### Adding Service with Yarn Source: https://github.com/tajo/ladle/blob/main/packages/example/src/README.md This command is used to add a service, likely a dependency or a specific configuration, within a project using Yarn. It's mentioned as a step before adding the React component. ```shell yarn add-service ``` -------------------------------- ### Adding Service with Yarn Source: https://github.com/tajo/ladle/blob/main/e2e/babel/src/README.md This command is used to add a service, likely related to the `Test` component's backend interactions, using Yarn. It's part of setting up the stateful version of the component. ```shell yarn add-service ``` -------------------------------- ### Importing Ladle Core Components - JavaScript Source: https://github.com/tajo/ladle/blob/main/packages/example/src/docs.stories.mdx This snippet imports essential components (Meta, Description, Story) from the `@ladle/react` library. These components are fundamental for defining metadata, providing descriptions, and structuring stories within a Ladle documentation page. ```JavaScript import { Meta, Description, Story } from "@ladle/react"; ``` -------------------------------- ### Setting Per-Story Viewport Width in Ladle Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/width.mdx This TypeScript example shows how to set a specific viewport width for individual stories using the `meta` property. It supports both named widths (e.g., 'xsmall') and direct pixel values, overriding global configurations for fine-grained control. ```ts import type { StoryDefault, Story } from "@ladle/react"; export default { meta: { width: "xsmall" // name or number can be used } } satisfies StoryDefault; // viewport width = 414px export const First: Story = () => <h1>First</h1>; // viewport width = 345px export const Second: Story = () => <h1>Second</h1>; Second.meta = { width: 345 }; ``` -------------------------------- ### Setting up BaseWeb and Styletron Global Provider in Ladle Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/css.md This `.ladle/components.tsx` snippet defines a global provider for BaseWeb and Styletron. It integrates Ladle's theme (dark/light) and RTL state, ensuring consistent styling across all stories and dynamic theme switching. ```tsx 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 }) => ( <StyletronProvider value={engine}> <BaseProvider theme={{ ...(globalState.theme === "dark" ? DarkTheme : LightTheme), direction: globalState.rtl ? "rtl" : "ltr", }} > {children} </BaseProvider> </StyletronProvider> ); ``` -------------------------------- ### Setting Playwright Viewport for Ladle Tests Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/width.mdx This TypeScript example shows how to configure the viewport size for Playwright tests using `test.use()`. This allows simulating specific screen dimensions during automated testing of Ladle stories, ensuring components behave correctly across different viewports. ```ts import { test, expect } from "@playwright/test"; test.use({ viewport: { width: 600, height: 900 } }); test("my portrait test", async ({ page }) => { // ... }); ``` -------------------------------- ### Creating a Basic UI Story - Ladle React - JSX Source: https://github.com/tajo/ladle/blob/main/e2e/babel/src/mdx.stories.mdx This `Story` block defines a simple UI component story named 'First'. It renders an `<input />` element and a basic `<button>` with the text 'simple', demonstrating a minimal, unconfigured component state within Ladle. ```jsx <Story name="First"> <input /> <button>simple</button> </Story> ``` -------------------------------- ### Cloning Project Repository Source: https://github.com/tajo/ladle/blob/main/e2e/addons/src/README.md This command clones the project repository from `gitolite@code.test` using Git, allowing developers to obtain the source code for local development. ```sh git clone gitolite@code.test ``` -------------------------------- ### Rendering Test Component with Props in JSX Source: https://github.com/tajo/ladle/blob/main/packages/example/src/README.md This JSX snippet demonstrates how to render the `Test` React component. It configures an `onNodeChange` callback to log selected node details and sets the `maxWidth` prop to '100%', illustrating basic component usage. ```jsx <Test onNodeChange={({ name, uuid }) => console.log(`Node selected ${name}`)} maxWidth="100%" /> ``` -------------------------------- ### Rendering Imported Readme - JSX Source: https://github.com/tajo/ladle/blob/main/packages/example/src/docs.stories.mdx This JSX snippet renders the `Readme` component, which was previously imported from `./README.md`. This action embeds the entire content of the Markdown file directly into the current documentation page, making it visible to the user. ```JSX <Readme /> ``` -------------------------------- ### Importing Ladle React Components - JavaScript Source: https://github.com/tajo/ladle/blob/main/e2e/babel/src/docs.stories.mdx This snippet imports core components (Meta, Description, Story) from the @ladle/react library. These components are essential for defining metadata, adding descriptions, and creating interactive stories within a Ladle documentation environment. ```JavaScript import { Meta, Description, Story } from "@ladle/react"; ``` -------------------------------- ### Rendering Imported Markdown Content - JSX Source: https://github.com/tajo/ladle/blob/main/e2e/babel/src/docs.stories.mdx This JSX snippet renders the Readme component, which was previously imported from ./README.md. This action displays the content of the Markdown file directly on the Ladle documentation page, integrating external documentation seamlessly. ```JSX <Readme /> ``` -------------------------------- ### Importing Local Markdown File - JavaScript Source: https://github.com/tajo/ladle/blob/main/e2e/babel/src/docs.stories.mdx This snippet imports a local Markdown file (./README.md) as a React component. This pattern allows Markdown content to be directly embedded and rendered within a Ladle documentation page, facilitating easy inclusion of project documentation. ```JavaScript import Readme from "./README.md"; ``` -------------------------------- ### Setting Base Path for Ladle Build (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Defines the base path for the built output of Ladle. This is particularly useful for deploying the storybook to subdirectories, such as GitHub Pages. The value must be serializable. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { base: "/my-project/" }; ``` -------------------------------- ### Defining a Basic Button Story - JSX Source: https://github.com/tajo/ladle/blob/main/packages/ladle/tests/fixtures/story.stories.mdx Defines a simple Ladle story named 'First' within an MDX file. This story renders a basic HTML input element followed by a standard button with the text 'simple'. ```JSX <Story name="First"> <input /> <button>simple</button> </Story> ``` -------------------------------- ### Setting Ladle Preview Server Host (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Specifies the host address for the Ladle preview server. This controls the network interface for the static preview build. The `previewHost` property accepts a string representing an IP address. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { previewHost: "0.0.0.0" }; ``` -------------------------------- ### Defining React Stories for Ladle Source: https://github.com/tajo/ladle/blob/main/packages/website/blog/2022-08-08-visual-snapshots.md Defines two simple React components as stories for Ladle. The `Second` story is marked with `meta.skip = true` to demonstrate how to skip specific stories during testing. ```tsx export const First = () => { return <h1>First</h1>; }; export const Second = () => { return <h1>Second</h1>; }; Second.meta = { skip: true, }; ``` -------------------------------- ### Setting Meta Parameters for Ladle MDX Stories Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/mdx.mdx This snippet demonstrates how to apply global and story-specific meta parameters using the `<Meta>` and `<Story>` components in Ladle MDX. The `meta` prop allows configuring rendering options, such as `iframed` for the entire file or `width` for individual stories, influencing how they are displayed in the Ladle UI. ```MDX import { Story, Meta } from "@ladle/react"; <Meta meta={{ iframed: true }} /> This part will be rendered as a separate `Readme` story. <Story name="First"> <input /> <button>simple</button> </Story> <Story name="Second" meta={{ width: 400 }}> <input /> <button>second</button> </Story> ``` -------------------------------- ### Setting Ladle Output Directory (JavaScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/config.md Specifies the output directory for Ladle's build artifacts, relative to the project root. This allows customizing where the compiled preview files are placed. The `outDir` property accepts a string representing a path. ```JavaScript /** @type {import('@ladle/react').UserConfig} */ export default { outDir: "build" }; ``` -------------------------------- ### Configuring Vite to Alias Next.js Image and Link Components Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/nextjs.md This Vite configuration snippet sets up aliases for `next/image` and `next/link` to custom unoptimized components. This is necessary because Ladle has its own build process and doesn't apply Next.js's build-time transformations, allowing these components to function correctly within Ladle stories. ```tsx 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") } } }); ``` -------------------------------- ### Creating Argument-Driven Button Story - JSX Source: https://github.com/tajo/ladle/blob/main/packages/example/src/mdx.stories.mdx Defines a UI story named 'Second' that accepts arguments, specifically `disabled: true`, for the `<Story>` component. It renders an `<input>` and a `<button>`, illustrating how to configure story behavior and component props via Ladle's `args` mechanism. ```jsx <input />\n <button>second</button> ``` -------------------------------- ### Setting File-Level Default Args and ArgTypes in Ladle (TypeScript) Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/controls.mdx This snippet shows how to define default `args` and `argTypes` that apply to all stories within a single file. This provides a convenient way to set common control configurations, which can then be overridden by per-story definitions. ```tsx export default { args: { label: "Hello world", }, argTypes: { cities: { options: ["Prague", "NYC"], control: { type: "check" }, }, }, }; ``` -------------------------------- ### Importing Story Component - JavaScript Source: https://github.com/tajo/ladle/blob/main/packages/ladle/tests/fixtures/story.stories.mdx Imports the `Story` component from the `@ladle/react` library, which is essential for defining interactive UI component stories directly within MDX files. ```JavaScript import { Story } from "@ladle/react"; ``` -------------------------------- ### Importing Ladle Components - TypeScript Source: https://github.com/tajo/ladle/blob/main/packages/example/src/mdx.stories.mdx Imports `Story` and `Meta` from `@ladle/react`, crucial for defining UI component stories and metadata within Ladle's development environment. These components enable structured story creation for React components. ```typescript import { Story, Meta } from "@ladle/react"; ``` -------------------------------- ### Configuring Vite for HTTP/2 with Local SSL Certificates Source: https://github.com/tajo/ladle/blob/main/packages/website/docs/http2.md This TypeScript snippet demonstrates how to configure vite.config.ts to enable HTTPS for the Vite development server. It reads the localhost-key.pem and localhost.pem files, generated by mkcert, to provide the necessary SSL key and certificate for HTTP/2. The server will then run over HTTPS/HTTP/2. ```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") } } }); ```