# Stories

Live previews of Vue components.

`@vuesho/story` adds a live preview of a Vue component to a page, with controls generated from its prop and slot types. Change a control below:

**Callout**

| Prop        | Type                                                              |
| ----------- | ----------------------------------------------------------------- |
| `title?`    | `string`                                                          |
| `type?`     | `"info" \| "warn" \| "error" \| "success" \| "warning" \| "idea"` |
| `icon?`     | `string`                                                          |
| `#icon?`    | `string`                                                          |
| `#title?`   | `string`                                                          |
| `#default?` | `string`                                                          |

## Setup [#setup]

### Install the Packages [#install-the-packages-step]

The plugin needs TypeScript 6's JavaScript API, which TypeScript 7 doesn't have:

```npm
npm i @vuesho/story
npm i -D typescript@6
```

### Add the Plugin [#add-the-plugin-step]

```ts title="vuesho.config.ts"
import { createSite, recommendedPreset } from "vuesho/config";
import { defineDocs } from "vuesho/content";
import { storyPlugin } from "@vuesho/story"; // [!code ++]

const docs = defineDocs();

export default createSite(docs.toSource()).plugins(
  recommendedPreset(),
  storyPlugin(), // [!code ++]
);
```

## Writing Stories [#writing-stories]

`<auto-story>` previews the component at `path`:

```md title="content/button.md"
<auto-story path="../src/components/Button.vue" display-name="Button" />
```

### AutoStoryProps

Attributes of `<auto-story>` in Markdown.

| Prop           | Type                                                    | Description                                                                   |
| -------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `path`         | `string`                                                | A module specifier or a path to the component, relative to the Markdown file. |
| `name?`        | `string \| undefined`                                   | The component's named export to preview. Default: `"default"`                 |
| `displayName?` | `string \| undefined`                                   | The name shown in the story's header.                                         |
| `args?`        | `StoryArgs \| (StoryArgs & VariantInfo)[] \| undefined` | Initial and fixed args for the component, or a list of named variants.        |
| `frame?`       | `StoryFrameOptions \| undefined`                        | Renders the component in an iframe at this page of the site.                  |

The panel has a control for each prop and each slot, where a slot's control has a `#` prefix, like `#default`. A prop whose type has no control, like a function, keeps its default.

Write `path` and `name` as plain attributes, since a bound one, like `:path`, makes the page fail to compile.

### Arguments [#arguments]

`:args` sets the initial values of the props and slots:

```md
<auto-story
  path="../src/components/Button.vue"
  :args="{ initial: { size: 'lg', disabled: true, '#default': 'Save' } }"
/>
```

### StoryArgs

| Prop        | Type                                                                            | Description                                                                                               |
| ----------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `initial?`  | `Record<string, unknown> \| undefined`                                          | The values the props and slots start from. A slot goes by its name after `#`, like `#default`.            |
| `fixed?`    | `Record<string, unknown> \| undefined`                                          | Values the controls can't change. A union keeps the members they match, and a fixed value has no control. |
| `controls?` | `{ node?: TypeNode; transform?: (node: ObjectNode) => TypeNode; } \| undefined` | Overrides or transforms the story's generated controls.                                                   |

A key that isn't a prop or a slot, or a value of the wrong type, makes the page fail to render, and the error lists the props and slots. `:args` also accepts `class`, `style` and attributes for the component's root element, like `id`.

### Variants [#variants]

A list in `:args` sets variants for the reader to pick from. The props in `fixed` keep their value, and their controls are hidden:

```md
<auto-story
  path="../src/components/Button.vue"
  :args="[
    { variant: 'Primary', initial: { '#default': 'Save' } },
    {
      variant: 'Danger',
      description: 'For destructive actions',
      initial: { '#default': 'Delete' },
      fixed: { tone: 'danger' },
    },
  ]"
/>
```

### Controls [#controls]

`controls.transform` changes the generated controls, and `controls.node` replaces them. To show no controls, set `controls.node` to `{ type: 'object', properties: [] }`. `@vuesho/story/type-tree` exports the control types:

```md title="content/graph.md"
<script setup lang="ts">
import type { ObjectNode } from "@vuesho/story/type-tree";

// Remove the control of the `data` prop
const transform = (node: ObjectNode) => ({
  ...node,
  properties: node.properties.filter((property) => property.name !== "data"), // [!code highlight]
});
</script>

<auto-story path="../src/components/Graph.vue" :args="{ controls: { transform } }" />
```

## Rendering in a Frame [#rendering-in-a-frame]

`:frame` renders a full-screen component, like a layout, in a scaled iframe. The iframe loads once the page is idle, and has a button to show it full screen:

```md title="content/shell.md"
<script setup lang="ts">
import Window from "../src/components/Window.vue";
</script>

<auto-story
  path="../src/components/AppShell.lazy.ts"
  :frame="{ src: '/story/app-shell', width: 1280, height: 800, Container: Window }"
/>
```

### StoryFrameOptions

| Prop         | Type                     | Description                                                                           |
| ------------ | ------------------------ | ------------------------------------------------------------------------------------- |
| `src`        | `string`                 | A page of the same origin that renders `StoryFrame`.                                  |
| `width?`     | `number \| undefined`    | The width of the viewport of the frame, scaled down to fit the panel. Default: `1280` |
| `height?`    | `number \| undefined`    | The height of the viewport of the frame. Default: `800`                               |
| `Container?` | `Component \| undefined` | Wraps the frame in its default slot, like a window around it.                         |

`src` is the path of a [custom page](/custom-pages), without the base path. The page renders the component in `StoryFrame`:

```vue title="src/pages/story/app-shell.vue"
<script setup lang="ts">
import { StoryFrame } from "@vuesho/story/ui/client/frame";
import AppShell from "../../components/AppShell.vue";
</script>

<template>
  <StoryFrame :Component="AppShell" />
</template>
```

Point `path` to an async component, so the docs page doesn't bundle it and only the iframe loads it. The arguments reach the iframe as JSON, so their values must be serializable:

```ts title="src/components/AppShell.lazy.ts"
import { defineAsyncComponent } from "vue";

export default defineAsyncComponent(() => import("./AppShell.vue"));
```

## Reusing Stories [#reusing-stories]

To use a story on several pages, put it in an [included](/markdown#includes) file. Its `path` is relative to that file:

```md title="content/_button-story.md"
<auto-story path="../src/components/Button.vue" :args="{ initial: { '#default': 'Save' } }" />
```

```md title="content/button.md"
<include>./_button-story.md</include>
```

In a [custom page](/custom-pages), or anywhere outside Markdown, `defineStory()` creates the story as a component. It takes the component and the options of `<auto-story>`:

```ts title="src/components/button-story.ts"
import { defineStory } from "@vuesho/story/client";
// `storyPlugin()` reads the props from the imported component's types.
import Button from "./Button.vue";

export const ButtonStory = defineStory(Button, {
  displayName: "Button",
  args: { initial: { "#default": "Save" } },
});
```

## Customizing the Panel [#customizing-the-panel]

Copy the panel's source into your project with [`vuesho add`](/cli#vuesho-add):

```npm
npx vuesho add client/with-control --from @vuesho/story
```

Then write a component that renders `Story` with your copy of the panel in its default slot, and place it as `Story.ts` in `src/components/content/`:

```ts title="src/components/content/Story.ts"
import { Story } from "@vuesho/story/client";
import type { WithControlProps } from "@vuesho/story/ui/provider";
import { h, type FunctionalComponent } from "vue";
import { WithControl } from "../../ui/@vuesho/story/client/with-control";

type StoryProps = InstanceType<typeof Story>["$props"];

const MyStory: FunctionalComponent<StoryProps> = (props) =>
  h(Story, props, { default: (panel: WithControlProps) => h(WithControl, panel) });

export default MyStory;
```

In your panel, read the story with the composables from `@vuesho/story/ui/provider`:

- `useStoryArgs()` returns the current values of the props and slots.
- `useStory()` returns the variants and the selected one.

## Options [#options]

### StoryPluginOptions

| Prop            | Type                  | Description                                                                                                                                                                                                                                           |
| --------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tsconfigPath?` | `string \| undefined` | The `tsconfig.json` to read component types with, relative to the working directory, like `tsconfig.app.json` in a project whose `tsconfig.json` only references others. Default: `"tsconfig.json", or the options of a new Vite project without one` |

In a project created by `create-vue`, `tsconfig.json` only references other configs, so point `tsconfigPath` to the one for your components. When a component's imports don't resolve, the build fails and names the file:

```ts title="vuesho.config.ts"
storyPlugin({ tsconfigPath: "tsconfig.app.json" });
```

## Translations [#translations]

The panel's labels come in English, Japanese, Simplified Chinese and Traditional Chinese, and follow the page's [language](/i18n). To replace a label or add a language, use `ui.translations`:

```ts title="vuesho.config.ts"
createSite(docs.toSource()).config({
  ui: {
    translations: { "Props(story controls)": "Properties" },
  },
});
```
