CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-storybook--preview-api

Storybook's core preview API providing hooks, decorators, story composition utilities, and simulation tools for building UI components in isolation

Pending
Overview
Eval results
Files

story-composition.mddocs/

Story Composition & CSF

Utilities for creating portable stories, composing story configurations, and working with Component Story Format. These tools enable story reuse across different environments, testing scenarios, and documentation systems.

Capabilities

Story Composition

Core functions for creating composed, portable stories from CSF exports.

/**
 * Creates a composed story function from story and component annotations
 * @param storyAnnotations - Individual story configuration
 * @param componentAnnotations - Component-level meta configuration  
 * @param projectAnnotations - Global project configuration
 * @param defaultConfig - Default fallback configuration
 * @param exportsName - Name of the story export for debugging
 * @returns Executable story function with metadata
 */
function composeStory<TRenderer>(
  storyAnnotations: StoryAnnotations<TRenderer, any>,
  componentAnnotations: ComponentAnnotations<TRenderer, any>,
  projectAnnotations?: ProjectAnnotations<TRenderer>,
  defaultConfig?: ProjectAnnotations<TRenderer>,
  exportsName?: string
): ComposedStoryFn<TRenderer, any>;

/**
 * Composes all stories from a story module
 * @param storiesImport - Imported stories module (*.stories.js)
 * @param globalConfig - Global project annotations
 * @param composeStoryFn - Custom compose function (defaults to composeStory)
 * @returns Object mapping story names to composed story functions
 */
function composeStories<TModule>(
  storiesImport: TModule,
  globalConfig: ProjectAnnotations<any>,
  composeStoryFn?: Function
): Record<string, ComposedStoryFn<any, any>>;

interface ComposedStoryFn<TRenderer = any, TArgs = any> {
  /** Execute the story with optional args override */
  (args?: Partial<TArgs>): any;
  /** Story display name */
  storyName?: string;
  /** Default story args */
  args?: TArgs;
  /** Story parameters */
  parameters?: Parameters;
  /** Story arg types */
  argTypes?: ArgTypes;
  /** Story ID */
  id?: string;
}

Usage Examples:

import { composeStory, composeStories } from "@storybook/preview-api";
import { render, screen } from "@testing-library/react";
import type { Meta, StoryObj } from '@storybook/react';

// Import your stories
import * as ButtonStories from './Button.stories';
import globalConfig from '../.storybook/preview';

// Compose individual story
const meta: Meta<typeof Button> = ButtonStories.default;
const Primary = composeStory(ButtonStories.Primary, meta, globalConfig);

// Use in tests
test('Primary button renders correctly', () => {
  render(<Primary />);
  expect(screen.getByRole('button')).toBeInTheDocument();
});

test('Primary button with custom args', () => {
  render(<Primary args={{ label: 'Custom Label', disabled: true }} />);
  expect(screen.getByRole('button')).toBeDisabled();
});

// Compose all stories from module
const composedStories = composeStories(ButtonStories, globalConfig);

// Iterate through all stories
Object.entries(composedStories).forEach(([name, Story]) => {
  test(`${name} story renders without errors`, () => {
    render(<Story />);
    expect(screen.getByRole('button')).toBeInTheDocument();
  });
});

Project Configuration

Functions for setting global project annotations and default configurations.

/**
 * Sets global project annotations for story composition
 * @param projectAnnotations - Global configuration for all stories
 */
function setProjectAnnotations<TRenderer>(projectAnnotations: ProjectAnnotations<TRenderer>): void;

/**
 * Sets default project annotations as fallback configuration
 * @param defaultProjectAnnotations - Default configuration when none provided
 */
function setDefaultProjectAnnotations<TRenderer>(
  defaultProjectAnnotations: ProjectAnnotations<TRenderer>
): void;

interface ProjectAnnotations<TRenderer = any> {
  /** Global parameters applied to all stories */
  parameters?: Parameters;
  /** Global decorators applied to all stories */
  decorators?: DecoratorFunction<TRenderer>[];
  /** Global args applied to all stories */
  args?: Args;
  /** Global arg types applied to all stories */
  argTypes?: ArgTypes;
  /** Global values available to all stories */
  globals?: Args;
  /** Global controls for globals */
  globalTypes?: GlobalTypes;
  /** Story rendering function */
  render?: (args: Args, context: StoryContext<TRenderer>) => any;
  /** Component rendering function for autodocs */
  component?: any;
}

Usage Examples:

import { setProjectAnnotations } from "@storybook/preview-api";

// Set global configuration for portable stories
setProjectAnnotations({
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
  },
  decorators: [
    (Story) => (
      <div style={{ margin: '3rem' }}>
        <Story />
      </div>
    ),
  ],
  globals: {
    theme: 'light',
    locale: 'en'
  }
});

Story Processing & Normalization

Low-level utilities for story preparation, normalization, and processing.

/**
 * Prepares a story for rendering by processing annotations
 * @param storyAnnotations - Raw story annotations
 * @param componentAnnotations - Component meta annotations
 * @param projectAnnotations - Project-level annotations
 * @returns Prepared story ready for rendering
 */
function prepareStory<TRenderer>(
  storyAnnotations: StoryAnnotations<TRenderer, any>,
  componentAnnotations: ComponentAnnotations<TRenderer, any>,
  projectAnnotations: ProjectAnnotations<TRenderer>
): PreparedStory<TRenderer>;

/**
 * Prepares component meta information
 * @param componentAnnotations - Raw component annotations
 * @param projectAnnotations - Project-level annotations
 * @returns Prepared component meta
 */
function prepareMeta<TRenderer>(
  componentAnnotations: ComponentAnnotations<TRenderer, any>,
  projectAnnotations: ProjectAnnotations<TRenderer>
): PreparedMeta<TRenderer>;

/**
 * Normalizes story annotations to standard format
 * @param storyAnnotations - Raw story annotations
 * @param componentAnnotations - Component meta annotations
 * @param projectAnnotations - Project-level annotations
 * @returns Normalized story annotations
 */
function normalizeStory<TRenderer>(
  storyAnnotations: StoryAnnotations<TRenderer, any>,
  componentAnnotations: ComponentAnnotations<TRenderer, any>,
  projectAnnotations: ProjectAnnotations<TRenderer>
): NormalizedStoryAnnotations<TRenderer>;

/**
 * Normalizes project annotations to standard format
 * @param projectAnnotations - Raw project annotations
 * @returns Normalized project annotations
 */
function normalizeProjectAnnotations<TRenderer>(
  projectAnnotations: ProjectAnnotations<TRenderer>
): NormalizedProjectAnnotations<TRenderer>;

Configuration Composition

Utilities for combining and composing multiple configuration objects.

/**
 * Composes multiple configuration objects safely
 * @param configs - Configuration objects to combine
 * @returns Combined configuration object
 */
function composeConfigs(...configs: any[]): any;

/**
 * Composes step runner functions for play function execution
 * @param runners - Step runner functions to combine
 * @returns Combined step runner function
 */
function composeStepRunners(...runners: Function[]): Function;

Args & Parameters Utilities

Functions for working with story arguments and parameters.

/**
 * Safely combines argument objects, handling special cases
 * @param value - Base args object
 * @param update - Args update to apply
 * @returns Combined args object
 */
function combineArgs(value: Args, update: Args): Args;

/**
 * Safely combines parameter objects with proper merging
 * @param parameterSets - Parameter objects to combine
 * @returns Combined parameters object
 */
function combineParameters(...parameterSets: Parameters[]): Parameters;

/**
 * Filters argTypes based on include/exclude criteria
 * @param argTypes - ArgTypes object to filter
 * @param include - Properties to include (RegExp or string array)
 * @param exclude - Properties to exclude (RegExp or string array)
 * @returns Filtered argTypes object
 */
function filterArgTypes(
  argTypes: ArgTypes,
  include?: PropDescriptor,
  exclude?: PropDescriptor
): ArgTypes;

/**
 * Infers control types from argTypes definitions
 * @param argTypes - ArgTypes to process
 * @returns ArgTypes with inferred controls
 */
function inferControls(argTypes: ArgTypes): ArgTypes;

/**
 * Normalizes project annotations to standard format
 * @param projectAnnotations - Raw project annotations
 * @returns Normalized project annotations
 */
function normalizeProjectAnnotations<TRenderer>(
  projectAnnotations: ProjectAnnotations<TRenderer>
): NormalizedProjectAnnotations<TRenderer>;

type PropDescriptor = string[] | RegExp;

Story Decoration

Functions for applying decorators to stories.

/**
 * Applies a decorator to a story function
 * @param storyFn - Original story function
 * @param decorator - Decorator to apply
 * @param bindWithContext - Whether to bind with story context
 * @returns Decorated story function
 */
function decorateStory<TRenderer>(
  storyFn: StoryFn<TRenderer>,
  decorator: DecoratorFunction<TRenderer>,
  bindWithContext?: boolean
): StoryFn<TRenderer>;

/**
 * Default story decoration implementation
 * @returns Default decorator function
 */
function defaultDecorateStory<TRenderer>(): DecoratorFunction<TRenderer>;

/**
 * Sanitizes story context updates for safety
 * @param update - Context update object
 * @returns Sanitized update object
 */
function sanitizeStoryContextUpdate(update: Partial<StoryContext>): Partial<StoryContext>;

Naming & Organization

Utilities for story naming and organization.

/**
 * Determines story title from user input or auto-generation
 * @param title - User-provided title
 * @param specifier - File specifier for auto-title
 * @returns Final story title
 */
function userOrAutoTitle(title: string | undefined, specifier: string): string;

/**
 * Gets title from file specifier for auto-title generation
 * @param specifier - File path specifier
 * @returns Generated title
 */
function userOrAutoTitleFromSpecifier(specifier: string): string;

/**
 * Sorts stories using Storybook v7 algorithm
 * @param stories - Stories to sort
 * @param storySort - Sort configuration
 * @returns Sorted stories array
 */
function sortStoriesV7(stories: any[], storySort: any): any[];

Usage Examples:

import { userOrAutoTitle, userOrAutoTitleFromSpecifier, sortStoriesV7 } from "@storybook/preview-api";

// Auto-generate title from file path
const autoTitle = userOrAutoTitleFromSpecifier('./components/Button/Button.stories.ts');
// Result: 'Components/Button'

// Use user title or auto-generate
const finalTitle = userOrAutoTitle('Custom/Button', './components/Button/Button.stories.ts');
// Result: 'Custom/Button'

// Sort stories with custom configuration
const sortedStories = sortStoriesV7(stories, {
  method: 'alphabetical',
  order: ['Intro', 'Components', '*', 'Examples']
});

Types & Interfaces

interface StoryAnnotations<TRenderer = any, TArgs = any> {
  args?: Partial<TArgs>;
  argTypes?: ArgTypes;
  parameters?: Parameters;
  decorators?: DecoratorFunction<TRenderer>[];
  render?: (args: TArgs, context: StoryContext<TRenderer>) => any;
  play?: (context: PlayFunctionContext<TRenderer, TArgs>) => Promise<void> | void;
}

interface ComponentAnnotations<TRenderer = any, TArgs = any> {
  title?: string;
  component?: any;
  args?: Partial<TArgs>;
  argTypes?: ArgTypes;
  parameters?: Parameters;
  decorators?: DecoratorFunction<TRenderer>[];
  render?: (args: TArgs, context: StoryContext<TRenderer>) => any;
}

interface PreparedStory<TRenderer = any> {
  id: string;
  name: string;
  title: string;
  args: Args;
  argTypes: ArgTypes;
  parameters: Parameters;
  component: any;
  renderFn: Function;
}

interface PlayFunctionContext<TRenderer = any, TArgs = any> {
  args: TArgs;
  canvasElement: HTMLElement;
  step: (label: string, play: Function) => Promise<void>;
}

interface NormalizedProjectAnnotations<TRenderer = any> {
  parameters: Parameters;
  decorators: DecoratorFunction<TRenderer>[];
  args: Args;
  argTypes: ArgTypes;
  globals: Args;
  globalTypes: GlobalTypes;
  render?: Function;
  component?: any;
}

Install with Tessl CLI

npx tessl i tessl/npm-storybook--preview-api

docs

decorators.md

hooks.md

index.md

preview-system.md

story-composition.md

story-store.md

testing-simulation.md

tile.json