storybookjs / storybook

Storybook is the industry standard workshop for building, documenting, and testing UI components in isolation
https://storybook.js.org
MIT License
83.77k stars 9.18k forks source link

how can I use the global variables provided by the toolbar in the mdxSource configuration of the MDX Canvas component #23537

Open TimYaoOo opened 1 year ago

TimYaoOo commented 1 year ago

Describe the bug

Hello Storybook team, I'm wondering how to make the mdxSource configuration of the Canvas component in MDX be affected by globalTypes. I've defined a dropdown option in the toolbar, and I want different options to correspond to different mdxSource content. However, from my various attempts, it seems that the content in globalTypes can only be accessed from the render function. So, I passed a function to mdxSource to fetch the URL parameters, differentiate the parameter values, and return the corresponding source code string accordingly. But this approach doesn't work either, as the function is executed before the URL parameters change. Is there any way to solve my current problem?

To Reproduce

image image image

System

"storybook": "^6.5.15"

main.js

module.exports = {
  "stories": [
    "../src/**/**.stories.mdx",
  ],
  "staticDirs": ['../public', '../components'],
  "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    {
      name: '@storybook/addon-docs',
      options: {
        configureJSX: true,
        babelOptions: {},
        sourceLoaderOptions: null,
        transcludeMarkdown: true,
      }
    }
  ],
  "framework": "@storybook/web-components",
  "features": {
    postcss: false,
  },
}

Additional context

No response

TimYaoOo commented 1 year ago

Now, I've adopted a different approach where I define custom code within the render function based on the global parameters from globals. However, I've encountered a bottleneck as this definition only takes effect during the initial rendering. After switching the globals parameters on the page, the source code is not being re-rendered. Nevertheless, based on the console log, the code attribute of the source has indeed been updated.

image image image
shilman commented 1 year ago

There's a docs.source.transform function whose second argument should receive a context containing a globals field with the current version of the toolbar values. I'd recommend trying that:

https://storybook.js.org/docs/react/api/doc-block-source#transform

TimYaoOo commented 1 year ago

docs.source.transform

Does the 'docs.source.transform' configuration exist in version 6.5? I added it, but it didn't take effect.