@storybook/preview-api 7.6.0-alpha.5 → 7.6.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ClientApi-05c010e0.d.ts → ClientApi-24d2bfd0.d.ts} +2 -2
- package/dist/{StoryStore-9da974c1.d.ts → StoryStore-f7424ddf.d.ts} +1 -1
- package/dist/{chunk-RNETQBO7.mjs → chunk-AWJHIX2X.mjs} +1 -1
- package/dist/{chunk-D4JSJKCX.mjs → chunk-G3V2D3GG.mjs} +2 -2
- package/dist/{chunk-6GQAXYXY.mjs → chunk-HOTYVPG7.mjs} +1 -1
- package/dist/chunk-VLGOEOTZ.mjs +53 -0
- package/dist/client-api.d.ts +3 -3
- package/dist/client-api.js +4 -4
- package/dist/client-api.mjs +2 -2
- package/dist/core-client.d.ts +2 -2
- package/dist/core-client.js +4 -4
- package/dist/core-client.mjs +4 -4
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -4
- package/dist/index.mjs +4 -4
- package/dist/preview-web.d.ts +10 -10
- package/dist/preview-web.js +4 -4
- package/dist/preview-web.mjs +2 -2
- package/dist/{sortStories-7312444d.d.ts → sortStories-436f1964.d.ts} +1 -1
- package/dist/store.d.ts +3 -3
- package/dist/store.js +4 -4
- package/dist/store.mjs +1 -1
- package/package.json +9 -10
- package/dist/chunk-ZVJD52XQ.mjs +0 -53
package/dist/index.js
CHANGED
|
@@ -11,21 +11,21 @@ Incoming: ${deps}`),(deps==null||hook.deps==null||!areDepsEqual(deps,hook.deps))
|
|
|
11
11
|
Invalid argType: '${key}.options' should only contain primitives. Use a 'mapping' for complex values.
|
|
12
12
|
|
|
13
13
|
More info: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
|
|
14
|
-
`),allowArg();let isArray=Array.isArray(args[key]),invalidIndex=isArray&&args[key].findIndex(val=>!options.includes(val)),isValidArray=isArray&&invalidIndex===-1;if(args[key]===void 0||options.includes(args[key])||isValidArray)return allowArg();let field=isArray?`${key}[${invalidIndex}]`:key,supportedOptions=options.map(opt=>typeof opt=="string"?`'${opt}'`:String(opt)).join(", ");return import_client_logger2.once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`),acc},{}),DEEPLY_EQUAL=Symbol("Deeply equal"),deepDiff=(value,update)=>{if(typeof value!=typeof update)return update;if((0,import_dequal.dequal)(value,update))return DEEPLY_EQUAL;if(Array.isArray(value)&&Array.isArray(update)){let res=update.reduce((acc,upd,index)=>{let diff=deepDiff(value[index],upd);return diff!==DEEPLY_EQUAL&&(acc[index]=diff),acc},new Array(update.length));return update.length>=value.length?res:res.concat(new Array(value.length-update.length).fill(void 0))}return(0,import_isPlainObject.default)(value)&&(0,import_isPlainObject.default)(update)?Object.keys({...value,...update}).reduce((acc,key)=>{let diff=deepDiff(value==null?void 0:value[key],update==null?void 0:update[key]);return diff===DEEPLY_EQUAL?acc:Object.assign(acc,{[key]:diff})},{}):update},UNTARGETED="UNTARGETED";function groupArgsByTarget({args,argTypes}){let groupedArgs={};return Object.entries(args).forEach(([name,value])=>{let{target=UNTARGETED}=argTypes[name]||{};groupedArgs[target]=groupedArgs[target]||{},groupedArgs[target][name]=value}),groupedArgs}function deleteUndefined(obj){return Object.keys(obj).forEach(key=>obj[key]===void 0&&delete obj[key]),obj}var ArgsStore=class{constructor(){this.initialArgsByStoryId={};this.argsByStoryId={}}get(storyId){if(!(storyId in this.argsByStoryId))throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);return this.argsByStoryId[storyId]}setInitial(story){if(!this.initialArgsByStoryId[story.id])this.initialArgsByStoryId[story.id]=story.initialArgs,this.argsByStoryId[story.id]=story.initialArgs;else if(this.initialArgsByStoryId[story.id]!==story.initialArgs){let delta=deepDiff(this.initialArgsByStoryId[story.id],this.argsByStoryId[story.id]);this.initialArgsByStoryId[story.id]=story.initialArgs,this.argsByStoryId[story.id]=story.initialArgs,delta!==DEEPLY_EQUAL&&this.updateFromDelta(story,delta)}}updateFromDelta(story,delta){let validatedDelta=validateOptions(delta,story.argTypes);this.argsByStoryId[story.id]=combineArgs(this.argsByStoryId[story.id],validatedDelta)}updateFromPersisted(story,persisted){let mappedPersisted=mapArgsToTypes(persisted,story.argTypes);return this.updateFromDelta(story,mappedPersisted)}update(storyId,argsUpdate){if(!(storyId in this.argsByStoryId))throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);this.argsByStoryId[storyId]=deleteUndefined({...this.argsByStoryId[storyId],...argsUpdate})}};var import_client_logger3=require("@storybook/client-logger");var getValuesFromArgTypes=(argTypes={})=>Object.entries(argTypes).reduce((acc,[arg,{defaultValue}])=>(typeof defaultValue<"u"&&(acc[arg]=defaultValue),acc),{});var GlobalsStore=class{constructor({globals={},globalTypes={}}){this.set({globals,globalTypes})}set({globals={},globalTypes={}}){let delta=this.initialGlobals&&deepDiff(this.initialGlobals,this.globals);this.allowedGlobalNames=new Set([...Object.keys(globals),...Object.keys(globalTypes)]);let defaultGlobals=getValuesFromArgTypes(globalTypes);this.initialGlobals={...defaultGlobals,...globals},this.globals=this.initialGlobals,delta&&delta!==DEEPLY_EQUAL&&this.updateFromPersisted(delta)}filterAllowedGlobals(globals){return Object.entries(globals).reduce((acc,[key,value])=>(this.allowedGlobalNames.has(key)?acc[key]=value:import_client_logger3.logger.warn(`Attempted to set a global (${key}) that is not defined in initial globals or globalTypes`),acc),{})}updateFromPersisted(persisted){let allowedUrlGlobals=this.filterAllowedGlobals(persisted);this.globals={...this.globals,...allowedUrlGlobals}}get(){return this.globals}update(newGlobals){this.globals={...this.globals,...this.filterAllowedGlobals(newGlobals)}}};var import_mapValues=__toESM(require("lodash/mapValues.js")),normalizeType=type=>typeof type=="string"?{name:type}:type,normalizeControl=control=>typeof control=="string"?{type:control}:control,normalizeInputType=(inputType,key)=>{let{type,control,...rest}=inputType,normalized={name:key,...rest};return type&&(normalized.type=normalizeType(type)),control?normalized.control=normalizeControl(control):control===!1&&(normalized.control={disable:!0}),normalized},normalizeInputTypes=inputTypes=>(0,import_mapValues.default)(inputTypes,normalizeInputType);var import_csf=require("@storybook/csf"),import_ts_dedent2=require("ts-dedent"),import_client_logger4=require("@storybook/client-logger"),import_util_deprecate=__toESM(require("util-deprecate"));var deprecatedStoryAnnotation=import_ts_dedent2.dedent`
|
|
14
|
+
`),allowArg();let isArray=Array.isArray(args[key]),invalidIndex=isArray&&args[key].findIndex(val=>!options.includes(val)),isValidArray=isArray&&invalidIndex===-1;if(args[key]===void 0||options.includes(args[key])||isValidArray)return allowArg();let field=isArray?`${key}[${invalidIndex}]`:key,supportedOptions=options.map(opt=>typeof opt=="string"?`'${opt}'`:String(opt)).join(", ");return import_client_logger2.once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`),acc},{}),DEEPLY_EQUAL=Symbol("Deeply equal"),deepDiff=(value,update)=>{if(typeof value!=typeof update)return update;if((0,import_dequal.dequal)(value,update))return DEEPLY_EQUAL;if(Array.isArray(value)&&Array.isArray(update)){let res=update.reduce((acc,upd,index)=>{let diff=deepDiff(value[index],upd);return diff!==DEEPLY_EQUAL&&(acc[index]=diff),acc},new Array(update.length));return update.length>=value.length?res:res.concat(new Array(value.length-update.length).fill(void 0))}return(0,import_isPlainObject.default)(value)&&(0,import_isPlainObject.default)(update)?Object.keys({...value,...update}).reduce((acc,key)=>{let diff=deepDiff(value==null?void 0:value[key],update==null?void 0:update[key]);return diff===DEEPLY_EQUAL?acc:Object.assign(acc,{[key]:diff})},{}):update},UNTARGETED="UNTARGETED";function groupArgsByTarget({args,argTypes}){let groupedArgs={};return Object.entries(args).forEach(([name,value])=>{let{target=UNTARGETED}=argTypes[name]||{};groupedArgs[target]=groupedArgs[target]||{},groupedArgs[target][name]=value}),groupedArgs}function deleteUndefined(obj){return Object.keys(obj).forEach(key=>obj[key]===void 0&&delete obj[key]),obj}var ArgsStore=class{constructor(){this.initialArgsByStoryId={};this.argsByStoryId={}}get(storyId){if(!(storyId in this.argsByStoryId))throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);return this.argsByStoryId[storyId]}setInitial(story){if(!this.initialArgsByStoryId[story.id])this.initialArgsByStoryId[story.id]=story.initialArgs,this.argsByStoryId[story.id]=story.initialArgs;else if(this.initialArgsByStoryId[story.id]!==story.initialArgs){let delta=deepDiff(this.initialArgsByStoryId[story.id],this.argsByStoryId[story.id]);this.initialArgsByStoryId[story.id]=story.initialArgs,this.argsByStoryId[story.id]=story.initialArgs,delta!==DEEPLY_EQUAL&&this.updateFromDelta(story,delta)}}updateFromDelta(story,delta){let validatedDelta=validateOptions(delta,story.argTypes);this.argsByStoryId[story.id]=combineArgs(this.argsByStoryId[story.id],validatedDelta)}updateFromPersisted(story,persisted){let mappedPersisted=mapArgsToTypes(persisted,story.argTypes);return this.updateFromDelta(story,mappedPersisted)}update(storyId,argsUpdate){if(!(storyId in this.argsByStoryId))throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);this.argsByStoryId[storyId]=deleteUndefined({...this.argsByStoryId[storyId],...argsUpdate})}};var import_client_logger3=require("@storybook/client-logger");var getValuesFromArgTypes=(argTypes={})=>Object.entries(argTypes).reduce((acc,[arg,{defaultValue}])=>(typeof defaultValue<"u"&&(acc[arg]=defaultValue),acc),{});var GlobalsStore=class{constructor({globals={},globalTypes={}}){this.set({globals,globalTypes})}set({globals={},globalTypes={}}){let delta=this.initialGlobals&&deepDiff(this.initialGlobals,this.globals);this.allowedGlobalNames=new Set([...Object.keys(globals),...Object.keys(globalTypes)]);let defaultGlobals=getValuesFromArgTypes(globalTypes);this.initialGlobals={...defaultGlobals,...globals},this.globals=this.initialGlobals,delta&&delta!==DEEPLY_EQUAL&&this.updateFromPersisted(delta)}filterAllowedGlobals(globals){return Object.entries(globals).reduce((acc,[key,value])=>(this.allowedGlobalNames.has(key)?acc[key]=value:import_client_logger3.logger.warn(`Attempted to set a global (${key}) that is not defined in initial globals or globalTypes`),acc),{})}updateFromPersisted(persisted){let allowedUrlGlobals=this.filterAllowedGlobals(persisted);this.globals={...this.globals,...allowedUrlGlobals}}get(){return this.globals}update(newGlobals){this.globals={...this.globals,...this.filterAllowedGlobals(newGlobals)}}};var import_mapValues=__toESM(require("lodash/mapValues.js")),normalizeType=type=>typeof type=="string"?{name:type}:type,normalizeControl=control=>typeof control=="string"?{type:control}:control,normalizeInputType=(inputType,key)=>{let{type,control,...rest}=inputType,normalized={name:key,...rest};return type&&(normalized.type=normalizeType(type)),control?normalized.control=normalizeControl(control):control===!1&&(normalized.control={disable:!0}),normalized},normalizeInputTypes=inputTypes=>(0,import_mapValues.default)(inputTypes,normalizeInputType);var import_csf=require("@storybook/csf"),import_ts_dedent2=require("ts-dedent"),import_client_logger4=require("@storybook/client-logger"),import_util_deprecate=__toESM(require("util-deprecate"));var normalizeArrays=array=>Array.isArray(array)?array:array?[array]:[];var deprecatedStoryAnnotation=import_ts_dedent2.dedent`
|
|
15
15
|
CSF .story annotations deprecated; annotate story functions directly:
|
|
16
16
|
- StoryFn.story.name => StoryFn.storyName
|
|
17
17
|
- StoryFn.story.(parameters|decorators) => StoryFn.(parameters|decorators)
|
|
18
18
|
See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-annotations for details and codemod.
|
|
19
|
-
`,deprecatedStoryAnnotationWarning=(0,import_util_deprecate.default)(()=>{},deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){let storyObject=storyAnnotations,userStoryFn=typeof storyAnnotations=="function"?storyAnnotations:null,{story}=storyObject;story&&(import_client_logger4.logger.debug("deprecated story",story),deprecatedStoryAnnotationWarning());let exportName=(0,import_csf.storyNameFromExport)(key),name=typeof storyObject!="function"&&storyObject.name||storyObject.storyName||(story==null?void 0:story.name)||exportName,decorators=[...storyObject.decorators
|
|
19
|
+
`,deprecatedStoryAnnotationWarning=(0,import_util_deprecate.default)(()=>{},deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){let storyObject=storyAnnotations,userStoryFn=typeof storyAnnotations=="function"?storyAnnotations:null,{story}=storyObject;story&&(import_client_logger4.logger.debug("deprecated story",story),deprecatedStoryAnnotationWarning());let exportName=(0,import_csf.storyNameFromExport)(key),name=typeof storyObject!="function"&&storyObject.name||storyObject.storyName||(story==null?void 0:story.name)||exportName,decorators=[...normalizeArrays(storyObject.decorators),...normalizeArrays(story==null?void 0:story.decorators)],parameters={...story==null?void 0:story.parameters,...storyObject.parameters},args={...story==null?void 0:story.args,...storyObject.args},argTypes={...story==null?void 0:story.argTypes,...storyObject.argTypes},loaders=[...normalizeArrays(storyObject.loaders),...normalizeArrays(story==null?void 0:story.loaders)],{render,play,tags=[]}=storyObject,id=parameters.__id||(0,import_csf.toId)(meta.id,exportName);return{moduleExport:storyAnnotations,id,name,tags,decorators,parameters,args,argTypes:normalizeInputTypes(argTypes),loaders,...render&&{render},...userStoryFn&&{userStoryFn},...play&&{play}}}var import_csf3=require("@storybook/csf"),import_client_logger5=require("@storybook/client-logger"),import_ts_dedent3=__toESM(require("ts-dedent"));var import_csf2=require("@storybook/csf");function normalizeComponentAnnotations(defaultExport,title=defaultExport.title,importPath){let{id,argTypes}=defaultExport;return{id:(0,import_csf2.sanitize)(id||title),...defaultExport,title,...argTypes&&{argTypes:normalizeInputTypes(argTypes)},parameters:{fileName:importPath,...defaultExport.parameters}}}var checkGlobals=parameters=>{let{globals,globalTypes}=parameters;(globals||globalTypes)&&import_client_logger5.logger.error("Global args/argTypes can only be set globally",JSON.stringify({globals,globalTypes}))},checkStorySort=parameters=>{let{options}=parameters;options!=null&&options.storySort&&import_client_logger5.logger.error("The storySort option parameter can only be set globally")},checkDisallowedParameters=parameters=>{parameters&&(checkGlobals(parameters),checkStorySort(parameters))},checkSubcomponents=meta=>{meta.subcomponents&&(0,import_client_logger5.deprecate)(import_ts_dedent3.default`The \`subcomponents\` annotation is deprecated.
|
|
20
20
|
|
|
21
21
|
Please refer to the migration guide: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#argstable-block'
|
|
22
|
-
`)};function processCSFFile(moduleExports,importPath,title){let{default:defaultExport,__namedExportsOrder,...namedExports}=moduleExports,meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters),checkSubcomponents(meta);let csfFile={meta,stories:{},moduleExports};return Object.keys(namedExports).forEach(key=>{if((0,import_csf3.isExportStory)(key,meta)){let storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta}}),csfFile}var import_global3=require("@storybook/global"),import_csf4=require("@storybook/csf");var import_isPlainObject2=__toESM(require("lodash/isPlainObject.js")),combineParameters=(...parameterSets)=>{let mergeKeys={},definedParametersSets=parameterSets.filter(Boolean),combined=definedParametersSets.reduce((acc,parameters)=>(Object.entries(parameters).forEach(([key,value])=>{let existing=acc[key];Array.isArray(value)||typeof existing>"u"?acc[key]=value:(0,import_isPlainObject2.default)(value)&&(0,import_isPlainObject2.default)(existing)?mergeKeys[key]=!0:typeof value<"u"&&(acc[key]=value)}),acc),{});return Object.keys(mergeKeys).forEach(key=>{let mergeValues=definedParametersSets.filter(Boolean).map(p=>p[key]).filter(value=>typeof value<"u");mergeValues.every(value=>(0,import_isPlainObject2.default)(value))?combined[key]=combineParameters(...mergeValues):combined[key]=mergeValues[mergeValues.length-1]}),combined};function decorateStory(storyFn,decorator,bindWithContext){let boundStoryFunction=bindWithContext(storyFn);return context=>decorator(boundStoryFunction,context)}function sanitizeStoryContextUpdate({componentId,title,kind,id,name,story,parameters,initialArgs,argTypes,...update}={}){return update}function defaultDecorateStory(storyFn,decorators){let contextStore={},bindWithContext=decoratedStoryFn=>update=>{if(!contextStore.value)throw new Error("Decorated function called without init");return contextStore.value={...contextStore.value,...sanitizeStoryContextUpdate(update)},decoratedStoryFn(contextStore.value)},decoratedWithContextStore=decorators.reduce((story,decorator)=>decorateStory(story,decorator,bindWithContext),storyFn);return context=>(contextStore.value=context,decoratedWithContextStore(context))}function prepareStory(storyAnnotations,componentAnnotations,projectAnnotations){let{moduleExport,id,name}=storyAnnotations||{},partialAnnotations=preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations),loaders
|
|
22
|
+
`)};function processCSFFile(moduleExports,importPath,title){let{default:defaultExport,__namedExportsOrder,...namedExports}=moduleExports,meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters),checkSubcomponents(meta);let csfFile={meta,stories:{},moduleExports};return Object.keys(namedExports).forEach(key=>{if((0,import_csf3.isExportStory)(key,meta)){let storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta}}),csfFile}var import_global3=require("@storybook/global"),import_csf4=require("@storybook/csf");var import_isPlainObject2=__toESM(require("lodash/isPlainObject.js")),combineParameters=(...parameterSets)=>{let mergeKeys={},definedParametersSets=parameterSets.filter(Boolean),combined=definedParametersSets.reduce((acc,parameters)=>(Object.entries(parameters).forEach(([key,value])=>{let existing=acc[key];Array.isArray(value)||typeof existing>"u"?acc[key]=value:(0,import_isPlainObject2.default)(value)&&(0,import_isPlainObject2.default)(existing)?mergeKeys[key]=!0:typeof value<"u"&&(acc[key]=value)}),acc),{});return Object.keys(mergeKeys).forEach(key=>{let mergeValues=definedParametersSets.filter(Boolean).map(p=>p[key]).filter(value=>typeof value<"u");mergeValues.every(value=>(0,import_isPlainObject2.default)(value))?combined[key]=combineParameters(...mergeValues):combined[key]=mergeValues[mergeValues.length-1]}),combined};function decorateStory(storyFn,decorator,bindWithContext){let boundStoryFunction=bindWithContext(storyFn);return context=>decorator(boundStoryFunction,context)}function sanitizeStoryContextUpdate({componentId,title,kind,id,name,story,parameters,initialArgs,argTypes,...update}={}){return update}function defaultDecorateStory(storyFn,decorators){let contextStore={},bindWithContext=decoratedStoryFn=>update=>{if(!contextStore.value)throw new Error("Decorated function called without init");return contextStore.value={...contextStore.value,...sanitizeStoryContextUpdate(update)},decoratedStoryFn(contextStore.value)},decoratedWithContextStore=decorators.reduce((story,decorator)=>decorateStory(story,decorator,bindWithContext),storyFn);return context=>(contextStore.value=context,decoratedWithContextStore(context))}function prepareStory(storyAnnotations,componentAnnotations,projectAnnotations){let{moduleExport,id,name}=storyAnnotations||{},partialAnnotations=preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations),applyLoaders=async context=>{let updatedContext={...context,loaded:{}};for(let loaders of[..."__STORYBOOK_TEST_LOADERS__"in import_global3.global&&Array.isArray(import_global3.global.__STORYBOOK_TEST_LOADERS__)?[import_global3.global.__STORYBOOK_TEST_LOADERS__]:[],normalizeArrays(projectAnnotations.loaders),normalizeArrays(componentAnnotations.loaders),normalizeArrays(storyAnnotations.loaders)]){let loadResults=await Promise.all(loaders.map(loader=>loader(updatedContext))),loaded=Object.assign({},...loadResults);updatedContext={...updatedContext,loaded:{...updatedContext.loaded,...loaded}}}return updatedContext},undecoratedStoryFn=context=>{let{passArgsFirst:renderTimePassArgsFirst=!0}=context.parameters;return renderTimePassArgsFirst?render(context.args,context):render(context)},{applyDecorators=defaultDecorateStory,runStep}=projectAnnotations,decorators=[...normalizeArrays(storyAnnotations==null?void 0:storyAnnotations.decorators),...normalizeArrays(componentAnnotations==null?void 0:componentAnnotations.decorators),...normalizeArrays(projectAnnotations==null?void 0:projectAnnotations.decorators)],render=(storyAnnotations==null?void 0:storyAnnotations.userStoryFn)||(storyAnnotations==null?void 0:storyAnnotations.render)||componentAnnotations.render||projectAnnotations.render;if(!render)throw new Error(`No render function available for storyId '${id}'`);let decoratedStoryFn=applyHooks(applyDecorators)(undecoratedStoryFn,decorators),unboundStoryFn=context=>decoratedStoryFn(context),play=(storyAnnotations==null?void 0:storyAnnotations.play)||componentAnnotations.play;return{...partialAnnotations,moduleExport,id,name,story:name,originalStoryFn:render,undecoratedStoryFn,unboundStoryFn,applyLoaders,playFunction:play&&(async storyContext=>{let playFunctionContext={...storyContext,step:(label,play2)=>runStep(label,play2,playFunctionContext)};return play(playFunctionContext)})}}function prepareMeta(componentAnnotations,projectAnnotations,moduleExport){return{...preparePartialAnnotations(void 0,componentAnnotations,projectAnnotations),moduleExport}}function preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations){let tags=[...(storyAnnotations==null?void 0:storyAnnotations.tags)||componentAnnotations.tags||[],"story"],parameters=combineParameters(projectAnnotations.parameters,componentAnnotations.parameters,storyAnnotations==null?void 0:storyAnnotations.parameters),{argTypesEnhancers=[],argsEnhancers=[]}=projectAnnotations,passedArgTypes=combineParameters(projectAnnotations.argTypes,componentAnnotations.argTypes,storyAnnotations==null?void 0:storyAnnotations.argTypes);if(storyAnnotations){let render=(storyAnnotations==null?void 0:storyAnnotations.userStoryFn)||(storyAnnotations==null?void 0:storyAnnotations.render)||componentAnnotations.render||projectAnnotations.render,{passArgsFirst=!0}=parameters;parameters.__isArgsStory=passArgsFirst&&render&&render.length>0}let passedArgs={...projectAnnotations.args,...componentAnnotations.args,...storyAnnotations==null?void 0:storyAnnotations.args},contextForEnhancers={componentId:componentAnnotations.id,title:componentAnnotations.title,kind:componentAnnotations.title,id:(storyAnnotations==null?void 0:storyAnnotations.id)||componentAnnotations.id,name:(storyAnnotations==null?void 0:storyAnnotations.name)||"__meta",story:(storyAnnotations==null?void 0:storyAnnotations.name)||"__meta",component:componentAnnotations.component,subcomponents:componentAnnotations.subcomponents,tags,parameters,initialArgs:passedArgs,argTypes:passedArgTypes};contextForEnhancers.argTypes=argTypesEnhancers.reduce((accumulatedArgTypes,enhancer)=>enhancer({...contextForEnhancers,argTypes:accumulatedArgTypes}),contextForEnhancers.argTypes);let initialArgsBeforeEnhancers={...passedArgs};contextForEnhancers.initialArgs=argsEnhancers.reduce((accumulatedArgs,enhancer)=>({...accumulatedArgs,...enhancer({...contextForEnhancers,initialArgs:accumulatedArgs})}),initialArgsBeforeEnhancers);let{name,story,...withoutStoryIdentifiers}=contextForEnhancers;return withoutStoryIdentifiers}function prepareContext(context){var _a;let{args:unmappedArgs}=context,targetedContext={...context,allArgs:void 0,argsByTarget:void 0};if((_a=import_global3.global.FEATURES)!=null&&_a.argTypeTargetsV7){let argsByTarget=groupArgsByTarget(context);targetedContext={...context,allArgs:context.args,argsByTarget,args:argsByTarget[UNTARGETED]||{}}}let mappedArgs=Object.entries(targetedContext.args).reduce((acc,[key,val])=>{var _a2;if(!((_a2=targetedContext.argTypes[key])!=null&&_a2.mapping))return acc[key]=val,acc;let mappingFn=originalValue=>originalValue in targetedContext.argTypes[key].mapping?targetedContext.argTypes[key].mapping[originalValue]:originalValue;return acc[key]=Array.isArray(val)?val.map(mappingFn):mappingFn(val),acc},{}),includedArgs=Object.entries(mappedArgs).reduce((acc,[key,val])=>{let argType=targetedContext.argTypes[key]||{};return(0,import_csf4.includeConditionalArg)(argType,mappedArgs,targetedContext.globals)&&(acc[key]=val),acc},{});return{...targetedContext,unmappedArgs,args:includedArgs}}var import_mapValues2=__toESM(require("lodash/mapValues.js")),import_ts_dedent4=require("ts-dedent"),import_client_logger6=require("@storybook/client-logger");var inferType=(value,name,visited)=>{let type=typeof value;switch(type){case"boolean":case"string":case"number":case"function":case"symbol":return{name:type};default:break}return value?visited.has(value)?(import_client_logger6.logger.warn(import_ts_dedent4.dedent`
|
|
23
23
|
We've detected a cycle in arg '${name}'. Args should be JSON-serializable.
|
|
24
24
|
|
|
25
25
|
Consider using the mapping feature or fully custom args:
|
|
26
26
|
- Mapping: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
|
|
27
27
|
- Custom args: https://storybook.js.org/docs/react/essentials/controls#fully-custom-args
|
|
28
|
-
`),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:(0,import_mapValues2.default)(value,field=>inferType(field,name,new Set(visited)))}):{name:"object",value:{}}},inferArgTypes=context=>{let{id,argTypes:userArgTypes={},initialArgs={}}=context,argTypes=(0,import_mapValues2.default)(initialArgs,(arg,key)=>({name:key,type:inferType(arg,`${id}.${key}`,new Set)})),userArgTypesNames=(0,import_mapValues2.default)(userArgTypes,(argType,key)=>({name:key}));return combineParameters(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var import_mapValues3=__toESM(require("lodash/mapValues.js")),import_client_logger7=require("@storybook/client-logger");var import_pickBy=__toESM(require("lodash/pickBy.js")),matches=(name,descriptor)=>Array.isArray(descriptor)?descriptor.includes(name):name.match(descriptor),filterArgTypes=(argTypes,include,exclude)=>!include&&!exclude?argTypes:argTypes&&(0,import_pickBy.default)(argTypes,(argType,key)=>{let name=argType.name||key;return(!include||matches(name,include))&&(!exclude||!matches(name,exclude))});var inferControl=(argType,name,matchers)=>{let{type,options}=argType;if(type){if(matchers.color&&matchers.color.test(name)){let controlType=type.name;if(controlType==="string")return{control:{type:"color"}};controlType!=="enum"&&import_client_logger7.logger.warn(`Addon controls: Control of type color only supports string, received "${controlType}" instead`)}if(matchers.date&&matchers.date.test(name))return{control:{type:"date"}};switch(type.name){case"array":return{control:{type:"object"}};case"boolean":return{control:{type:"boolean"}};case"string":return{control:{type:"text"}};case"number":return{control:{type:"number"}};case"enum":{let{value}=type;return{control:{type:(value==null?void 0:value.length)<=5?"radio":"select"},options:value}}case"function":case"symbol":return null;default:return{control:{type:options?"select":"object"}}}}},inferControls=context=>{let{argTypes,parameters:{__isArgsStory,controls:{include=null,exclude=null,matchers={}}={}}}=context;if(!__isArgsStory)return argTypes;let filteredArgTypes=filterArgTypes(argTypes,include,exclude),withControls=(0,import_mapValues3.default)(filteredArgTypes,(argType,name)=>(argType==null?void 0:argType.type)&&inferControl(argType,name,matchers));return combineParameters(withControls,filteredArgTypes)};inferControls.secondPass=!0;function normalizeProjectAnnotations({argTypes,globalTypes,argTypesEnhancers,...annotations}){return{...argTypes&&{argTypes:normalizeInputTypes(argTypes)},...globalTypes&&{globalTypes:normalizeInputTypes(globalTypes)},argTypesEnhancers:[...argTypesEnhancers||[],inferArgTypes,inferControls],...annotations}}var import_global4=require("@storybook/global");function composeStepRunners(stepRunners){return async(label,play,playContext)=>{await stepRunners.reduceRight((innerPlay,stepRunner)=>async()=>stepRunner(label,innerPlay,playContext),async()=>play(playContext))()}}function getField(moduleExportList,field){return moduleExportList.map(xs=>{var _a;return((_a=xs.default)==null?void 0:_a[field])??xs[field]}).filter(Boolean)}function getArrayField(moduleExportList,field,options={}){return getField(moduleExportList,field).reduce((a,b)=>options.reverseFileOrder?[...b,...a]:[...a,...b],[])}function getObjectField(moduleExportList,field){return Object.assign({},...getField(moduleExportList,field))}function getSingletonField(moduleExportList,field){return getField(moduleExportList,field).pop()}function composeConfigs(moduleExportList){var _a;let allArgTypeEnhancers=getArrayField(moduleExportList,"argTypesEnhancers"),stepRunners=getField(moduleExportList,"runStep");return{parameters:combineParameters(...getField(moduleExportList,"parameters")),decorators:getArrayField(moduleExportList,"decorators",{reverseFileOrder:!(((_a=import_global4.global.FEATURES)==null?void 0:_a.legacyDecoratorFileOrder)??!1)}),args:getObjectField(moduleExportList,"args"),argsEnhancers:getArrayField(moduleExportList,"argsEnhancers"),argTypes:getObjectField(moduleExportList,"argTypes"),argTypesEnhancers:[...allArgTypeEnhancers.filter(e=>!e.secondPass),...allArgTypeEnhancers.filter(e=>e.secondPass)],globals:getObjectField(moduleExportList,"globals"),globalTypes:getObjectField(moduleExportList,"globalTypes"),loaders:getArrayField(moduleExportList,"loaders"),render:getSingletonField(moduleExportList,"render"),renderToCanvas:getSingletonField(moduleExportList,"renderToCanvas"),renderToDOM:getSingletonField(moduleExportList,"renderToDOM"),applyDecorators:getSingletonField(moduleExportList,"applyDecorators"),runStep:composeStepRunners(stepRunners)}}var import_csf5=require("@storybook/csf");var GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS=composeConfigs([]);function setProjectAnnotations(projectAnnotations){let annotations=Array.isArray(projectAnnotations)?projectAnnotations:[projectAnnotations];GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS=composeConfigs(annotations)}function composeStory(storyAnnotations,componentAnnotations,projectAnnotations=GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS,defaultConfig={},exportsName){var _a;if(storyAnnotations===void 0)throw new Error("Expected a story but received undefined.");componentAnnotations.title=componentAnnotations.title??"ComposedStory";let normalizedComponentAnnotations=normalizeComponentAnnotations(componentAnnotations),storyName=exportsName||storyAnnotations.storyName||((_a=storyAnnotations.story)==null?void 0:_a.name)||storyAnnotations.name||"unknown",normalizedStory=normalizeStory(storyName,storyAnnotations,normalizedComponentAnnotations),normalizedProjectAnnotations=normalizeProjectAnnotations({...projectAnnotations,...defaultConfig}),story=prepareStory(normalizedStory,normalizedComponentAnnotations,normalizedProjectAnnotations),defaultGlobals=getValuesFromArgTypes(projectAnnotations.globalTypes);return Object.assign(extraArgs=>{let context={...story,hooks:new HooksContext,globals:defaultGlobals,args:{...story.initialArgs,...extraArgs}};return story.unboundStoryFn(prepareContext(context))},{storyName,args:story.initialArgs,play:story.playFunction,parameters:story.parameters,id:story.id})}function composeStories(storiesImport,globalConfig,composeStoryFn){let{default:meta,__esModule,__namedExportsOrder,...stories}=storiesImport;return Object.entries(stories).reduce((storiesMap,[exportsName,story])=>(0,import_csf5.isExportStory)(exportsName,meta)?Object.assign(storiesMap,{[exportsName]:composeStoryFn(story,meta,globalConfig,exportsName)}):storiesMap,{})}var CSF_CACHE_SIZE=1e3,STORY_CACHE_SIZE=1e4,EXTRACT_BATCH_SIZE=20,StoryStore=class{constructor(){this.getStoriesJsonData=()=>{let{storyIndex}=this;if(!storyIndex)throw new Error("getStoriesJsonData called before initialization");let value=this.getSetStoriesPayload(),allowedParameters=["fileName","docsOnly","framework","__id","__isArgsStory"];return{v:3,stories:(0,import_mapValues4.default)(value.stories,story=>{let{importPath}=storyIndex.entries[story.id];return{...(0,import_pick.default)(story,["id","name","title"]),importPath,kind:story.title,story:story.name,parameters:{...(0,import_pick.default)(story.parameters,allowedParameters),fileName:importPath}}})}};this.args=new ArgsStore,this.hooks={},this.processCSFFileWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(processCSFFile),this.prepareMetaWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(prepareMeta),this.prepareStoryWithCache=(0,import_memoizerific2.default)(STORY_CACHE_SIZE)(prepareStory),this.initializationPromise=new import_synchronous_promise.SynchronousPromise(resolve=>{this.resolveInitializationPromise=resolve})}setProjectAnnotations(projectAnnotations){this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.globals?this.globals.set({globals,globalTypes}):this.globals=new GlobalsStore({globals,globalTypes})}initialize({storyIndex,importFn,cache=!1}){return this.storyIndex=new StoryIndexStore(storyIndex),this.importFn=importFn,this.resolveInitializationPromise(),cache?this.cacheAllCSFFiles():import_synchronous_promise.SynchronousPromise.resolve()}async onStoriesChanged({importFn,storyIndex}){await this.initializationPromise,importFn&&(this.importFn=importFn),storyIndex&&(this.storyIndex.entries=storyIndex.entries),this.cachedCSFFiles&&await this.cacheAllCSFFiles()}async storyIdToEntry(storyId){return await this.initializationPromise,this.storyIndex.storyIdToEntry(storyId)}loadCSFFileByStoryId(storyId){if(!this.storyIndex||!this.importFn)throw new Error("loadCSFFileByStoryId called before initialization");let{importPath,title}=this.storyIndex.storyIdToEntry(storyId);return this.importFn(importPath).then(moduleExports=>this.processCSFFileWithCache(moduleExports,importPath,title))}loadAllCSFFiles({batchSize=EXTRACT_BATCH_SIZE}={}){if(!this.storyIndex)throw new Error("loadAllCSFFiles called before initialization");let importPaths=Object.entries(this.storyIndex.entries).map(([storyId,{importPath}])=>[importPath,storyId]),loadInBatches=remainingImportPaths=>{if(remainingImportPaths.length===0)return import_synchronous_promise.SynchronousPromise.resolve([]);let csfFilePromiseList=remainingImportPaths.slice(0,batchSize).map(([importPath,storyId])=>this.loadCSFFileByStoryId(storyId).then(csfFile=>({importPath,csfFile})));return import_synchronous_promise.SynchronousPromise.all(csfFilePromiseList).then(firstResults=>loadInBatches(remainingImportPaths.slice(batchSize)).then(restResults=>firstResults.concat(restResults)))};return loadInBatches(importPaths).then(list=>list.reduce((acc,{importPath,csfFile})=>(acc[importPath]=csfFile,acc),{}))}cacheAllCSFFiles(){return this.initializationPromise.then(()=>this.loadAllCSFFiles().then(csfFiles=>{this.cachedCSFFiles=csfFiles}))}preparedMetaFromCSFFile({csfFile}){if(!this.projectAnnotations)throw new Error("storyFromCSFFile called before initialization");let componentAnnotations=csfFile.meta;return this.prepareMetaWithCache(componentAnnotations,this.projectAnnotations,csfFile.moduleExports.default)}async loadStory({storyId}){await this.initializationPromise;let csfFile=await this.loadCSFFileByStoryId(storyId);return this.storyFromCSFFile({storyId,csfFile})}storyFromCSFFile({storyId,csfFile}){if(!this.projectAnnotations)throw new Error("storyFromCSFFile called before initialization");let storyAnnotations=csfFile.stories[storyId];if(!storyAnnotations)throw new Error(`Didn't find '${storyId}' in CSF file, this is unexpected`);let componentAnnotations=csfFile.meta,story=this.prepareStoryWithCache(storyAnnotations,componentAnnotations,this.projectAnnotations);return this.args.setInitial(story),this.hooks[story.id]=this.hooks[story.id]||new HooksContext,story}componentStoriesFromCSFFile({csfFile}){if(!this.storyIndex)throw new Error("componentStoriesFromCSFFile called before initialization");return Object.keys(this.storyIndex.entries).filter(storyId=>!!csfFile.stories[storyId]).map(storyId=>this.storyFromCSFFile({storyId,csfFile}))}async loadEntry(id){let entry=await this.storyIdToEntry(id),{importFn,storyIndex}=this;if(!storyIndex||!importFn)throw new Error("loadEntry called before initialization");let storyImports=entry.type==="docs"?entry.storiesImports:[],[entryExports,...csfFiles]=await Promise.all([importFn(entry.importPath),...storyImports.map(storyImportPath=>{let firstStoryEntry=storyIndex.importPathToEntry(storyImportPath);return this.loadCSFFileByStoryId(firstStoryEntry.id)})]);return{entryExports,csfFiles}}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.globals)throw new Error("getStoryContext called before initialization");return prepareContext({...story,args:forceInitialArgs?story.initialArgs:this.args.get(story.id),globals:this.globals.get(),hooks:this.hooks[story.id]})}cleanupStory(story){this.hooks[story.id].clean()}extract(options={includeDocsOnly:!1}){if(!this.storyIndex)throw new Error("extract called before initialization");let{cachedCSFFiles}=this;if(!cachedCSFFiles)throw new Error("Cannot call extract() unless you call cacheAllCSFFiles() first.");return Object.entries(this.storyIndex.entries).reduce((acc,[storyId,{type,importPath}])=>{if(type==="docs")return acc;let csfFile=cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return!options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((storyAcc,[key,value])=>key==="moduleExport"||typeof value=="function"?storyAcc:Array.isArray(value)?Object.assign(storyAcc,{[key]:value.slice().sort()}):Object.assign(storyAcc,{[key]:value}),{args:story.initialArgs})),acc},{})}getSetStoriesPayload(){if(!this.globals)throw new Error("getSetStoriesPayload called before initialization");let stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((acc,{title})=>(acc[title]={},acc),{});return{v:2,globals:this.globals.get(),globalParameters:{},kindParameters,stories}}getSetIndexPayload(){if(!this.storyIndex)throw new Error("getSetIndexPayload called before initialization");if(!this.cachedCSFFiles)throw new Error("Cannot call getSetIndexPayload() unless you call cacheAllCSFFiles() first");let{cachedCSFFiles}=this,stories=this.extract({includeDocsOnly:!0});return{v:4,entries:Object.fromEntries(Object.entries(this.storyIndex.entries).map(([id,entry])=>[id,stories[id]?{...entry,args:stories[id].initialArgs,initialArgs:stories[id].initialArgs,argTypes:stories[id].argTypes,parameters:stories[id].parameters}:{...entry,parameters:this.preparedMetaFromCSFFile({csfFile:cachedCSFFiles[entry.importPath]}).parameters}]))}}raw(){return Object.values(this.extract()).map(({id})=>this.fromId(id)).filter(Boolean)}fromId(storyId){if(!this.storyIndex)throw new Error("fromId called before initialization");if(!this.cachedCSFFiles)throw new Error("Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.");let importPath;try{({importPath}=this.storyIndex.storyIdToEntry(storyId))}catch{return null}let csfFile=this.cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return{...story,storyFn:update=>{let context={...this.getStoryContext(story),viewMode:"story"};return story.unboundStoryFn({...context,...update})}}}};function slash(path){return path.startsWith("\\\\?\\")?path:path.replace(/\\/g,"/")}var import_ts_dedent5=require("ts-dedent"),import_client_logger8=require("@storybook/client-logger"),stripExtension=path=>{let parts=[...path],last=parts[parts.length-1],dotIndex=last.indexOf("."),stripped=dotIndex>0?last.substr(0,dotIndex):last;parts[parts.length-1]=stripped;let[first,...rest]=parts;return first===""&&(parts=rest),parts},indexRe=/^index$/i,removeRedundantFilename=paths=>{let prevVal;return paths.filter((val,index)=>index===paths.length-1&&(val===prevVal||indexRe.test(val))?!1:(prevVal=val,!0))};function pathJoin(paths){let slashes=new RegExp("/{1,}","g");return paths.join("/").replace(slashes,"/")}var userOrAutoTitleFromSpecifier=(fileName,entry,userTitle)=>{let{directory,importPathMatcher,titlePrefix=""}=entry||{};typeof fileName=="number"&&import_client_logger8.once.warn(import_ts_dedent5.dedent`
|
|
28
|
+
`),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:(0,import_mapValues2.default)(value,field=>inferType(field,name,new Set(visited)))}):{name:"object",value:{}}},inferArgTypes=context=>{let{id,argTypes:userArgTypes={},initialArgs={}}=context,argTypes=(0,import_mapValues2.default)(initialArgs,(arg,key)=>({name:key,type:inferType(arg,`${id}.${key}`,new Set)})),userArgTypesNames=(0,import_mapValues2.default)(userArgTypes,(argType,key)=>({name:key}));return combineParameters(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var import_mapValues3=__toESM(require("lodash/mapValues.js")),import_client_logger7=require("@storybook/client-logger");var import_pickBy=__toESM(require("lodash/pickBy.js")),matches=(name,descriptor)=>Array.isArray(descriptor)?descriptor.includes(name):name.match(descriptor),filterArgTypes=(argTypes,include,exclude)=>!include&&!exclude?argTypes:argTypes&&(0,import_pickBy.default)(argTypes,(argType,key)=>{let name=argType.name||key;return(!include||matches(name,include))&&(!exclude||!matches(name,exclude))});var inferControl=(argType,name,matchers)=>{let{type,options}=argType;if(type){if(matchers.color&&matchers.color.test(name)){let controlType=type.name;if(controlType==="string")return{control:{type:"color"}};controlType!=="enum"&&import_client_logger7.logger.warn(`Addon controls: Control of type color only supports string, received "${controlType}" instead`)}if(matchers.date&&matchers.date.test(name))return{control:{type:"date"}};switch(type.name){case"array":return{control:{type:"object"}};case"boolean":return{control:{type:"boolean"}};case"string":return{control:{type:"text"}};case"number":return{control:{type:"number"}};case"enum":{let{value}=type;return{control:{type:(value==null?void 0:value.length)<=5?"radio":"select"},options:value}}case"function":case"symbol":return null;default:return{control:{type:options?"select":"object"}}}}},inferControls=context=>{let{argTypes,parameters:{__isArgsStory,controls:{include=null,exclude=null,matchers={}}={}}}=context;if(!__isArgsStory)return argTypes;let filteredArgTypes=filterArgTypes(argTypes,include,exclude),withControls=(0,import_mapValues3.default)(filteredArgTypes,(argType,name)=>(argType==null?void 0:argType.type)&&inferControl(argType,name,matchers));return combineParameters(withControls,filteredArgTypes)};inferControls.secondPass=!0;function normalizeProjectAnnotations({argTypes,globalTypes,argTypesEnhancers,decorators,loaders,...annotations}){return{...argTypes&&{argTypes:normalizeInputTypes(argTypes)},...globalTypes&&{globalTypes:normalizeInputTypes(globalTypes)},decorators:normalizeArrays(decorators),loaders:normalizeArrays(loaders),argTypesEnhancers:[...argTypesEnhancers||[],inferArgTypes,inferControls],...annotations}}var import_global4=require("@storybook/global");function composeStepRunners(stepRunners){return async(label,play,playContext)=>{await stepRunners.reduceRight((innerPlay,stepRunner)=>async()=>stepRunner(label,innerPlay,playContext),async()=>play(playContext))()}}function getField(moduleExportList,field){return moduleExportList.map(xs=>{var _a;return((_a=xs.default)==null?void 0:_a[field])??xs[field]}).filter(Boolean)}function getArrayField(moduleExportList,field,options={}){return getField(moduleExportList,field).reduce((a,b)=>options.reverseFileOrder?[...b,...a]:[...a,...b],[])}function getObjectField(moduleExportList,field){return Object.assign({},...getField(moduleExportList,field))}function getSingletonField(moduleExportList,field){return getField(moduleExportList,field).pop()}function composeConfigs(moduleExportList){var _a;let allArgTypeEnhancers=getArrayField(moduleExportList,"argTypesEnhancers"),stepRunners=getField(moduleExportList,"runStep");return{parameters:combineParameters(...getField(moduleExportList,"parameters")),decorators:getArrayField(moduleExportList,"decorators",{reverseFileOrder:!(((_a=import_global4.global.FEATURES)==null?void 0:_a.legacyDecoratorFileOrder)??!1)}),args:getObjectField(moduleExportList,"args"),argsEnhancers:getArrayField(moduleExportList,"argsEnhancers"),argTypes:getObjectField(moduleExportList,"argTypes"),argTypesEnhancers:[...allArgTypeEnhancers.filter(e=>!e.secondPass),...allArgTypeEnhancers.filter(e=>e.secondPass)],globals:getObjectField(moduleExportList,"globals"),globalTypes:getObjectField(moduleExportList,"globalTypes"),loaders:getArrayField(moduleExportList,"loaders"),render:getSingletonField(moduleExportList,"render"),renderToCanvas:getSingletonField(moduleExportList,"renderToCanvas"),renderToDOM:getSingletonField(moduleExportList,"renderToDOM"),applyDecorators:getSingletonField(moduleExportList,"applyDecorators"),runStep:composeStepRunners(stepRunners)}}var import_csf5=require("@storybook/csf");var GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS=composeConfigs([]);function setProjectAnnotations(projectAnnotations){let annotations=Array.isArray(projectAnnotations)?projectAnnotations:[projectAnnotations];GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS=composeConfigs(annotations)}function composeStory(storyAnnotations,componentAnnotations,projectAnnotations=GLOBAL_STORYBOOK_PROJECT_ANNOTATIONS,defaultConfig={},exportsName){var _a;if(storyAnnotations===void 0)throw new Error("Expected a story but received undefined.");componentAnnotations.title=componentAnnotations.title??"ComposedStory";let normalizedComponentAnnotations=normalizeComponentAnnotations(componentAnnotations),storyName=exportsName||storyAnnotations.storyName||((_a=storyAnnotations.story)==null?void 0:_a.name)||storyAnnotations.name||"unknown",normalizedStory=normalizeStory(storyName,storyAnnotations,normalizedComponentAnnotations),normalizedProjectAnnotations=normalizeProjectAnnotations({...projectAnnotations,...defaultConfig}),story=prepareStory(normalizedStory,normalizedComponentAnnotations,normalizedProjectAnnotations),defaultGlobals=getValuesFromArgTypes(projectAnnotations.globalTypes);return Object.assign(extraArgs=>{let context={...story,hooks:new HooksContext,globals:defaultGlobals,args:{...story.initialArgs,...extraArgs}};return story.unboundStoryFn(prepareContext(context))},{storyName,args:story.initialArgs,play:story.playFunction,parameters:story.parameters,id:story.id})}function composeStories(storiesImport,globalConfig,composeStoryFn){let{default:meta,__esModule,__namedExportsOrder,...stories}=storiesImport;return Object.entries(stories).reduce((storiesMap,[exportsName,story])=>(0,import_csf5.isExportStory)(exportsName,meta)?Object.assign(storiesMap,{[exportsName]:composeStoryFn(story,meta,globalConfig,exportsName)}):storiesMap,{})}var CSF_CACHE_SIZE=1e3,STORY_CACHE_SIZE=1e4,EXTRACT_BATCH_SIZE=20,StoryStore=class{constructor(){this.getStoriesJsonData=()=>{let{storyIndex}=this;if(!storyIndex)throw new Error("getStoriesJsonData called before initialization");let value=this.getSetStoriesPayload(),allowedParameters=["fileName","docsOnly","framework","__id","__isArgsStory"];return{v:3,stories:(0,import_mapValues4.default)(value.stories,story=>{let{importPath}=storyIndex.entries[story.id];return{...(0,import_pick.default)(story,["id","name","title"]),importPath,kind:story.title,story:story.name,parameters:{...(0,import_pick.default)(story.parameters,allowedParameters),fileName:importPath}}})}};this.args=new ArgsStore,this.hooks={},this.processCSFFileWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(processCSFFile),this.prepareMetaWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(prepareMeta),this.prepareStoryWithCache=(0,import_memoizerific2.default)(STORY_CACHE_SIZE)(prepareStory),this.initializationPromise=new import_synchronous_promise.SynchronousPromise(resolve=>{this.resolveInitializationPromise=resolve})}setProjectAnnotations(projectAnnotations){this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.globals?this.globals.set({globals,globalTypes}):this.globals=new GlobalsStore({globals,globalTypes})}initialize({storyIndex,importFn,cache=!1}){return this.storyIndex=new StoryIndexStore(storyIndex),this.importFn=importFn,this.resolveInitializationPromise(),cache?this.cacheAllCSFFiles():import_synchronous_promise.SynchronousPromise.resolve()}async onStoriesChanged({importFn,storyIndex}){await this.initializationPromise,importFn&&(this.importFn=importFn),storyIndex&&(this.storyIndex.entries=storyIndex.entries),this.cachedCSFFiles&&await this.cacheAllCSFFiles()}async storyIdToEntry(storyId){return await this.initializationPromise,this.storyIndex.storyIdToEntry(storyId)}loadCSFFileByStoryId(storyId){if(!this.storyIndex||!this.importFn)throw new Error("loadCSFFileByStoryId called before initialization");let{importPath,title}=this.storyIndex.storyIdToEntry(storyId);return this.importFn(importPath).then(moduleExports=>this.processCSFFileWithCache(moduleExports,importPath,title))}loadAllCSFFiles({batchSize=EXTRACT_BATCH_SIZE}={}){if(!this.storyIndex)throw new Error("loadAllCSFFiles called before initialization");let importPaths=Object.entries(this.storyIndex.entries).map(([storyId,{importPath}])=>[importPath,storyId]),loadInBatches=remainingImportPaths=>{if(remainingImportPaths.length===0)return import_synchronous_promise.SynchronousPromise.resolve([]);let csfFilePromiseList=remainingImportPaths.slice(0,batchSize).map(([importPath,storyId])=>this.loadCSFFileByStoryId(storyId).then(csfFile=>({importPath,csfFile})));return import_synchronous_promise.SynchronousPromise.all(csfFilePromiseList).then(firstResults=>loadInBatches(remainingImportPaths.slice(batchSize)).then(restResults=>firstResults.concat(restResults)))};return loadInBatches(importPaths).then(list=>list.reduce((acc,{importPath,csfFile})=>(acc[importPath]=csfFile,acc),{}))}cacheAllCSFFiles(){return this.initializationPromise.then(()=>this.loadAllCSFFiles().then(csfFiles=>{this.cachedCSFFiles=csfFiles}))}preparedMetaFromCSFFile({csfFile}){if(!this.projectAnnotations)throw new Error("storyFromCSFFile called before initialization");let componentAnnotations=csfFile.meta;return this.prepareMetaWithCache(componentAnnotations,this.projectAnnotations,csfFile.moduleExports.default)}async loadStory({storyId}){await this.initializationPromise;let csfFile=await this.loadCSFFileByStoryId(storyId);return this.storyFromCSFFile({storyId,csfFile})}storyFromCSFFile({storyId,csfFile}){if(!this.projectAnnotations)throw new Error("storyFromCSFFile called before initialization");let storyAnnotations=csfFile.stories[storyId];if(!storyAnnotations)throw new Error(`Didn't find '${storyId}' in CSF file, this is unexpected`);let componentAnnotations=csfFile.meta,story=this.prepareStoryWithCache(storyAnnotations,componentAnnotations,this.projectAnnotations);return this.args.setInitial(story),this.hooks[story.id]=this.hooks[story.id]||new HooksContext,story}componentStoriesFromCSFFile({csfFile}){if(!this.storyIndex)throw new Error("componentStoriesFromCSFFile called before initialization");return Object.keys(this.storyIndex.entries).filter(storyId=>!!csfFile.stories[storyId]).map(storyId=>this.storyFromCSFFile({storyId,csfFile}))}async loadEntry(id){let entry=await this.storyIdToEntry(id),{importFn,storyIndex}=this;if(!storyIndex||!importFn)throw new Error("loadEntry called before initialization");let storyImports=entry.type==="docs"?entry.storiesImports:[],[entryExports,...csfFiles]=await Promise.all([importFn(entry.importPath),...storyImports.map(storyImportPath=>{let firstStoryEntry=storyIndex.importPathToEntry(storyImportPath);return this.loadCSFFileByStoryId(firstStoryEntry.id)})]);return{entryExports,csfFiles}}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.globals)throw new Error("getStoryContext called before initialization");return prepareContext({...story,args:forceInitialArgs?story.initialArgs:this.args.get(story.id),globals:this.globals.get(),hooks:this.hooks[story.id]})}cleanupStory(story){this.hooks[story.id].clean()}extract(options={includeDocsOnly:!1}){if(!this.storyIndex)throw new Error("extract called before initialization");let{cachedCSFFiles}=this;if(!cachedCSFFiles)throw new Error("Cannot call extract() unless you call cacheAllCSFFiles() first.");return Object.entries(this.storyIndex.entries).reduce((acc,[storyId,{type,importPath}])=>{if(type==="docs")return acc;let csfFile=cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return!options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((storyAcc,[key,value])=>key==="moduleExport"||typeof value=="function"?storyAcc:Array.isArray(value)?Object.assign(storyAcc,{[key]:value.slice().sort()}):Object.assign(storyAcc,{[key]:value}),{args:story.initialArgs})),acc},{})}getSetStoriesPayload(){if(!this.globals)throw new Error("getSetStoriesPayload called before initialization");let stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((acc,{title})=>(acc[title]={},acc),{});return{v:2,globals:this.globals.get(),globalParameters:{},kindParameters,stories}}getSetIndexPayload(){if(!this.storyIndex)throw new Error("getSetIndexPayload called before initialization");if(!this.cachedCSFFiles)throw new Error("Cannot call getSetIndexPayload() unless you call cacheAllCSFFiles() first");let{cachedCSFFiles}=this,stories=this.extract({includeDocsOnly:!0});return{v:4,entries:Object.fromEntries(Object.entries(this.storyIndex.entries).map(([id,entry])=>[id,stories[id]?{...entry,args:stories[id].initialArgs,initialArgs:stories[id].initialArgs,argTypes:stories[id].argTypes,parameters:stories[id].parameters}:{...entry,parameters:this.preparedMetaFromCSFFile({csfFile:cachedCSFFiles[entry.importPath]}).parameters}]))}}raw(){return Object.values(this.extract()).map(({id})=>this.fromId(id)).filter(Boolean)}fromId(storyId){if(!this.storyIndex)throw new Error("fromId called before initialization");if(!this.cachedCSFFiles)throw new Error("Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.");let importPath;try{({importPath}=this.storyIndex.storyIdToEntry(storyId))}catch{return null}let csfFile=this.cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return{...story,storyFn:update=>{let context={...this.getStoryContext(story),viewMode:"story"};return story.unboundStoryFn({...context,...update})}}}};function slash(path){return path.startsWith("\\\\?\\")?path:path.replace(/\\/g,"/")}var import_ts_dedent5=require("ts-dedent"),import_client_logger8=require("@storybook/client-logger"),stripExtension=path=>{let parts=[...path],last=parts[parts.length-1],dotIndex=last.indexOf("."),stripped=dotIndex>0?last.substr(0,dotIndex):last;parts[parts.length-1]=stripped;let[first,...rest]=parts;return first===""&&(parts=rest),parts},indexRe=/^index$/i,removeRedundantFilename=paths=>{let prevVal;return paths.filter((val,index)=>index===paths.length-1&&(val===prevVal||indexRe.test(val))?!1:(prevVal=val,!0))};function pathJoin(paths){let slashes=new RegExp("/{1,}","g");return paths.join("/").replace(slashes,"/")}var userOrAutoTitleFromSpecifier=(fileName,entry,userTitle)=>{let{directory,importPathMatcher,titlePrefix=""}=entry||{};typeof fileName=="number"&&import_client_logger8.once.warn(import_ts_dedent5.dedent`
|
|
29
29
|
CSF Auto-title received a numeric fileName. This typically happens when
|
|
30
30
|
webpack is mis-configured in production mode. To force webpack to produce
|
|
31
31
|
filenames, set optimization.moduleIds = "named" in your webpack config.
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { start } from './chunk-
|
|
1
|
+
export { start } from './chunk-G3V2D3GG.mjs';
|
|
2
2
|
export { makeDecorator } from './chunk-GRRYLBAT.mjs';
|
|
3
|
-
export { ClientApi, addArgTypes, addArgTypesEnhancer, addArgs, addArgsEnhancer, addDecorator, addLoader, addParameters, addStepRunner, getQueryParam, getQueryParams, setGlobalRender } from './chunk-
|
|
4
|
-
export { DocsContext, Preview, PreviewWeb, simulateDOMContentLoaded, simulatePageLoad } from './chunk-
|
|
5
|
-
export { StoryStore, combineArgs, combineParameters, composeConfigs, composeStepRunners, composeStories, composeStory, decorateStory, defaultDecorateStory, filterArgTypes, inferControls, normalizeStory, prepareMeta, prepareStory, sanitizeStoryContextUpdate, setProjectAnnotations, sortStoriesV7, userOrAutoTitle, userOrAutoTitleFromSpecifier } from './chunk-
|
|
3
|
+
export { ClientApi, addArgTypes, addArgTypesEnhancer, addArgs, addArgsEnhancer, addDecorator, addLoader, addParameters, addStepRunner, getQueryParam, getQueryParams, setGlobalRender } from './chunk-AWJHIX2X.mjs';
|
|
4
|
+
export { DocsContext, Preview, PreviewWeb, simulateDOMContentLoaded, simulatePageLoad } from './chunk-HOTYVPG7.mjs';
|
|
5
|
+
export { StoryStore, combineArgs, combineParameters, composeConfigs, composeStepRunners, composeStories, composeStory, decorateStory, defaultDecorateStory, filterArgTypes, inferControls, normalizeStory, prepareMeta, prepareStory, sanitizeStoryContextUpdate, setProjectAnnotations, sortStoriesV7, userOrAutoTitle, userOrAutoTitleFromSpecifier } from './chunk-VLGOEOTZ.mjs';
|
|
6
6
|
export { HooksContext, addons, applyHooks, mockChannel, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-2WNKQWTL.mjs';
|
package/dist/preview-web.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { Renderer, StoryId, StoryRenderOptions, ViewMode, PreparedStory, RenderT
|
|
|
3
3
|
export { DocsContextProps, DocsRenderFunction, ProjectAnnotations as WebProjectAnnotations } from '@storybook/types';
|
|
4
4
|
export { c as composeConfigs } from './composeConfigs-62a04721.js';
|
|
5
5
|
import { Channel } from '@storybook/channels';
|
|
6
|
-
import { S as StoryStore, d as StorySpecifier } from './StoryStore-
|
|
6
|
+
import { S as StoryStore, d as StorySpecifier } from './StoryStore-f7424ddf.js';
|
|
7
7
|
import 'synchronous-promise';
|
|
8
8
|
import './hooks-655fa363.js';
|
|
9
9
|
|
|
@@ -67,7 +67,7 @@ declare class StoryRender<TRenderer extends Renderer> implements Render<TRendere
|
|
|
67
67
|
declare class DocsContext<TRenderer extends Renderer> implements DocsContextProps<TRenderer> {
|
|
68
68
|
channel: Channel;
|
|
69
69
|
protected store: StoryStore<TRenderer>;
|
|
70
|
-
renderStoryToElement: DocsContextProps['renderStoryToElement'];
|
|
70
|
+
renderStoryToElement: DocsContextProps<TRenderer>['renderStoryToElement'];
|
|
71
71
|
private componentStoriesValue;
|
|
72
72
|
private storyIdToCSFFile;
|
|
73
73
|
private exportToStory;
|
|
@@ -75,7 +75,7 @@ declare class DocsContext<TRenderer extends Renderer> implements DocsContextProp
|
|
|
75
75
|
private nameToStoryId;
|
|
76
76
|
private attachedCSFFile?;
|
|
77
77
|
private primaryStory?;
|
|
78
|
-
constructor(channel: Channel, store: StoryStore<TRenderer>, renderStoryToElement: DocsContextProps['renderStoryToElement'],
|
|
78
|
+
constructor(channel: Channel, store: StoryStore<TRenderer>, renderStoryToElement: DocsContextProps<TRenderer>['renderStoryToElement'],
|
|
79
79
|
/** The CSF files known (via the index) to be refererenced by this docs file */
|
|
80
80
|
csfFiles: CSFFile<TRenderer>[]);
|
|
81
81
|
referenceCSFFile(csfFile: CSFFile<TRenderer>): void;
|
|
@@ -88,7 +88,7 @@ declare class DocsContext<TRenderer extends Renderer> implements DocsContextProp
|
|
|
88
88
|
storyIdByName: (storyName: StoryName) => string;
|
|
89
89
|
componentStories: () => PreparedStory<TRenderer>[];
|
|
90
90
|
storyById: (storyId?: StoryId) => PreparedStory<TRenderer>;
|
|
91
|
-
getStoryContext: (story: PreparedStory<TRenderer>) => StoryContextForLoaders<TRenderer>;
|
|
91
|
+
getStoryContext: (story: PreparedStory<TRenderer>) => StoryContextForLoaders<TRenderer, _storybook_types.Args>;
|
|
92
92
|
loadStory: (id: StoryId) => Promise<PreparedStory<TRenderer>>;
|
|
93
93
|
}
|
|
94
94
|
|
|
@@ -125,8 +125,8 @@ declare class CsfDocsRender<TRenderer extends Renderer> implements Render<TRende
|
|
|
125
125
|
isPreparing(): boolean;
|
|
126
126
|
prepare(): Promise<void>;
|
|
127
127
|
isEqual(other: Render<TRenderer>): boolean;
|
|
128
|
-
docsContext(renderStoryToElement: DocsContextProps['renderStoryToElement']): DocsContext<TRenderer>;
|
|
129
|
-
renderToElement(canvasElement: TRenderer['canvasElement'], renderStoryToElement: DocsContextProps['renderStoryToElement']): Promise<void>;
|
|
128
|
+
docsContext(renderStoryToElement: DocsContextProps<TRenderer>['renderStoryToElement']): DocsContext<TRenderer>;
|
|
129
|
+
renderToElement(canvasElement: TRenderer['canvasElement'], renderStoryToElement: DocsContextProps<TRenderer>['renderStoryToElement']): Promise<void>;
|
|
130
130
|
teardown({ viewModeChanged }?: {
|
|
131
131
|
viewModeChanged?: boolean;
|
|
132
132
|
}): Promise<void>;
|
|
@@ -162,8 +162,8 @@ declare class MdxDocsRender<TRenderer extends Renderer> implements Render<TRende
|
|
|
162
162
|
isPreparing(): boolean;
|
|
163
163
|
prepare(): Promise<void>;
|
|
164
164
|
isEqual(other: Render<TRenderer>): boolean;
|
|
165
|
-
docsContext(renderStoryToElement: DocsContextProps['renderStoryToElement']): DocsContext<TRenderer>;
|
|
166
|
-
renderToElement(canvasElement: TRenderer['canvasElement'], renderStoryToElement: DocsContextProps['renderStoryToElement']): Promise<void>;
|
|
165
|
+
docsContext(renderStoryToElement: DocsContextProps<TRenderer>['renderStoryToElement']): DocsContext<TRenderer>;
|
|
166
|
+
renderToElement(canvasElement: TRenderer['canvasElement'], renderStoryToElement: DocsContextProps<TRenderer>['renderStoryToElement']): Promise<void>;
|
|
167
167
|
teardown({ viewModeChanged }?: {
|
|
168
168
|
viewModeChanged?: boolean;
|
|
169
169
|
}): Promise<void>;
|
|
@@ -224,7 +224,7 @@ declare class Preview<TRenderer extends Renderer> {
|
|
|
224
224
|
}): Promise<void>;
|
|
225
225
|
extract(options?: {
|
|
226
226
|
includeDocsOnly: boolean;
|
|
227
|
-
}): Promise<Record<string, _storybook_types.StoryContextForEnhancers<TRenderer>>>;
|
|
227
|
+
}): Promise<Record<string, _storybook_types.StoryContextForEnhancers<TRenderer, Args>>>;
|
|
228
228
|
renderPreviewEntryError(reason: string, err: Error): void;
|
|
229
229
|
}
|
|
230
230
|
|
|
@@ -307,7 +307,7 @@ declare class PreviewWithSelection<TFramework extends Renderer> extends Preview<
|
|
|
307
307
|
}): Promise<void>;
|
|
308
308
|
extract(options?: {
|
|
309
309
|
includeDocsOnly: boolean;
|
|
310
|
-
}): Promise<Record<string, _storybook_types.StoryContextForEnhancers<TFramework>>>;
|
|
310
|
+
}): Promise<Record<string, _storybook_types.StoryContextForEnhancers<TFramework, Args>>>;
|
|
311
311
|
mainStoryCallbacks(storyId: StoryId): {
|
|
312
312
|
showMain: () => void;
|
|
313
313
|
showError: (err: {
|
package/dist/preview-web.js
CHANGED
|
@@ -8,21 +8,21 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
8
8
|
Invalid argType: '${key}.options' should only contain primitives. Use a 'mapping' for complex values.
|
|
9
9
|
|
|
10
10
|
More info: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
|
|
11
|
-
`),allowArg();let isArray=Array.isArray(args[key]),invalidIndex=isArray&&args[key].findIndex(val=>!options.includes(val)),isValidArray=isArray&&invalidIndex===-1;if(args[key]===void 0||options.includes(args[key])||isValidArray)return allowArg();let field=isArray?`${key}[${invalidIndex}]`:key,supportedOptions=options.map(opt=>typeof opt=="string"?`'${opt}'`:String(opt)).join(", ");return import_client_logger2.once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`),acc},{}),DEEPLY_EQUAL=Symbol("Deeply equal"),deepDiff=(value,update)=>{if(typeof value!=typeof update)return update;if((0,import_dequal.dequal)(value,update))return DEEPLY_EQUAL;if(Array.isArray(value)&&Array.isArray(update)){let res=update.reduce((acc,upd,index)=>{let diff=deepDiff(value[index],upd);return diff!==DEEPLY_EQUAL&&(acc[index]=diff),acc},new Array(update.length));return update.length>=value.length?res:res.concat(new Array(value.length-update.length).fill(void 0))}return(0,import_isPlainObject.default)(value)&&(0,import_isPlainObject.default)(update)?Object.keys({...value,...update}).reduce((acc,key)=>{let diff=deepDiff(value==null?void 0:value[key],update==null?void 0:update[key]);return diff===DEEPLY_EQUAL?acc:Object.assign(acc,{[key]:diff})},{}):update},UNTARGETED="UNTARGETED";function groupArgsByTarget({args,argTypes}){let groupedArgs={};return Object.entries(args).forEach(([name,value])=>{let{target=UNTARGETED}=argTypes[name]||{};groupedArgs[target]=groupedArgs[target]||{},groupedArgs[target][name]=value}),groupedArgs}function deleteUndefined(obj){return Object.keys(obj).forEach(key=>obj[key]===void 0&&delete obj[key]),obj}var ArgsStore=class{constructor(){this.initialArgsByStoryId={};this.argsByStoryId={}}get(storyId){if(!(storyId in this.argsByStoryId))throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);return this.argsByStoryId[storyId]}setInitial(story){if(!this.initialArgsByStoryId[story.id])this.initialArgsByStoryId[story.id]=story.initialArgs,this.argsByStoryId[story.id]=story.initialArgs;else if(this.initialArgsByStoryId[story.id]!==story.initialArgs){let delta=deepDiff(this.initialArgsByStoryId[story.id],this.argsByStoryId[story.id]);this.initialArgsByStoryId[story.id]=story.initialArgs,this.argsByStoryId[story.id]=story.initialArgs,delta!==DEEPLY_EQUAL&&this.updateFromDelta(story,delta)}}updateFromDelta(story,delta){let validatedDelta=validateOptions(delta,story.argTypes);this.argsByStoryId[story.id]=combineArgs(this.argsByStoryId[story.id],validatedDelta)}updateFromPersisted(story,persisted){let mappedPersisted=mapArgsToTypes(persisted,story.argTypes);return this.updateFromDelta(story,mappedPersisted)}update(storyId,argsUpdate){if(!(storyId in this.argsByStoryId))throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);this.argsByStoryId[storyId]=deleteUndefined({...this.argsByStoryId[storyId],...argsUpdate})}};var import_client_logger3=require("@storybook/client-logger");var getValuesFromArgTypes=(argTypes={})=>Object.entries(argTypes).reduce((acc,[arg,{defaultValue}])=>(typeof defaultValue<"u"&&(acc[arg]=defaultValue),acc),{});var GlobalsStore=class{constructor({globals={},globalTypes={}}){this.set({globals,globalTypes})}set({globals={},globalTypes={}}){let delta=this.initialGlobals&&deepDiff(this.initialGlobals,this.globals);this.allowedGlobalNames=new Set([...Object.keys(globals),...Object.keys(globalTypes)]);let defaultGlobals=getValuesFromArgTypes(globalTypes);this.initialGlobals={...defaultGlobals,...globals},this.globals=this.initialGlobals,delta&&delta!==DEEPLY_EQUAL&&this.updateFromPersisted(delta)}filterAllowedGlobals(globals){return Object.entries(globals).reduce((acc,[key,value])=>(this.allowedGlobalNames.has(key)?acc[key]=value:import_client_logger3.logger.warn(`Attempted to set a global (${key}) that is not defined in initial globals or globalTypes`),acc),{})}updateFromPersisted(persisted){let allowedUrlGlobals=this.filterAllowedGlobals(persisted);this.globals={...this.globals,...allowedUrlGlobals}}get(){return this.globals}update(newGlobals){this.globals={...this.globals,...this.filterAllowedGlobals(newGlobals)}}};var import_mapValues=__toESM(require("lodash/mapValues.js")),normalizeType=type=>typeof type=="string"?{name:type}:type,normalizeControl=control=>typeof control=="string"?{type:control}:control,normalizeInputType=(inputType,key)=>{let{type,control,...rest}=inputType,normalized={name:key,...rest};return type&&(normalized.type=normalizeType(type)),control?normalized.control=normalizeControl(control):control===!1&&(normalized.control={disable:!0}),normalized},normalizeInputTypes=inputTypes=>(0,import_mapValues.default)(inputTypes,normalizeInputType);var import_csf=require("@storybook/csf"),import_ts_dedent2=require("ts-dedent"),import_client_logger4=require("@storybook/client-logger"),import_util_deprecate=__toESM(require("util-deprecate"));var deprecatedStoryAnnotation=import_ts_dedent2.dedent`
|
|
11
|
+
`),allowArg();let isArray=Array.isArray(args[key]),invalidIndex=isArray&&args[key].findIndex(val=>!options.includes(val)),isValidArray=isArray&&invalidIndex===-1;if(args[key]===void 0||options.includes(args[key])||isValidArray)return allowArg();let field=isArray?`${key}[${invalidIndex}]`:key,supportedOptions=options.map(opt=>typeof opt=="string"?`'${opt}'`:String(opt)).join(", ");return import_client_logger2.once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`),acc},{}),DEEPLY_EQUAL=Symbol("Deeply equal"),deepDiff=(value,update)=>{if(typeof value!=typeof update)return update;if((0,import_dequal.dequal)(value,update))return DEEPLY_EQUAL;if(Array.isArray(value)&&Array.isArray(update)){let res=update.reduce((acc,upd,index)=>{let diff=deepDiff(value[index],upd);return diff!==DEEPLY_EQUAL&&(acc[index]=diff),acc},new Array(update.length));return update.length>=value.length?res:res.concat(new Array(value.length-update.length).fill(void 0))}return(0,import_isPlainObject.default)(value)&&(0,import_isPlainObject.default)(update)?Object.keys({...value,...update}).reduce((acc,key)=>{let diff=deepDiff(value==null?void 0:value[key],update==null?void 0:update[key]);return diff===DEEPLY_EQUAL?acc:Object.assign(acc,{[key]:diff})},{}):update},UNTARGETED="UNTARGETED";function groupArgsByTarget({args,argTypes}){let groupedArgs={};return Object.entries(args).forEach(([name,value])=>{let{target=UNTARGETED}=argTypes[name]||{};groupedArgs[target]=groupedArgs[target]||{},groupedArgs[target][name]=value}),groupedArgs}function deleteUndefined(obj){return Object.keys(obj).forEach(key=>obj[key]===void 0&&delete obj[key]),obj}var ArgsStore=class{constructor(){this.initialArgsByStoryId={};this.argsByStoryId={}}get(storyId){if(!(storyId in this.argsByStoryId))throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);return this.argsByStoryId[storyId]}setInitial(story){if(!this.initialArgsByStoryId[story.id])this.initialArgsByStoryId[story.id]=story.initialArgs,this.argsByStoryId[story.id]=story.initialArgs;else if(this.initialArgsByStoryId[story.id]!==story.initialArgs){let delta=deepDiff(this.initialArgsByStoryId[story.id],this.argsByStoryId[story.id]);this.initialArgsByStoryId[story.id]=story.initialArgs,this.argsByStoryId[story.id]=story.initialArgs,delta!==DEEPLY_EQUAL&&this.updateFromDelta(story,delta)}}updateFromDelta(story,delta){let validatedDelta=validateOptions(delta,story.argTypes);this.argsByStoryId[story.id]=combineArgs(this.argsByStoryId[story.id],validatedDelta)}updateFromPersisted(story,persisted){let mappedPersisted=mapArgsToTypes(persisted,story.argTypes);return this.updateFromDelta(story,mappedPersisted)}update(storyId,argsUpdate){if(!(storyId in this.argsByStoryId))throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);this.argsByStoryId[storyId]=deleteUndefined({...this.argsByStoryId[storyId],...argsUpdate})}};var import_client_logger3=require("@storybook/client-logger");var getValuesFromArgTypes=(argTypes={})=>Object.entries(argTypes).reduce((acc,[arg,{defaultValue}])=>(typeof defaultValue<"u"&&(acc[arg]=defaultValue),acc),{});var GlobalsStore=class{constructor({globals={},globalTypes={}}){this.set({globals,globalTypes})}set({globals={},globalTypes={}}){let delta=this.initialGlobals&&deepDiff(this.initialGlobals,this.globals);this.allowedGlobalNames=new Set([...Object.keys(globals),...Object.keys(globalTypes)]);let defaultGlobals=getValuesFromArgTypes(globalTypes);this.initialGlobals={...defaultGlobals,...globals},this.globals=this.initialGlobals,delta&&delta!==DEEPLY_EQUAL&&this.updateFromPersisted(delta)}filterAllowedGlobals(globals){return Object.entries(globals).reduce((acc,[key,value])=>(this.allowedGlobalNames.has(key)?acc[key]=value:import_client_logger3.logger.warn(`Attempted to set a global (${key}) that is not defined in initial globals or globalTypes`),acc),{})}updateFromPersisted(persisted){let allowedUrlGlobals=this.filterAllowedGlobals(persisted);this.globals={...this.globals,...allowedUrlGlobals}}get(){return this.globals}update(newGlobals){this.globals={...this.globals,...this.filterAllowedGlobals(newGlobals)}}};var import_mapValues=__toESM(require("lodash/mapValues.js")),normalizeType=type=>typeof type=="string"?{name:type}:type,normalizeControl=control=>typeof control=="string"?{type:control}:control,normalizeInputType=(inputType,key)=>{let{type,control,...rest}=inputType,normalized={name:key,...rest};return type&&(normalized.type=normalizeType(type)),control?normalized.control=normalizeControl(control):control===!1&&(normalized.control={disable:!0}),normalized},normalizeInputTypes=inputTypes=>(0,import_mapValues.default)(inputTypes,normalizeInputType);var import_csf=require("@storybook/csf"),import_ts_dedent2=require("ts-dedent"),import_client_logger4=require("@storybook/client-logger"),import_util_deprecate=__toESM(require("util-deprecate"));var normalizeArrays=array=>Array.isArray(array)?array:array?[array]:[];var deprecatedStoryAnnotation=import_ts_dedent2.dedent`
|
|
12
12
|
CSF .story annotations deprecated; annotate story functions directly:
|
|
13
13
|
- StoryFn.story.name => StoryFn.storyName
|
|
14
14
|
- StoryFn.story.(parameters|decorators) => StoryFn.(parameters|decorators)
|
|
15
15
|
See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-annotations for details and codemod.
|
|
16
|
-
`,deprecatedStoryAnnotationWarning=(0,import_util_deprecate.default)(()=>{},deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){let storyObject=storyAnnotations,userStoryFn=typeof storyAnnotations=="function"?storyAnnotations:null,{story}=storyObject;story&&(import_client_logger4.logger.debug("deprecated story",story),deprecatedStoryAnnotationWarning());let exportName=(0,import_csf.storyNameFromExport)(key),name=typeof storyObject!="function"&&storyObject.name||storyObject.storyName||(story==null?void 0:story.name)||exportName,decorators=[...storyObject.decorators
|
|
16
|
+
`,deprecatedStoryAnnotationWarning=(0,import_util_deprecate.default)(()=>{},deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){let storyObject=storyAnnotations,userStoryFn=typeof storyAnnotations=="function"?storyAnnotations:null,{story}=storyObject;story&&(import_client_logger4.logger.debug("deprecated story",story),deprecatedStoryAnnotationWarning());let exportName=(0,import_csf.storyNameFromExport)(key),name=typeof storyObject!="function"&&storyObject.name||storyObject.storyName||(story==null?void 0:story.name)||exportName,decorators=[...normalizeArrays(storyObject.decorators),...normalizeArrays(story==null?void 0:story.decorators)],parameters={...story==null?void 0:story.parameters,...storyObject.parameters},args={...story==null?void 0:story.args,...storyObject.args},argTypes={...story==null?void 0:story.argTypes,...storyObject.argTypes},loaders=[...normalizeArrays(storyObject.loaders),...normalizeArrays(story==null?void 0:story.loaders)],{render,play,tags=[]}=storyObject,id=parameters.__id||(0,import_csf.toId)(meta.id,exportName);return{moduleExport:storyAnnotations,id,name,tags,decorators,parameters,args,argTypes:normalizeInputTypes(argTypes),loaders,...render&&{render},...userStoryFn&&{userStoryFn},...play&&{play}}}var import_csf3=require("@storybook/csf"),import_client_logger5=require("@storybook/client-logger"),import_ts_dedent3=__toESM(require("ts-dedent"));var import_csf2=require("@storybook/csf");function normalizeComponentAnnotations(defaultExport,title=defaultExport.title,importPath){let{id,argTypes}=defaultExport;return{id:(0,import_csf2.sanitize)(id||title),...defaultExport,title,...argTypes&&{argTypes:normalizeInputTypes(argTypes)},parameters:{fileName:importPath,...defaultExport.parameters}}}var checkGlobals=parameters=>{let{globals,globalTypes}=parameters;(globals||globalTypes)&&import_client_logger5.logger.error("Global args/argTypes can only be set globally",JSON.stringify({globals,globalTypes}))},checkStorySort=parameters=>{let{options}=parameters;options!=null&&options.storySort&&import_client_logger5.logger.error("The storySort option parameter can only be set globally")},checkDisallowedParameters=parameters=>{parameters&&(checkGlobals(parameters),checkStorySort(parameters))},checkSubcomponents=meta=>{meta.subcomponents&&(0,import_client_logger5.deprecate)(import_ts_dedent3.default`The \`subcomponents\` annotation is deprecated.
|
|
17
17
|
|
|
18
18
|
Please refer to the migration guide: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#argstable-block'
|
|
19
|
-
`)};function processCSFFile(moduleExports,importPath,title){let{default:defaultExport,__namedExportsOrder,...namedExports}=moduleExports,meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters),checkSubcomponents(meta);let csfFile={meta,stories:{},moduleExports};return Object.keys(namedExports).forEach(key=>{if((0,import_csf3.isExportStory)(key,meta)){let storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta}}),csfFile}var import_global3=require("@storybook/global"),import_csf4=require("@storybook/csf");var import_isPlainObject2=__toESM(require("lodash/isPlainObject.js")),combineParameters=(...parameterSets)=>{let mergeKeys={},definedParametersSets=parameterSets.filter(Boolean),combined=definedParametersSets.reduce((acc,parameters)=>(Object.entries(parameters).forEach(([key,value])=>{let existing=acc[key];Array.isArray(value)||typeof existing>"u"?acc[key]=value:(0,import_isPlainObject2.default)(value)&&(0,import_isPlainObject2.default)(existing)?mergeKeys[key]=!0:typeof value<"u"&&(acc[key]=value)}),acc),{});return Object.keys(mergeKeys).forEach(key=>{let mergeValues=definedParametersSets.filter(Boolean).map(p=>p[key]).filter(value=>typeof value<"u");mergeValues.every(value=>(0,import_isPlainObject2.default)(value))?combined[key]=combineParameters(...mergeValues):combined[key]=mergeValues[mergeValues.length-1]}),combined};function decorateStory(storyFn,decorator,bindWithContext){let boundStoryFunction=bindWithContext(storyFn);return context=>decorator(boundStoryFunction,context)}function sanitizeStoryContextUpdate({componentId,title,kind,id,name,story,parameters,initialArgs,argTypes,...update}={}){return update}function defaultDecorateStory(storyFn,decorators){let contextStore={},bindWithContext=decoratedStoryFn=>update=>{if(!contextStore.value)throw new Error("Decorated function called without init");return contextStore.value={...contextStore.value,...sanitizeStoryContextUpdate(update)},decoratedStoryFn(contextStore.value)},decoratedWithContextStore=decorators.reduce((story,decorator)=>decorateStory(story,decorator,bindWithContext),storyFn);return context=>(contextStore.value=context,decoratedWithContextStore(context))}function prepareStory(storyAnnotations,componentAnnotations,projectAnnotations){let{moduleExport,id,name}=storyAnnotations||{},partialAnnotations=preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations),loaders
|
|
19
|
+
`)};function processCSFFile(moduleExports,importPath,title){let{default:defaultExport,__namedExportsOrder,...namedExports}=moduleExports,meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters),checkSubcomponents(meta);let csfFile={meta,stories:{},moduleExports};return Object.keys(namedExports).forEach(key=>{if((0,import_csf3.isExportStory)(key,meta)){let storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta}}),csfFile}var import_global3=require("@storybook/global"),import_csf4=require("@storybook/csf");var import_isPlainObject2=__toESM(require("lodash/isPlainObject.js")),combineParameters=(...parameterSets)=>{let mergeKeys={},definedParametersSets=parameterSets.filter(Boolean),combined=definedParametersSets.reduce((acc,parameters)=>(Object.entries(parameters).forEach(([key,value])=>{let existing=acc[key];Array.isArray(value)||typeof existing>"u"?acc[key]=value:(0,import_isPlainObject2.default)(value)&&(0,import_isPlainObject2.default)(existing)?mergeKeys[key]=!0:typeof value<"u"&&(acc[key]=value)}),acc),{});return Object.keys(mergeKeys).forEach(key=>{let mergeValues=definedParametersSets.filter(Boolean).map(p=>p[key]).filter(value=>typeof value<"u");mergeValues.every(value=>(0,import_isPlainObject2.default)(value))?combined[key]=combineParameters(...mergeValues):combined[key]=mergeValues[mergeValues.length-1]}),combined};function decorateStory(storyFn,decorator,bindWithContext){let boundStoryFunction=bindWithContext(storyFn);return context=>decorator(boundStoryFunction,context)}function sanitizeStoryContextUpdate({componentId,title,kind,id,name,story,parameters,initialArgs,argTypes,...update}={}){return update}function defaultDecorateStory(storyFn,decorators){let contextStore={},bindWithContext=decoratedStoryFn=>update=>{if(!contextStore.value)throw new Error("Decorated function called without init");return contextStore.value={...contextStore.value,...sanitizeStoryContextUpdate(update)},decoratedStoryFn(contextStore.value)},decoratedWithContextStore=decorators.reduce((story,decorator)=>decorateStory(story,decorator,bindWithContext),storyFn);return context=>(contextStore.value=context,decoratedWithContextStore(context))}function prepareStory(storyAnnotations,componentAnnotations,projectAnnotations){let{moduleExport,id,name}=storyAnnotations||{},partialAnnotations=preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations),applyLoaders=async context=>{let updatedContext={...context,loaded:{}};for(let loaders of[..."__STORYBOOK_TEST_LOADERS__"in import_global3.global&&Array.isArray(import_global3.global.__STORYBOOK_TEST_LOADERS__)?[import_global3.global.__STORYBOOK_TEST_LOADERS__]:[],normalizeArrays(projectAnnotations.loaders),normalizeArrays(componentAnnotations.loaders),normalizeArrays(storyAnnotations.loaders)]){let loadResults=await Promise.all(loaders.map(loader=>loader(updatedContext))),loaded=Object.assign({},...loadResults);updatedContext={...updatedContext,loaded:{...updatedContext.loaded,...loaded}}}return updatedContext},undecoratedStoryFn=context=>{let{passArgsFirst:renderTimePassArgsFirst=!0}=context.parameters;return renderTimePassArgsFirst?render(context.args,context):render(context)},{applyDecorators=defaultDecorateStory,runStep}=projectAnnotations,decorators=[...normalizeArrays(storyAnnotations==null?void 0:storyAnnotations.decorators),...normalizeArrays(componentAnnotations==null?void 0:componentAnnotations.decorators),...normalizeArrays(projectAnnotations==null?void 0:projectAnnotations.decorators)],render=(storyAnnotations==null?void 0:storyAnnotations.userStoryFn)||(storyAnnotations==null?void 0:storyAnnotations.render)||componentAnnotations.render||projectAnnotations.render;if(!render)throw new Error(`No render function available for storyId '${id}'`);let decoratedStoryFn=applyHooks(applyDecorators)(undecoratedStoryFn,decorators),unboundStoryFn=context=>decoratedStoryFn(context),play=(storyAnnotations==null?void 0:storyAnnotations.play)||componentAnnotations.play;return{...partialAnnotations,moduleExport,id,name,story:name,originalStoryFn:render,undecoratedStoryFn,unboundStoryFn,applyLoaders,playFunction:play&&(async storyContext=>{let playFunctionContext={...storyContext,step:(label,play2)=>runStep(label,play2,playFunctionContext)};return play(playFunctionContext)})}}function prepareMeta(componentAnnotations,projectAnnotations,moduleExport){return{...preparePartialAnnotations(void 0,componentAnnotations,projectAnnotations),moduleExport}}function preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations){let tags=[...(storyAnnotations==null?void 0:storyAnnotations.tags)||componentAnnotations.tags||[],"story"],parameters=combineParameters(projectAnnotations.parameters,componentAnnotations.parameters,storyAnnotations==null?void 0:storyAnnotations.parameters),{argTypesEnhancers=[],argsEnhancers=[]}=projectAnnotations,passedArgTypes=combineParameters(projectAnnotations.argTypes,componentAnnotations.argTypes,storyAnnotations==null?void 0:storyAnnotations.argTypes);if(storyAnnotations){let render=(storyAnnotations==null?void 0:storyAnnotations.userStoryFn)||(storyAnnotations==null?void 0:storyAnnotations.render)||componentAnnotations.render||projectAnnotations.render,{passArgsFirst=!0}=parameters;parameters.__isArgsStory=passArgsFirst&&render&&render.length>0}let passedArgs={...projectAnnotations.args,...componentAnnotations.args,...storyAnnotations==null?void 0:storyAnnotations.args},contextForEnhancers={componentId:componentAnnotations.id,title:componentAnnotations.title,kind:componentAnnotations.title,id:(storyAnnotations==null?void 0:storyAnnotations.id)||componentAnnotations.id,name:(storyAnnotations==null?void 0:storyAnnotations.name)||"__meta",story:(storyAnnotations==null?void 0:storyAnnotations.name)||"__meta",component:componentAnnotations.component,subcomponents:componentAnnotations.subcomponents,tags,parameters,initialArgs:passedArgs,argTypes:passedArgTypes};contextForEnhancers.argTypes=argTypesEnhancers.reduce((accumulatedArgTypes,enhancer)=>enhancer({...contextForEnhancers,argTypes:accumulatedArgTypes}),contextForEnhancers.argTypes);let initialArgsBeforeEnhancers={...passedArgs};contextForEnhancers.initialArgs=argsEnhancers.reduce((accumulatedArgs,enhancer)=>({...accumulatedArgs,...enhancer({...contextForEnhancers,initialArgs:accumulatedArgs})}),initialArgsBeforeEnhancers);let{name,story,...withoutStoryIdentifiers}=contextForEnhancers;return withoutStoryIdentifiers}function prepareContext(context){var _a;let{args:unmappedArgs}=context,targetedContext={...context,allArgs:void 0,argsByTarget:void 0};if((_a=import_global3.global.FEATURES)!=null&&_a.argTypeTargetsV7){let argsByTarget=groupArgsByTarget(context);targetedContext={...context,allArgs:context.args,argsByTarget,args:argsByTarget[UNTARGETED]||{}}}let mappedArgs=Object.entries(targetedContext.args).reduce((acc,[key,val])=>{var _a2;if(!((_a2=targetedContext.argTypes[key])!=null&&_a2.mapping))return acc[key]=val,acc;let mappingFn=originalValue=>originalValue in targetedContext.argTypes[key].mapping?targetedContext.argTypes[key].mapping[originalValue]:originalValue;return acc[key]=Array.isArray(val)?val.map(mappingFn):mappingFn(val),acc},{}),includedArgs=Object.entries(mappedArgs).reduce((acc,[key,val])=>{let argType=targetedContext.argTypes[key]||{};return(0,import_csf4.includeConditionalArg)(argType,mappedArgs,targetedContext.globals)&&(acc[key]=val),acc},{});return{...targetedContext,unmappedArgs,args:includedArgs}}var import_mapValues2=__toESM(require("lodash/mapValues.js")),import_ts_dedent4=require("ts-dedent"),import_client_logger6=require("@storybook/client-logger");var inferType=(value,name,visited)=>{let type=typeof value;switch(type){case"boolean":case"string":case"number":case"function":case"symbol":return{name:type};default:break}return value?visited.has(value)?(import_client_logger6.logger.warn(import_ts_dedent4.dedent`
|
|
20
20
|
We've detected a cycle in arg '${name}'. Args should be JSON-serializable.
|
|
21
21
|
|
|
22
22
|
Consider using the mapping feature or fully custom args:
|
|
23
23
|
- Mapping: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
|
|
24
24
|
- Custom args: https://storybook.js.org/docs/react/essentials/controls#fully-custom-args
|
|
25
|
-
`),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:(0,import_mapValues2.default)(value,field=>inferType(field,name,new Set(visited)))}):{name:"object",value:{}}},inferArgTypes=context=>{let{id,argTypes:userArgTypes={},initialArgs={}}=context,argTypes=(0,import_mapValues2.default)(initialArgs,(arg,key)=>({name:key,type:inferType(arg,`${id}.${key}`,new Set)})),userArgTypesNames=(0,import_mapValues2.default)(userArgTypes,(argType,key)=>({name:key}));return combineParameters(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var import_mapValues3=__toESM(require("lodash/mapValues.js")),import_client_logger7=require("@storybook/client-logger");var import_pickBy=__toESM(require("lodash/pickBy.js")),matches=(name,descriptor)=>Array.isArray(descriptor)?descriptor.includes(name):name.match(descriptor),filterArgTypes=(argTypes,include,exclude)=>!include&&!exclude?argTypes:argTypes&&(0,import_pickBy.default)(argTypes,(argType,key)=>{let name=argType.name||key;return(!include||matches(name,include))&&(!exclude||!matches(name,exclude))});var inferControl=(argType,name,matchers)=>{let{type,options}=argType;if(type){if(matchers.color&&matchers.color.test(name)){let controlType=type.name;if(controlType==="string")return{control:{type:"color"}};controlType!=="enum"&&import_client_logger7.logger.warn(`Addon controls: Control of type color only supports string, received "${controlType}" instead`)}if(matchers.date&&matchers.date.test(name))return{control:{type:"date"}};switch(type.name){case"array":return{control:{type:"object"}};case"boolean":return{control:{type:"boolean"}};case"string":return{control:{type:"text"}};case"number":return{control:{type:"number"}};case"enum":{let{value}=type;return{control:{type:(value==null?void 0:value.length)<=5?"radio":"select"},options:value}}case"function":case"symbol":return null;default:return{control:{type:options?"select":"object"}}}}},inferControls=context=>{let{argTypes,parameters:{__isArgsStory,controls:{include=null,exclude=null,matchers={}}={}}}=context;if(!__isArgsStory)return argTypes;let filteredArgTypes=filterArgTypes(argTypes,include,exclude),withControls=(0,import_mapValues3.default)(filteredArgTypes,(argType,name)=>(argType==null?void 0:argType.type)&&inferControl(argType,name,matchers));return combineParameters(withControls,filteredArgTypes)};inferControls.secondPass=!0;function normalizeProjectAnnotations({argTypes,globalTypes,argTypesEnhancers,...annotations}){return{...argTypes&&{argTypes:normalizeInputTypes(argTypes)},...globalTypes&&{globalTypes:normalizeInputTypes(globalTypes)},argTypesEnhancers:[...argTypesEnhancers||[],inferArgTypes,inferControls],...annotations}}var import_global4=require("@storybook/global");function composeStepRunners(stepRunners){return async(label,play,playContext)=>{await stepRunners.reduceRight((innerPlay,stepRunner)=>async()=>stepRunner(label,innerPlay,playContext),async()=>play(playContext))()}}function getField(moduleExportList,field){return moduleExportList.map(xs=>{var _a;return((_a=xs.default)==null?void 0:_a[field])??xs[field]}).filter(Boolean)}function getArrayField(moduleExportList,field,options={}){return getField(moduleExportList,field).reduce((a,b)=>options.reverseFileOrder?[...b,...a]:[...a,...b],[])}function getObjectField(moduleExportList,field){return Object.assign({},...getField(moduleExportList,field))}function getSingletonField(moduleExportList,field){return getField(moduleExportList,field).pop()}function composeConfigs(moduleExportList){var _a;let allArgTypeEnhancers=getArrayField(moduleExportList,"argTypesEnhancers"),stepRunners=getField(moduleExportList,"runStep");return{parameters:combineParameters(...getField(moduleExportList,"parameters")),decorators:getArrayField(moduleExportList,"decorators",{reverseFileOrder:!(((_a=import_global4.global.FEATURES)==null?void 0:_a.legacyDecoratorFileOrder)??!1)}),args:getObjectField(moduleExportList,"args"),argsEnhancers:getArrayField(moduleExportList,"argsEnhancers"),argTypes:getObjectField(moduleExportList,"argTypes"),argTypesEnhancers:[...allArgTypeEnhancers.filter(e=>!e.secondPass),...allArgTypeEnhancers.filter(e=>e.secondPass)],globals:getObjectField(moduleExportList,"globals"),globalTypes:getObjectField(moduleExportList,"globalTypes"),loaders:getArrayField(moduleExportList,"loaders"),render:getSingletonField(moduleExportList,"render"),renderToCanvas:getSingletonField(moduleExportList,"renderToCanvas"),renderToDOM:getSingletonField(moduleExportList,"renderToDOM"),applyDecorators:getSingletonField(moduleExportList,"applyDecorators"),runStep:composeStepRunners(stepRunners)}}var CSF_CACHE_SIZE=1e3,STORY_CACHE_SIZE=1e4,EXTRACT_BATCH_SIZE=20,StoryStore=class{constructor(){this.getStoriesJsonData=()=>{let{storyIndex}=this;if(!storyIndex)throw new Error("getStoriesJsonData called before initialization");let value=this.getSetStoriesPayload(),allowedParameters=["fileName","docsOnly","framework","__id","__isArgsStory"];return{v:3,stories:(0,import_mapValues4.default)(value.stories,story=>{let{importPath}=storyIndex.entries[story.id];return{...(0,import_pick.default)(story,["id","name","title"]),importPath,kind:story.title,story:story.name,parameters:{...(0,import_pick.default)(story.parameters,allowedParameters),fileName:importPath}}})}};this.args=new ArgsStore,this.hooks={},this.processCSFFileWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(processCSFFile),this.prepareMetaWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(prepareMeta),this.prepareStoryWithCache=(0,import_memoizerific2.default)(STORY_CACHE_SIZE)(prepareStory),this.initializationPromise=new import_synchronous_promise.SynchronousPromise(resolve=>{this.resolveInitializationPromise=resolve})}setProjectAnnotations(projectAnnotations){this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.globals?this.globals.set({globals,globalTypes}):this.globals=new GlobalsStore({globals,globalTypes})}initialize({storyIndex,importFn,cache=!1}){return this.storyIndex=new StoryIndexStore(storyIndex),this.importFn=importFn,this.resolveInitializationPromise(),cache?this.cacheAllCSFFiles():import_synchronous_promise.SynchronousPromise.resolve()}async onStoriesChanged({importFn,storyIndex}){await this.initializationPromise,importFn&&(this.importFn=importFn),storyIndex&&(this.storyIndex.entries=storyIndex.entries),this.cachedCSFFiles&&await this.cacheAllCSFFiles()}async storyIdToEntry(storyId){return await this.initializationPromise,this.storyIndex.storyIdToEntry(storyId)}loadCSFFileByStoryId(storyId){if(!this.storyIndex||!this.importFn)throw new Error("loadCSFFileByStoryId called before initialization");let{importPath,title}=this.storyIndex.storyIdToEntry(storyId);return this.importFn(importPath).then(moduleExports=>this.processCSFFileWithCache(moduleExports,importPath,title))}loadAllCSFFiles({batchSize=EXTRACT_BATCH_SIZE}={}){if(!this.storyIndex)throw new Error("loadAllCSFFiles called before initialization");let importPaths=Object.entries(this.storyIndex.entries).map(([storyId,{importPath}])=>[importPath,storyId]),loadInBatches=remainingImportPaths=>{if(remainingImportPaths.length===0)return import_synchronous_promise.SynchronousPromise.resolve([]);let csfFilePromiseList=remainingImportPaths.slice(0,batchSize).map(([importPath,storyId])=>this.loadCSFFileByStoryId(storyId).then(csfFile=>({importPath,csfFile})));return import_synchronous_promise.SynchronousPromise.all(csfFilePromiseList).then(firstResults=>loadInBatches(remainingImportPaths.slice(batchSize)).then(restResults=>firstResults.concat(restResults)))};return loadInBatches(importPaths).then(list=>list.reduce((acc,{importPath,csfFile})=>(acc[importPath]=csfFile,acc),{}))}cacheAllCSFFiles(){return this.initializationPromise.then(()=>this.loadAllCSFFiles().then(csfFiles=>{this.cachedCSFFiles=csfFiles}))}preparedMetaFromCSFFile({csfFile}){if(!this.projectAnnotations)throw new Error("storyFromCSFFile called before initialization");let componentAnnotations=csfFile.meta;return this.prepareMetaWithCache(componentAnnotations,this.projectAnnotations,csfFile.moduleExports.default)}async loadStory({storyId}){await this.initializationPromise;let csfFile=await this.loadCSFFileByStoryId(storyId);return this.storyFromCSFFile({storyId,csfFile})}storyFromCSFFile({storyId,csfFile}){if(!this.projectAnnotations)throw new Error("storyFromCSFFile called before initialization");let storyAnnotations=csfFile.stories[storyId];if(!storyAnnotations)throw new Error(`Didn't find '${storyId}' in CSF file, this is unexpected`);let componentAnnotations=csfFile.meta,story=this.prepareStoryWithCache(storyAnnotations,componentAnnotations,this.projectAnnotations);return this.args.setInitial(story),this.hooks[story.id]=this.hooks[story.id]||new HooksContext,story}componentStoriesFromCSFFile({csfFile}){if(!this.storyIndex)throw new Error("componentStoriesFromCSFFile called before initialization");return Object.keys(this.storyIndex.entries).filter(storyId=>!!csfFile.stories[storyId]).map(storyId=>this.storyFromCSFFile({storyId,csfFile}))}async loadEntry(id){let entry=await this.storyIdToEntry(id),{importFn,storyIndex}=this;if(!storyIndex||!importFn)throw new Error("loadEntry called before initialization");let storyImports=entry.type==="docs"?entry.storiesImports:[],[entryExports,...csfFiles]=await Promise.all([importFn(entry.importPath),...storyImports.map(storyImportPath=>{let firstStoryEntry=storyIndex.importPathToEntry(storyImportPath);return this.loadCSFFileByStoryId(firstStoryEntry.id)})]);return{entryExports,csfFiles}}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.globals)throw new Error("getStoryContext called before initialization");return prepareContext({...story,args:forceInitialArgs?story.initialArgs:this.args.get(story.id),globals:this.globals.get(),hooks:this.hooks[story.id]})}cleanupStory(story){this.hooks[story.id].clean()}extract(options={includeDocsOnly:!1}){if(!this.storyIndex)throw new Error("extract called before initialization");let{cachedCSFFiles}=this;if(!cachedCSFFiles)throw new Error("Cannot call extract() unless you call cacheAllCSFFiles() first.");return Object.entries(this.storyIndex.entries).reduce((acc,[storyId,{type,importPath}])=>{if(type==="docs")return acc;let csfFile=cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return!options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((storyAcc,[key,value])=>key==="moduleExport"||typeof value=="function"?storyAcc:Array.isArray(value)?Object.assign(storyAcc,{[key]:value.slice().sort()}):Object.assign(storyAcc,{[key]:value}),{args:story.initialArgs})),acc},{})}getSetStoriesPayload(){if(!this.globals)throw new Error("getSetStoriesPayload called before initialization");let stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((acc,{title})=>(acc[title]={},acc),{});return{v:2,globals:this.globals.get(),globalParameters:{},kindParameters,stories}}getSetIndexPayload(){if(!this.storyIndex)throw new Error("getSetIndexPayload called before initialization");if(!this.cachedCSFFiles)throw new Error("Cannot call getSetIndexPayload() unless you call cacheAllCSFFiles() first");let{cachedCSFFiles}=this,stories=this.extract({includeDocsOnly:!0});return{v:4,entries:Object.fromEntries(Object.entries(this.storyIndex.entries).map(([id,entry])=>[id,stories[id]?{...entry,args:stories[id].initialArgs,initialArgs:stories[id].initialArgs,argTypes:stories[id].argTypes,parameters:stories[id].parameters}:{...entry,parameters:this.preparedMetaFromCSFFile({csfFile:cachedCSFFiles[entry.importPath]}).parameters}]))}}raw(){return Object.values(this.extract()).map(({id})=>this.fromId(id)).filter(Boolean)}fromId(storyId){if(!this.storyIndex)throw new Error("fromId called before initialization");if(!this.cachedCSFFiles)throw new Error("Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.");let importPath;try{({importPath}=this.storyIndex.storyIdToEntry(storyId))}catch{return null}let csfFile=this.cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return{...story,storyFn:update=>{let context={...this.getStoryContext(story),viewMode:"story"};return story.unboundStoryFn({...context,...update})}}}};var import_ts_dedent5=require("ts-dedent"),import_global5=require("@storybook/global"),import_synchronous_promise2=require("synchronous-promise"),import_core_events3=require("@storybook/core-events"),import_client_logger9=require("@storybook/client-logger");var import_client_logger8=require("@storybook/client-logger"),import_core_events2=require("@storybook/core-events");var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return{name,message,stack}}catch{return{name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing")}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}))}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id})}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return["preparing"].includes(this.phase)}isPending(){return["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode})}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{})}),this.notYetRendered=!1,abortSignal.aborted)return;if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext)}),await this.runPhase(abortSignal,"played")}catch(error){if(import_client_logger8.logger.error(error),await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(import_core_events2.PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error))}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error}if(this.disableKeyListeners=!1,abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(import_core_events2.STORY_RENDERED,id))}catch(err){this.phase="errored",this.callbacks.showException(err)}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){var _a;(_a=this.abortController)==null||_a.abort()}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0))}window.location.reload(),await new Promise(()=>{})}};var{fetch}=import_global5.global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(channel=addons.getChannel()){this.channel=channel;this.storyRenders=[];var _a;(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7&&addons.hasServerChannel()&&(this.serverChannel=addons.getServerChannel()),this.storyStore=new StoryStore}initialize({getStoryIndex,importFn,getProjectAnnotations}){return this.getStoryIndex=getStoryIndex,this.importFn=importFn,this.setupListeners(),this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(projectAnnotations=>this.initializeWithProjectAnnotations(projectAnnotations))}setupListeners(){this.channel.on(import_core_events3.STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(import_core_events3.UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(import_core_events3.UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(import_core_events3.RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(import_core_events3.FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(import_core_events3.FORCE_REMOUNT,this.onForceRemount.bind(this))}getProjectAnnotationsOrRenderError(getProjectAnnotations){return import_synchronous_promise2.SynchronousPromise.resolve().then(getProjectAnnotations).then(projectAnnotations=>{if(projectAnnotations.renderToDOM&&(0,import_client_logger9.deprecate)("`renderToDOM` is deprecated, please rename to `renderToCanvas`"),this.renderToCanvas=projectAnnotations.renderToCanvas||projectAnnotations.renderToDOM,!this.renderToCanvas)throw new Error(import_ts_dedent5.dedent`
|
|
25
|
+
`),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:(0,import_mapValues2.default)(value,field=>inferType(field,name,new Set(visited)))}):{name:"object",value:{}}},inferArgTypes=context=>{let{id,argTypes:userArgTypes={},initialArgs={}}=context,argTypes=(0,import_mapValues2.default)(initialArgs,(arg,key)=>({name:key,type:inferType(arg,`${id}.${key}`,new Set)})),userArgTypesNames=(0,import_mapValues2.default)(userArgTypes,(argType,key)=>({name:key}));return combineParameters(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var import_mapValues3=__toESM(require("lodash/mapValues.js")),import_client_logger7=require("@storybook/client-logger");var import_pickBy=__toESM(require("lodash/pickBy.js")),matches=(name,descriptor)=>Array.isArray(descriptor)?descriptor.includes(name):name.match(descriptor),filterArgTypes=(argTypes,include,exclude)=>!include&&!exclude?argTypes:argTypes&&(0,import_pickBy.default)(argTypes,(argType,key)=>{let name=argType.name||key;return(!include||matches(name,include))&&(!exclude||!matches(name,exclude))});var inferControl=(argType,name,matchers)=>{let{type,options}=argType;if(type){if(matchers.color&&matchers.color.test(name)){let controlType=type.name;if(controlType==="string")return{control:{type:"color"}};controlType!=="enum"&&import_client_logger7.logger.warn(`Addon controls: Control of type color only supports string, received "${controlType}" instead`)}if(matchers.date&&matchers.date.test(name))return{control:{type:"date"}};switch(type.name){case"array":return{control:{type:"object"}};case"boolean":return{control:{type:"boolean"}};case"string":return{control:{type:"text"}};case"number":return{control:{type:"number"}};case"enum":{let{value}=type;return{control:{type:(value==null?void 0:value.length)<=5?"radio":"select"},options:value}}case"function":case"symbol":return null;default:return{control:{type:options?"select":"object"}}}}},inferControls=context=>{let{argTypes,parameters:{__isArgsStory,controls:{include=null,exclude=null,matchers={}}={}}}=context;if(!__isArgsStory)return argTypes;let filteredArgTypes=filterArgTypes(argTypes,include,exclude),withControls=(0,import_mapValues3.default)(filteredArgTypes,(argType,name)=>(argType==null?void 0:argType.type)&&inferControl(argType,name,matchers));return combineParameters(withControls,filteredArgTypes)};inferControls.secondPass=!0;function normalizeProjectAnnotations({argTypes,globalTypes,argTypesEnhancers,decorators,loaders,...annotations}){return{...argTypes&&{argTypes:normalizeInputTypes(argTypes)},...globalTypes&&{globalTypes:normalizeInputTypes(globalTypes)},decorators:normalizeArrays(decorators),loaders:normalizeArrays(loaders),argTypesEnhancers:[...argTypesEnhancers||[],inferArgTypes,inferControls],...annotations}}var import_global4=require("@storybook/global");function composeStepRunners(stepRunners){return async(label,play,playContext)=>{await stepRunners.reduceRight((innerPlay,stepRunner)=>async()=>stepRunner(label,innerPlay,playContext),async()=>play(playContext))()}}function getField(moduleExportList,field){return moduleExportList.map(xs=>{var _a;return((_a=xs.default)==null?void 0:_a[field])??xs[field]}).filter(Boolean)}function getArrayField(moduleExportList,field,options={}){return getField(moduleExportList,field).reduce((a,b)=>options.reverseFileOrder?[...b,...a]:[...a,...b],[])}function getObjectField(moduleExportList,field){return Object.assign({},...getField(moduleExportList,field))}function getSingletonField(moduleExportList,field){return getField(moduleExportList,field).pop()}function composeConfigs(moduleExportList){var _a;let allArgTypeEnhancers=getArrayField(moduleExportList,"argTypesEnhancers"),stepRunners=getField(moduleExportList,"runStep");return{parameters:combineParameters(...getField(moduleExportList,"parameters")),decorators:getArrayField(moduleExportList,"decorators",{reverseFileOrder:!(((_a=import_global4.global.FEATURES)==null?void 0:_a.legacyDecoratorFileOrder)??!1)}),args:getObjectField(moduleExportList,"args"),argsEnhancers:getArrayField(moduleExportList,"argsEnhancers"),argTypes:getObjectField(moduleExportList,"argTypes"),argTypesEnhancers:[...allArgTypeEnhancers.filter(e=>!e.secondPass),...allArgTypeEnhancers.filter(e=>e.secondPass)],globals:getObjectField(moduleExportList,"globals"),globalTypes:getObjectField(moduleExportList,"globalTypes"),loaders:getArrayField(moduleExportList,"loaders"),render:getSingletonField(moduleExportList,"render"),renderToCanvas:getSingletonField(moduleExportList,"renderToCanvas"),renderToDOM:getSingletonField(moduleExportList,"renderToDOM"),applyDecorators:getSingletonField(moduleExportList,"applyDecorators"),runStep:composeStepRunners(stepRunners)}}var CSF_CACHE_SIZE=1e3,STORY_CACHE_SIZE=1e4,EXTRACT_BATCH_SIZE=20,StoryStore=class{constructor(){this.getStoriesJsonData=()=>{let{storyIndex}=this;if(!storyIndex)throw new Error("getStoriesJsonData called before initialization");let value=this.getSetStoriesPayload(),allowedParameters=["fileName","docsOnly","framework","__id","__isArgsStory"];return{v:3,stories:(0,import_mapValues4.default)(value.stories,story=>{let{importPath}=storyIndex.entries[story.id];return{...(0,import_pick.default)(story,["id","name","title"]),importPath,kind:story.title,story:story.name,parameters:{...(0,import_pick.default)(story.parameters,allowedParameters),fileName:importPath}}})}};this.args=new ArgsStore,this.hooks={},this.processCSFFileWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(processCSFFile),this.prepareMetaWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(prepareMeta),this.prepareStoryWithCache=(0,import_memoizerific2.default)(STORY_CACHE_SIZE)(prepareStory),this.initializationPromise=new import_synchronous_promise.SynchronousPromise(resolve=>{this.resolveInitializationPromise=resolve})}setProjectAnnotations(projectAnnotations){this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.globals?this.globals.set({globals,globalTypes}):this.globals=new GlobalsStore({globals,globalTypes})}initialize({storyIndex,importFn,cache=!1}){return this.storyIndex=new StoryIndexStore(storyIndex),this.importFn=importFn,this.resolveInitializationPromise(),cache?this.cacheAllCSFFiles():import_synchronous_promise.SynchronousPromise.resolve()}async onStoriesChanged({importFn,storyIndex}){await this.initializationPromise,importFn&&(this.importFn=importFn),storyIndex&&(this.storyIndex.entries=storyIndex.entries),this.cachedCSFFiles&&await this.cacheAllCSFFiles()}async storyIdToEntry(storyId){return await this.initializationPromise,this.storyIndex.storyIdToEntry(storyId)}loadCSFFileByStoryId(storyId){if(!this.storyIndex||!this.importFn)throw new Error("loadCSFFileByStoryId called before initialization");let{importPath,title}=this.storyIndex.storyIdToEntry(storyId);return this.importFn(importPath).then(moduleExports=>this.processCSFFileWithCache(moduleExports,importPath,title))}loadAllCSFFiles({batchSize=EXTRACT_BATCH_SIZE}={}){if(!this.storyIndex)throw new Error("loadAllCSFFiles called before initialization");let importPaths=Object.entries(this.storyIndex.entries).map(([storyId,{importPath}])=>[importPath,storyId]),loadInBatches=remainingImportPaths=>{if(remainingImportPaths.length===0)return import_synchronous_promise.SynchronousPromise.resolve([]);let csfFilePromiseList=remainingImportPaths.slice(0,batchSize).map(([importPath,storyId])=>this.loadCSFFileByStoryId(storyId).then(csfFile=>({importPath,csfFile})));return import_synchronous_promise.SynchronousPromise.all(csfFilePromiseList).then(firstResults=>loadInBatches(remainingImportPaths.slice(batchSize)).then(restResults=>firstResults.concat(restResults)))};return loadInBatches(importPaths).then(list=>list.reduce((acc,{importPath,csfFile})=>(acc[importPath]=csfFile,acc),{}))}cacheAllCSFFiles(){return this.initializationPromise.then(()=>this.loadAllCSFFiles().then(csfFiles=>{this.cachedCSFFiles=csfFiles}))}preparedMetaFromCSFFile({csfFile}){if(!this.projectAnnotations)throw new Error("storyFromCSFFile called before initialization");let componentAnnotations=csfFile.meta;return this.prepareMetaWithCache(componentAnnotations,this.projectAnnotations,csfFile.moduleExports.default)}async loadStory({storyId}){await this.initializationPromise;let csfFile=await this.loadCSFFileByStoryId(storyId);return this.storyFromCSFFile({storyId,csfFile})}storyFromCSFFile({storyId,csfFile}){if(!this.projectAnnotations)throw new Error("storyFromCSFFile called before initialization");let storyAnnotations=csfFile.stories[storyId];if(!storyAnnotations)throw new Error(`Didn't find '${storyId}' in CSF file, this is unexpected`);let componentAnnotations=csfFile.meta,story=this.prepareStoryWithCache(storyAnnotations,componentAnnotations,this.projectAnnotations);return this.args.setInitial(story),this.hooks[story.id]=this.hooks[story.id]||new HooksContext,story}componentStoriesFromCSFFile({csfFile}){if(!this.storyIndex)throw new Error("componentStoriesFromCSFFile called before initialization");return Object.keys(this.storyIndex.entries).filter(storyId=>!!csfFile.stories[storyId]).map(storyId=>this.storyFromCSFFile({storyId,csfFile}))}async loadEntry(id){let entry=await this.storyIdToEntry(id),{importFn,storyIndex}=this;if(!storyIndex||!importFn)throw new Error("loadEntry called before initialization");let storyImports=entry.type==="docs"?entry.storiesImports:[],[entryExports,...csfFiles]=await Promise.all([importFn(entry.importPath),...storyImports.map(storyImportPath=>{let firstStoryEntry=storyIndex.importPathToEntry(storyImportPath);return this.loadCSFFileByStoryId(firstStoryEntry.id)})]);return{entryExports,csfFiles}}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.globals)throw new Error("getStoryContext called before initialization");return prepareContext({...story,args:forceInitialArgs?story.initialArgs:this.args.get(story.id),globals:this.globals.get(),hooks:this.hooks[story.id]})}cleanupStory(story){this.hooks[story.id].clean()}extract(options={includeDocsOnly:!1}){if(!this.storyIndex)throw new Error("extract called before initialization");let{cachedCSFFiles}=this;if(!cachedCSFFiles)throw new Error("Cannot call extract() unless you call cacheAllCSFFiles() first.");return Object.entries(this.storyIndex.entries).reduce((acc,[storyId,{type,importPath}])=>{if(type==="docs")return acc;let csfFile=cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return!options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((storyAcc,[key,value])=>key==="moduleExport"||typeof value=="function"?storyAcc:Array.isArray(value)?Object.assign(storyAcc,{[key]:value.slice().sort()}):Object.assign(storyAcc,{[key]:value}),{args:story.initialArgs})),acc},{})}getSetStoriesPayload(){if(!this.globals)throw new Error("getSetStoriesPayload called before initialization");let stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((acc,{title})=>(acc[title]={},acc),{});return{v:2,globals:this.globals.get(),globalParameters:{},kindParameters,stories}}getSetIndexPayload(){if(!this.storyIndex)throw new Error("getSetIndexPayload called before initialization");if(!this.cachedCSFFiles)throw new Error("Cannot call getSetIndexPayload() unless you call cacheAllCSFFiles() first");let{cachedCSFFiles}=this,stories=this.extract({includeDocsOnly:!0});return{v:4,entries:Object.fromEntries(Object.entries(this.storyIndex.entries).map(([id,entry])=>[id,stories[id]?{...entry,args:stories[id].initialArgs,initialArgs:stories[id].initialArgs,argTypes:stories[id].argTypes,parameters:stories[id].parameters}:{...entry,parameters:this.preparedMetaFromCSFFile({csfFile:cachedCSFFiles[entry.importPath]}).parameters}]))}}raw(){return Object.values(this.extract()).map(({id})=>this.fromId(id)).filter(Boolean)}fromId(storyId){if(!this.storyIndex)throw new Error("fromId called before initialization");if(!this.cachedCSFFiles)throw new Error("Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.");let importPath;try{({importPath}=this.storyIndex.storyIdToEntry(storyId))}catch{return null}let csfFile=this.cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return{...story,storyFn:update=>{let context={...this.getStoryContext(story),viewMode:"story"};return story.unboundStoryFn({...context,...update})}}}};var import_ts_dedent5=require("ts-dedent"),import_global5=require("@storybook/global"),import_synchronous_promise2=require("synchronous-promise"),import_core_events3=require("@storybook/core-events"),import_client_logger9=require("@storybook/client-logger");var import_client_logger8=require("@storybook/client-logger"),import_core_events2=require("@storybook/core-events");var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return{name,message,stack}}catch{return{name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing")}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}))}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id})}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return["preparing"].includes(this.phase)}isPending(){return["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode})}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{})}),this.notYetRendered=!1,abortSignal.aborted)return;if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext)}),await this.runPhase(abortSignal,"played")}catch(error){if(import_client_logger8.logger.error(error),await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(import_core_events2.PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error))}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error}if(this.disableKeyListeners=!1,abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(import_core_events2.STORY_RENDERED,id))}catch(err){this.phase="errored",this.callbacks.showException(err)}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){var _a;(_a=this.abortController)==null||_a.abort()}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0))}window.location.reload(),await new Promise(()=>{})}};var{fetch}=import_global5.global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(channel=addons.getChannel()){this.channel=channel;this.storyRenders=[];var _a;(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7&&addons.hasServerChannel()&&(this.serverChannel=addons.getServerChannel()),this.storyStore=new StoryStore}initialize({getStoryIndex,importFn,getProjectAnnotations}){return this.getStoryIndex=getStoryIndex,this.importFn=importFn,this.setupListeners(),this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(projectAnnotations=>this.initializeWithProjectAnnotations(projectAnnotations))}setupListeners(){this.channel.on(import_core_events3.STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(import_core_events3.UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(import_core_events3.UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(import_core_events3.RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(import_core_events3.FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(import_core_events3.FORCE_REMOUNT,this.onForceRemount.bind(this))}getProjectAnnotationsOrRenderError(getProjectAnnotations){return import_synchronous_promise2.SynchronousPromise.resolve().then(getProjectAnnotations).then(projectAnnotations=>{if(projectAnnotations.renderToDOM&&(0,import_client_logger9.deprecate)("`renderToDOM` is deprecated, please rename to `renderToCanvas`"),this.renderToCanvas=projectAnnotations.renderToCanvas||projectAnnotations.renderToDOM,!this.renderToCanvas)throw new Error(import_ts_dedent5.dedent`
|
|
26
26
|
Expected your framework's preset to export a \`renderToCanvas\` field.
|
|
27
27
|
|
|
28
28
|
Perhaps it needs to be upgraded for Storybook 6.4?
|
package/dist/preview-web.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { DocsContext, Preview, PreviewWeb, PreviewWithSelection, simulateDOMContentLoaded, simulatePageLoad } from './chunk-
|
|
2
|
-
export { composeConfigs } from './chunk-
|
|
1
|
+
export { DocsContext, Preview, PreviewWeb, PreviewWithSelection, simulateDOMContentLoaded, simulatePageLoad } from './chunk-HOTYVPG7.mjs';
|
|
2
|
+
export { composeConfigs } from './chunk-VLGOEOTZ.mjs';
|
|
3
3
|
import './chunk-2WNKQWTL.mjs';
|
|
@@ -64,6 +64,6 @@ declare const userOrAutoTitleFromSpecifier: (fileName: string | number, entry: N
|
|
|
64
64
|
declare const userOrAutoTitle: (fileName: string, storiesEntries: NormalizedStoriesSpecifier[], userTitle?: string) => string | undefined;
|
|
65
65
|
|
|
66
66
|
declare const sortStoriesV7: (stories: IndexEntry[], storySortParameter: Addon_StorySortParameterV7, fileNameOrder: Path[]) => IndexEntry[];
|
|
67
|
-
declare const sortStoriesV6: (stories: [string, PreparedStory
|
|
67
|
+
declare const sortStoriesV6: <TRenderer extends Renderer>(stories: [string, PreparedStory<TRenderer>, Parameters, Parameters][], storySortParameter: Addon_StorySortParameter, fileNameOrder: Path[]) => IndexEntry[];
|
|
68
68
|
|
|
69
69
|
export { DEEPLY_EQUAL as D, PropDescriptor as P, UNTARGETED as U, combineParameters as a, composeStepRunners as b, combineArgs as c, composeStories as d, composeStory as e, decorateStory as f, defaultDecorateStory as g, filterArgTypes as h, setProjectAnnotations as i, inferControls as j, userOrAutoTitle as k, sortStoriesV7 as l, mapArgsToTypes as m, normalizeStory as n, deepDiff as o, groupArgsByTarget as p, noTargetArgs as q, sortStoriesV6 as r, sanitizeStoryContextUpdate as s, userOrAutoTitleFromSpecifier as u, validateOptions as v };
|
package/dist/store.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { S as StoryStore, c as prepareContext, a as prepareMeta, p as prepareStory, b as processCSFFile } from './StoryStore-
|
|
2
|
-
export { D as DEEPLY_EQUAL, P as PropDescriptor, U as UNTARGETED, c as combineArgs, a as combineParameters, b as composeStepRunners, d as composeStories, e as composeStory, f as decorateStory, o as deepDiff, g as defaultDecorateStory, h as filterArgTypes, p as groupArgsByTarget, j as inferControls, m as mapArgsToTypes, q as noTargetArgs, n as normalizeStory, s as sanitizeStoryContextUpdate, i as setProjectAnnotations, r as sortStoriesV6, l as sortStoriesV7, k as userOrAutoTitle, u as userOrAutoTitleFromSpecifier, v as validateOptions } from './sortStories-
|
|
1
|
+
export { S as StoryStore, c as prepareContext, a as prepareMeta, p as prepareStory, b as processCSFFile } from './StoryStore-f7424ddf.js';
|
|
2
|
+
export { D as DEEPLY_EQUAL, P as PropDescriptor, U as UNTARGETED, c as combineArgs, a as combineParameters, b as composeStepRunners, d as composeStories, e as composeStory, f as decorateStory, o as deepDiff, g as defaultDecorateStory, h as filterArgTypes, p as groupArgsByTarget, j as inferControls, m as mapArgsToTypes, q as noTargetArgs, n as normalizeStory, s as sanitizeStoryContextUpdate, i as setProjectAnnotations, r as sortStoriesV6, l as sortStoriesV7, k as userOrAutoTitle, u as userOrAutoTitleFromSpecifier, v as validateOptions } from './sortStories-436f1964.js';
|
|
3
3
|
import * as _storybook_types from '@storybook/types';
|
|
4
4
|
import { InputType, StrictInputType, ArgTypes, GlobalTypes, StrictArgTypes, StrictGlobalTypes, Renderer, ModuleExports, NormalizedComponentAnnotations, ProjectAnnotations, NormalizedProjectAnnotations } from '@storybook/types';
|
|
5
5
|
export { c as composeConfigs, a as getArrayField, g as getField, b as getObjectField, d as getSingletonField } from './composeConfigs-62a04721.js';
|
|
@@ -11,7 +11,7 @@ declare const normalizeInputTypes: (inputTypes: ArgTypes | GlobalTypes) => Stric
|
|
|
11
11
|
|
|
12
12
|
declare function normalizeComponentAnnotations<TRenderer extends Renderer>(defaultExport: ModuleExports['default'], title?: string, importPath?: string): NormalizedComponentAnnotations<TRenderer>;
|
|
13
13
|
|
|
14
|
-
declare function normalizeProjectAnnotations<TRenderer extends Renderer>({ argTypes, globalTypes, argTypesEnhancers, ...annotations }: ProjectAnnotations<TRenderer>): NormalizedProjectAnnotations<TRenderer>;
|
|
14
|
+
declare function normalizeProjectAnnotations<TRenderer extends Renderer>({ argTypes, globalTypes, argTypesEnhancers, decorators, loaders, ...annotations }: ProjectAnnotations<TRenderer>): NormalizedProjectAnnotations<TRenderer>;
|
|
15
15
|
|
|
16
16
|
declare const getValuesFromArgTypes: (argTypes?: ArgTypes) => ArgTypes<_storybook_types.Args>;
|
|
17
17
|
|