storybookjs / storybook

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

Storybook Docs not expanding to fit story within Canvas in MDX #12258

Closed jonniedarko closed 3 years ago

jonniedarko commented 4 years ago

Describe the bug When adding an existing story to an .mdx docs file, the canvas or preview does not expand to fit the story

To Reproduce Steps to reproduce the behavior:

  1. created component (I use https://material-ui.com/components/lists/#pinned-subheader-list for reproduction example but happens with others)
  2. created a story (see story snippet below)
  3. create .mdx doc file (see mdx file snippet below)

Expected behavior The docs canvas should expand to fill entire component but does not

Screenshots Component within Story:

Screen Shot 18

Within Doc

Screen Shot 16

could be related to iframe parent div height being set to somewhere 100px:

Screen Shot 20

If I manually set a Height here in chrome tools I can make it fit:

Screen Shot 21

Code snippets story:

import React from 'react';
import PinnedSubheaderList from './index';

export default { title: 'List' };
export const PinnedSubheaderListStory = () => <PinnedSubheaderList />;

MDX file


import { Meta, Story, Canvas } from '@storybook/addon-docs/blocks';
import PinnedSubheaderList from './index';

<Meta title="mdx/PinnedSubheaderList" component={PinnedSubheaderList} />

# PinnedSubheaderList

<Canvas>
    <Story
    id="list--pinned-subheader-list-story">
    </Story>
</Canvas>

storybook/peview.js

import { addParameters, addDecorator } from '@storybook/react';
import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks';
import { withKnobs } from '@storybook/addon-knobs';
import withTheme from './themeProviderDecorator';

addParameters({
  backgrounds: {
    default: 'Dark',
    values: [
      { name: 'Light', value: '#fff' },
      { name: 'Dark', value: '#1c233f' }
    ]
  },
  docs: {
    container: DocsContainer,
    page: DocsPage,
  }
});

addDecorator(withKnobs)
addDecorator(withTheme)

storybook/main.js

const path = require('path');
const createCompiler = require('@storybook/addon-docs/mdx-compiler-plugin');

module.exports = {
  addons: [
    '@storybook/addon-backgrounds/register',
    '@storybook/addon-knobs/register',
    '@storybook/addon-actions/register',
    '@storybook/addon-docs/register'
  ],
  stories: ['../src/**/*.stories.@(js|mdx)'],
  webpackFinal: async (config, { configType }) => {
    config.devtool = 'inline-source-map';
    config.resolve = {
      ...config.resolve,
      alias: {
        ...(config.resolve.alias || []),
        src: path.resolve(__dirname, '..', 'src'),
        stories: path.resolve(__dirname, '..', 'stories')
      }

    };
    config.module.rules.push({
      // 2a. Load `.stories.mdx` / `.story.mdx` files as CSF and generate
      //     the docs page from the markdown
      test: /\.(stories|story)\.mdx$/,
      use: [
        {
          loader: 'babel-loader',
          // may or may not need this line depending on your app's setup
          options: {
            plugins: ['@babel/plugin-transform-react-jsx'],
          },
        },
        {
          loader: '@mdx-js/loader',
          options: {
            compilers: [createCompiler({})],
          },
        },
      ],
    });
    // 2b. Run `source-loader` on story files to show their source code
    //     automatically in `DocsPage` or the `Source` doc block.
    config.module.rules.push({
      test: /\.(stories|story)\.[tj]sx?$/,
      loader: require.resolve('@storybook/source-loader'),
      exclude: [/node_modules/],
      enforce: 'pre',
    });

    return config;
  }
};

System: npx sb@next info output.

Environment Info:
  System:
    OS: macOS 10.15.6
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
  Binaries:
    Node: 10.15.3 - ~/.nvm/versions/node/v10.15.3/bin/node
    npm: 6.14.8 - ~/.nvm/versions/node/v10.15.3/bin/npm
  Browsers:
    Chrome: 84.0.4147.135
    Firefox: 79.0
    Safari: 13.1.2
  npmPackages:
    @storybook/addon-actions: ^6.0.18 => 6.0.18
    @storybook/addon-backgrounds: ^6.0.18 => 6.0.18
    @storybook/addon-docs: ^6.0.18 => 6.0.18
    @storybook/addon-knobs: ^6.0.18 => 6.0.18
    @storybook/addon-storyshots: ^6.0.18 => 6.0.18
    @storybook/addon-storyshots-puppeteer: ^6.0.18 => 6.0.18
    @storybook/react: ^6.0.18 => 6.0.18

Additional context I also tried Preview instead of Canvas and had the same issue

lhz516 commented 4 years ago

Same issue here after upgrading from v5.x to v6.

Currently I set height on Story element manually as a walkaround

<Story name="Width" height="700px">
shilman commented 3 years ago

@jonniedarko looks like you're manually configuring addon-docs. If you use the preset instead, it will set docs.inlineStories parameter to true and this problem should go away. if you prefer your stories to be rendered in iframes, then this is a duplicate to https://github.com/storybookjs/storybook/issues/8112

Closing this but LMK if that doesn't do it for you.

eikonomega commented 2 years ago

Hey @shilman thanks for all your work. Storybook is a remarkable tool. Wanted to follow-up on this as I'm still seeing iFrames being injected into my custom MDX pages and was wondering if you could help me pinpoint my error.

Here are the relevant code snippets.

# preview.js
export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
  docs: {
    inlineStories: true,
  },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
}
#main.js
const path = require('path');
const toPath = (_path) => path.join(process.cwd(), _path);

module.exports = {
  typescript: {
    check: true,
  },
  stories: [
    "../src/stories/**/*.stories.mdx",
    "../src/stories/**/*.stories.@(js|jsx|ts|tsx)",
    "../src/stories/**/*.stories.(js|jsx|ts|tsx)"
  ],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
  ],
  babel: async (options) => {
    return ({
      ...options,
      presets: [...options.presets, '@emotion/babel-preset-css-prop'],
    })
  },
  webpackFinal: async (config) => {
    const { mode: environment, plugins, module } = config;
    return {
      ...config,
      resolve: {
        ...config.resolve,
        alias: {
          ...config.resolve.alias,

          /**
           * Map Emotion 10 libraries to Emotion 11 libraries.
           *
           * Otherwise Storybook fails to compile with "Module not found: Error: Can't resolve '@emotion/styled/base'", etc.
           * It wasn't necessary to do this until we imported React component using "@emotion/styled".
           * This issue is probably caused because Storybook uses Emotion 10 while we have Emotion 11.
           *
           * @see https://github.com/storybookjs/storybook/issues/13277#issuecomment-751747964
           */
          '@emotion/core': toPath('node_modules/@emotion/react'),
          '@emotion/styled': toPath('node_modules/@emotion/styled'),
          'emotion-theming': toPath('node_modules/@emotion/react'),
        },
      },
    };
  },
}
# Story Definition: ColorPalettes.stories.tsx
import { Story, Meta } from '@storybook/react/types-6-0';

import {
  gray,
  faded_blue,
  blue,
  teal,
  green,
  yellow,
  orange,
  red,
  magenta,
  purple,
} from '../definitions/colors';
import typography from '../styleDefinitions/typography';
import ColorPalettesMDX from './ColorPalettes.mdx';

export default {
  title: 'Color/Palettes',
  parameters: {
    docs: {
      page: ColorPalettesMDX,
    },
  },
} as Meta;

const ColorSwatch = (props: { colorKey: number; hexCode: string }) => {
  return (
    <div
      css={{
        width: 200,
        height: 35,
        backgroundColor: props.hexCode,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingLeft: 10,
        paddingRight: 10,
        marginBottom: 5,
        boxSizing: 'border-box',
      }}
    >
      <span
        css={[
          typography.metaData,
          { flex: 1, color: props.colorKey > 200 ? 'white' : gray[600] },
        ]}
      >
        {props.colorKey}
      </span>
      <span
        css={[
          typography.metaData,
          {
            flex: 1,
            color: props.colorKey > 200 ? 'white' : gray[600],
            textAlign: 'end',
          },
        ]}
      >
        {props.hexCode}
      </span>
    </div>
  );
};

export const Palettes: Story = (args) => (
  <div css={{ display: 'flex', flexWrap: 'wrap' }}>
    {[
      gray,
      faded_blue,
      blue,
      teal,
      green,
      yellow,
      orange,
      red,
      magenta,
      purple,
    ].map((colorHue) => (
      <div css={{ marginRight: 20, marginBottom: 20 }}>
        {Object.entries(colorHue).map((entry) => (
          <ColorSwatch colorKey={+entry[0]} hexCode={entry[1]} />
        ))}
      </div>
    ))}
  </div>
);
MDX Docs

import { Story, Canvas } from '@storybook/addon-docs';

# Color Palettes

My friends. I know you're asking yourself, _"how am I going to find that perfect color!?"_

Well, good news. Here are a whole bunch of perfect colors, separated into different hue families
and with standardized lightness variations. You can help your interfaces have a clean, consistent look
by choosing from these options.

<Story id='color-palettes' />

And here is an image showing that the iFrame is still be injected... :( image

And finally, the version info on my setup.

Environment Info:

  System:
    OS: macOS 11.5.2
    CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
  Binaries:
    Node: 14.17.5 - ~/.volta/tools/image/node/14.17.5/bin/node
    Yarn: 1.22.11 - ~/.volta/tools/image/yarn/1.22.11/bin/yarn
    npm: 6.14.14 - ~/.volta/tools/image/node/14.17.5/bin/npm
  Browsers:
    Chrome: 95.0.4638.69
    Firefox: 72.0.2
    Safari: 14.1.2
  npmPackages:
    @storybook/addon-actions: ^6.3.12 => 6.3.12 
    @storybook/addon-essentials: ^6.3.12 => 6.3.12 
    @storybook/addon-links: ^6.3.12 => 6.3.12 
    @storybook/react: ^6.3.12 => 6.3.12