Best JavaScript code snippet using storybook-root
preview.js
Source:preview.js  
1import { document } from 'global';2import React, { Fragment, useEffect } from 'react';3import isChromatic from 'chromatic/isChromatic';4import {5  Global,6  ThemeProvider,7  themes,8  createReset,9  convert,10  styled,11  useTheme,12} from '@storybook/theming';13import { withCssResources } from '@storybook/addon-cssresources';14import { DocsPage } from '@storybook/addon-docs/blocks';15import addHeadWarning from './head-warning';16if (process.env.NODE_ENV === 'development') {17  if (!process.env.DOTENV_DEVELOPMENT_DISPLAY_WARNING) {18    addHeadWarning('dotenv-env', 'Dotenv development file not loaded');19  }20  if (!process.env.STORYBOOK_DISPLAY_WARNING) {21    addHeadWarning('env-glob', 'Global storybook env var not loaded');22  }23  if (process.env.DISPLAY_WARNING) {24    addHeadWarning('env-extra', 'Global non-storybook env var loaded');25  }26}27addHeadWarning('preview-head-not-loaded', 'Preview head not loaded');28addHeadWarning('dotenv-file-not-loaded', 'Dotenv file not loaded');29const ThemeBlock = styled.div(30  {31    position: 'absolute',32    top: 0,33    left: 0,34    right: '50vw',35    width: '50vw',36    height: '100vh',37    bottom: 0,38    overflow: 'auto',39    padding: 10,40  },41  ({ theme }) => ({42    background: theme.background.app,43    color: theme.color.defaultText,44  }),45  ({ side }) =>46    side === 'left'47      ? {48          left: 0,49          right: '50vw',50        }51      : {52          right: 0,53          left: '50vw',54        }55);56const ThemeStack = styled.div(57  {58    position: 'relative',59    minHeight: 'calc(50vh - 15px)',60  },61  ({ theme }) => ({62    background: theme.background.app,63    color: theme.color.defaultText,64  })65);66const ThemedSetRoot = () => {67  const theme = useTheme();68  useEffect(() => {69    document.body.style.background = theme.background.app;70    document.body.style.color = theme.defaultText;71    return () => {72      //73    };74  });75  return null;76};77export const decorators = [78  withCssResources,79  (StoryFn, { globals: { theme = 'light' } }) => {80    switch (theme) {81      case 'side-by-side': {82        return (83          <Fragment>84            <ThemeProvider theme={convert(themes.light)}>85              <Global styles={createReset} />86            </ThemeProvider>87            <ThemeProvider theme={convert(themes.light)}>88              <ThemeBlock side="left">89                <StoryFn />90              </ThemeBlock>91            </ThemeProvider>92            <ThemeProvider theme={convert(themes.dark)}>93              <ThemeBlock side="right">94                <StoryFn />95              </ThemeBlock>96            </ThemeProvider>97          </Fragment>98        );99      }100      case 'stacked': {101        return (102          <Fragment>103            <ThemeProvider theme={convert(themes.light)}>104              <Global styles={createReset} />105            </ThemeProvider>106            <ThemeProvider theme={convert(themes.light)}>107              <ThemeStack side="left">108                <StoryFn />109              </ThemeStack>110            </ThemeProvider>111            <ThemeProvider theme={convert(themes.dark)}>112              <ThemeStack side="right">113                <StoryFn />114              </ThemeStack>115            </ThemeProvider>116          </Fragment>117        );118      }119      default: {120        return (121          <ThemeProvider theme={convert(themes[theme])}>122            <Global styles={createReset} />123            <ThemedSetRoot />124            <StoryFn />125          </ThemeProvider>126        );127      }128    }129  },130];131export const parameters = {132  exportedParameter: 'exportedParameter',133  a11y: {134    config: {},135    options: {136      checks: { 'color-contrast': { options: { noScroll: true } } },137      restoreScroll: true,138    },139  },140  options: {141    storySort: (a, b) =>142      a[1].kind === b[1].kind ? 0 : a[1].id.localeCompare(b[1].id, undefined, { numeric: true }),143  },144  docs: {145    theme: themes.light,146    page: () => <DocsPage subtitleSlot={({ kind }) => `Subtitle: ${kind}`} />,147  },148};149export const globals = {150  foo: 'fooValue',151};152export const globalTypes = {153  foo: { defaultValue: 'fooDefaultValue' },154  bar: { defaultValue: 'barDefaultValue' },155  theme: {156    name: 'Theme',157    description: 'Global theme for components',158    defaultValue: isChromatic() ? 'stacked' : 'light',159    toolbar: {160      icon: 'circlehollow',161      items: [162        { value: 'light', icon: 'circlehollow', title: 'light' },163        { value: 'dark', icon: 'circle', title: 'dark' },164        { value: 'side-by-side', icon: 'sidebar', title: 'side by side' },165        { value: 'stacked', icon: 'bottombar', title: 'stacked' },166      ],167    },168  },169  locale: {170    name: 'Locale',171    description: 'Internationalization locale',172    defaultValue: 'en',173    toolbar: {174      icon: 'globe',175      items: [176        { value: 'en', right: 'ðºð¸', title: 'English' },177        { value: 'es', right: 'ðªð¸', title: 'Español' },178        { value: 'zh', right: 'ð¨ð³', title: '䏿' },179        { value: 'kr', right: 'ð°ð·', title: 'íêµì´' },180      ],181    },182  },...ThemeProvider.jsx
Source:ThemeProvider.jsx  
1import React, { Component } from 'react';2import _ from 'lodash';3import PropTypes from 'prop-types';4import { ThemeProvider as EThemeProvider } from 'emotion-theming';5import { generateTheme } from './theme';6import { setRuntimeTheme } from './runtime';7let themeStack = [];8const themeMap = {};9const updateRuntimeTheme = () => {10    setRuntimeTheme(themeMap[themeStack[themeStack.length - 1]]);11};12class ThemeProvider extends Component {13    constructor(props) {14        super(props);15        const theme = this.getMergedTheme(props.theme);16        this.cache = JSON.stringify(theme);17        this.state = {18            theme19        };20        this.uid = _.uniqueId('_theme_provider_');21        themeStack.push(this.uid);22        themeMap[this.uid] = theme;23        updateRuntimeTheme();24    }25    static propTypes = {26        /**27         * èªå®ä¹ä¸»é¢28         */29        theme: PropTypes.object.isRequired30    };31    getMergedTheme = theme => {32        return generateTheme(theme);33    };34    componentWillReceiveProps(nextProps) {35        const { theme } = nextProps;36        if (JSON.stringify(theme) !== this.cache) {37            const mergedTheme = this.getMergedTheme(theme);38            this.cache = JSON.stringify(theme);39            this.setState(40                {41                    theme: mergedTheme42                },43                () => {44                    themeMap[this.uid] = mergedTheme;45                    updateRuntimeTheme();46                }47            );48        }49    }50    componentWillUnmount = () => {51        delete themeMap[this.uid];52        themeStack = themeStack.filter(uid => uid !== this.uid);53        updateRuntimeTheme();54    };55    render() {56        // eslint-disable-next-line no-unused-vars57        const { theme: _theme, ...rest } = this.props;58        const { theme } = this.state;59        return <EThemeProvider theme={theme} {...rest} />;60    }61}...Using AI Code Generation
1import React from 'react';2import ThemeStack from 'storybook-root-decorator';3import { storiesOf } from '@storybook/react';4import { withInfo } from '@storybook/addon-info';5import { withKnobs } from '@storybook/addon-knobs';6storiesOf('test', module)7  .addDecorator(withInfo)8  .addDecorator(withKnobs)9  .addDecorator(ThemeStack)10  .add('test', () => {11    return <div>test</div>;12  });13import React from 'react';14import { ThemeProvider } from 'styled-components';15import { lightTheme } from '../src/theme';16export default story => (17  <ThemeProvider theme={lightTheme}>{story()}</ThemeProvider>18);19export const lightTheme = {20  colors: {21  },22};23import { configure } from '@storybook/react';24configure(require.context('../src', true, /\.stories\.js$/), module);25const path = require('path');26module.exports = ({ config }) => {27  config.module.rules.push({28    loaders: [require.resolve('@storybook/addon-storysource/loader')],29  });30  config.resolve.alias = {31    'storybook-root-decorator': path.resolve(__dirname, '../storybook-root-decorator.js'),32  };33  return config;34};35import React from 'react';36import { ThemeProvider } from 'styled-components';37import { lightTheme } from '../src/theme';38export default story => (39  <ThemeProvider theme={lightTheme}>{story()}</ThemeProvider>40);41const path = require('path');42module.exports = ({ config }) => {43  config.module.rules.push({44    loaders: [require.resolve('@storybook/addon-storysource/loader')],45  });46  config.resolve.alias = {47    'storybook-root-decorator': path.resolve(__dirnameUsing AI Code Generation
1import { ThemeStack } from 'storybook-root-decorator';2import { storiesOf } from '@storybook/react';3import { withKnobs } from '@storybook/addon-knobs';4import { withInfo } from '@storybook/addon-info';5import MyComponent from './MyComponent';6const stories = storiesOf('MyComponent', module);7stories.addDecorator(withKnobs);8stories.addDecorator(withInfo);9stories.add('default', () => {10  return <MyComponent />;11});12stories.add('dark theme', () => {13  return (14    <ThemeStack themes={['dark']}>15  );16});17stories.add('dark theme + custom theme', () => {18  return (19    <ThemeStack themes={['dark', { background: 'blue' }]}>20  );21});22stories.add('dark theme + custom theme + custom theme', () => {23  return (24    <ThemeStack themes={['dark', { background: 'blue' }, { background: 'red' }]}>25  );26});27import React from 'react';28import PropTypes from 'prop-types';29import styled, { ThemeProvider } from 'styled-components';30  background: ${props => props.theme.background};31  color: ${props => props.theme.color};32`;33const MyComponent = ({ theme }) => {34  return (35    <ThemeProvider theme={theme}>36  );37};38MyComponent.propTypes = {39};40MyComponent.defaultProps = {41  theme: {42  },43};44export default MyComponent;45import { addDecorator } from '@storybook/react';46import { withThemesProvider } from 'storybook-addon-styled-component-theme';47import { ThemeProvider } from 'styled-components';48import { defaultTheme, darkTheme } from '../src/theme';49const themes = [defaultTheme, darkTheme];50addDecorator(withThemesProvider(themes));51export const defaultTheme = {52};53export const darkTheme = {Using AI Code Generation
1import { ThemeStack } from 'storybook-root';2import { storiesOf } from '@storybook/react';3import { withKnobs, text } from '@storybook/addon-knobs';4storiesOf('ThemeStack', module)5  .addDecorator(withKnobs)6  .add('default', () => (7      theme={text('Theme', 'light')}8      themeStack={text('Theme Stack', 'light|dark')}9  ));10export { ThemeStack } from './ThemeStack';11import React, { Component } from 'react';12import PropTypes from 'prop-types';13export class ThemeStack extends Component {14  static propTypes = {15  };16  render() {17    const { theme, themeStack, children } = this.props;18    const themeStackArray = themeStack.split('|');19    const index = themeStackArray.indexOf(theme);20    const themeStackArraySplice = themeStackArray.splice(index);21    const themeStackString = themeStackArraySplice.join(' ');22    return (23      <div className={themeStackString}>24        {children}25    );26  }27}28.light {29  background-color: #fff;30}31.dark {32  background-color: #000;33}34import React from 'react';35import { shallow } from 'enzyme';36import { ThemeStack } from './ThemeStack';37describe('ThemeStack', () => {38  it('renders without crashing', () => {39    const wrapper = shallow(40    );41    expect(wrapper).toMatchSnapshot();42  });43});44import { ThemeStack } from 'storybook-root';45addParameters({46  options: {47  },48});49import { ThemeStack } from 'storybook-root';50addDecorator(storyFn =>Using AI Code Generation
1import { ThemeStack } from 'storybook-root-decorator';2import { theme } from 'theme';3export const decorators = [ThemeStack(theme)];4export const parameters = {5  actions: { argTypesRegex: '^on[A-Z].*' },6};7import { createMuiTheme } from '@material-ui/core/styles';8import { red } from '@material-ui/core/colors';9const theme = createMuiTheme({10  palette: {11    primary: {12    },13    secondary: {14    },15    error: {16    },17    background: {18    },19  },20});21export { theme };22import React from 'react';23import { Button } from './button';24export default {25  argTypes: {26    backgroundColor: { control: 'color' },27  },28};29const Template = (args) => <Button {...args} />;30export const Primary = Template.bind({});31Primary.args = {32};33export const Secondary = Template.bind({});34Secondary.args = {35};36export const Large = Template.bind({});37Large.args = {38};39export const Small = Template.bind({});40Small.args = {41};42import React from 'react';43import { Header } from './header';44export default {45};46const Template = (args) => <Header {...args} />;47export const Default = Template.bind({});48Default.args = {49};50import React from 'react';51import { Icon } from './icon';52export default {53};54const Template = (args) => <Icon {...args} />;55export const Default = Template.bind({});56Default.args = {57};58import React from 'react';59import { Input } fromUsing AI Code Generation
1import { ThemeStack } from 'storybook-root-decorator'2  (Story) => (3export const parameters = {4  actions: { argTypesRegex: '^on[A-Z].*' },5}6import { ThemeStack } from 'storybook-root-decorator'7  (Story) => (8export const parameters = {9  actions: { argTypesRegex: '^on[A-Z].*' },10}11module.exports = {12  stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],13  webpackFinal: async (config) => {14    config.module.rules.push({15      include: path.resolve(__dirname, '../'),16    })17  },18}19import { ThemeProvider } from 'styled-components'20import { ThemeStack } from 'storybook-root-decorator'21import { theme } from '../src/theme'22  (Story) => (23    <ThemeProvider theme={theme}>24export const parameters = {25  actions: { argTypesRegex: '^on[A-Z].*' },26}27module.exports = {28  stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],29  webpackFinal: async (config) => {30    config.module.rules.push({Using AI Code Generation
1import { ThemeStack } from 'storybook-root'2import { useTheme } from '@material-ui/core/styles'3import { ThemeProvider } from '@material-ui/styles'4export const ThemeDecorator = (storyFn) => {5  const theme = useTheme()6  return (7    <ThemeProvider theme={theme}>8      <ThemeStack>{storyFn()}</ThemeStack>9}10import { ThemeDecorator } from '../test'11addDecorator(ThemeDecorator)12import { ThemeDecorator } from '../test'13addDecorator(ThemeDecorator)14module.exports = {15  stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],16  webpackFinal: async (config) => {17    config.resolve.alias['storybook-root'] = path.resolve(__dirname, '..')18  },19}20import { createMuiTheme } from '@material-ui/core/styles'21import { ThemeProvider } from '@material-ui/styles'22import { ThemeStack } from 'storybook-root'23const theme = createMuiTheme({24  palette: {25    primary: {26    },27    secondary: {28    },29    error: {30    },31    background: {32    },33  },34})35export const ThemeDecorator = (storyFn) => {36  return (37    <ThemeProvider theme={theme}>38      <ThemeStack>{storyFn()}</ThemeStack>39}40import { ThemeDecorator } from './theme'41addDecorator(ThemeDecorator)42module.exports = {43  stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],44  webpackFinal: async (config) => {45    config.resolve.alias['storybook-root'] = path.resolve(__dirname, '..')46  },47}Using AI Code Generation
1import { ThemeProvider } from 'styled-components';2import { ThemeStack } from 'storybook-root-decorator';3import { theme } from './src/theme';4  Story => (5    <ThemeProvider theme={theme}>6];7import { ThemeProvider } from 'styled-components';8import { ThemeStack } from 'storybook-root-decorator';9import { theme } from '../src/theme';10  Story => (11    <ThemeProvider theme={theme}>12];13import { ThemeProvider } from 'styled-components';14import { ThemeStack } from 'storybook-root-decorator';15import { theme } from '../src/theme';16  Story => (17    <ThemeProvider theme={theme}>18];19import { ThemeProvider } from 'styled-components';20import { ThemeStack } from 'storybook-root-decorator';21import { theme } from '../src/theme';22  Story => (23    <ThemeProvider theme={theme}>24];Using AI Code Generation
1import { ThemeStack } from 'storybook-root-decorator';2import { theme } from '@some/package';3export default {4  decorators: [ThemeStack([theme])],5};6export const test = () => (7);8import { ThemeStack } from 'storybook-root-decorator';9import { theme } from '@some/package';10export const decorators = [ThemeStack([theme])];11import { ThemeStack } from 'storybook-root-decorator';12import { theme } from '@some/package';13export const parameters = {14  decorators: [ThemeStack([theme])],15};16import { ThemeStack } from 'storybook-root-decorator';17import { theme } from '@some/package';18addDecorator(ThemeStack([theme]));19import { ThemeStack } from 'storybook-root-decorator';20import { theme } from '@some/package';21addParameters({22  decorators: [ThemeStack([theme])],23});24import { ThemeStack } from 'storybook-root-decorator';25import { theme } from '@some/package';26export const decorators = [ThemeStack([theme])];27import { ThemeStack } from 'storybook-root-decorator';28import { theme } from '@some/package';29export const parameters = {30  decorators: [ThemeStack([theme])],31};32import { ThemeStack } from 'storybook-root-decorator';33import { theme } from '@some/package';34addDecorator(ThemeStack([theme]));Using AI Code Generation
1import { ThemeProvider } from "@material-ui/core/styles";2import { ThemeProvider as StyledComponentsThemeProvider } from "styled-components";3import { ThemeProvider as EmotionThemeProvider } from "@emotion/react";4import { theme } from "./src/theme";5import { ThemeStack } from "storybook-root-decorator";6import { themeDecorator } from "storybook-addon-material-ui";7  (Story) => (8    <ThemeStack themes={[theme]}>9      <ThemeProvider theme={theme}>10        <StyledComponentsThemeProvider theme={theme}>11          <EmotionThemeProvider theme={theme}>12];13import { createMuiTheme } from "@material-ui/core/styles";14const theme = createMuiTheme({15  palette: {16    primary: {17    },18    secondary: {19    },20  },21});22export { theme };23import React from "react";24import MyButton from "./MyButton";25export default {26};27const Template = (args) => <MyButton {...args} />;28export const Primary = Template.bind({});29Primary.args = {30};31export const Secondary = Template.bind({});32Secondary.args = {33};34export const Large = Template.bind({});35Large.args = {36};37export const Small = Template.bind({});38Small.args = {39};40import React from "react";41import Button from "@material-ui/core/Button";42import { makeStyles } from "@material-ui/core/styles";43const useStyles = makeStyles((theme) => ({44  root: {45    margin: theme.spacing(1),46  },47  label: {48  },49}));50const MyButton = (props) =>Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
