Storybook Addon SDC
Drupal Single Directory Components as stories
Storybook SDC Addon
Drupal Single Directory Components (SDC) in Storybook, without a Drupal site. Every *.component.yml becomes stories, its props and slots become Controls, and its Twig template renders with Drupal's Twig functions and filters, in Twig.js or Twing.
Live demo and feature guide: every feature has a page with an explanation and a working example.
Table of Contents
- Quickstart
- Configuration
- Features
- Addon options
- Story options
- Twig engines
- Production static build
- Dependencies
- Known issues
Quickstart
-
In a theme, a module or an empty folder, create
package.jsonif there is none:npm init echo "node_modules/" >> .gitignore -
Install the addon and Vite:
npm i vite storybook-addon-sdc --save-dev -
Initialize Storybook and remove its example stories:
npx storybook@latest init --builder vite --type html --no-dev rm -rf ./stories -
Set
"type": "module"inpackage.json. -
Configure
.storybook/main.jsas below, then runnpm run storybook.
Configuration
// .storybook/main.js
export default {
stories: ['../components/**/*.component.yml'],
addons: [
{
name: 'storybook-addon-sdc',
options: {
sdcStorybookOptions: {
twigLib: 'twig', // or 'twing'
},
},
},
],
framework: { name: '@storybook/html-vite', options: {} },
}
Without options, addons: ['storybook-addon-sdc'] uses Twig.js and the folder name as the namespace.
In .storybook/main.ts the options are typed:
import type { StorybookConfig } from '@storybook/html-vite'
import type { SDCAddonOptions } from 'storybook-addon-sdc'
const sdcOptions: SDCAddonOptions = {
sdcStorybookOptions: { twigLib: 'twing' },
}
const config: StorybookConfig = {
stories: ['../components/**/*.component.yml'],
addons: [{ name: 'storybook-addon-sdc', options: sdcOptions }],
framework: { name: '@storybook/html-vite', options: {} },
}
export default config
If the theme already has a vite.config.js (for its asset build or its own Storybook), Storybook loads it too, and its plugins can break the stories. Give Storybook an empty config instead:
// .storybook/main.js
framework: {
name: '@storybook/html-vite',
options: { builder: { viteConfigPath: '.storybook/vite.config.js' } },
},
// .storybook/vite.config.js
export default {}
Features
Each link opens the feature's page in the live demo.
Writing stories:
- Stories in YAML: more stories in the component YAML or in
*.story.ymlfiles, parameters, globals,library_wrapper. - Story nodes: fill slots with components, HTML, images and icons.
- Custom nodes: your own node types for repeated markup.
- Schemas and mock data: default values, generated values, Controls, shared definitions.
Drupal APIs:
- Namespaces: components from base themes, modules and other folders.
- Icon API:
{theme}.icons.ymlandicon(), Drupal 11.1. - Design tokens:
{theme}.tokens.ymlas CSS variables, Drupal 11.5. - Variants and html_cva(): component variants (Drupal 11.2) and
html_cva()(Drupal 11.4). - Form elements:
form_statefor components used as form fields, Drupal 11.4. - Libraries and CDN: library dependencies from a CDN, Drupal behaviors.
Storybook:
- Sidebar and noUi: grouping, folders and the
no-uitag, Drupal 11.3. - SDC in CSF stories: components in regular
.stories.jsfiles. - Accessibility: the a11y addon on SDC stories.
Addon options
sdcStorybookOptions
twigLib:'twig'(Twig.js, default) or'twing'.namespace: the name of your own namespace. Default: the name of the folder that holdscomponents/.namespaces: other namespaces,{ name: path }. Add their component folders tostoriestoo. A path without acomponents/folder is a plain Twig namespace,@name/file.svg.customNodes: your own story node types,[{ match(node), render(node) }].resolveIconSource:(source) => url, rewrites icon sources such as/libraries/....dependencyMap: Drupal library names to CDN assets,{ 'core/jquery': [{ type: 'js', url }] }. See below.externalDefs: URLs or paths of schema definition files for$ref.customDefs: schema definitions keyed by their$ref.validate:truechecks component YAML against its$schemaor Drupal's metadata schema; a URL is used for components without$schema. Problems are logged as warnings.useBasicArgsForStories:true(default) starts every story from the Basic story's values.
dependencyMap
These are always loaded, so Drupal behaviors work:
| Key | Assets |
|---|---|
system/base/hidden |
hidden.module.css (.visually-hidden utility) |
core/drupalSettings |
drupalSettingsLoader.js |
core/drupal |
drupal.js, drupal.init.js |
core/once |
once.min.js |
Other entries load only for stories of components that list them in libraryOverrides.dependencies.
dependencyMap: {
// Add a dependency
'core/jquery': [{ type: 'js', url: 'https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js' }],
// Replace a built-in one
'core/once': [{ type: 'js', url: 'https://cdn.example.com/once@2.min.js' }],
// Turn a built-in one off
'system/base/hidden': [],
},
vitePluginTwigDrupalOptions
Options for vite-plugin-twig-drupal when twigLib is 'twig', such as extra Twig functions and global variables:
vitePluginTwigDrupalOptions: {
functions: {
reverse: (twig) =>
twig.extendFunction('reverse', () => (text) => text.split(' ').reverse().join(' ')),
},
globalContext: {
active_theme: 'my_theme',
is_front_page: false,
},
},
vitePluginTwingDrupalOptions
Options for vite-plugin-twing-drupal when twigLib is 'twing'. hooks points to a module that can change the Twing environment:
vitePluginTwingDrupalOptions: {
hooks: join(cwd(), '.storybook/twing-hooks.js'),
},
// .storybook/twing-hooks.js
import { createSynchronousFunction } from 'twing'
export function initEnvironment(env) {
env.addFunction(
createSynchronousFunction('shout', (_context, text) => `${text}!`, [
{ name: 'text' },
])
)
}
jsonSchemaFakerOptions
Options for json-schema-faker, which fills props and slots that have no default or examples.
Story options
Story settings live in the component YAML under thirdPartySettings.sdcStorybook:
thirdPartySettings:
sdcStorybook:
tags: [autodocs]
disabledStories: [basic]
parameters:
layout: centered
globals:
theme: dark
stories:
preview:
name: Preview
description: Card with an image.
props:
html_tag: div
slots:
content: Hello!
parameters: {}
globals: {}
library_wrapper: '<div class="wrapper">{{ _story }}</div>'
tags: Storybook tags, such asautodocs.disabledStories: story keys to hide,basicfor the Basic story, orall.parametersandglobals: for every story of the component; a story's own values win.stories: extra stories by key. A story can setname,description,props,slots,parameters,globalsandlibrary_wrapper.
A story can also be its own file, {component}.{story}.story.yml, in the component folder or below it, with the same keys as one entry of stories.
Globals
Globals need globalTypes in .storybook/preview.js. This demo's theme:
// .storybook/preview.js
export default {
globalTypes: {
theme: {
description: 'Global theme for components',
toolbar: {
title: 'Theme',
icon: 'circlehollow',
items: ['light', 'dark'],
dynamicTitle: true,
},
},
},
initialGlobals: { theme: 'light' },
decorators: [
(Story, context) => {
document.documentElement.dataset.theme = context.globals.theme || 'light'
return Story()
},
],
}
Twig engines
Twig.js and Twing lack some of what Drupal templates use. The addon adds it, so the same templates work on both engines:
icon()from the Icon API, both engines.html_cva(), both engines, with named arguments on Twig.js too.|add_classand|set_attributefrom Drupal core: the class or attribute goes on the element itself. Twig.js had no such filters; Twing's wrapped the value in a<div>.include()as a function on Twig.js, which only had the{% include %}tag.|safe_joinof an empty value gives an empty string on Twing, as in Drupal, instead of an error.is sequenceandis mappingtests and the|shufflefilter from Twig 3.11, both engines.addClass()andremoveClass()take arrays, Twing Maps and the hashes Twig.js makes frommerge, also oncreate_attribute()objects.- Lists in slots print item by item, without commas, on Twig.js.
Twig.js cannot parse arrow functions (|map(v => …), |filter(…)), named arguments written with = (with_context = false) or a ? b without : c inside a list ([a ? b, c]), and list ?: [] gives the length of the list instead of the list. Templates that use them work on Twing. On Twig.js, a library_wrapper can print a component with include(), but the {% include %} tag finds it only if a template already includes it with the tag.
Production static build
Icon pack sources are copied into the build automatically.
With Twig.js, if templates read component files with source(componentMetadata.path ~ '/icons/x.svg'), add the component folders to staticDirs for production builds:
...(process.env.NODE_ENV === 'production'
? { staticDirs: [{ from: '../components', to: '/components' }] }
: {}),
Twing needs no setup, and is the engine to use when a base theme lives outside the Storybook project.
Dependencies
- vite-plugin-twig-drupal: Twig.js with Drupal functions.
- vite-plugin-twing-drupal: Twing with Drupal functions.
- json-schema-faker: values for props and slots without
defaultorexamples. - jsonschema: the
validateoption.
Known issues
- The addon relies on Storybook's experimental indexers.
- A component included in Twig with
onlyand withoutattributesgets noattributesobject. Passattributes: create_attribute().
