Astrobook is a UI component playground that supports multiple frameworks, including React, Vue, Preact, Svelte, Solid, Lit, and Astro. It offers a unified environment to develop, test, and showcase components.
-
An example of using multiple UI rendering frameworks (React, Preact, Vue, Svelte, Solid, Lit, Astro) with Astrobook.
Online demo: astrobook.pages.dev
-
An example of using custom
<head>tags with Astrobook. -
An example that shows how to add Astrobook into an existing Astro project.
-
An example of using TailwindCSS with Astrobook.
-
An example of using UnoCSS with Astrobook.
-
An example of using a custom homepage with Astrobook.
-
An example of using PandaCSS with Astrobook.
Note
Astrobook supports various frameworks. We use React as an example here but you can also use other frameworks like Vue, Preact, Svelte, Solid, Lit, etc. Check the Astro docs for other integrations.
-
Install the packages
npm install astro @astrojs/react astrobook
-
Create
astro.config.mjsand add theastrobookintegration// astro.config.mjs import react from '@astrojs/react' import { defineConfig } from 'astro/config' import astrobook from 'astrobook' // https://astro.build/config export default defineConfig({ integrations: [react(), astrobook()], })
-
Add scripts to your
package.json"scripts": { "dev": "astro dev", "build": "astro build", "preview": "astro preview" }
Please refer to the Astro docs for more information on these commands.
-
Update your
.gitignorefile to exclude the build output.# build output dist/ # generated types .astro/
-
Write stories. Astrobook scans all
.stories.{ts,tsx,js,jsx,mts,mjs}files. It's compatible with a limited subset of Storybook's Component Story Format v3. In particular,args,decorators, andparametersproperties are supported. Every component story file consists of a required default export and one or more named exports.// src/components/Button.stories.ts import { Button, type ButtonProps } from './Button.tsx' export default { component: Button, } export const PrimaryButton = { args: { variant: 'primary' } satisfies ButtonProps, } export const SecondaryButton = { args: { variant: 'secondary' } satisfies ButtonProps, }
-
Run
npm run devand openhttp://localhost:4321to see your stories.
Render a component with every value of a prop in one story:
// Badge.stories.ts
import Badge from './Badge.astro'
export default { component: Badge }
export const AllSizes = {
args: { label: 'New' },
variants: { size: ['sm', 'md', 'lg'] },
}
export const ColorsAndSizes = {
args: { label: 'New' },
variants: {
size: { Small: 'sm', Medium: 'md', Large: 'lg' },
color: ['neutral', 'accent'],
},
}Each axis is a non-empty array or a non-empty record mapping display labels to prop values. Arrays use String(value) as labels, or JSON.stringify for objects and arrays. Axis key order determines the cartesian product: one axis renders a wrapping row of labeled figures; two or more axes render a table with the last axis as columns. Other axes form the rows, with labels joined by /.
Cell values override args, and each cell receives the story's slots. Framework cells hydrate as separate islands. Global decorators wrap the whole grid once; the story's own decorators wrap each cell. Stories without variants, or with an empty variants object, render as usual.
Style the grid through .astrobook-variants, .astrobook-variants-cell, and .astrobook-variants-label. The scoped defaults use :where() so your project styles can override them. Variant stories also include variants: { size: ['Small', 'Medium', 'Large'], color: ['neutral', 'accent'] } in meta.json, using the displayed axis labels for visual test names.
Decorators are objects that have a property for the component and the props that will be passed to it on render. This component must have a slot for children to be rendered. Currently, decorators only support styling changes and are not able to change a component's context or any client-side behaviors. Any decorators are rendered into HTML by Astro and sent to the client.
You can use decorators to wrap a component with a custom style.
For example, this is a React decorator that adds a green border to a component and an Astro decorator that adds a red border to a component.
// ReactGreenBorderDecorator.tsx
import type { ComponentChildren } from 'react'
export function GreenBorderDecorator({
width = 2,
children,
}: {
width?: number
children?: ComponentChildren
}) {
return <div style={{ border: `solid ${width}px green` }}>{children}</div>
}<!-- AstroRedBorderDecorator.astro -->
<div style="border: solid 2px red;">
<slot />
</div>In your stories, you can use the decorators like this:
// Button.stories.tsx
import RedBorderDecorator from './AstroRedBorderDecorator.astro'
import { Button, type ButtonProps } from './Button.tsx'
import { GreenBorderDecorator } from './ReactGreenBorderDecorator.tsx'
export default {
component: Button,
}
export const PrimaryButton = {
args: { variant: 'primary' } satisfies ButtonProps,
decorators: [
{ component: GreenBorderDecorator, props: { width: 10 } },
{ component: RedBorderDecorator },
],
}This will render the button, wrapped in a red border, which is then wrapped in a green border.
Parameters are free-form data passed to global decorators through the story.parameters prop. Set defaults in the default export and override them in individual stories. The merge is shallow: a story's value replaces the default value for the same key.
export default {
component: Button,
parameters: { theme: 'light', layout: 'centered' },
}
export const Dark = {
parameters: { theme: 'dark' },
}The Dark story's parameters are { theme: 'dark', layout: 'centered' }. Both exports accept null or omitted parameters.
A story's slots property fills the component's slots, keyed by slot name. Use default for the default slot. A slot takes an HTML string, a component, an object with a component and the props to pass to it, or an array of these, rendered in order.
<!-- Card.astro -->
<article>
<header><slot name="header" /></header>
<slot />
</article>// Card.stories.ts
import Badge from './Badge.astro'
import Card from './Card.astro'
export default {
component: Card,
}
export const WithText = {
slots: {
header: '<h2>Kitchen notes</h2>',
default: '<p>A surface for <strong>content</strong>.</p>',
},
}
export const WithBadge = {
slots: {
header: { component: Badge, props: { label: 'New' } },
default: Badge,
},
}
export const WithBadgeAndText = {
slots: {
default: [{ component: Badge, props: { label: 'New' } }, 'Kitchen notes'],
},
}Slots work for framework components too: Astro passes them the way it passes slots from an .astro file, so a React component gets the default slot as children. Slot content is rendered into HTML by Astro, so components in a slot are not hydrated.
Set title on the default export to label the module, and name on a story to label it in the sidebar, search, and browser tab:
export default { component: Button, title: 'Action buttons' }
export const Large = { name: 'Large button', args: { size: 'large' } }Labels can also come from story helper calls. Both fields accept a string or undefined; omitted labels fall back to the file name and export name. IDs and URLs always use the file path and export name. Single-story hoisting still compares those original names, and its label uses the story name, then module title, then file name.
Decorators receive the display label as story.name and the module label as story.module.title; story.module.name keeps the original file name.
Stories named the same as their module will get automatically hoisted up to replace their parent component in the UI, if they're the only story exported from their module.
This helps avoid redundant nesting in the sidebar (e.g. Button/Button):
// Button.stories.ts
import { Button as ButtonComponent } from './Button.tsx'
export default {
component: ButtonComponent,
}
// Single named export.
// Export name matches module name (Button.stories.ts)
export const Button = {}This story will not get nested to Button/Button in the UI, but simply Button.
Astrobook exposes <Astro base>/<Astrobook subpath>/meta.json in development and production. Its stories array follows sidebar order and includes display names, module details, merged JSON-safe parameters, preview url, and dashboardUrl. Unsupported parameter values are omitted according to JSON.stringify; serialization failures emit a warning and use {} for that story.
Story pages set data-astrobook-story-loaded on <html> after fonts load, client:load, client:idle, and client:only islands hydrate, and two animation frames pass. This also works with dashboard navigation. It does not wait for client:visible or client:media islands.
Install Playwright (npm install -D @playwright/test and npx playwright install), start Astrobook, and save this as tests/visual.spec.ts. Run it with npx playwright test --update-snapshots to create baselines, then npx playwright test to compare them.
import { expect, test } from '@playwright/test'
const origin = 'http://localhost:4321'
// Include your Astro base and Astrobook subpath here, if configured.
const metaUrl = `${origin}/meta.json`
interface Story {
id: string
url: string
parameters: { screenshot?: boolean }
}
test('story screenshots', async ({ page, request }) => {
test.setTimeout(0)
const response = await request.get(metaUrl)
expect(response.ok()).toBe(true)
const { stories }: { stories: Story[] } = await response.json()
for (const story of stories) {
if (story.parameters.screenshot === false) continue
await test.step(story.id, async () => {
await page.goto(new URL(story.url, origin).href)
await page.locator('html[data-astrobook-story-loaded]').waitFor()
await expect(page).toHaveScreenshot(
`${story.id.replaceAll('/', '--')}.png`,
)
})
}
})Setting parameters: { screenshot: false } is a convention used by this test suite to skip a story; Astrobook itself does not interpret that parameter. Configure Playwright timeouts to suit your stories; the readiness signal has no timeout.
You can use the directory option to specify the directory to scan for stories. The default directory is current working directory.
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
export default defineConfig({
integrations: [
astrobook({
directory: 'src/components',
}),
/* ...other integrations */
],
})You can run Astrobook as a standalone app. You can also add it to your existing Astro project. In the latter case, you can use the subpath option to specify the subpath of Astrobook.
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
export default defineConfig({
integrations: [
astrobook({
subpath: '/playground',
}),
],
})In the example above, Astrobook will be available at http://localhost:4321/playground.
Notice that the subpath option is relative to your Astro project's base path. For example, if you configure both Astro's base and astrobook's subpath, like so:
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
export default defineConfig({
base: '/docs',
integrations: [
astrobook({
subpath: '/playground',
}),
],
})Your Astro project will be available at http://localhost:4321/docs and Astrobook will be available at http://localhost:4321/docs/playground.
You can customize the styles by using the css option to specify the CSS files to be imported into your Astrobook site.
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
export default defineConfig({
integrations: [
astrobook({
css: [
// Relative path to your custom CSS file
'./src/styles/custom.css',
],
}),
],
})Wrap every story with Astro or framework components. Paths can be relative to the project root or package identifiers. Defaults to [].
astrobook({
decorators: ['./src/decorators/StoryContext.astro'],
})The first entry is outermost. Global decorators wrap outside the story's own decorators. Each receives one prop, story, with the story's id, export name, module id, name, and directory, and merged parameters.
---
import type { StoryContext } from '@astrobook/types'
interface Props {
story: StoryContext
}
const { story } = Astro.props
---
<div data-theme={story.parameters.theme} data-story-id={story.id}>
<slot />
</div>Set the viewport presets shown above dashboard stories. The default presets are Mobile (375px), Tablet (768px), and Desktop (1440px). Select a preset to render the story in an iframe at that width, so CSS media queries use the selected viewport. Full restores the inline story. The selected name is saved in local storage and restored when navigating between stories or reloading.
astrobook({
viewports: [
{ name: 'Phone', width: 390, height: 844 },
{ name: 'Laptop', width: 1280 },
],
})Widths and optional heights are positive integers in CSS pixels. Without a height,
the preview fills the remaining dashboard height. Names must be non-empty and
unique. A saved name missing from the configured presets falls back to Full.
Set viewports: false or viewports: [] to hide the toolbar. The toolbar appears
only on dashboard story pages; preview pages render stories directly.
You can further customize your Astrobook project by providing a custom head options. It's a path to an Astro component that includes custom tags to the <head> of your Astrobook site. It should only include elements permitted inside <head>, like <link>, <style>, <script>, etc.
Below is an example of a custom head component that configures the global styles and fonts.
<!-- Load custom fonts -->
<link rel="preconnect" href="https://rsms.me/" />
<link rel="stylesheet" href="https://rsms.me/inter/inter.css" />
<!-- Apply global styles -->
<style is:global>
html {
font-family: 'Inter', sans-serif;
}
</style>// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
export default defineConfig({
integrations: [
astrobook({
// Relative path to your custom head component
head: './src/components/CustomHead.astro',
}),
],
})You can customize the homepage by providing a path to an Astro component using the home option. This component will be rendered on the dashboard homepage instead of the default one.
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
export default defineConfig({
integrations: [
astrobook({
home: './src/components/CustomHome.astro',
}),
],
})Customize the content of the built-in home page without replacing it entirely. You can configure the title, subtitle, version badge, and repository badge. Each field can be set to a custom value, set to false to hide it, or omitted to use the default.
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
import { version } from './package.json'
export default defineConfig({
integrations: [
astrobook({
homeContent: {
title: 'Acme UI',
subtitle: 'Internal component library',
// Display your project's own version and link to your own changelog.
version: {
label: `v${version}`,
href: 'https://example.com/CHANGELOG',
},
// Customize the repository badge.
repo: {
href: 'https://github.com/acme/ui',
label: 'View on GitHub',
},
},
}),
],
})| Field | Type | Default | Description |
|---|---|---|---|
title |
string | false |
'Astrobook' |
Main heading on the home page. |
subtitle |
string | false |
'The minimal UI component playground' |
Text below the title. |
version |
object | false |
{} (shows Astrobook version) |
Version badge configuration. |
version.href |
string |
Astrobook CHANGELOG URL | Link target for the badge. |
version.label |
string |
Current Astrobook version (e.g. v0.12.7) |
Text displayed in the badge. |
repo |
object | false |
{} (links to Astrobook repo) |
Repository badge configuration. |
repo.href |
string |
'https://github.com/ocavue/astrobook' |
Link target for the badge. |
repo.label |
string |
'Star on GitHub' |
Text displayed in the badge. |
This option is only used when home is left at its default value. If you provide a custom home component or set home: false, homeContent is ignored.
You can set the title for your website.
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
export default defineConfig({
integrations: [
astrobook({
title: 'My Components Playground',
}),
],
})You can enable Astrobook only on development by using the process.env.NODE_ENV
to conditionally include the astrobook integration. This is useful when you
want to include Astrobook in your existing Astro project but don't want to build
it in production.
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'
// https://astro.build/config
export default defineConfig({
integrations: [
// On development, Astrobook is available at http://localhost:4321/astrobook.
// On production, Astrobook is not included.
process.env.NODE_ENV === 'development'
? astrobook({ subpath: '/astrobook' })
: null,
],
})If you're running Astrobook in an iframe, you can toggle the theme via a message.
const theme = 'light' // or "dark"
iframe.contentWindow.postMessage({ type: 'astrobook:set-theme', theme }, '*')MIT