@storybook/preview 7.0.0-beta.16 → 7.0.0-beta.17
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/runtime.js +4 -4
- package/dist/runtime.mjs +4 -4
- package/package.json +8 -8
package/dist/runtime.js
CHANGED
|
@@ -50,7 +50,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
50
50
|
Are you using a V6-style sort function in V7 mode?
|
|
51
51
|
|
|
52
52
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
53
|
-
`)}},toIndexEntry=story=>{let{id,title,name:name2,parameters,type}=story;return{id,title,name:name2,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_client_logger9=__toESM(require_dist3(),1);var import_synchronous_promise2=__toESM(require_synchronous_promise(),1);var import_client_logger10=__toESM(require_dist3(),1);var import_qs=__toESM(require_lib(),1),StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise2.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){var _a,_b;let fileNameOrder=Object.keys(this.csfExports),storySortParameter=(_b=(_a=this.projectAnnotations.parameters)==null?void 0:_a.options)==null?void 0:_b.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:toId(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(dedent`
|
|
53
|
+
`)}},toIndexEntry=story=>{let{id,title,name:name2,parameters,type}=story;return{id,title,name:name2,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_client_logger9=__toESM(require_dist3(),1);var import_synchronous_promise2=__toESM(require_synchronous_promise(),1);var import_client_logger10=__toESM(require_dist3(),1);var import_qs=__toESM(require_lib(),1),AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise2.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){var _a,_b;let fileNameOrder=Object.keys(this.csfExports),storySortParameter=(_b=(_a=this.projectAnnotations.parameters)==null?void 0:_a.options)==null?void 0:_b.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:toId(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(dedent`
|
|
54
54
|
Error sorting stories with sort parameter ${storySortParameter}:
|
|
55
55
|
|
|
56
56
|
> ${err.message}
|
|
@@ -58,7 +58,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
58
58
|
Are you using a V7-style sort function in V6 compatibility mode?
|
|
59
59
|
|
|
60
60
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
61
|
-
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(scope.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger10.logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name2=>{let namedExport=namedExports[name2];namedExport&&(sortedExports[name2]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key2])=>isExportStory(key2,defaultExport)),docsOptions=scope.DOCS_OPTIONS||{},
|
|
61
|
+
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(scope.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger10.logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name2=>{let namedExport=namedExports[name2];namedExport&&(sortedExports[name2]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key2])=>isExportStory(key2,defaultExport)),docsOptions=scope.DOCS_OPTIONS||{},{autodocs}=docsOptions,componentAutodocs=componentTags.includes(AUTODOCS_TAG),autodocsOptedIn=autodocs===!0||autodocs==="tag"&&componentAutodocs;if(!docsOptions.disable&&storyExports.length&&(componentTags.includes(STORIES_MDX_TAG)||autodocsOptedIn)){let name2=docsOptions.defaultName,docsId=toId(componentId||title,name2);this.entries[docsId]={type:"docs",id:docsId,title,name:name2,importPath:fileName,...componentId&&{componentId},tags:[...componentTags,"docs",...autodocsOptedIn&&!componentAutodocs?[AUTODOCS_TAG]:[]],storiesImports:[]}}storyExports.forEach(([key2,storyExport])=>{var _a,_b,_c;let exportName=storyNameFromExport(key2),id=((_a=storyExport.parameters)==null?void 0:_a.__id)||toId(componentId||title,exportName),name2=typeof storyExport!="function"&&storyExport.name||storyExport.storyName||((_b=storyExport.story)==null?void 0:_b.name)||exportName;(_c=storyExport.parameters)!=null&&_c.docsOnly||(this.entries[id]={type:"story",id,name:name2,title,importPath:fileName,...componentId&&{componentId},tags:[...storyExport.tags||componentTags,"story"]})})}},warningAlternatives={addDecorator:"Instead, use `export const decorators = [];` in your `preview.js`.",addParameters:"Instead, use `export const parameters = {};` in your `preview.js`.",addLoader:"Instead, use `export const loaders = [];` in your `preview.js`.",addArgs:"",addArgTypes:"",addArgsEnhancer:"",addArgTypesEnhancer:"",addStepRunner:"",getGlobalRender:"",setGlobalRender:""},checkMethod=method=>{var _a;if((_a=scope.FEATURES)!=null&&_a.storyStoreV7)throw new Error(dedent`You cannot use \`${method}\` with the new Story Store.
|
|
62
62
|
|
|
63
63
|
${warningAlternatives[method]}`);if(!scope.__STORYBOOK_CLIENT_API__)throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`)},addDecorator=decorator=>{var _a;checkMethod("addDecorator"),(_a=scope.__STORYBOOK_CLIENT_API__)==null||_a.addDecorator(decorator)},addParameters=parameters=>{var _a;checkMethod("addParameters"),(_a=scope.__STORYBOOK_CLIENT_API__)==null||_a.addParameters(parameters)},addLoader=loader=>{var _a;checkMethod("addLoader"),(_a=scope.__STORYBOOK_CLIENT_API__)==null||_a.addLoader(loader)},addArgs=args2=>{var _a;checkMethod("addArgs"),(_a=scope.__STORYBOOK_CLIENT_API__)==null||_a.addArgs(args2)},addArgTypes=argTypes=>{var _a;checkMethod("addArgTypes"),(_a=scope.__STORYBOOK_CLIENT_API__)==null||_a.addArgTypes(argTypes)},addArgsEnhancer=enhancer=>{var _a;checkMethod("addArgsEnhancer"),(_a=scope.__STORYBOOK_CLIENT_API__)==null||_a.addArgsEnhancer(enhancer)},addArgTypesEnhancer=enhancer=>{var _a;checkMethod("addArgTypesEnhancer"),(_a=scope.__STORYBOOK_CLIENT_API__)==null||_a.addArgTypesEnhancer(enhancer)},addStepRunner=stepRunner=>{var _a;checkMethod("addStepRunner"),(_a=scope.__STORYBOOK_CLIENT_API__)==null||_a.addStepRunner(stepRunner)},setGlobalRender=render=>{checkMethod("setGlobalRender"),scope.__STORYBOOK_CLIENT_API__&&(scope.__STORYBOOK_CLIENT_API__.facade.projectAnnotations.render=render)},invalidStoryTypes=new Set(["string","number","boolean","symbol"]),ClientApi=class{constructor({storyStore}={}){this.lastFileName=0,this.addDecorator=decorator=>{var _a;(_a=this.facade.projectAnnotations.decorators)==null||_a.push(decorator)},this.addParameters=({globals:globals2,globalTypes,...parameters})=>{this.facade.projectAnnotations.parameters=combineParameters(this.facade.projectAnnotations.parameters,parameters),globals2&&(this.facade.projectAnnotations.globals={...this.facade.projectAnnotations.globals,...globals2}),globalTypes&&(this.facade.projectAnnotations.globalTypes={...this.facade.projectAnnotations.globalTypes,...normalizeInputTypes(globalTypes)})},this.addStepRunner=stepRunner=>{this.facade.projectAnnotations.runStep=composeStepRunners([this.facade.projectAnnotations.runStep,stepRunner].filter(Boolean))},this.addLoader=loader=>{var _a;(_a=this.facade.projectAnnotations.loaders)==null||_a.push(loader)},this.addArgs=args2=>{this.facade.projectAnnotations.args={...this.facade.projectAnnotations.args,...args2}},this.addArgTypes=argTypes=>{this.facade.projectAnnotations.argTypes={...this.facade.projectAnnotations.argTypes,...normalizeInputTypes(argTypes)}},this.addArgsEnhancer=enhancer=>{var _a;(_a=this.facade.projectAnnotations.argsEnhancers)==null||_a.push(enhancer)},this.addArgTypesEnhancer=enhancer=>{var _a;(_a=this.facade.projectAnnotations.argTypesEnhancers)==null||_a.push(enhancer)},this._addedExports={},this.storiesOf=(kind,m)=>{if(!kind&&typeof kind!="string")throw new Error("Invalid or missing kind provided for stories, should be a string");if(m||import_client_logger9.logger.warn(`Missing 'module' parameter for story with a kind of '${kind}'. It will break your HMR`),m){let proto=Object.getPrototypeOf(m);proto.exports&&proto.exports.default&&import_client_logger9.logger.error(`Illegal mix of CSF default export and storiesOf calls in a single file: ${proto.i}`)}let baseFilename=m&&m.id?`${m.id}`:(this.lastFileName++).toString(),fileName=baseFilename,i=1;for(;this._addedExports[fileName];)i+=1,fileName=`${baseFilename}-${i}`;m&&m.hot&&m.hot.accept&&(m.hot.accept(),m.hot.dispose(()=>{this.facade.clearFilenameExports(fileName),delete this._addedExports[fileName],setTimeout(()=>{var _a;this._loadAddedExports(),(_a=this.onImportFnChanged)==null||_a.call(this,{importFn:this.importFn.bind(this)})},0)}));let hasAdded=!1,api={kind:kind.toString(),add:()=>api,addDecorator:()=>api,addLoader:()=>api,addParameters:()=>api};Object.keys(this.addons).forEach(name2=>{let addon=this.addons[name2];api[name2]=(...args2)=>(addon.apply(api,args2),api)});let meta={id:sanitize(kind),title:kind,decorators:[],loaders:[],parameters:{}};this._addedExports[fileName]={default:meta};let counter=0;return api.add=(storyName,storyFn,parameters={})=>{if(hasAdded=!0,typeof storyName!="string")throw new Error(`Invalid or missing storyName provided for a "${kind}" story.`);if(!storyFn||Array.isArray(storyFn)||invalidStoryTypes.has(typeof storyFn))throw new Error(`Cannot load story "${storyName}" in "${kind}" due to invalid format. Storybook expected a function/object but received ${typeof storyFn} instead.`);let{decorators,loaders,component,args:args2,argTypes,...storyParameters}=parameters,storyId=parameters.__id||toId(kind,storyName),csfExports=this._addedExports[fileName];return csfExports[`story${counter}`]={name:storyName,parameters:{fileName,__id:storyId,...storyParameters},decorators,loaders,args:args2,argTypes,component,render:storyFn},counter+=1,api},api.addDecorator=decorator=>{var _a;if(hasAdded)throw new Error(`You cannot add a decorator after the first story for a kind.
|
|
64
64
|
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);return(_a=meta.decorators)==null||_a.push(decorator),api},api.addLoader=loader=>{var _a;if(hasAdded)throw new Error("You cannot add a loader after the first story for a kind.");return(_a=meta.loaders)==null||_a.push(loader),api},api.addParameters=({component,args:args2,argTypes,tags,...parameters})=>{if(hasAdded)throw new Error(`You cannot add parameters after the first story for a kind.
|
|
@@ -72,7 +72,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
72
72
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
73
73
|
`);return projectAnnotations}).catch(err=>{throw this.renderPreviewEntryError("Error reading preview.js:",err),err})}initializeWithProjectAnnotations(projectAnnotations){var _a;this.storyStore.setProjectAnnotations(projectAnnotations),this.setInitialGlobals();let storyIndexPromise;if((_a=scope.FEATURES)!=null&&_a.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=import_synchronous_promise3.SynchronousPromise.resolve().then(this.getStoryIndex)}return storyIndexPromise.then(storyIndex=>this.initializeWithStoryIndex(storyIndex)).catch(err=>{throw this.renderPreviewEntryError("Error loading story index:",err),err})}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStore.globals||!this.storyStore.projectAnnotations)throw new Error("Cannot emit before initialization");let payload={globals:this.storyStore.globals.get()||{},globalTypes:this.storyStore.projectAnnotations.globalTypes||{}};this.channel.emit(import_core_events3.SET_GLOBALS,payload)}async getStoryIndexFromServer(){let result2=await fetch(STORY_INDEX_PATH);if(result2.status===200)return result2.json();throw new Error(await result2.text())}initializeWithStoryIndex(storyIndex){var _a;if(!this.importFn)throw new Error("Cannot call initializeWithStoryIndex before initialization");return this.storyStore.initialize({storyIndex,importFn:this.importFn,cache:!((_a=scope.FEATURES)!=null&&_a.storyStoreV7)})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError;let projectAnnotations=await this.getProjectAnnotationsOrRenderError(getProjectAnnotations);if(!this.storyStore.projectAnnotations){await this.initializeWithProjectAnnotations(projectAnnotations);return}await this.storyStore.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!!this.storyStore.projectAnnotations)try{let storyIndex=await this.getStoryIndexFromServer();this.storyStore.storyIndex||await this.initializeWithStoryIndex(storyIndex),await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){await this.storyStore.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals:globals2}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals2),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(import_core_events3.GLOBALS_UPDATED,{globals:this.storyStore.globals.get(),initialGlobals:this.storyStore.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){this.storyStore.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){var _a;let story=((_a=this.storyRenders.find(r=>r.id===storyId))==null?void 0:_a.story)||await this.storyStore.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStore.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs})}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()))}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()))}renderStoryToElement(story,element,options2){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,this.inlineStoryCallbacks(story.id),story.id,"docs",options2,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render)}}async teardownRender(render,{viewModeChanged}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options2){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent`Failed to initialize Storybook.
|
|
74
74
|
|
|
75
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=scope.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options2)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger11.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger11.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger11.logger.error(reason),import_client_logger11.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}},DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel,this.store=store,this.renderStoryToElement=renderStoryToElement,this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)},this.componentStories=()=>this.componentStoriesValue,this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})},this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"}),this.loadStory=id=>this.store.loadStory({storyId:id}),this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}},
|
|
75
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=scope.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options2)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger11.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger11.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger11.logger.error(reason),import_client_logger11.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}},DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel,this.store=store,this.renderStoryToElement=renderStoryToElement,this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)},this.componentStories=()=>this.componentStoriesValue,this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})},this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"}),this.loadStory=id=>this.store.loadStory({storyId:id}),this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}},CsfDocsRender=class{constructor(channel,store,entry){this.channel=channel,this.store=store,this.entry=entry,this.type="docs",this.torndown=!1,this.disableKeyListeners=!1,this.preparing=!1,this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!0),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(import_core_events6.DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}},MdxDocsRender=class{constructor(channel,store,entry){this.channel=channel,this.store=store,this.entry=entry,this.type="docs",this.torndown=!1,this.disableKeyListeners=!1,this.preparing=!1,this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.exports&&this.exports===other.exports)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!1),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(import_core_events7.DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0)},renderDocs()}async teardown({viewModeChanged}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}},globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG2="autodocs",STORIES_MDX_TAG2="stories-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG2))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG2))}function isStoryRender(r){return r.type==="story"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super(),this.selectionStore=selectionStore,this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events5.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events5.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events5.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}initializeWithProjectAnnotations(projectAnnotations){return super.initializeWithProjectAnnotations(projectAnnotations).then(()=>this.setInitialGlobals())}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals:globals2}=this.selectionStore.selectionSpecifier||{};globals2&&this.storyStore.globals.updateFromPersisted(globals2),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=scope.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events5.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args:args2}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(dedent`
|
|
76
76
|
Couldn't find any stories in your Storybook.
|
|
77
77
|
- Please check your stories field of your main.js config.
|
|
78
78
|
- Also check the browser console and terminal for error messages.
|
|
@@ -81,7 +81,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
81
81
|
- Are you sure a story with that id exists?
|
|
82
82
|
- Please check your stories field of your main.js config.
|
|
83
83
|
- Also check the browser console and terminal for error messages.
|
|
84
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events5.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events5.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args2})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=scope.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events5.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key:key2,code,keyCode}=event;this.channel.emit(import_core_events5.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key:key2,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events5.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals:globals2}){var _a,_b;super.onUpdateGlobals({globals:globals2}),(this.currentRender instanceof
|
|
84
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events5.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events5.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args2})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=scope.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events5.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key:key2,code,keyCode}=event;this.channel.emit(import_core_events5.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key:key2,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events5.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals:globals2}){var _a,_b;super.onUpdateGlobals({globals:globals2}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs(),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args2)=>(this.view.showStoryDuringRender(),renderToCanvas(...args2)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry):render=new CsfDocsRender(this.channel,this.storyStore,entry);let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events5.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events5.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args:args2}=this.storyStore.getStoryContext(render.story);(_d=scope.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events5.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:args2}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events5.STORY_ARGS_UPDATED,{storyId,args:args2})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options2){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent`Failed to initialize Storybook.
|
|
85
85
|
|
|
86
86
|
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=scope.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options2)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger13.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger13.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events5.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger13.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events5.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name:name2="Error",message=String(error),stack}=error;this.channel.emit(import_core_events5.STORY_THREW_EXCEPTION,{name:name2,message,stack}),this.channel.emit(import_core_events5.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),(_a=error.message)!=null&&_a.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger13.logger.error(`Error rendering story '${storyId}':`),import_client_logger13.logger.error(error))}renderError(storyId,{title,description}){import_client_logger13.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events5.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events5.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}},VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key2="",value2)=>key2===null||key2===""||!VALIDATION_REGEXP.test(key2)?!1:value2==null||value2 instanceof Date||typeof value2=="number"||typeof value2=="boolean"?!0:typeof value2=="string"?VALIDATION_REGEXP.test(value2)||NUMBER_REGEXP.test(value2)||HEX_REGEXP.test(value2)||COLOR_REGEXP.test(value2):Array.isArray(value2)?value2.every(v=>validateArgs(key2,v)):(0,import_isPlainObject3.default)(value2)?Object.entries(value2).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(import_qs3.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key2,value2])=>validateArgs(key2,value2)?Object.assign(acc,{[key2]:value2}):(import_client_logger14.once.warn(dedent`
|
|
87
87
|
Omitted potentially unsafe URL args.
|
package/dist/runtime.mjs
CHANGED
|
@@ -50,7 +50,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
50
50
|
Are you using a V6-style sort function in V7 mode?
|
|
51
51
|
|
|
52
52
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
53
|
-
`)}},toIndexEntry=story=>{let{id,title,name:name2,parameters,type}=story;return{id,title,name:name2,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_synchronous_promise2=__toESM(require_synchronous_promise(),1);var import_qs2=__toESM(require_lib(),1),StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise2.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){let fileNameOrder=Object.keys(this.csfExports),storySortParameter=this.projectAnnotations.parameters?.options?.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:toId(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(dedent`
|
|
53
|
+
`)}},toIndexEntry=story=>{let{id,title,name:name2,parameters,type}=story;return{id,title,name:name2,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_synchronous_promise2=__toESM(require_synchronous_promise(),1);var import_qs2=__toESM(require_lib(),1),AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise2.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){let fileNameOrder=Object.keys(this.csfExports),storySortParameter=this.projectAnnotations.parameters?.options?.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:toId(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(dedent`
|
|
54
54
|
Error sorting stories with sort parameter ${storySortParameter}:
|
|
55
55
|
|
|
56
56
|
> ${err.message}
|
|
@@ -58,7 +58,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
58
58
|
Are you using a V7-style sort function in V6 compatibility mode?
|
|
59
59
|
|
|
60
60
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
61
|
-
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(scope.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name2=>{let namedExport=namedExports[name2];namedExport&&(sortedExports[name2]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key2])=>isExportStory(key2,defaultExport)),docsOptions=scope.DOCS_OPTIONS||{},
|
|
61
|
+
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(scope.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name2=>{let namedExport=namedExports[name2];namedExport&&(sortedExports[name2]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key2])=>isExportStory(key2,defaultExport)),docsOptions=scope.DOCS_OPTIONS||{},{autodocs}=docsOptions,componentAutodocs=componentTags.includes(AUTODOCS_TAG),autodocsOptedIn=autodocs===!0||autodocs==="tag"&&componentAutodocs;if(!docsOptions.disable&&storyExports.length&&(componentTags.includes(STORIES_MDX_TAG)||autodocsOptedIn)){let name2=docsOptions.defaultName,docsId=toId(componentId||title,name2);this.entries[docsId]={type:"docs",id:docsId,title,name:name2,importPath:fileName,...componentId&&{componentId},tags:[...componentTags,"docs",...autodocsOptedIn&&!componentAutodocs?[AUTODOCS_TAG]:[]],storiesImports:[]}}storyExports.forEach(([key2,storyExport])=>{let exportName=storyNameFromExport(key2),id=storyExport.parameters?.__id||toId(componentId||title,exportName),name2=typeof storyExport!="function"&&storyExport.name||storyExport.storyName||storyExport.story?.name||exportName;storyExport.parameters?.docsOnly||(this.entries[id]={type:"story",id,name:name2,title,importPath:fileName,...componentId&&{componentId},tags:[...storyExport.tags||componentTags,"story"]})})}},warningAlternatives={addDecorator:"Instead, use `export const decorators = [];` in your `preview.js`.",addParameters:"Instead, use `export const parameters = {};` in your `preview.js`.",addLoader:"Instead, use `export const loaders = [];` in your `preview.js`.",addArgs:"",addArgTypes:"",addArgsEnhancer:"",addArgTypesEnhancer:"",addStepRunner:"",getGlobalRender:"",setGlobalRender:""},checkMethod=method=>{if(scope.FEATURES?.storyStoreV7)throw new Error(dedent`You cannot use \`${method}\` with the new Story Store.
|
|
62
62
|
|
|
63
63
|
${warningAlternatives[method]}`);if(!scope.__STORYBOOK_CLIENT_API__)throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`)},addDecorator=decorator=>{checkMethod("addDecorator"),scope.__STORYBOOK_CLIENT_API__?.addDecorator(decorator)},addParameters=parameters=>{checkMethod("addParameters"),scope.__STORYBOOK_CLIENT_API__?.addParameters(parameters)},addLoader=loader=>{checkMethod("addLoader"),scope.__STORYBOOK_CLIENT_API__?.addLoader(loader)},addArgs=args2=>{checkMethod("addArgs"),scope.__STORYBOOK_CLIENT_API__?.addArgs(args2)},addArgTypes=argTypes=>{checkMethod("addArgTypes"),scope.__STORYBOOK_CLIENT_API__?.addArgTypes(argTypes)},addArgsEnhancer=enhancer=>{checkMethod("addArgsEnhancer"),scope.__STORYBOOK_CLIENT_API__?.addArgsEnhancer(enhancer)},addArgTypesEnhancer=enhancer=>{checkMethod("addArgTypesEnhancer"),scope.__STORYBOOK_CLIENT_API__?.addArgTypesEnhancer(enhancer)},addStepRunner=stepRunner=>{checkMethod("addStepRunner"),scope.__STORYBOOK_CLIENT_API__?.addStepRunner(stepRunner)},setGlobalRender=render=>{checkMethod("setGlobalRender"),scope.__STORYBOOK_CLIENT_API__&&(scope.__STORYBOOK_CLIENT_API__.facade.projectAnnotations.render=render)},invalidStoryTypes=new Set(["string","number","boolean","symbol"]),ClientApi=class{constructor({storyStore}={}){this.lastFileName=0,this.addDecorator=decorator=>{this.facade.projectAnnotations.decorators?.push(decorator)},this.addParameters=({globals:globals2,globalTypes,...parameters})=>{this.facade.projectAnnotations.parameters=combineParameters(this.facade.projectAnnotations.parameters,parameters),globals2&&(this.facade.projectAnnotations.globals={...this.facade.projectAnnotations.globals,...globals2}),globalTypes&&(this.facade.projectAnnotations.globalTypes={...this.facade.projectAnnotations.globalTypes,...normalizeInputTypes(globalTypes)})},this.addStepRunner=stepRunner=>{this.facade.projectAnnotations.runStep=composeStepRunners([this.facade.projectAnnotations.runStep,stepRunner].filter(Boolean))},this.addLoader=loader=>{this.facade.projectAnnotations.loaders?.push(loader)},this.addArgs=args2=>{this.facade.projectAnnotations.args={...this.facade.projectAnnotations.args,...args2}},this.addArgTypes=argTypes=>{this.facade.projectAnnotations.argTypes={...this.facade.projectAnnotations.argTypes,...normalizeInputTypes(argTypes)}},this.addArgsEnhancer=enhancer=>{this.facade.projectAnnotations.argsEnhancers?.push(enhancer)},this.addArgTypesEnhancer=enhancer=>{this.facade.projectAnnotations.argTypesEnhancers?.push(enhancer)},this._addedExports={},this.storiesOf=(kind,m)=>{if(!kind&&typeof kind!="string")throw new Error("Invalid or missing kind provided for stories, should be a string");if(m||logger.warn(`Missing 'module' parameter for story with a kind of '${kind}'. It will break your HMR`),m){let proto=Object.getPrototypeOf(m);proto.exports&&proto.exports.default&&logger.error(`Illegal mix of CSF default export and storiesOf calls in a single file: ${proto.i}`)}let baseFilename=m&&m.id?`${m.id}`:(this.lastFileName++).toString(),fileName=baseFilename,i=1;for(;this._addedExports[fileName];)i+=1,fileName=`${baseFilename}-${i}`;m&&m.hot&&m.hot.accept&&(m.hot.accept(),m.hot.dispose(()=>{this.facade.clearFilenameExports(fileName),delete this._addedExports[fileName],setTimeout(()=>{this._loadAddedExports(),this.onImportFnChanged?.({importFn:this.importFn.bind(this)})},0)}));let hasAdded=!1,api={kind:kind.toString(),add:()=>api,addDecorator:()=>api,addLoader:()=>api,addParameters:()=>api};Object.keys(this.addons).forEach(name2=>{let addon=this.addons[name2];api[name2]=(...args2)=>(addon.apply(api,args2),api)});let meta={id:sanitize(kind),title:kind,decorators:[],loaders:[],parameters:{}};this._addedExports[fileName]={default:meta};let counter=0;return api.add=(storyName,storyFn,parameters={})=>{if(hasAdded=!0,typeof storyName!="string")throw new Error(`Invalid or missing storyName provided for a "${kind}" story.`);if(!storyFn||Array.isArray(storyFn)||invalidStoryTypes.has(typeof storyFn))throw new Error(`Cannot load story "${storyName}" in "${kind}" due to invalid format. Storybook expected a function/object but received ${typeof storyFn} instead.`);let{decorators,loaders,component,args:args2,argTypes,...storyParameters}=parameters,storyId=parameters.__id||toId(kind,storyName),csfExports=this._addedExports[fileName];return csfExports[`story${counter}`]={name:storyName,parameters:{fileName,__id:storyId,...storyParameters},decorators,loaders,args:args2,argTypes,component,render:storyFn},counter+=1,api},api.addDecorator=decorator=>{if(hasAdded)throw new Error(`You cannot add a decorator after the first story for a kind.
|
|
64
64
|
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);return meta.decorators?.push(decorator),api},api.addLoader=loader=>{if(hasAdded)throw new Error("You cannot add a loader after the first story for a kind.");return meta.loaders?.push(loader),api},api.addParameters=({component,args:args2,argTypes,tags,...parameters})=>{if(hasAdded)throw new Error(`You cannot add parameters after the first story for a kind.
|
|
@@ -72,7 +72,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
72
72
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
73
73
|
`);return projectAnnotations}).catch(err=>{throw this.renderPreviewEntryError("Error reading preview.js:",err),err})}initializeWithProjectAnnotations(projectAnnotations){this.storyStore.setProjectAnnotations(projectAnnotations),this.setInitialGlobals();let storyIndexPromise;if(scope.FEATURES?.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=import_synchronous_promise3.SynchronousPromise.resolve().then(this.getStoryIndex)}return storyIndexPromise.then(storyIndex=>this.initializeWithStoryIndex(storyIndex)).catch(err=>{throw this.renderPreviewEntryError("Error loading story index:",err),err})}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStore.globals||!this.storyStore.projectAnnotations)throw new Error("Cannot emit before initialization");let payload={globals:this.storyStore.globals.get()||{},globalTypes:this.storyStore.projectAnnotations.globalTypes||{}};this.channel.emit(SET_GLOBALS,payload)}async getStoryIndexFromServer(){let result2=await fetch(STORY_INDEX_PATH);if(result2.status===200)return result2.json();throw new Error(await result2.text())}initializeWithStoryIndex(storyIndex){if(!this.importFn)throw new Error("Cannot call initializeWithStoryIndex before initialization");return this.storyStore.initialize({storyIndex,importFn:this.importFn,cache:!scope.FEATURES?.storyStoreV7})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError;let projectAnnotations=await this.getProjectAnnotationsOrRenderError(getProjectAnnotations);if(!this.storyStore.projectAnnotations){await this.initializeWithProjectAnnotations(projectAnnotations);return}await this.storyStore.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!!this.storyStore.projectAnnotations)try{let storyIndex=await this.getStoryIndexFromServer();this.storyStore.storyIndex||await this.initializeWithStoryIndex(storyIndex),await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){await this.storyStore.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals:globals2}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals2),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(GLOBALS_UPDATED,{globals:this.storyStore.globals.get(),initialGlobals:this.storyStore.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){this.storyStore.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.rerender())),this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){let story=this.storyRenders.find(r=>r.id===storyId)?.story||await this.storyStore.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStore.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs})}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()))}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()))}renderStoryToElement(story,element,options2){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,this.inlineStoryCallbacks(story.id),story.id,"docs",options2,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render)}}async teardownRender(render,{viewModeChanged}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged})}async extract(options2){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent`Failed to initialize Storybook.
|
|
74
74
|
|
|
75
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return scope.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options2)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger.error(reason),logger.error(err),this.channel.emit(CONFIG_ERROR,err)}},DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel,this.store=store,this.renderStoryToElement=renderStoryToElement,this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)},this.componentStories=()=>this.componentStoriesValue,this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})},this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"}),this.loadStory=id=>this.store.loadStory({storyId:id}),this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}},
|
|
75
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return scope.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options2)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger.error(reason),logger.error(err),this.channel.emit(CONFIG_ERROR,err)}},DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel,this.store=store,this.renderStoryToElement=renderStoryToElement,this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)},this.componentStories=()=>this.componentStoriesValue,this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})},this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"}),this.loadStory=id=>this.store.loadStory({storyId:id}),this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}},CsfDocsRender=class{constructor(channel,store,entry){this.channel=channel,this.store=store,this.entry=entry,this.type="docs",this.torndown=!1,this.disableKeyListeners=!1,this.preparing=!1,this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!0),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}},MdxDocsRender=class{constructor(channel,store,entry){this.channel=channel,this.store=store,this.entry=entry,this.type="docs",this.torndown=!1,this.disableKeyListeners=!1,this.preparing=!1,this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.exports&&this.exports===other.exports)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!1),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}},globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG2="autodocs",STORIES_MDX_TAG2="stories-mdx";function isMdxEntry({tags}){return!tags?.includes(AUTODOCS_TAG2)&&!tags?.includes(STORIES_MDX_TAG2)}function isStoryRender(r){return r.type==="story"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super(),this.selectionStore=selectionStore,this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}initializeWithProjectAnnotations(projectAnnotations){return super.initializeWithProjectAnnotations(projectAnnotations).then(()=>this.setInitialGlobals())}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals:globals2}=this.selectionStore.selectionSpecifier||{};globals2&&this.storyStore.globals.updateFromPersisted(globals2),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>(scope.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()))}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args:args2}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(dedent`
|
|
76
76
|
Couldn't find any stories in your Storybook.
|
|
77
77
|
- Please check your stories field of your main.js config.
|
|
78
78
|
- Also check the browser console and terminal for error messages.
|
|
@@ -81,7 +81,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
81
81
|
- Are you sure a story with that id exists?
|
|
82
82
|
- Please check your stories field of your main.js config.
|
|
83
83
|
- Also check the browser console and terminal for error messages.
|
|
84
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args2})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),scope.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key:key2,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key:key2,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals:globals2}){super.onUpdateGlobals({globals:globals2}),(this.currentRender instanceof
|
|
84
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args2})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),scope.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key:key2,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key:key2,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals:globals2}){super.onUpdateGlobals({globals:globals2}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.()}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=this.currentSelection?.storyId!==storyId,viewModeChanged=this.currentRender?.type!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs(),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args2)=>(this.view.showStoryDuringRender(),renderToCanvas(...args2)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry):render=new CsfDocsRender(this.channel,this.storyStore,entry);let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args:args2}=this.storyStore.getStoryContext(render.story);scope.FEATURES?.storyStoreV7&&this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:args2}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:args2})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged})}async extract(options2){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent`Failed to initialize Storybook.
|
|
85
85
|
|
|
86
86
|
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return scope.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options2)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(STORY_MISSING,storySpecifier)}renderException(storyId,error){let{name:name2="Error",message=String(error),stack}=error;this.channel.emit(STORY_THREW_EXCEPTION,{name:name2,message,stack}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),logger.error(`Error rendering story '${storyId}':`),logger.error(error))}renderError(storyId,{title,description}){logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(STORY_ERRORED,{title,description}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}},VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key2="",value2)=>key2===null||key2===""||!VALIDATION_REGEXP.test(key2)?!1:value2==null||value2 instanceof Date||typeof value2=="number"||typeof value2=="boolean"?!0:typeof value2=="string"?VALIDATION_REGEXP.test(value2)||NUMBER_REGEXP.test(value2)||HEX_REGEXP.test(value2)||COLOR_REGEXP.test(value2):Array.isArray(value2)?value2.every(v=>validateArgs(key2,v)):(0,import_isPlainObject3.default)(value2)?Object.entries(value2).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(import_qs4.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key2,value2])=>validateArgs(key2,value2)?Object.assign(acc,{[key2]:value2}):(once.warn(dedent`
|
|
87
87
|
Omitted potentially unsafe URL args.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storybook/preview",
|
|
3
|
-
"version": "7.0.0-beta.
|
|
3
|
+
"version": "7.0.0-beta.17",
|
|
4
4
|
"description": "",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"storybook"
|
|
@@ -57,12 +57,12 @@
|
|
|
57
57
|
"prep": "../../../scripts/prepare/bundle.ts"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
|
-
"@storybook/channel-postmessage": "7.0.0-beta.
|
|
61
|
-
"@storybook/channel-websocket": "7.0.0-beta.
|
|
62
|
-
"@storybook/channels": "7.0.0-beta.
|
|
63
|
-
"@storybook/client-logger": "7.0.0-beta.
|
|
64
|
-
"@storybook/core-events": "7.0.0-beta.
|
|
65
|
-
"@storybook/preview-api": "7.0.0-beta.
|
|
60
|
+
"@storybook/channel-postmessage": "7.0.0-beta.17",
|
|
61
|
+
"@storybook/channel-websocket": "7.0.0-beta.17",
|
|
62
|
+
"@storybook/channels": "7.0.0-beta.17",
|
|
63
|
+
"@storybook/client-logger": "7.0.0-beta.17",
|
|
64
|
+
"@storybook/core-events": "7.0.0-beta.17",
|
|
65
|
+
"@storybook/preview-api": "7.0.0-beta.17",
|
|
66
66
|
"typescript": "~4.9.3"
|
|
67
67
|
},
|
|
68
68
|
"publishConfig": {
|
|
@@ -74,5 +74,5 @@
|
|
|
74
74
|
"./src/globals.ts"
|
|
75
75
|
]
|
|
76
76
|
},
|
|
77
|
-
"gitHead": "
|
|
77
|
+
"gitHead": "6559b419625c2dcf76bad1a12fcf75e3dd7c4187"
|
|
78
78
|
}
|