Created
November 20, 2024 15:51
-
-
Save diarcastro/a5e87574bf42b2cbb18832e8944dd752 to your computer and use it in GitHub Desktop.
Migrate Storybook yml stories to Storybook module twig stories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const { sync } = require('glob'); | |
| const { | |
| join, | |
| dirname, | |
| basename, | |
| } = require('path'); | |
| const yaml = require('js-yaml'); | |
| const { | |
| readFileSync, | |
| rmSync, | |
| writeFileSync, | |
| } = require('fs'); | |
| const chalk = require('chalk'); | |
| const infoChalk = chalk.blueBright; | |
| const warningChalk = infoChalk.bgYellowBright.black.bold; | |
| // Components Path | |
| const COMPONENTS_PATH = join(process.cwd(), 'docroot', 'modules', 'custom', 'my-components', 'components'); | |
| const files = sync(join(COMPONENTS_PATH, '**', '*.stories.yml')); | |
| const safeName = (name) => name.replace(/[^a-zA-Z0-9]/g, '_'); | |
| files.forEach((fileName) => { | |
| const componentDir = dirname(fileName); | |
| const componentName = basename(componentDir); | |
| const ymlStringContent = readFileSync(fileName, 'utf8'); | |
| const { | |
| title, | |
| argTypes, | |
| stories, | |
| } = yaml.load(ymlStringContent); | |
| const distFileName = join(componentDir, `${componentName}.stories.twig`); | |
| let storiesString = ''; | |
| if (stories && stories.length) { | |
| storiesString = stories.reduce((acc, story) => { | |
| const { | |
| name, | |
| args, | |
| parameters = {}, | |
| } = story; | |
| if (!args) { | |
| return acc; | |
| } | |
| const keys = Object.keys(args).join(', '); | |
| return `${acc} {% story ${safeName(name)} with { name: "${name}", args: ${JSON.stringify(args, null, 8)}, parameters: ${JSON.stringify(parameters || {})}} %} | |
| {{ include('my-components:${componentName}', {${keys}}) }} | |
| {% endstory %} | |
| `; | |
| }, ''); | |
| } | |
| const storiesTwigContent = `{% stories ${safeName(componentName)} with { | |
| title: "${title}", | |
| argTypes: ${JSON.stringify(argTypes || {}, null, 2)} | |
| } %} | |
| ${storiesString}{% endstories %} | |
| `; | |
| // eslint-disable-next-line no-console | |
| console.log(infoChalk(`Writing ${distFileName}`)); | |
| writeFileSync(distFileName, storiesTwigContent, { encoding: 'utf8' }); | |
| // Removing the yml file | |
| rmSync(fileName); | |
| }); | |
| // eslint-disable-next-line no-console | |
| console.log(warningChalk(`Consider run ${chalk.bgRed('ddev drush storybook:generate-all-stories')} to generate all stories`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment