Preview runtime and story rendering
The preview runtime is the browser-side system that turns a selected story or docs entry into visible content. It reads the selection from the URL or the manager channel, prepares the story with project settings, renders it through the active framework adapter, and reports state back to the manager through the channel. It is the rendering part of the storybook runtime; the CLI and server lifecycle, manager UI, and story format and analysis pages describe the systems around it.
Preview boundary
The preview runs in the content frame. It owns the current selection, the story store, the visible story or docs page, and the render lifecycle. The manager remains the source of navigation commands and consumes preview status events.
Runtime initialization
The preview starts by evaluating project annotations and loading the story index from the server. It then creates a story store, applies globals and args persisted in the selection, and tells the manager that the preview is ready. A failure while reading project settings or the story index is shown in the preview and sent as a configuration error.
The initial globals are also sent to the manager with their declared global types. This gives the manager the state it needs before it sends later input changes. code/…/PreviewWeb.test.ts• L141-252
The preview also installs browser-side support for telemetry errors, focus blocking, content sizing, and optional direct story navigation. These services support the render frame but do not choose or render a story themselves. code/…/Preview.tsx• L124-245 and code/…/runtime.ts• L31-80
References: code/…/Preview.tsx• L124-245 code/…/runtime.ts• L31-80 code/…/PreviewWeb.test.ts• L141-252
Story selection
The selection store converts the URL into a story specifier, view mode, args, and globals. URL args and globals use a controlled query format that supports typed values and nested data; unsafe keys or values are omitted before they reach the story. The preview resolves the specifier against the story index, records the resulting story ID and view mode, and updates the URL when the selection changes. A manager SET_CURRENT_STORY event follows the same path, so direct links and manager navigation produce one selection model. code/…/UrlStore.ts• L84-107 and code/…/parseArgsParam.ts• L8-52
If a manager selection arrives during startup, it becomes the active selection and prevents the older URL selection from taking over. When no selection matches, the preview shows a missing-story state instead of starting a render. It also accepts query-parameter updates and preloads entries without changing the visible selection. code/…/PreviewWithSelection.tsx• L173-218 and code/…/PreviewWeb.test.ts• L1846-1915
Preload requests are queued separately from visible navigation. The preview runs one batch at a time, replaces a waiting request from the same source with its newest request, gives interactive requests priority over sibling guesses, and lets unknown entries fail without stopping the batch. This keeps sidebar or hover preloads useful without allowing stale work to delay newer requests. code/…/PreviewWithSelection.tsx• L317-341 and code/…/PreviewWeb.test.ts• L1426-1490
When the selection changes, the preview compares the story ID, view mode, and prepared story implementation before deciding whether to keep the current render, replace it, or reload after an unsafe interruption. An unchanged selection produces STORY_UNCHANGED without a new framework render. code/…/UrlStore.ts• L84-129, code/…/PreviewWithSelection.tsx• L304-437, and code/…/PreviewWeb.test.ts• L1936-1979
The URL argument contract covers scalar values, arrays, nested objects, typed values, and rejected input. Numeric text remains text when converting it to a number would change its written form. This preserves values such as 007, 03, and 1.50 for string args while still converting unambiguous numeric args. Color values retain their alpha form and case when the URL parser restores them. code/…/parseArgsParam.ts• L55-115 and code/…/ArgsStore.ts• L69-75
The parser applies the same safety rule to nested keys and values. If any part of a nested arg is invalid, that arg is omitted before the story receives it. The store then maps persisted values to the selected story's arg types, checks allowed options, and applies only the accepted delta. code/…/parseArgsParam.test.ts• L171-290 and code/…/ArgsStore.test.ts• L155-228
References: code/…/UrlStore.ts• L84-129 code/…/parseArgsParam.ts• L8-115 code/…/parseArgsParam.test.ts• L9-169 code/…/parseArgsParam.test.ts• L171-290 code/…/ArgsStore.ts• L43-75 code/…/ArgsStore.test.ts• L155-228 code/…/PreviewWithSelection.tsx• L173-218 code/…/PreviewWithSelection.tsx• L317-341 code/…/PreviewWithSelection.tsx• L304-437 code/…/PreviewWeb.test.ts• L1426-1490 code/…/PreviewWeb.test.ts• L1846-1915 code/…/PreviewWeb.test.ts• L1936-1979
Story preparation
Story preparation converts a story index entry and its module into a prepared story that can run in the preview. The story store loads the module, combines project, component, and story annotations, and keeps changing args and globals separate from the prepared story.
Story context
The story context is the request-time view of a prepared story. It contains the current args, globals, parameters, loaded data, hooks, canvas, and control functions that the story and framework adapter use during a render. The preview rebuilds this context when args or globals change, while preserving the story's initial values as the reset point.
The context keeps the manager-facing args separate from the values sent to the story. Arg mappings convert control values before render, while conditional and targeted args decide which values the story receives. This lets controls describe the full input state without forcing every input into the main story render. code/…/prepareStory.ts• L301-345 and code/…/prepareStory.test.ts• L465-717
Args updates are limited to the selected story and are validated against its arg types. Globals are limited to names declared by the project and are merged with story-level global overrides. This separation lets the manager change inputs without rebuilding the story definition. code/…/StoryStore.ts• L268-287
References: code/…/StoryStore.ts• L268-287 code/…/ArgsStore.ts• L30-86 code/…/GlobalsStore.ts• L24-69 code/…/prepareStory.ts• L301-345 code/…/prepareStory.test.ts• L465-717
Decorator and hook composition
Decorators wrap the story before the framework adapter receives it. Project, component, and story annotations contribute to the final render function, parameters, args, globals, and arg types. More specific story settings override component settings, and component settings override project settings where values overlap. code/…/prepareStory.ts• L200-263 and code/…/prepareStory.test.ts• L111-167
Loaders run before mounting and merge their data in project, component, and story order. beforeEach hooks can register cleanup work, and afterEach hooks run after the story finishes in reverse scope order. The resulting prepared story is stateless with respect to live args and globals, so each render supplies a fresh context while preserving the configured wrapper order. code/…/prepareStory.ts• L53-102 and code/…/prepareStory.test.ts• L403-463
When project annotations change, the preview prepares the current story again with the new decorators, args, and globals. It treats this as a same-story update, so the existing content stays mounted until the replacement is ready. code/…/PreviewWithSelection.tsx• L222-251 and code/…/PreviewWeb.test.ts• L3683-3856
References: code/…/prepareStory.ts• L53-102 code/…/prepareStory.ts• L110-168 code/…/prepareStory.ts• L200-263 code/…/prepareStory.test.ts• L111-167 code/…/prepareStory.test.ts• L403-463 code/…/PreviewWithSelection.tsx• L222-251 code/…/PreviewWeb.test.ts• L3683-3856
Rendering modes
The preview has two visible modes. Story mode renders one prepared story into the story root. Docs mode renders a docs page into the docs root and can use the same preview to render stories embedded inside that page.
Story rendering
Story rendering moves through preparation, loading, mounting, play, completion, and cleanup. The render controller emits phase changes and uses an abort signal so a new selection, remount, or input update can stop work that is still in progress. A completed render reports both that the story rendered and whether its checks finished successfully.
The framework adapter receives the decorated story context through the shared renderToCanvas contract. It decides how to mount, update, remount, and unmount the framework component, while the preview owns the surrounding lifecycle and error reporting. A same-story update keeps the current content in place until the new render commits, so args changes, hot reloads, and changed project annotations do not collapse the page or reset scroll. If an input change arrives during an active render, the preview completes the current boundary and then renders the newer state. code/…/StoryRender.ts• L136-175, code/…/PreviewWithSelection.tsx• L417-465, and code/…/PreviewWeb.test.ts• L1110-1282
Before it marks a render complete, the preview lets finite document-timeline animations settle. It does not wait for infinite or scroll-driven animations. In test environments, it instead moves supported CSS animations to a stable point and restores their prior state during cleanup. This keeps lifecycle completion useful for real pages without letting animations block the render forever. code/…/animation-utils.ts• L10-128 and code/…/StoryRender.ts• L386-405
This diagram shows how a selected story moves from the index to a framework adapter and then reports its result to the manager.
flowchart LR
A[URL or manager selection] --> B[Story index lookup]
B --> C[Story store preparation]
C --> D[Context with args globals decorators]
D --> E[Framework adapter]
E --> F[Mounted story]
F --> G[Play and cleanup]
G --> H[Lifecycle events to manager]
References: code/…/StoryRender.ts• L106-145 code/…/StoryRender.ts• L233-305 code/…/StoryRender.ts• L386-433 code/…/animation-utils.ts• L10-128 code/…/PreviewWithSelection.tsx• L417-465 code/…/PreviewWeb.test.ts• L1110-1282 code/…/PreviewWeb.test.ts• L3107-3359
Framework adapters
Each framework supplies the renderer-specific part of the preview contract. The adapter receives a story function and context, mounts the framework tree into the canvas element, and returns cleanup behavior. It can also report framework errors through the preview callbacks.
The contract allows the preview to support React, Vue, and other renderers without changing selection or lifecycle rules. For example, the React adapter controls its component tree and remount behavior, while the Vue adapter can update reactive args and globals without recreating the app. code/…/renderToCanvas.tsx• L69-137 and code/…/render.ts• L53-122
References: code/…/renderToCanvas.tsx• L69-137 code/…/render.ts• L53-122 code/…/StoryRender.ts• L272-290
Docs rendering
Docs rendering prepares either a CSF-backed docs entry or an MDX entry. The docs renderer receives a docs context that can attach referenced CSF files and render stories into the page. It reports DOCS_RENDERED when the docs page is complete, while embedded stories use the normal story render path.
The preview switches the visible root and applies fullscreen layout for docs. It keeps the project or attached story docs settings as the page configuration, so an MDX page and an autodocs page can use different sources while sharing the same preview frame. Global changes refresh inline stories before the docs container renders again. Args changes for an inline story update that story without rebuilding the docs container. code/…/PreviewWithSelection.tsx• L295-305, code/…/PreviewWithSelection.tsx• L473-539, and code/…/PreviewWeb.test.ts• L957-991
References: code/…/CsfDocsRender.ts• L64-120 code/…/MdxDocsRender.ts• L69-125 code/…/CsfDocsRender.ts• L123-167 code/…/MdxDocsRender.ts• L128-175 code/…/PreviewWithSelection.tsx• L295-305 code/…/PreviewWithSelection.tsx• L473-539 code/…/PreviewWeb.test.ts• L693-834 code/…/PreviewWeb.test.ts• L957-991
Preview view
The web view controls which root is visible and which loading or error state the user sees. Story mode uses #storybook-root, docs mode uses #storybook-docs, and story parameters can select a centered, fullscreen, padded, or unstyled layout. The view avoids resetting scroll during same-story updates so hot reload and input changes do not move the page unexpectedly. code/…/WebView.ts• L69-137
References: code/…/WebView.ts• L69-137 code/…/WebView.ts• L172-243
Manager channel
The preview and manager communicate through a shared channel. The manager sends selection and input changes; the preview sends readiness, prepared data, render state, errors, and completion events. These events let the manager update its URL, controls, interactions, and status without rendering the story itself.
Lifecycle events
The main event groups describe different points in the preview lifecycle:
| Direction | Event group | Purpose |
|---|---|---|
| Manager to preview | SET_CURRENT_STORY | Choose a story and view mode. |
| Manager to preview | UPDATE_STORY_ARGS, RESET_STORY_ARGS, UPDATE_GLOBALS, FORCE_RE_RENDER, FORCE_REMOUNT | Change render inputs or restart rendering. |
| Manager to preview | UPDATE_QUERY_PARAMS, PRELOAD_ENTRIES, NAVIGATE_URL | Update URL state, load entries early, or move to an in-page anchor. |
| Preview to manager | PREVIEW_INITIALIZED, SET_GLOBALS, STORY_SPECIFIED, CURRENT_STORY_WAS_SET | Report startup, declared inputs, and selection state. |
| Preview to manager | STORY_PREPARED, DOCS_PREPARED, GLOBALS_UPDATED, STORY_ARGS_UPDATED | Publish data needed by the manager UI. |
| Preview to manager | STORY_CHANGED, STORY_UNCHANGED, STORY_RENDER_PHASE_CHANGED, STORY_RENDERED, STORY_FINISHED | Report progress and final status. |
| Preview to manager | STORY_MISSING, STORY_ERRORED, STORY_THREW_EXCEPTION, PLAY_FUNCTION_THREW_EXCEPTION | Report selection or render failures. |
The event names and their direction form a contract between the two frames. A manager feature that changes selection or inputs must use the matching preview event so the preview can update its store before it renders again. Anchor navigation is different: it scrolls the current view and does not start a render. An unchanged selection reports STORY_UNCHANGED, which tells the manager that the current preview remains valid without a new render. code/…/index.ts• L17-62, code/…/PreviewWithSelection.tsx• L138-163, and code/…/PreviewWeb.test.ts• L843-955
References: code/…/index.ts• L17-62 code/…/Preview.tsx• L144-153 code/…/PreviewWithSelection.tsx• L138-163 code/…/PreviewWithSelection.tsx• L437-448 code/…/PreviewWeb.test.ts• L843-955 code/…/PreviewWeb.test.ts• L1936-1979
Update and interruption handling
Args and globals updates normally reuse the prepared story and trigger a render with the new context. A remount is stronger: it asks the adapter to create fresh component instances. If an update arrives while loading or rendering, the preview can queue or abort work; if user code does not stop after teardown attempts, the preview reloads the frame to restore a clean boundary.
Story changes follow the same safety rule. The old render is torn down before a different story or view mode takes over, while a same-story hot update can keep the old DOM in place until the new render commits. A newer selection can supersede a render that is still tearing down, so the superseded render does not publish prepared or docs state. In docs mode, global changes first update inline story renders and then refresh the docs container. This avoids stale content and preserves scroll when the story implementation changes. code/…/Preview.tsx• L310-430, code/…/StoryRender.ts• L443-509, code/…/PreviewWithSelection.tsx• L417-465, and code/…/PreviewWeb.test.ts• L1707-1797
The preview marks the replacement as current before asynchronous preparation starts. If another selection takes over during teardown, the older render is cleaned up and cannot emit its prepared or docs event. The same rule applies when a docs render is replaced: the old docs render is torn down instead of being reused. This prevents a slow selection from overwriting the manager state for a newer selection. code/…/PreviewWithSelection.tsx• L409-465 and code/…/PreviewWeb.test.ts• L1798-1888
References: code/…/Preview.tsx• L310-430 code/…/StoryRender.ts• L443-509 code/…/PreviewWithSelection.tsx• L295-305 code/…/PreviewWithSelection.tsx• L409-465 code/…/PreviewWithSelection.tsx• L417-465 code/…/PreviewWeb.test.ts• L1110-1282 code/…/PreviewWeb.test.ts• L1707-1797 code/…/PreviewWeb.test.ts• L1798-1888
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the URL selection fields and
SET_CURRENT_STORYpayload aligned. They must resolve to the same story ID and view mode. - Keep URL args and globals within the shared query grammar and validation rules. Changes must remain compatible with both URL parsing and the router's validation contract.
- Keep URL numeric and color value restoration compatible with arg-type mapping. Values that look numeric can be meaningful strings, and color alpha form can be meaningful to consumers.
- Keep
SET_GLOBALS,STORY_PREPARED,DOCS_PREPARED,GLOBALS_UPDATED, andSTORY_ARGS_UPDATEDpayloads compatible with the manager consumers that update controls and globals. - When changing render phases or abort behavior, preserve the matching
STORY_RENDER_PHASE_CHANGED,STORY_RENDERED, andSTORY_FINISHEDsequence. - When changing animation settling, preserve the distinction between finite document-timeline animations and animations that must not block completion. Keep the bounded wait and abort behavior aligned with render teardown.
- When changing selection replacement, preserve the rule that a newer selection can prevent an older prepared or docs event from reaching the manager.
- When changing same-story refresh behavior, keep the old content mounted until the new content commits and keep scroll reset disabled.
- When changing the renderer contract, update every framework adapter and the docs path that renders embedded stories.
- When changing story preparation precedence, check project, component, and story decorators, loaders, hooks, args, globals, parameters, and arg types together.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
Project annotations do not provide a renderToCanvas function. | The preview cannot render stories and shows a configuration error. | Validate the project annotations during initialization. |
| A URL or manager specifier does not match the story index. | The preview shows a missing-story or empty-index state. | Resolve the specifier before creating a render. |
| A URL arg or global contains an invalid key or value. | The unsafe entry is omitted, so the story receives less input than the URL appears to request. | Keep URL parsing and router validation rules aligned, and warn when input is omitted. |
| Numeric text is restored as a number without checking its written form. | String args can lose leading zeros or decimal formatting. | Preserve numeric text when numeric conversion changes the original string. |
| A color alpha value is normalized as if the original color form did not contain alpha. | A story can receive a different color value than the URL requested. | Preserve the color function form and its optional alpha component when decoding. |
| A global name is not declared by initial globals or global types. | The update is ignored and a warning is logged. | Filter globals through the declared global names. |
| A finite document-timeline animation never finishes. | The preview delays render completion until the bounded animation wait ends. | Wait only for finite document-timeline animations and enforce the five-second bound. |
| A story render remains pending after abort and teardown attempts. | The next render cannot safely reuse the frame. | Reload the preview frame after the bounded teardown wait. |
| A newer selection replaces a render while the older render is tearing down. | The older render can publish stale prepared or docs state if it is not discarded. | Check that the render is still current before publishing preparation data. |
| A docs entry has no usable docs renderer or CSF reference. | The docs page fails instead of rendering its content. | Prepare the entry and attached CSF files before invoking the docs renderer. |
| A loader or render function throws while a story loads. | The preview shows an error and reports a story exception instead of completing the render. | Keep failures inside the preview render boundary and publish the matching error event. |
Key files
| File | Why to read it |
|---|---|
| code/…/Preview.tsx | Preview initialization, channel listeners, store creation, and input updates. |
| code/…/PreviewWithSelection.tsx | URL and manager selection, story/docs branching, preload ordering, render replacement, same-story refresh, and preview events. |
| code/…/StoryRender.ts | Story phases, framework render calls, play functions, cleanup, animation settling, and abort handling. |
| code/…/animation-utils.ts | Browser animation settling and test-time animation control used before render completion. |
| code/…/StoryStore.ts | Story loading, prepared context creation, args, globals, and cleanup ownership. |
| code/…/prepareStory.ts | Annotation composition, decorators, loaders, arg preparation, and lifecycle hooks. |
| code/…/CsfDocsRender.ts | CSF-backed docs preparation and story embedding. |
| code/…/MdxDocsRender.ts | MDX docs preparation and attached story handling. |
| code/…/WebView.ts | Story/docs roots, loading states, layout, and error display. |
| code/…/UrlStore.ts | URL selection, args, globals, and query parameter updates. |
| code/…/parseArgsParam.ts | URL arg and global decoding, typed values, nested data, numeric text preservation, color values, and input filtering. |
| code/…/parseArgsParam.test.ts | The URL input contract for scalar values, nested values, typed values, color forms, and rejected keys or values. |
| code/…/ArgsStore.ts | Persistence and type mapping for story args after URL or manager updates. |
| code/…/ArgsStore.test.ts | The contract for persisted arg types, options, numeric strings, sparse arrays, and server docgen behavior. |
| code/…/index.ts | The channel event names used by the manager and preview. |
| code/…/renderToCanvas.tsx | A framework adapter example for mounting and remounting a story. |
| code/…/render.ts | A framework adapter example for reactive input updates and teardown. |
| code/…/PreviewWeb.test.ts | The end-to-end behavior contract for selection, input updates, rendering, docs, preloads, hot updates, interruption, and lifecycle events. |
| code/…/prepareStory.test.ts | The behavior contract for annotation merging, context values, args, decorators, loaders, and play functions. |