Best JavaScript code snippet using storybook-root
prepareStory.ts
Source:prepareStory.ts  
1import { dedent } from 'ts-dedent';2import deprecate from 'util-deprecate';3import global from 'global';4import type {5  Parameters,6  Args,7  LegacyStoryFn,8  ArgsStoryFn,9  StoryContextForEnhancers,10  StoryContext,11  AnyFramework,12  StrictArgTypes,13  StoryContextForLoaders,14  PlayFunctionContext,15  StepLabel,16  PlayFunction,17} from '@storybook/csf';18import { includeConditionalArg } from '@storybook/csf';19import type {20  NormalizedComponentAnnotations,21  Story,22  NormalizedStoryAnnotations,23  NormalizedProjectAnnotations,24} from '../types';25import { combineParameters } from '../parameters';26import { applyHooks } from '../hooks';27import { defaultDecorateStory } from '../decorators';28import { groupArgsByTarget, NO_TARGET_NAME } from '../args';29import { getValuesFromArgTypes } from './getValuesFromArgTypes';30const argTypeDefaultValueWarning = deprecate(31  () => {},32  dedent`33  \`argType.defaultValue\` is deprecated and will be removed in Storybook 7.0.34  https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#no-longer-inferring-default-values-of-args`35);36// Combine all the metadata about a story (both direct and inherited from the component/global scope)37// into a "renderable" story function, with all decorators applied, parameters passed as context etc38//39// Note that this story function is *stateless* in the sense that it does not track args or globals40// Instead, it is expected these are tracked separately (if necessary) and are passed into each invocation.41export function prepareStory<TFramework extends AnyFramework>(42  storyAnnotations: NormalizedStoryAnnotations<TFramework>,43  componentAnnotations: NormalizedComponentAnnotations<TFramework>,44  projectAnnotations: NormalizedProjectAnnotations<TFramework>45): Story<TFramework> {46  // NOTE: in the current implementation we are doing everything once, up front, rather than doing47  // anything at render time. The assumption is that as we don't load all the stories at once, this48  // will have a limited cost. If this proves misguided, we can refactor it.49  const { moduleExport, id, name } = storyAnnotations;50  const { title } = componentAnnotations;51  const parameters: Parameters = combineParameters(52    projectAnnotations.parameters,53    componentAnnotations.parameters,54    storyAnnotations.parameters55  );56  const decorators = [57    ...(storyAnnotations.decorators || []),58    ...(componentAnnotations.decorators || []),59    ...(projectAnnotations.decorators || []),60  ];61  // Currently it is only possible to set these globally62  const {63    applyDecorators = defaultDecorateStory,64    argTypesEnhancers = [],65    argsEnhancers = [],66    runStep,67  } = projectAnnotations;68  const loaders = [69    ...(projectAnnotations.loaders || []),70    ...(componentAnnotations.loaders || []),71    ...(storyAnnotations.loaders || []),72  ];73  // The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize74  // CSFv1/2, we use a new field called `userStoryFn` so we know that it can be a LegacyStoryFn75  const render =76    storyAnnotations.userStoryFn ||77    storyAnnotations.render ||78    componentAnnotations.render ||79    projectAnnotations.render;80  if (!render) throw new Error(`No render function available for storyId '${id}'`);81  const passedArgTypes: StrictArgTypes = combineParameters(82    projectAnnotations.argTypes,83    componentAnnotations.argTypes,84    storyAnnotations.argTypes85  ) as StrictArgTypes;86  const { passArgsFirst = true } = parameters;87  // eslint-disable-next-line no-underscore-dangle88  parameters.__isArgsStory = passArgsFirst && render.length > 0;89  // Pull out args[X] into initialArgs for argTypes enhancers90  const passedArgs: Args = {91    ...projectAnnotations.args,92    ...componentAnnotations.args,93    ...storyAnnotations.args,94  } as Args;95  const contextForEnhancers: StoryContextForEnhancers<TFramework> = {96    componentId: componentAnnotations.id,97    title,98    kind: title, // Back compat99    id,100    name,101    story: name, // Back compat102    component: componentAnnotations.component,103    subcomponents: componentAnnotations.subcomponents,104    parameters,105    initialArgs: passedArgs,106    argTypes: passedArgTypes,107  };108  contextForEnhancers.argTypes = argTypesEnhancers.reduce(109    (accumulatedArgTypes, enhancer) =>110      enhancer({ ...contextForEnhancers, argTypes: accumulatedArgTypes }),111    contextForEnhancers.argTypes112  );113  // Add argTypes[X].defaultValue to initial args (note this deprecated)114  // We need to do this *after* the argTypesEnhancers as they may add defaultValues115  const defaultArgs = getValuesFromArgTypes(contextForEnhancers.argTypes);116  if (Object.keys(defaultArgs).length > 0) {117    argTypeDefaultValueWarning();118  }119  const initialArgsBeforeEnhancers = { ...defaultArgs, ...passedArgs };120  contextForEnhancers.initialArgs = argsEnhancers.reduce(121    (accumulatedArgs: Args, enhancer) => ({122      ...accumulatedArgs,123      ...enhancer({124        ...contextForEnhancers,125        initialArgs: accumulatedArgs,126      }),127    }),128    initialArgsBeforeEnhancers129  );130  // Add some of our metadata into parameters as we used to do this in 6.x and users may be relying on it131  if (!global.FEATURES?.breakingChangesV7) {132    contextForEnhancers.parameters = {133      ...contextForEnhancers.parameters,134      __id: id,135      globals: projectAnnotations.globals,136      globalTypes: projectAnnotations.globalTypes,137      args: contextForEnhancers.initialArgs,138      argTypes: contextForEnhancers.argTypes,139    };140  }141  const applyLoaders = async (context: StoryContextForLoaders<TFramework>) => {142    const loadResults = await Promise.all(loaders.map((loader) => loader(context)));143    const loaded = Object.assign({}, ...loadResults);144    return { ...context, loaded };145  };146  const undecoratedStoryFn: LegacyStoryFn<TFramework> = (context: StoryContext<TFramework>) => {147    const mappedArgs = Object.entries(context.args).reduce((acc, [key, val]) => {148      const mapping = context.argTypes[key]?.mapping;149      acc[key] = mapping && val in mapping ? mapping[val] : val;150      return acc;151    }, {} as Args);152    const includedArgs = Object.entries(mappedArgs).reduce((acc, [key, val]) => {153      const argType = context.argTypes[key] || {};154      if (includeConditionalArg(argType, mappedArgs, context.globals)) acc[key] = val;155      return acc;156    }, {} as Args);157    const includedContext = { ...context, args: includedArgs };158    const { passArgsFirst: renderTimePassArgsFirst = true } = context.parameters;159    return renderTimePassArgsFirst160      ? (render as ArgsStoryFn<TFramework>)(includedContext.args, includedContext)161      : (render as LegacyStoryFn<TFramework>)(includedContext);162  };163  const decoratedStoryFn = applyHooks<TFramework>(applyDecorators)(undecoratedStoryFn, decorators);164  const unboundStoryFn = (context: StoryContext<TFramework>) => {165    let finalContext: StoryContext<TFramework> = context;166    if (global.FEATURES?.argTypeTargetsV7) {167      const argsByTarget = groupArgsByTarget(context);168      finalContext = {169        ...context,170        allArgs: context.args,171        argsByTarget,172        args: argsByTarget[NO_TARGET_NAME] || {},173      };174    }175    return decoratedStoryFn(finalContext);176  };177  const { play } = storyAnnotations;178  const playFunction =179    play &&180    (async (storyContext: StoryContext<TFramework>) => {181      const playFunctionContext: PlayFunctionContext<TFramework> = {182        ...storyContext,183        step: (label: StepLabel, play: PlayFunction<TFramework>) =>184          // TODO: We know runStep is defined, we need a proper normalized annotations type185          runStep!(label, play, playFunctionContext),186      };187      return play(playFunctionContext);188    });189  return Object.freeze({190    ...contextForEnhancers,191    moduleExport,192    originalStoryFn: render,193    undecoratedStoryFn,194    unboundStoryFn,195    applyLoaders,196    playFunction,197  });...validation.js
Source:validation.js  
1var async = require('async');2var merge = require('merge');3var util = require('util');4var registry = require('./registry');5var stringify = require('./stringify');6var validation = module.exports = {};7validation.init = function(){8  this._negative = false;9  this._required = true;10  this._attrs = [];11  this._alert = 'invalid';12  this._alertTag = 'invalid';13  this._requiredMessage = 'required';14  this._requiredTag = 'required';15  this._validation = null;16  this._validationArgs = [];17  this._takeIn= [];18  return this;19}20validation.required = function() {21  this._required = true;22  return this;23}24validation.isPresent = validation.required;25validation.notRequired = function() {26  this._required = false;27  return this;28}29validation.ifPresent = validation.notRequired;30validation.setValidation = function() {31  this._validation = arguments[0];32  this._validationArgs = Array.prototype.slice.call(arguments, 1, arguments.length);33  if(typeof arguments[0] == 'string') {34    this.tag(arguments[0]);35  }36  return this;37}38validation.with = validation.setValidation;39validation.is = validation.setValidation;40validation.isNot = function(){41  this._negative = true;42  return this.is.apply(this, arguments);43}44validation.negative = function(){45  this._negative = true;46  return this;47}48validation.attrs = function(arg) {49  if (typeof arg == 'string') {50    this._attrs = this._attrs.concat(arg.split(' '));51  } else if (arg instanceof Array) {52    this._attrs = this._attrs.concat(arg);53  } else {54    throw('You need to pass a string or array.');55  }56  return this;57}58validation.alert = function(value) {59  this._alert = value;60  return this;61}62validation.orSay = validation.alert;63validation.tag = function(value) {64  this._alertTag = value;65  return this;66}67validation.requiredTag = function(value) {68  this._requiredTag = value;69  return this;70}71validation.takeIn = function() {72  this._takeIn = Array.prototype.slice.call(arguments);73  return this;74}75validation.execute = function(obj, callback) {76  var self = this;77  setImmediate(function(){78    var fns = [];79    for(var i = 0; i < self._attrs.length; i++) {80      var attrName = self._attrs[i];81      fns.push(function(attrName){82        return function(cb) {83          self.executeOnAttr(attrName, obj, cb);84        }85      }(attrName));86    }87    async.parallel(fns, function(err, results){88      var result = {};89      for(var i = 0; i < results.length; i++) {90        //result = merge.recursive(result, results[i]);91        for (var property in results[i]) {92          if (results[i].hasOwnProperty(property)) {93            if (typeof result[property] != 'undefined') {94              result[property] = result[property].concat(results[i][property]);95            } else {96              result[property] = results[i][property];97            }98          }99        }100      }101      result = (Object.keys(result).length > 0) ? result : null;102      callback(err, result);103    });104  });105}106validation.executeOnAttr = function(attrName, obj, callback) {107  var includedArgs = this._validationArgs;108  for(var i = 0; i < this._takeIn.length; i++) {109    includedArgs.push(obj[this._takeIn[i]]);110  }111  if (typeof this._validation.execute == 'function') {112    this._validation(obj[attrName], function(nestedError, newObj){113      obj[attrName] = newObj; // update the sanitized object114      if(nestedError) {115        var r = {};116        for (var property in nestedError) {117          if (nestedError.hasOwnProperty(property)) {118            if (typeof r[attrName + "." + property] != 'undefined') {119              r[attrName + "." + property] = r[attrName + "." + property].concat(nestedError[property]);120            } else {121              r[attrName + "." + property] = nestedError[property];122            }123          }124        }125        callback(null, r);126      } else {127        callback(null, null);128      }129    });130  } else {131    var error = null;132    if(typeof obj[attrName] == 'undefined') {133      if(this._required) {134        error = error || {};135        error[attrName] = error[attrName] || [];136        error[attrName].push({ code: this._requiredTag.toUpperCase(), message: this._requiredMessage });137      }138      callback(null, error);139    } else {140      var validationFunction = (typeof this._validation == 'string') ? registry.registry(this._validation) : this._validation;141      var self = this;142      validationFunction.apply(null, [stringify(obj[attrName])].concat(includedArgs).concat([function(err, vResult){143        if(self._negative) vResult = !vResult;144        if(!vResult) {145          error = error || {};146          error[attrName] = error[attrName] || [];147          error[attrName].push({ code: self._alertTag.toUpperCase(), message: self._alert });148        }149        callback(null, error);150      }]));151    }152  }...main.js
Source:main.js  
1import spawn from 'cross-spawn';2import { fileURLToPath } from 'url';3import { dirname, extname, join, sep } from 'path';4import fs from 'fs-extra';5import yargs from 'yargs';6import options from './options.js';7const __filename = fileURLToPath(import.meta.url);8const __dirname = dirname(__filename);9export const outDirDefault = 'lib';10const npmBin = spawn.sync('npm', ['bin']).stdout.toString().trim();11// 'babel' command does not work, when developing other package and12// libary-scripts is linked locally (babel is not added to the target13// package's node_modules/.bin.). Use absolute path.14const babelBin = fs.existsSync(join(npmBin, 'babel'))15  ? 'babel'16  : __dirname17      .split(sep)18      .map((part, index, parts) => parts.slice(0, parts.length - index))19      .map((parts) => parts.join(sep))20      .map((parts) => join(parts, 'node_modules/.bin/babel'))21      .find((path) => fs.pathExistsSync(path));22const excludeArgs = ['--type'];23const createBuild =24  ({ args, commandArgs, NODE_ENV, outDir, srcDirs }) =>25  ({ outFileExtension, type }) => {26    const configFile = join(27      __dirname,28      `babel.config.${type}${outFileExtension === '.js' ? '-js' : ''}${extname(29        __filename30      )}`31    );32    const includedArgs = commandArgs.filter(33      (arg, index, array) =>34        !(excludeArgs.includes(arg) || excludeArgs.includes(array[index - 1]))35    );36    spawn(37      babelBin,38      [39        ...srcDirs,40        '--out-dir',41        outDir,42        '--out-file-extension',43        outFileExtension,44        '--config-file',45        configFile,46        '--copy-files',47        '--no-copy-ignored',48        ...args.split(' '),49        ...includedArgs,50      ],51      {52        stdio: 'inherit',53        env: {54          NODE_ENV,55          ...process.env,56        },57      }58    );59  };60export default ({ args, NODE_ENV }) =>61  (...commandArgs) => {62    const { argv } = yargs(commandArgs);63    const { outDir = outDirDefault, outFileExtension = '.js', type } = argv;64    const srcDirs = argv._.length ? argv._ : ['src'];65    const build = createBuild({66      args,67      commandArgs,68      NODE_ENV,69      outDir,70      srcDirs,71    });72    fs.removeSync(outDir);73    fs.ensureDirSync(outDir);74    if (type) {75      build({ outFileExtension, type });76    } else {77      for (const [outFileExtension, type] of options(78        fs.readJsonSync(process.env.npm_package_json)79      )) {80        build({ outFileExtension, type });81      }82    }...Using AI Code Generation
1const { includedArgs } = require('storybook-root');2const { includedArgs } = require('storybook-root');3const { includedArgs } = require('storybook-root');4const { includedArgs } = require('storybook-root');5const { includedArgs } = require('storybook-root');6const { includedArgs } = require('storybook-root');7const { includedArgs } = require('storybook-root');8const { includedArgs } = require('storybook-root');9const { includedArgs } = require('storybook-root');10const { includedArgs } = require('storybook-root');11const { includedArgs } = require('storybook-root');Using AI Code Generation
1import { includedArgs } from 'storybook-root'2const args = includedArgs('TestComponent')3export default {4}5export const Test = (args) => <TestComponent {...args} />6import Test from './test'7import { includedArgs } from 'storybook-root'8const args = includedArgs('TestComponent')9export default {10}11export const Test = (args) => <TestComponent {...args} />12import { includedArgs } from 'storybook-root'13const args = includedArgs('TestComponent')14export default {15}16export const Test = (args) => <TestComponent {...args} />17import { includedArgs } from 'storybook-root'18const args = includedArgs('TestComponent')19export default {20}21export const Test = (args) => <TestComponent {...args} />22import { includedArgs } from 'storybook-root'23const args = includedArgs('TestComponent')24export default {25}26export const Test = (args) => <TestComponent {...args} />27import { includedArgs } from 'storybook-root'28const args = includedArgs('TestComponent')29export default {30}31export const Test = (args) => <TestComponent {...args} />32import Test from './test'Using AI Code Generation
1import { includedArgs } from 'storybook-root';2export const test = () => {3  const args = includedArgs('test', { a: 1, b: 2, c: 3 }, ['a', 'b']);4  console.log(args);5};6test.story = {7  parameters: {8  },9};10import { test } from './test';11export default {12};13export { test };14module.exports = {15};16import { withIncludedArgs } from 'storybook-root';17export const decorators = [withIncludedArgs];18import { addons } from '@storybook/addons';19import { create } from 'storybook-root';20addons.setConfig({21  theme: create({Using AI Code Generation
1import includedArgs from 'storybook-root'2const args = includedArgs('test.js')3console.log(args)4import includedArgs from 'storybook-root'5const args = includedArgs('test.js')6console.log(args)7import includedArgs from 'storybook-root'8const args = includedArgs('test.js')9console.log(args)10import includedArgs from 'storybook-root'11const args = includedArgs('test.js')12console.log(args)13import includedArgs from 'storybook-root'14const args = includedArgs('test.js')15console.log(args)16import includedArgs from 'storybook-root'17const args = includedArgs('test.js')18console.log(args)19import includedArgs from 'storybook-root'20const args = includedArgs('test.js')21console.log(args)22import includedArgs from 'storybook-root'23const args = includedArgs('test.js')24console.log(args)25import includedArgs from 'storybook-root'26const args = includedArgs('test.js')27console.log(args)28import includedArgs from 'storybook-root'29const args = includedArgs('test.js')30console.log(args)31import includedArgs from 'storybook-root'32const args = includedArgs('test.js')33console.log(args)34import includedArgs from 'storybook-root'35const args = includedArgs('test.js')36console.log(args)Using AI Code Generation
1import { includedArgs } from "storybook-root";2const args = includedArgs(["a", "b", "c"]);3import { excludedArgs } from "storybook-root";4const args = excludedArgs(["a", "b", "c"]);5import { argsFrom } from "storybook-root";6const args = argsFrom({ a: "a", b: "b", c: "c" });7import { argsExcept } from "storybook-root";8const args = argsExcept(["a", "b", "c"]);9import { argsOf } from "storybook-root";10const args = argsOf("story-id");11import { argsOf } from "storybook-root";12const args = argsOf("story-id", ["a", "b", "c"]);13import { argsOf } from "storybook-root";14const args = argsOf("story-id", { a: "a", b: "b", c: "c" });15import { argsOf } from "storybook-root";16const args = argsOf("story-id", ["a", "b", "c"], { a: "a", b: "b", c: "c" });Using AI Code Generation
1import { includedArgs } from 'storybook-root'2const args = includedArgs('MyComponent', 'MyStory')3import { includedArgs } from 'storybook-root'4const args = includedArgs('MyComponent', 'MyStory')5import { includedArgs } from 'storybook-root'6const args = includedArgs('MyComponent', 'MyStory')7import { includedArgs } from 'storybook-root'8const args = includedArgs('MyComponent', 'MyStory')9import { includedArgs } from 'storybook-root'10const args = includedArgs('MyComponent', 'MyStory')11import { includedArgs } from 'storybook-root'12const args = includedArgs('MyComponent', 'MyStory')13import { includedArgs } from 'storybook-root'14const args = includedArgs('MyComponent', 'MyStory')15import { includedArgs } from 'storybook-root'16const args = includedArgs('MyComponent', 'MyStory')17import { includedArgs } from 'storybook-root'18const args = includedArgs('MyComponent', 'MyStory')Using AI Code Generation
1import { includedArgs } from 'storybook-root';2export const testStory = () => {3  const args = includedArgs('includedStory');4  return <div>args: {args}</div>;5};6import { includedArgs } from 'storybook-root';7export const includedStory = () => {8  const args = includedArgs('testStory');9  return <div>args: {args}</div>;10};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!!
