@storybook/preview-api 7.0.0-rc.3 → 7.0.0-rc.4
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-4bc526c1.d.ts → ClientApi-5a0be40f.d.ts} +1 -1
- package/dist/{StoryStore-8dcb90f9.d.ts → StoryStore-a6898638.d.ts} +1 -1
- package/dist/{chunk-NH5CIMMM.mjs → chunk-HB7O7BUT.mjs} +1 -1
- package/dist/{chunk-R4BJAWK4.mjs → chunk-TDNSAGO4.mjs} +8 -5
- package/dist/client-api.d.ts +3 -3
- package/dist/core-client.d.ts +3 -3
- package/dist/core-client.js +8 -5
- package/dist/core-client.mjs +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +11 -8
- package/dist/index.mjs +1 -1
- package/dist/preview-web.d.ts +2 -2
- package/dist/preview-web.js +8 -5
- package/dist/preview-web.mjs +1 -1
- package/dist/{simulate-pageload-7048af7a.d.ts → simulate-pageload-813b23ff.d.ts} +1 -1
- package/dist/{sortStories-bcf0764a.d.ts → sortStories-582c1134.d.ts} +2 -8
- package/dist/{start-62db31b6.d.ts → start-f654a494.d.ts} +1 -1
- package/dist/store.d.ts +2 -2
- package/package.json +8 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _storybook_types from '@storybook/types';
|
|
2
2
|
import { Renderer, NormalizedProjectAnnotations, StoryId, IndexEntry, ComponentId, Path, ModuleExports, DecoratorFunction, Parameters, LoaderFunction, Args, ArgTypes, ArgsEnhancer, ArgTypesEnhancer, StepRunner, ModuleImportFn, Globals, GlobalTypes, Addon_StoryApi } from '@storybook/types';
|
|
3
|
-
import { S as StoryStore } from './StoryStore-
|
|
3
|
+
import { S as StoryStore } from './StoryStore-a6898638.js';
|
|
4
4
|
|
|
5
5
|
declare class StoryStoreFacade<TRenderer extends Renderer> {
|
|
6
6
|
projectAnnotations: NormalizedProjectAnnotations<TRenderer>;
|
|
@@ -109,4 +109,4 @@ declare class StoryStore<TRenderer extends Renderer> {
|
|
|
109
109
|
fromId(storyId: StoryId): BoundStory<TRenderer> | null;
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
-
export { StoryStore as S, prepareMeta as a,
|
|
112
|
+
export { StoryStore as S, prepareMeta as a, processCSFFile as b, StorySpecifier as c, prepareStory as p };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ClientApi}from"./chunk-NVVQ6KTD.mjs";import{PreviewWeb}from"./chunk-
|
|
1
|
+
import{ClientApi}from"./chunk-NVVQ6KTD.mjs";import{PreviewWeb}from"./chunk-TDNSAGO4.mjs";import{addons}from"./chunk-RTGEOU4B.mjs";import{global}from"@storybook/global";import{createChannel}from"@storybook/channel-postmessage";import{FORCE_RE_RENDER}from"@storybook/core-events";import{logger}from"@storybook/client-logger";function executeLoadable(loadable){let reqs=null;Array.isArray(loadable)?reqs=loadable:loadable.keys&&(reqs=[loadable]);let exportsMap=new Map;if(reqs)reqs.forEach(req=>{req.keys().forEach(filename=>{try{let fileExports=req(filename);exportsMap.set(typeof req.resolve=="function"?req.resolve(filename):filename,fileExports)}catch(error){let errorString=error.message&&error.stack?`${error.message}
|
|
2
2
|
${error.stack}`:error.toString();logger.error(`Unexpected error while loading ${filename}: ${errorString}`)}})});else{let exported=loadable();Array.isArray(exported)&&exported.every(obj=>obj.default!=null)?exportsMap=new Map(exported.map((fileExports,index)=>[`exports-map-${index}`,fileExports])):exported&&logger.warn(`Loader function passed to 'configure' should return void or an array of module exports that all contain a 'default' export. Received: ${JSON.stringify(exported)}`)}return exportsMap}function executeLoadableForChanges(loadable,m){let lastExportsMap=m?.hot?.data?.lastExportsMap||new Map;m?.hot?.dispose&&(m.hot.accept(),m.hot.dispose(data=>{data.lastExportsMap=lastExportsMap}));let exportsMap=executeLoadable(loadable),added=new Map;Array.from(exportsMap.entries()).filter(([,fileExports])=>!!fileExports.default).filter(([fileName,fileExports])=>lastExportsMap.get(fileName)!==fileExports).forEach(([fileName,fileExports])=>added.set(fileName,fileExports));let removed=new Map;return Array.from(lastExportsMap.keys()).filter(fileName=>!exportsMap.has(fileName)).forEach(fileName=>{let value=lastExportsMap.get(fileName);value&&removed.set(fileName,value)}),lastExportsMap=exportsMap,{added,removed}}var{FEATURES}=global,removedApi=name=>()=>{throw new Error(`@storybook/client-api:${name} was removed in storyStoreV7.`)};function start(renderToCanvas,{decorateStory,render}={}){if(global&&(global.IS_STORYBOOK=!0),FEATURES?.storyStoreV7)return{forceReRender:removedApi("forceReRender"),configure:removedApi("configure"),clientApi:{storiesOf:removedApi("clientApi.storiesOf"),raw:removedApi("raw")}};let channel=createChannel({page:"preview"});addons.setChannel(channel);let clientApi=global?.__STORYBOOK_CLIENT_API__||new ClientApi,preview=global?.__STORYBOOK_PREVIEW__||new PreviewWeb,initialized=!1,importFn=path=>clientApi.importFn(path);function onStoriesChanged(){let storyIndex=clientApi.getStoryIndex();preview.onStoriesChanged({storyIndex,importFn})}return clientApi.onImportFnChanged=onStoriesChanged,clientApi.storyStore=preview.storyStore,global&&(global.__STORYBOOK_CLIENT_API__=clientApi,global.__STORYBOOK_ADDONS_CHANNEL__=channel,global.__STORYBOOK_PREVIEW__=preview,global.__STORYBOOK_STORY_STORE__=preview.storyStore),{forceReRender:()=>channel.emit(FORCE_RE_RENDER),clientApi,configure(renderer,loadable,m,disableBackwardCompatibility=!0){if(disableBackwardCompatibility)throw new Error("unexpected configure() call");clientApi.addParameters({renderer});let getProjectAnnotations=()=>{let{added,removed}=executeLoadableForChanges(loadable,m);return clientApi._loadAddedExports(),Array.from(added.entries()).forEach(([fileName,fileExports])=>clientApi.facade.addStoriesFromExports(fileName,fileExports)),Array.from(removed.entries()).forEach(([fileName])=>clientApi.facade.clearFilenameExports(fileName)),{render,...clientApi.facade.projectAnnotations,renderToCanvas,applyDecorators:decorateStory}};initialized?(getProjectAnnotations(),onStoriesChanged()):(preview.initialize({getStoryIndex:()=>clientApi.getStoryIndex(),importFn,getProjectAnnotations}),initialized=!0)}}}export{start};
|
|
@@ -8,22 +8,25 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
8
8
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
9
9
|
`);return projectAnnotations}).catch(err=>{throw this.renderPreviewEntryError("Error reading preview.js:",err),err})}initializeWithProjectAnnotations(projectAnnotations){this.storyStore.setProjectAnnotations(projectAnnotations),this.setInitialGlobals();let storyIndexPromise;if(global.FEATURES?.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=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 result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new Error(await result.text())}initializeWithStoryIndex(storyIndex){if(!this.importFn)throw new Error("Cannot call initializeWithStoryIndex before initialization");return this.storyStore.initialize({storyIndex,importFn:this.importFn,cache:!global.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}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals),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&&!r.renderOptions.forceInitialArgs).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,callbacks,options){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,callbacks,story.id,"docs",options,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(options){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent`Failed to initialize Storybook.
|
|
10
10
|
|
|
11
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger2.error(reason),logger2.error(err),this.channel.emit(CONFIG_ERROR,err)}};import{global as global5}from"@storybook/global";import{dedent as dedent2}from"ts-dedent";import{global as global2}from"@storybook/global";import{CURRENT_STORY_WAS_SET,PRELOAD_ENTRIES,PREVIEW_KEYDOWN,SET_CURRENT_STORY,SET_INDEX,STORY_ARGS_UPDATED as STORY_ARGS_UPDATED2,STORY_CHANGED,STORY_ERRORED,STORY_MISSING,STORY_PREPARED,STORY_RENDER_PHASE_CHANGED as STORY_RENDER_PHASE_CHANGED2,STORY_SPECIFIED,STORY_THREW_EXCEPTION,STORY_UNCHANGED,UPDATE_QUERY_PARAMS}from"@storybook/core-events";import{logger as logger3}from"@storybook/client-logger";import{DOCS_RENDERED}from"@storybook/core-events";var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){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.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("Cannot reference a non-meta or module export in <Meta of={} />");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:prepareMeta(resolved.csfFile.meta,this.projectAnnotations,resolved.csfFile.moduleExports.default)};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};import{DOCS_RENDERED as DOCS_RENDERED2}from"@storybook/core-events";var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(DOCS_RENDERED2,this.id)}catch(err){this.callbacks.showException(err)}};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}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}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}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>(global2.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}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(dedent2`
|
|
11
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger2.error(reason),logger2.error(err),this.channel.emit(CONFIG_ERROR,err)}};import{global as global5}from"@storybook/global";import{dedent as dedent3}from"ts-dedent";import{global as global2}from"@storybook/global";import{CURRENT_STORY_WAS_SET,PRELOAD_ENTRIES,PREVIEW_KEYDOWN,SET_CURRENT_STORY,SET_INDEX,STORY_ARGS_UPDATED as STORY_ARGS_UPDATED2,STORY_CHANGED,STORY_ERRORED,STORY_MISSING,STORY_PREPARED,STORY_RENDER_PHASE_CHANGED as STORY_RENDER_PHASE_CHANGED2,STORY_SPECIFIED,STORY_THREW_EXCEPTION,STORY_UNCHANGED,UPDATE_QUERY_PARAMS}from"@storybook/core-events";import{logger as logger3}from"@storybook/client-logger";import{DOCS_RENDERED}from"@storybook/core-events";import dedent2 from"ts-dedent";var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){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.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(dedent2`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
|
|
12
|
+
- Did you pass a component to the 'of' prop when the block only supports a story or a meta?
|
|
13
|
+
- ... or vice versa?
|
|
14
|
+
- Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:prepareMeta(resolved.csfFile.meta,this.projectAnnotations,resolved.csfFile.moduleExports.default)};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};import{DOCS_RENDERED as DOCS_RENDERED2}from"@storybook/core-events";var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(DOCS_RENDERED2,this.id)}catch(err){this.callbacks.showException(err)}};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}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}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}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>(global2.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}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(dedent3`
|
|
12
15
|
Couldn't find any stories in your Storybook.
|
|
13
16
|
- Please check your stories field of your main.js config.
|
|
14
17
|
- Also check the browser console and terminal for error messages.
|
|
15
|
-
`)):this.renderStoryLoadingException(storySpecifier,new Error(
|
|
18
|
+
`)):this.renderStoryLoadingException(storySpecifier,new Error(dedent3`
|
|
16
19
|
Couldn't find story matching '${storySpecifier}'.
|
|
17
20
|
- Are you sure a story with that id exists?
|
|
18
21
|
- Please check your stories field of your main.js config.
|
|
19
22
|
- Also check the browser console and terminal for error messages.
|
|
20
|
-
`));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:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),global2.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,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,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}){super.onUpdateGlobals({globals}),(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({immediate:viewModeChanged}),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));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}=this.storyStore.getStoryContext(render.story);global2.FEATURES?.storyStoreV7&&this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED2,{storyId,args})}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(options){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(
|
|
23
|
+
`));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:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),global2.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,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,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}){super.onUpdateGlobals({globals}),(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({immediate:viewModeChanged}),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));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}=this.storyStore.getStoryContext(render.story);global2.FEATURES?.storyStoreV7&&this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED2,{storyId,args})}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(options){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent3`Failed to initialize Storybook.
|
|
21
24
|
|
|
22
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global2.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(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){logger3.error(err),this.view.showErrorDisplay(err),this.channel.emit(STORY_MISSING,storySpecifier)}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(STORY_RENDER_PHASE_CHANGED2,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),logger3.error(`Error rendering story '${storyId}':`),logger3.error(error))}renderError(storyId,{title,description}){logger3.error(`Error rendering story ${title}: ${description}`),this.channel.emit(STORY_ERRORED,{title,description}),this.channel.emit(STORY_RENDER_PHASE_CHANGED2,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};import{global as global3}from"@storybook/global";import qs2 from"qs";import qs from"qs";import{dedent as
|
|
25
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global2.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(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){logger3.error(err),this.view.showErrorDisplay(err),this.channel.emit(STORY_MISSING,storySpecifier)}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(STORY_RENDER_PHASE_CHANGED2,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),logger3.error(`Error rendering story '${storyId}':`),logger3.error(error))}renderError(storyId,{title,description}){logger3.error(`Error rendering story ${title}: ${description}`),this.channel.emit(STORY_ERRORED,{title,description}),this.channel.emit(STORY_RENDER_PHASE_CHANGED2,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};import{global as global3}from"@storybook/global";import qs2 from"qs";import qs from"qs";import{dedent as dedent4}from"ts-dedent";import{once}from"@storybook/client-logger";import isPlainObject from"lodash/isPlainObject.js";var 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=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):isPlainObject(value)?Object.entries(value).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==="!true")return!0;if(str==="!false")return!1;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(qs.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(once.warn(dedent4`
|
|
23
26
|
Omitted potentially unsafe URL args.
|
|
24
27
|
|
|
25
28
|
More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
|
|
26
|
-
`),acc),{})};var{history,document}=global3;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=qs2.parse(search,{ignoreQueryPrefix:!0});return qs2.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=qs2.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_ansi_to_html=__toESM(require_ansi_to_html());import{global as global4}from"@storybook/global";import{logger as logger4}from"@storybook/client-logger";import{dedent as
|
|
29
|
+
`),acc),{})};var{history,document}=global3;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=qs2.parse(search,{ignoreQueryPrefix:!0});return qs2.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=qs2.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_ansi_to_html=__toESM(require_ansi_to_html());import{global as global4}from"@storybook/global";import{logger as logger4}from"@storybook/client-logger";import{dedent as dedent5}from"ts-dedent";import qs3 from"qs";var{document:document2}=global4,PREPARING_DELAY=100,Mode=(Mode2=>(Mode2.MAIN="MAIN",Mode2.NOPREVIEW="NOPREVIEW",Mode2.PREPARING_STORY="PREPARING_STORY",Mode2.PREPARING_DOCS="PREPARING_DOCS",Mode2.ERROR="ERROR",Mode2))(Mode||{}),classes={PREPARING_STORY:"sb-show-preparing-story",PREPARING_DOCS:"sb-show-preparing-docs",MAIN:"sb-show-main",NOPREVIEW:"sb-show-nopreview",ERROR:"sb-show-errordisplay"},layoutClassMap={centered:"sb-main-centered",fullscreen:"sb-main-fullscreen",padded:"sb-main-padded"},ansiConverter=new import_ansi_to_html.default({escapeXML:!0}),WebView=class{constructor(){this.testing=!1;let{__SPECIAL_TEST_PARAMETER__}=qs3.parse(document2.location.search,{ignoreQueryPrefix:!0});switch(__SPECIAL_TEST_PARAMETER__){case"preparing-story":{this.showPreparingStory(),this.testing=!0;break}case"preparing-docs":{this.showPreparingDocs(),this.testing=!0;break}default:}}prepareForStory(story){return this.showStory(),this.applyLayout(story.parameters.layout),document2.documentElement.scrollTop=0,document2.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document2.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),this.docsRoot()}docsRoot(){return document2.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document2.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document2.body.classList.remove(this.currentLayoutClass),document2.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}checkIfLayoutExists(layout){layoutClassMap[layout]||logger4.warn(dedent5`The desired layout: ${layout} is not a valid option.
|
|
27
30
|
The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.`)}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document2.body.classList.add(classes[otherMode]):document2.body.classList.remove(classes[otherMode])})}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
|
|
28
31
|
`);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
|
|
29
32
|
`)),document2.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document2.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){this.testing||(this.showMode("NOPREVIEW"),this.storyRoot()?.setAttribute("hidden","true"),this.docsRoot()?.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_DOCS"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document2.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(){super(new UrlStore,new WebView),global5.__STORYBOOK_PREVIEW__=this}};import{global as global6}from"@storybook/global";var{document:document3}=global6,runScriptTypes=["application/javascript","application/ecmascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript","module"],SCRIPT="script",SCRIPTS_ROOT_ID="scripts-root";function simulateDOMContentLoaded(){let DOMContentLoadedEvent=document3.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document3.dispatchEvent(DOMContentLoadedEvent)}function insertScript($script,callback,$scriptRoot){let scriptEl=document3.createElement("script");scriptEl.type=$script.type==="module"?"module":"text/javascript",$script.src?(scriptEl.onload=callback,scriptEl.onerror=callback,scriptEl.src=$script.src):scriptEl.textContent=$script.innerText,$scriptRoot?$scriptRoot.appendChild(scriptEl):document3.head.appendChild(scriptEl),$script.parentNode.removeChild($script),$script.src||callback()}function insertScriptsSequentially(scriptsToExecute,callback,index=0){scriptsToExecute[index](()=>{index++,index===scriptsToExecute.length?callback():insertScriptsSequentially(scriptsToExecute,callback,index)})}function simulatePageLoad($container){let $scriptsRoot=document3.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document3.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document3.body.appendChild($scriptsRoot));let $scripts=Array.from($container.querySelectorAll(SCRIPT));if($scripts.length){let scriptsToExecute=[];$scripts.forEach($script=>{let typeAttr=$script.getAttribute("type");(!typeAttr||runScriptTypes.includes(typeAttr))&&scriptsToExecute.push(callback=>insertScript($script,callback,$scriptsRoot))}),scriptsToExecute.length&&insertScriptsSequentially(scriptsToExecute,simulateDOMContentLoaded,void 0)}else simulateDOMContentLoaded()}export{Preview,DocsContext,PreviewWithSelection,PreviewWeb,simulateDOMContentLoaded,simulatePageLoad};
|
package/dist/client-api.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { C as ClientApi, a as addArgTypes, b as addArgTypesEnhancer, c as addArgs, d as addArgsEnhancer, e as addDecorator, f as addLoader, g as addParameters, h as addStepRunner, s as setGlobalRender } from './ClientApi-
|
|
2
|
-
export { S as StoryStore, a as prepareMeta, p as prepareStory,
|
|
3
|
-
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 { C as ClientApi, a as addArgTypes, b as addArgTypesEnhancer, c as addArgs, d as addArgsEnhancer, e as addDecorator, f as addLoader, g as addParameters, h as addStepRunner, s as setGlobalRender } from './ClientApi-5a0be40f.js';
|
|
2
|
+
export { S as StoryStore, a as prepareMeta, p as prepareStory, b as processCSFFile } from './StoryStore-a6898638.js';
|
|
3
|
+
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-582c1134.js';
|
|
4
4
|
export { g as getValuesFromArgTypes, b as normalizeComponentAnnotations, n as normalizeInputType, a as normalizeInputTypes, c as normalizeProjectAnnotations, d as useAddonState, u as useSharedState } from './hooks-0a0ec0e3.js';
|
|
5
5
|
export { c as composeConfigs, a as getArrayField, g as getField, b as getObjectField, d as getSingletonField } from './composeConfigs-62a04721.js';
|
|
6
6
|
export { g as getQueryParam, a as getQueryParams } from './queryparams-d12445b8.js';
|
package/dist/core-client.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { C as ClientApi } from './ClientApi-
|
|
2
|
-
export { S as StoryStore } from './StoryStore-
|
|
3
|
-
export { s as start } from './start-
|
|
1
|
+
export { C as ClientApi } from './ClientApi-5a0be40f.js';
|
|
2
|
+
export { S as StoryStore } from './StoryStore-a6898638.js';
|
|
3
|
+
export { s as start } from './start-f654a494.js';
|
|
4
4
|
import '@storybook/types';
|
|
5
5
|
import 'synchronous-promise';
|
|
6
6
|
import './hooks-55c56a89.js';
|
package/dist/core-client.js
CHANGED
|
@@ -56,22 +56,25 @@ Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.m
|
|
|
56
56
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
57
57
|
`);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=import_global6.global.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 result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new Error(await result.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=import_global6.global.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}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals),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&&!r.renderOptions.forceInitialArgs).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){let render=this.storyRenders.find(r=>r.id===storyId),story=(render==null?void 0:render.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,callbacks,options){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,callbacks,story.id,"docs",options,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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent10.dedent`Failed to initialize Storybook.
|
|
58
58
|
|
|
59
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger12.logger.error(reason),import_client_logger12.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global10=require("@storybook/global");var import_ts_dedent11=require("ts-dedent"),import_global7=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger13=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){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.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("Cannot reference a non-meta or module export in <Meta of={} />");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:prepareMeta(resolved.csfFile.meta,this.projectAnnotations,resolved.csfFile.moduleExports.default)};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var 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_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.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}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent11.dedent`
|
|
59
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger12.logger.error(reason),import_client_logger12.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global10=require("@storybook/global");var import_ts_dedent12=require("ts-dedent"),import_global7=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger13=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var import_ts_dedent11=__toESM(require("ts-dedent"));var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){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.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent11.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
|
|
60
|
+
- Did you pass a component to the 'of' prop when the block only supports a story or a meta?
|
|
61
|
+
- ... or vice versa?
|
|
62
|
+
- Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:prepareMeta(resolved.csfFile.meta,this.projectAnnotations,resolved.csfFile.moduleExports.default)};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var 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_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.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}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent12.dedent`
|
|
60
63
|
Couldn't find any stories in your Storybook.
|
|
61
64
|
- Please check your stories field of your main.js config.
|
|
62
65
|
- Also check the browser console and terminal for error messages.
|
|
63
|
-
`)):this.renderStoryLoadingException(storySpecifier,new Error(
|
|
66
|
+
`)):this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent12.dedent`
|
|
64
67
|
Couldn't find story matching '${storySpecifier}'.
|
|
65
68
|
- Are you sure a story with that id exists?
|
|
66
69
|
- Please check your stories field of your main.js config.
|
|
67
70
|
- Also check the browser console and terminal for error messages.
|
|
68
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(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({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));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_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global7.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(
|
|
71
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(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({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));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_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global7.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent12.dedent`Failed to initialize Storybook.
|
|
69
72
|
|
|
70
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger13.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.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_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global8=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),
|
|
73
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger13.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.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_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global8=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent13=require("ts-dedent"),import_client_logger14=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject.js")),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=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):(0,import_isPlainObject3.default)(value)?Object.entries(value).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==="!true")return!0;if(str==="!false")return!1;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_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger14.once.warn(import_ts_dedent13.dedent`
|
|
71
74
|
Omitted potentially unsafe URL args.
|
|
72
75
|
|
|
73
76
|
More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
|
|
74
|
-
`),acc),{})};var{history,document}=import_global8.global;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=import_qs2.default.parse(search,{ignoreQueryPrefix:!0});return import_qs2.default.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=import_qs2.default.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_global9=require("@storybook/global"),import_client_logger15=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),
|
|
77
|
+
`),acc),{})};var{history,document}=import_global8.global;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=import_qs2.default.parse(search,{ignoreQueryPrefix:!0});return import_qs2.default.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=import_qs2.default.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_global9=require("@storybook/global"),import_client_logger15=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),import_ts_dedent14=require("ts-dedent"),import_qs3=__toESM(require("qs")),{document:document2}=import_global9.global,PREPARING_DELAY=100,Mode=(Mode2=>(Mode2.MAIN="MAIN",Mode2.NOPREVIEW="NOPREVIEW",Mode2.PREPARING_STORY="PREPARING_STORY",Mode2.PREPARING_DOCS="PREPARING_DOCS",Mode2.ERROR="ERROR",Mode2))(Mode||{}),classes={PREPARING_STORY:"sb-show-preparing-story",PREPARING_DOCS:"sb-show-preparing-docs",MAIN:"sb-show-main",NOPREVIEW:"sb-show-nopreview",ERROR:"sb-show-errordisplay"},layoutClassMap={centered:"sb-main-centered",fullscreen:"sb-main-fullscreen",padded:"sb-main-padded"},ansiConverter=new import_ansi_to_html.default({escapeXML:!0}),WebView=class{constructor(){this.testing=!1;let{__SPECIAL_TEST_PARAMETER__}=import_qs3.default.parse(document2.location.search,{ignoreQueryPrefix:!0});switch(__SPECIAL_TEST_PARAMETER__){case"preparing-story":{this.showPreparingStory(),this.testing=!0;break}case"preparing-docs":{this.showPreparingDocs(),this.testing=!0;break}default:}}prepareForStory(story){return this.showStory(),this.applyLayout(story.parameters.layout),document2.documentElement.scrollTop=0,document2.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document2.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),this.docsRoot()}docsRoot(){return document2.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document2.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document2.body.classList.remove(this.currentLayoutClass),document2.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}checkIfLayoutExists(layout){layoutClassMap[layout]||import_client_logger15.logger.warn(import_ts_dedent14.dedent`The desired layout: ${layout} is not a valid option.
|
|
75
78
|
The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.`)}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document2.body.classList.add(classes[otherMode]):document2.body.classList.remove(classes[otherMode])})}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
|
|
76
79
|
`);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
|
|
77
80
|
`)),document2.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document2.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){var _a,_b;this.testing||(this.showMode("NOPREVIEW"),(_a=this.storyRoot())==null||_a.setAttribute("hidden","true"),(_b=this.docsRoot())==null||_b.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_DOCS"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document2.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(){super(new UrlStore,new WebView),import_global10.global.__STORYBOOK_PREVIEW__=this}};var import_client_logger16=require("@storybook/client-logger");function executeLoadable(loadable){let reqs=null;Array.isArray(loadable)?reqs=loadable:loadable.keys&&(reqs=[loadable]);let exportsMap=new Map;if(reqs)reqs.forEach(req=>{req.keys().forEach(filename=>{try{let fileExports=req(filename);exportsMap.set(typeof req.resolve=="function"?req.resolve(filename):filename,fileExports)}catch(error){let errorString=error.message&&error.stack?`${error.message}
|
package/dist/core-client.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{start}from"./chunk-
|
|
1
|
+
import{start}from"./chunk-HB7O7BUT.mjs";import"./chunk-GRRYLBAT.mjs";import{ClientApi}from"./chunk-NVVQ6KTD.mjs";import"./chunk-TDNSAGO4.mjs";import{StoryStore}from"./chunk-U6GFELHZ.mjs";import"./chunk-RTGEOU4B.mjs";export{ClientApi,StoryStore,start};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
export { a as addons, m as makeDecorator, b as mockChannel } from './storybook-channel-mock-a19cd233.js';
|
|
2
2
|
export { H as HooksContext, k as applyHooks, u as useArgs, a as useCallback, b as useChannel, c as useEffect, d as useGlobals, e as useMemo, f as useParameter, g as useReducer, h as useRef, i as useState, j as useStoryContext } from './hooks-55c56a89.js';
|
|
3
|
-
export { S as StoryStore, a as prepareMeta, p as prepareStory } from './StoryStore-
|
|
4
|
-
export { P as PropDescriptor, c as combineArgs, a as combineParameters, b as composeStepRunners, d as composeStories, e as composeStory, f as decorateStory, g as defaultDecorateStory, h as filterArgTypes, j as inferControls, n as normalizeStory, s as sanitizeStoryContextUpdate, i as setProjectAnnotations, l as sortStoriesV7, k as userOrAutoTitle, u as userOrAutoTitleFromSpecifier } from './sortStories-
|
|
3
|
+
export { S as StoryStore, a as prepareMeta, p as prepareStory } from './StoryStore-a6898638.js';
|
|
4
|
+
export { P as PropDescriptor, c as combineArgs, a as combineParameters, b as composeStepRunners, d as composeStories, e as composeStory, f as decorateStory, g as defaultDecorateStory, h as filterArgTypes, j as inferControls, n as normalizeStory, s as sanitizeStoryContextUpdate, i as setProjectAnnotations, l as sortStoriesV7, k as userOrAutoTitle, u as userOrAutoTitleFromSpecifier } from './sortStories-582c1134.js';
|
|
5
5
|
export { c as composeConfigs } from './composeConfigs-62a04721.js';
|
|
6
|
-
export { D as DocsContext, P as Preview, b as PreviewWeb, a as simulateDOMContentLoaded, s as simulatePageLoad } from './simulate-pageload-
|
|
7
|
-
export { C as ClientApi, a as addArgTypes, b as addArgTypesEnhancer, c as addArgs, d as addArgsEnhancer, e as addDecorator, f as addLoader, g as addParameters, h as addStepRunner, s as setGlobalRender } from './ClientApi-
|
|
6
|
+
export { D as DocsContext, P as Preview, b as PreviewWeb, a as simulateDOMContentLoaded, s as simulatePageLoad } from './simulate-pageload-813b23ff.js';
|
|
7
|
+
export { C as ClientApi, a as addArgTypes, b as addArgTypesEnhancer, c as addArgs, d as addArgsEnhancer, e as addDecorator, f as addLoader, g as addParameters, h as addStepRunner, s as setGlobalRender } from './ClientApi-5a0be40f.js';
|
|
8
8
|
export { g as getQueryParam, a as getQueryParams } from './queryparams-d12445b8.js';
|
|
9
|
-
export { s as start } from './start-
|
|
9
|
+
export { s as start } from './start-f654a494.js';
|
|
10
10
|
import '@storybook/channels';
|
|
11
11
|
import '@storybook/types';
|
|
12
12
|
import 'synchronous-promise';
|
package/dist/index.js
CHANGED
|
@@ -49,25 +49,28 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
49
49
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
50
50
|
`);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=import_global5.global.FEATURES)!=null&&_a.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=import_synchronous_promise2.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 result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new Error(await result.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=import_global5.global.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}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals),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&&!r.renderOptions.forceInitialArgs).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){let render=this.storyRenders.find(r=>r.id===storyId),story=(render==null?void 0:render.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,callbacks,options){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,callbacks,story.id,"docs",options,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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent8.dedent`Failed to initialize Storybook.
|
|
51
51
|
|
|
52
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger10.logger.error(reason),import_client_logger10.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global9=require("@storybook/global");var import_ts_dedent9=require("ts-dedent"),import_global6=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger11=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){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.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("Cannot reference a non-meta or module export in <Meta of={} />");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:prepareMeta(resolved.csfFile.meta,this.projectAnnotations,resolved.csfFile.moduleExports.default)};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}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_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.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}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent9.dedent`
|
|
52
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger10.logger.error(reason),import_client_logger10.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global9=require("@storybook/global");var import_ts_dedent10=require("ts-dedent"),import_global6=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger11=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var import_ts_dedent9=__toESM(require("ts-dedent"));var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){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.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent9.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
|
|
53
|
+
- Did you pass a component to the 'of' prop when the block only supports a story or a meta?
|
|
54
|
+
- ... or vice versa?
|
|
55
|
+
- Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:prepareMeta(resolved.csfFile.meta,this.projectAnnotations,resolved.csfFile.moduleExports.default)};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}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_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.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}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent10.dedent`
|
|
53
56
|
Couldn't find any stories in your Storybook.
|
|
54
57
|
- Please check your stories field of your main.js config.
|
|
55
58
|
- Also check the browser console and terminal for error messages.
|
|
56
|
-
`)):this.renderStoryLoadingException(storySpecifier,new Error(
|
|
59
|
+
`)):this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent10.dedent`
|
|
57
60
|
Couldn't find story matching '${storySpecifier}'.
|
|
58
61
|
- Are you sure a story with that id exists?
|
|
59
62
|
- Please check your stories field of your main.js config.
|
|
60
63
|
- Also check the browser console and terminal for error messages.
|
|
61
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(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({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));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_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global6.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(
|
|
64
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(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({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));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_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global6.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent10.dedent`Failed to initialize Storybook.
|
|
62
65
|
|
|
63
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger11.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),(_a=error.message)!=null&&_a.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger11.logger.error(`Error rendering story '${storyId}':`),import_client_logger11.logger.error(error))}renderError(storyId,{title,description}){import_client_logger11.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global7=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),
|
|
66
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger11.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),(_a=error.message)!=null&&_a.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger11.logger.error(`Error rendering story '${storyId}':`),import_client_logger11.logger.error(error))}renderError(storyId,{title,description}){import_client_logger11.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global7=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent11=require("ts-dedent"),import_client_logger12=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject.js")),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=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):(0,import_isPlainObject3.default)(value)?Object.entries(value).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==="!true")return!0;if(str==="!false")return!1;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_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger12.once.warn(import_ts_dedent11.dedent`
|
|
64
67
|
Omitted potentially unsafe URL args.
|
|
65
68
|
|
|
66
69
|
More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
|
|
67
|
-
`),acc),{})};var{history,document}=import_global7.global;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=import_qs2.default.parse(search,{ignoreQueryPrefix:!0});return import_qs2.default.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=import_qs2.default.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_global8=require("@storybook/global"),import_client_logger13=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),
|
|
70
|
+
`),acc),{})};var{history,document}=import_global7.global;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=import_qs2.default.parse(search,{ignoreQueryPrefix:!0});return import_qs2.default.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=import_qs2.default.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_global8=require("@storybook/global"),import_client_logger13=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),import_ts_dedent12=require("ts-dedent"),import_qs3=__toESM(require("qs")),{document:document2}=import_global8.global,PREPARING_DELAY=100,Mode=(Mode2=>(Mode2.MAIN="MAIN",Mode2.NOPREVIEW="NOPREVIEW",Mode2.PREPARING_STORY="PREPARING_STORY",Mode2.PREPARING_DOCS="PREPARING_DOCS",Mode2.ERROR="ERROR",Mode2))(Mode||{}),classes={PREPARING_STORY:"sb-show-preparing-story",PREPARING_DOCS:"sb-show-preparing-docs",MAIN:"sb-show-main",NOPREVIEW:"sb-show-nopreview",ERROR:"sb-show-errordisplay"},layoutClassMap={centered:"sb-main-centered",fullscreen:"sb-main-fullscreen",padded:"sb-main-padded"},ansiConverter=new import_ansi_to_html.default({escapeXML:!0}),WebView=class{constructor(){this.testing=!1;let{__SPECIAL_TEST_PARAMETER__}=import_qs3.default.parse(document2.location.search,{ignoreQueryPrefix:!0});switch(__SPECIAL_TEST_PARAMETER__){case"preparing-story":{this.showPreparingStory(),this.testing=!0;break}case"preparing-docs":{this.showPreparingDocs(),this.testing=!0;break}default:}}prepareForStory(story){return this.showStory(),this.applyLayout(story.parameters.layout),document2.documentElement.scrollTop=0,document2.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document2.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),this.docsRoot()}docsRoot(){return document2.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document2.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document2.body.classList.remove(this.currentLayoutClass),document2.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}checkIfLayoutExists(layout){layoutClassMap[layout]||import_client_logger13.logger.warn(import_ts_dedent12.dedent`The desired layout: ${layout} is not a valid option.
|
|
68
71
|
The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.`)}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document2.body.classList.add(classes[otherMode]):document2.body.classList.remove(classes[otherMode])})}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
|
|
69
72
|
`);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
|
|
70
|
-
`)),document2.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document2.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){var _a,_b;this.testing||(this.showMode("NOPREVIEW"),(_a=this.storyRoot())==null||_a.setAttribute("hidden","true"),(_b=this.docsRoot())==null||_b.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_DOCS"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document2.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(){super(new UrlStore,new WebView),import_global9.global.__STORYBOOK_PREVIEW__=this}};var import_global10=require("@storybook/global"),{document:document3}=import_global10.global,runScriptTypes=["application/javascript","application/ecmascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript","module"],SCRIPT="script",SCRIPTS_ROOT_ID="scripts-root";function simulateDOMContentLoaded(){let DOMContentLoadedEvent=document3.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document3.dispatchEvent(DOMContentLoadedEvent)}function insertScript($script,callback,$scriptRoot){let scriptEl=document3.createElement("script");scriptEl.type=$script.type==="module"?"module":"text/javascript",$script.src?(scriptEl.onload=callback,scriptEl.onerror=callback,scriptEl.src=$script.src):scriptEl.textContent=$script.innerText,$scriptRoot?$scriptRoot.appendChild(scriptEl):document3.head.appendChild(scriptEl),$script.parentNode.removeChild($script),$script.src||callback()}function insertScriptsSequentially(scriptsToExecute,callback,index=0){scriptsToExecute[index](()=>{index++,index===scriptsToExecute.length?callback():insertScriptsSequentially(scriptsToExecute,callback,index)})}function simulatePageLoad($container){let $scriptsRoot=document3.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document3.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document3.body.appendChild($scriptsRoot));let $scripts=Array.from($container.querySelectorAll(SCRIPT));if($scripts.length){let scriptsToExecute=[];$scripts.forEach($script=>{let typeAttr=$script.getAttribute("type");(!typeAttr||runScriptTypes.includes(typeAttr))&&scriptsToExecute.push(callback=>insertScript($script,callback,$scriptsRoot))}),scriptsToExecute.length&&insertScriptsSequentially(scriptsToExecute,simulateDOMContentLoaded,void 0)}else simulateDOMContentLoaded()}var
|
|
73
|
+
`)),document2.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document2.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){var _a,_b;this.testing||(this.showMode("NOPREVIEW"),(_a=this.storyRoot())==null||_a.setAttribute("hidden","true"),(_b=this.docsRoot())==null||_b.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_DOCS"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document2.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(){super(new UrlStore,new WebView),import_global9.global.__STORYBOOK_PREVIEW__=this}};var import_global10=require("@storybook/global"),{document:document3}=import_global10.global,runScriptTypes=["application/javascript","application/ecmascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript","module"],SCRIPT="script",SCRIPTS_ROOT_ID="scripts-root";function simulateDOMContentLoaded(){let DOMContentLoadedEvent=document3.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document3.dispatchEvent(DOMContentLoadedEvent)}function insertScript($script,callback,$scriptRoot){let scriptEl=document3.createElement("script");scriptEl.type=$script.type==="module"?"module":"text/javascript",$script.src?(scriptEl.onload=callback,scriptEl.onerror=callback,scriptEl.src=$script.src):scriptEl.textContent=$script.innerText,$scriptRoot?$scriptRoot.appendChild(scriptEl):document3.head.appendChild(scriptEl),$script.parentNode.removeChild($script),$script.src||callback()}function insertScriptsSequentially(scriptsToExecute,callback,index=0){scriptsToExecute[index](()=>{index++,index===scriptsToExecute.length?callback():insertScriptsSequentially(scriptsToExecute,callback,index)})}function simulatePageLoad($container){let $scriptsRoot=document3.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document3.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document3.body.appendChild($scriptsRoot));let $scripts=Array.from($container.querySelectorAll(SCRIPT));if($scripts.length){let scriptsToExecute=[];$scripts.forEach($script=>{let typeAttr=$script.getAttribute("type");(!typeAttr||runScriptTypes.includes(typeAttr))&&scriptsToExecute.push(callback=>insertScript($script,callback,$scriptsRoot))}),scriptsToExecute.length&&insertScriptsSequentially(scriptsToExecute,simulateDOMContentLoaded,void 0)}else simulateDOMContentLoaded()}var import_ts_dedent14=require("ts-dedent"),import_global12=require("@storybook/global"),import_client_logger15=require("@storybook/client-logger"),import_csf8=require("@storybook/csf");var import_global11=require("@storybook/global"),import_ts_dedent13=require("ts-dedent"),import_synchronous_promise3=require("synchronous-promise"),import_csf7=require("@storybook/csf"),import_client_logger14=require("@storybook/client-logger");var AUTODOCS_TAG2="autodocs",STORIES_MDX_TAG2="stories-mdx",StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise3.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:(0,import_csf7.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(import_ts_dedent13.dedent`
|
|
71
74
|
Error sorting stories with sort parameter ${storySortParameter}:
|
|
72
75
|
|
|
73
76
|
> ${err.message}
|
|
@@ -75,7 +78,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
75
78
|
Are you using a V7-style sort function in V6 compatibility mode?
|
|
76
79
|
|
|
77
80
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
78
|
-
`):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){var _a;if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)&&((_a=import_global11.global.FEATURES)==null?void 0:_a.storyStoreV7MdxErrors)!==!1)throw new Error(
|
|
81
|
+
`):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){var _a;if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)&&((_a=import_global11.global.FEATURES)==null?void 0:_a.storyStoreV7MdxErrors)!==!1)throw new Error(import_ts_dedent13.dedent`
|
|
79
82
|
Cannot index \`.mdx\` file (\`${fileName}\`) in \`storyStoreV7: false\` mode.
|
|
80
83
|
|
|
81
84
|
The legacy story store does not support new-style \`.mdx\` files. If the file above
|
|
@@ -83,7 +86,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
83
86
|
exclude it from your \`stories\` glob, or add <Meta isTemplate /> to it.
|
|
84
87
|
|
|
85
88
|
If you wanted to index the file, you'll need to name it \`stories.mdx\` and stick to the
|
|
86
|
-
legacy (6.x) MDX API, or use the new store.`);if(this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(import_global11.global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger14.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(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>(0,import_csf7.isExportStory)(key,defaultExport)),docsOptions=import_global11.global.DOCS_OPTIONS||{},{autodocs}=docsOptions,componentAutodocs=componentTags.includes(AUTODOCS_TAG2),autodocsOptedIn=autodocs===!0||autodocs==="tag"&&componentAutodocs;if(storyExports.length&&(componentTags.includes(STORIES_MDX_TAG2)||autodocsOptedIn)){let name=docsOptions.defaultName,docsId=(0,import_csf7.toId)(componentId||title,name);this.entries[docsId]={type:"docs",id:docsId,title,name,importPath:fileName,...componentId&&{componentId},tags:[...componentTags,"docs",...autodocsOptedIn&&!componentAutodocs?[AUTODOCS_TAG2]:[]],storiesImports:[]}}storyExports.forEach(([key,storyExport])=>{var _a2,_b,_c;let exportName=(0,import_csf7.storyNameFromExport)(key),id=((_a2=storyExport.parameters)==null?void 0:_a2.__id)||(0,import_csf7.toId)(componentId||title,exportName),name=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,title,importPath:fileName,...componentId&&{componentId},tags:[...storyExport.tags||componentTags,"story"]})})}};var 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=import_global12.global.FEATURES)!=null&&_a.storyStoreV7)throw new Error(
|
|
89
|
+
legacy (6.x) MDX API, or use the new store.`);if(this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(import_global11.global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger14.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(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>(0,import_csf7.isExportStory)(key,defaultExport)),docsOptions=import_global11.global.DOCS_OPTIONS||{},{autodocs}=docsOptions,componentAutodocs=componentTags.includes(AUTODOCS_TAG2),autodocsOptedIn=autodocs===!0||autodocs==="tag"&&componentAutodocs;if(storyExports.length&&(componentTags.includes(STORIES_MDX_TAG2)||autodocsOptedIn)){let name=docsOptions.defaultName,docsId=(0,import_csf7.toId)(componentId||title,name);this.entries[docsId]={type:"docs",id:docsId,title,name,importPath:fileName,...componentId&&{componentId},tags:[...componentTags,"docs",...autodocsOptedIn&&!componentAutodocs?[AUTODOCS_TAG2]:[]],storiesImports:[]}}storyExports.forEach(([key,storyExport])=>{var _a2,_b,_c;let exportName=(0,import_csf7.storyNameFromExport)(key),id=((_a2=storyExport.parameters)==null?void 0:_a2.__id)||(0,import_csf7.toId)(componentId||title,exportName),name=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,title,importPath:fileName,...componentId&&{componentId},tags:[...storyExport.tags||componentTags,"story"]})})}};var 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=import_global12.global.FEATURES)!=null&&_a.storyStoreV7)throw new Error(import_ts_dedent14.dedent`You cannot use \`${method}\` with the new Story Store.
|
|
87
90
|
|
|
88
91
|
${warningAlternatives[method]}`);if(!import_global12.global.__STORYBOOK_CLIENT_API__)throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`)},addDecorator=decorator=>{var _a;checkMethod("addDecorator"),(_a=import_global12.global.__STORYBOOK_CLIENT_API__)==null||_a.addDecorator(decorator)},addParameters=parameters=>{var _a;checkMethod("addParameters"),(_a=import_global12.global.__STORYBOOK_CLIENT_API__)==null||_a.addParameters(parameters)},addLoader=loader=>{var _a;checkMethod("addLoader"),(_a=import_global12.global.__STORYBOOK_CLIENT_API__)==null||_a.addLoader(loader)},addArgs=args=>{var _a;checkMethod("addArgs"),(_a=import_global12.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgs(args)},addArgTypes=argTypes=>{var _a;checkMethod("addArgTypes"),(_a=import_global12.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgTypes(argTypes)},addArgsEnhancer=enhancer=>{var _a;checkMethod("addArgsEnhancer"),(_a=import_global12.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgsEnhancer(enhancer)},addArgTypesEnhancer=enhancer=>{var _a;checkMethod("addArgTypesEnhancer"),(_a=import_global12.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgTypesEnhancer(enhancer)},addStepRunner=stepRunner=>{var _a;checkMethod("addStepRunner"),(_a=import_global12.global.__STORYBOOK_CLIENT_API__)==null||_a.addStepRunner(stepRunner)};var setGlobalRender=render=>{checkMethod("setGlobalRender"),import_global12.global.__STORYBOOK_CLIENT_API__&&(import_global12.global.__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,globalTypes,...parameters})=>{this.facade.projectAnnotations.parameters=combineParameters(this.facade.projectAnnotations.parameters,parameters),globals&&(this.facade.projectAnnotations.globals={...this.facade.projectAnnotations.globals,...globals}),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=args=>{this.facade.projectAnnotations.args={...this.facade.projectAnnotations.args,...args}};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_logger15.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_logger15.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(name=>{let addon=this.addons[name];api[name]=(...args)=>(addon.apply(api,args),api)});let meta={id:(0,import_csf8.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,argTypes,...storyParameters}=parameters,storyId=parameters.__id||(0,import_csf8.toId)(kind,storyName),csfExports=this._addedExports[fileName];return csfExports[`story${counter}`]={name:storyName,parameters:{fileName,__id:storyId,...storyParameters},decorators,loaders,args,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.
|
|
89
92
|
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,argTypes,tags,...parameters})=>{if(hasAdded)throw new Error(`You cannot add parameters after the first story for a kind.
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{start}from"./chunk-
|
|
1
|
+
import{start}from"./chunk-HB7O7BUT.mjs";import{makeDecorator}from"./chunk-GRRYLBAT.mjs";import{ClientApi,addArgTypes,addArgTypesEnhancer,addArgs,addArgsEnhancer,addDecorator,addLoader,addParameters,addStepRunner,getQueryParam,getQueryParams,setGlobalRender}from"./chunk-NVVQ6KTD.mjs";import{DocsContext,Preview,PreviewWeb,simulateDOMContentLoaded,simulatePageLoad}from"./chunk-TDNSAGO4.mjs";import{StoryStore,combineArgs,combineParameters,composeConfigs,composeStepRunners,composeStories,composeStory,decorateStory,defaultDecorateStory,filterArgTypes,inferControls,normalizeStory,prepareMeta,prepareStory,sanitizeStoryContextUpdate,setProjectAnnotations,sortStoriesV7,userOrAutoTitle,userOrAutoTitleFromSpecifier}from"./chunk-U6GFELHZ.mjs";import{HooksContext,addons,applyHooks,mockChannel,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext}from"./chunk-RTGEOU4B.mjs";export{ClientApi,DocsContext,HooksContext,Preview,PreviewWeb,StoryStore,addArgTypes,addArgTypesEnhancer,addArgs,addArgsEnhancer,addDecorator,addLoader,addParameters,addStepRunner,addons,applyHooks,combineArgs,combineParameters,composeConfigs,composeStepRunners,composeStories,composeStory,decorateStory,defaultDecorateStory,filterArgTypes,getQueryParam,getQueryParams,inferControls,makeDecorator,mockChannel,normalizeStory,prepareMeta,prepareStory,sanitizeStoryContextUpdate,setGlobalRender,setProjectAnnotations,simulateDOMContentLoaded,simulatePageLoad,sortStoriesV7,start,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext,userOrAutoTitle,userOrAutoTitleFromSpecifier};
|
package/dist/preview-web.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { DocsContextProps, DocsRenderFunction, ProjectAnnotations as WebProjectAnnotations } from '@storybook/types';
|
|
2
2
|
export { c as composeConfigs } from './composeConfigs-62a04721.js';
|
|
3
|
-
export { D as DocsContext, P as Preview, b as PreviewWeb, c as PreviewWithSelection, a as simulateDOMContentLoaded, s as simulatePageLoad } from './simulate-pageload-
|
|
3
|
+
export { D as DocsContext, P as Preview, b as PreviewWeb, c as PreviewWithSelection, a as simulateDOMContentLoaded, s as simulatePageLoad } from './simulate-pageload-813b23ff.js';
|
|
4
4
|
import '@storybook/channels';
|
|
5
|
-
import './StoryStore-
|
|
5
|
+
import './StoryStore-a6898638.js';
|
|
6
6
|
import 'synchronous-promise';
|
|
7
7
|
import './hooks-55c56a89.js';
|
package/dist/preview-web.js
CHANGED
|
@@ -34,22 +34,25 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
34
34
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
35
35
|
`);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=import_global5.global.FEATURES)!=null&&_a.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=import_synchronous_promise2.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 result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new Error(await result.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=import_global5.global.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}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals),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&&!r.renderOptions.forceInitialArgs).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){let render=this.storyRenders.find(r=>r.id===storyId),story=(render==null?void 0:render.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,callbacks,options){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,callbacks,story.id,"docs",options,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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent6.dedent`Failed to initialize Storybook.
|
|
36
36
|
|
|
37
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger9.logger.error(reason),import_client_logger9.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global9=require("@storybook/global");var import_ts_dedent7=require("ts-dedent"),import_global6=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger10=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){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.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("Cannot reference a non-meta or module export in <Meta of={} />");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:prepareMeta(resolved.csfFile.meta,this.projectAnnotations,resolved.csfFile.moduleExports.default)};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}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_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.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}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent7.dedent`
|
|
37
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger9.logger.error(reason),import_client_logger9.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global9=require("@storybook/global");var import_ts_dedent8=require("ts-dedent"),import_global6=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger10=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var import_ts_dedent7=__toESM(require("ts-dedent"));var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){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.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent7.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
|
|
38
|
+
- Did you pass a component to the 'of' prop when the block only supports a story or a meta?
|
|
39
|
+
- ... or vice versa?
|
|
40
|
+
- Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:prepareMeta(resolved.csfFile.meta,this.projectAnnotations,resolved.csfFile.moduleExports.default)};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;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)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{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()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};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}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}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_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.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}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent8.dedent`
|
|
38
41
|
Couldn't find any stories in your Storybook.
|
|
39
42
|
- Please check your stories field of your main.js config.
|
|
40
43
|
- Also check the browser console and terminal for error messages.
|
|
41
|
-
`)):this.renderStoryLoadingException(storySpecifier,new Error(
|
|
44
|
+
`)):this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent8.dedent`
|
|
42
45
|
Couldn't find story matching '${storySpecifier}'.
|
|
43
46
|
- Are you sure a story with that id exists?
|
|
44
47
|
- Please check your stories field of your main.js config.
|
|
45
48
|
- Also check the browser console and terminal for error messages.
|
|
46
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(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({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));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_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global6.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(
|
|
49
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.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,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(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({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));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_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global6.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}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(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent8.dedent`Failed to initialize Storybook.
|
|
47
50
|
|
|
48
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger10.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),(_a=error.message)!=null&&_a.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger10.logger.error(`Error rendering story '${storyId}':`),import_client_logger10.logger.error(error))}renderError(storyId,{title,description}){import_client_logger10.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global7=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),
|
|
51
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger10.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),(_a=error.message)!=null&&_a.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger10.logger.error(`Error rendering story '${storyId}':`),import_client_logger10.logger.error(error))}renderError(storyId,{title,description}){import_client_logger10.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global7=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent9=require("ts-dedent"),import_client_logger11=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject.js")),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=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):(0,import_isPlainObject3.default)(value)?Object.entries(value).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==="!true")return!0;if(str==="!false")return!1;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_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger11.once.warn(import_ts_dedent9.dedent`
|
|
49
52
|
Omitted potentially unsafe URL args.
|
|
50
53
|
|
|
51
54
|
More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
|
|
52
|
-
`),acc),{})};var{history,document}=import_global7.global;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=import_qs2.default.parse(search,{ignoreQueryPrefix:!0});return import_qs2.default.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=import_qs2.default.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_global8=require("@storybook/global"),import_client_logger12=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),
|
|
55
|
+
`),acc),{})};var{history,document}=import_global7.global;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=import_qs2.default.parse(search,{ignoreQueryPrefix:!0});return import_qs2.default.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=import_qs2.default.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_global8=require("@storybook/global"),import_client_logger12=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),import_ts_dedent10=require("ts-dedent"),import_qs3=__toESM(require("qs")),{document:document2}=import_global8.global,PREPARING_DELAY=100,Mode=(Mode2=>(Mode2.MAIN="MAIN",Mode2.NOPREVIEW="NOPREVIEW",Mode2.PREPARING_STORY="PREPARING_STORY",Mode2.PREPARING_DOCS="PREPARING_DOCS",Mode2.ERROR="ERROR",Mode2))(Mode||{}),classes={PREPARING_STORY:"sb-show-preparing-story",PREPARING_DOCS:"sb-show-preparing-docs",MAIN:"sb-show-main",NOPREVIEW:"sb-show-nopreview",ERROR:"sb-show-errordisplay"},layoutClassMap={centered:"sb-main-centered",fullscreen:"sb-main-fullscreen",padded:"sb-main-padded"},ansiConverter=new import_ansi_to_html.default({escapeXML:!0}),WebView=class{constructor(){this.testing=!1;let{__SPECIAL_TEST_PARAMETER__}=import_qs3.default.parse(document2.location.search,{ignoreQueryPrefix:!0});switch(__SPECIAL_TEST_PARAMETER__){case"preparing-story":{this.showPreparingStory(),this.testing=!0;break}case"preparing-docs":{this.showPreparingDocs(),this.testing=!0;break}default:}}prepareForStory(story){return this.showStory(),this.applyLayout(story.parameters.layout),document2.documentElement.scrollTop=0,document2.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document2.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),this.docsRoot()}docsRoot(){return document2.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document2.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document2.body.classList.remove(this.currentLayoutClass),document2.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}checkIfLayoutExists(layout){layoutClassMap[layout]||import_client_logger12.logger.warn(import_ts_dedent10.dedent`The desired layout: ${layout} is not a valid option.
|
|
53
56
|
The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.`)}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document2.body.classList.add(classes[otherMode]):document2.body.classList.remove(classes[otherMode])})}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
|
|
54
57
|
`);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
|
|
55
58
|
`)),document2.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document2.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){var _a,_b;this.testing||(this.showMode("NOPREVIEW"),(_a=this.storyRoot())==null||_a.setAttribute("hidden","true"),(_b=this.docsRoot())==null||_b.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_DOCS"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document2.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(){super(new UrlStore,new WebView),import_global9.global.__STORYBOOK_PREVIEW__=this}};var import_global10=require("@storybook/global"),{document:document3}=import_global10.global,runScriptTypes=["application/javascript","application/ecmascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript","module"],SCRIPT="script",SCRIPTS_ROOT_ID="scripts-root";function simulateDOMContentLoaded(){let DOMContentLoadedEvent=document3.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document3.dispatchEvent(DOMContentLoadedEvent)}function insertScript($script,callback,$scriptRoot){let scriptEl=document3.createElement("script");scriptEl.type=$script.type==="module"?"module":"text/javascript",$script.src?(scriptEl.onload=callback,scriptEl.onerror=callback,scriptEl.src=$script.src):scriptEl.textContent=$script.innerText,$scriptRoot?$scriptRoot.appendChild(scriptEl):document3.head.appendChild(scriptEl),$script.parentNode.removeChild($script),$script.src||callback()}function insertScriptsSequentially(scriptsToExecute,callback,index=0){scriptsToExecute[index](()=>{index++,index===scriptsToExecute.length?callback():insertScriptsSequentially(scriptsToExecute,callback,index)})}function simulatePageLoad($container){let $scriptsRoot=document3.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document3.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document3.body.appendChild($scriptsRoot));let $scripts=Array.from($container.querySelectorAll(SCRIPT));if($scripts.length){let scriptsToExecute=[];$scripts.forEach($script=>{let typeAttr=$script.getAttribute("type");(!typeAttr||runScriptTypes.includes(typeAttr))&&scriptsToExecute.push(callback=>insertScript($script,callback,$scriptsRoot))}),scriptsToExecute.length&&insertScriptsSequentially(scriptsToExecute,simulateDOMContentLoaded,void 0)}else simulateDOMContentLoaded()}0&&(module.exports={DocsContext,Preview,PreviewWeb,PreviewWithSelection,composeConfigs,simulateDOMContentLoaded,simulatePageLoad});
|
package/dist/preview-web.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DocsContext,Preview,PreviewWeb,PreviewWithSelection,simulateDOMContentLoaded,simulatePageLoad}from"./chunk-
|
|
1
|
+
import{DocsContext,Preview,PreviewWeb,PreviewWithSelection,simulateDOMContentLoaded,simulatePageLoad}from"./chunk-TDNSAGO4.mjs";import{composeConfigs}from"./chunk-U6GFELHZ.mjs";import"./chunk-RTGEOU4B.mjs";export{DocsContext,Preview,PreviewWeb,PreviewWithSelection,composeConfigs,simulateDOMContentLoaded,simulatePageLoad};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as _storybook_types from '@storybook/types';
|
|
2
2
|
import { Renderer, StoryId, StoryRenderOptions, ViewMode, PreparedStory, RenderToCanvas, RenderContextCallbacks, DocsContextProps, CSFFile, ModuleExports, ResolvedModuleExportType, ModuleExport, ResolvedModuleExportFromType, StoryName, StoryContextForLoaders, IndexEntry, StoryIndex, ModuleImportFn, ProjectAnnotations, Globals, Args } from '@storybook/types';
|
|
3
3
|
import { Channel } from '@storybook/channels';
|
|
4
|
-
import { S as StoryStore,
|
|
4
|
+
import { S as StoryStore, c as StorySpecifier } from './StoryStore-a6898638.js';
|
|
5
5
|
|
|
6
6
|
type RenderType = 'story' | 'docs';
|
|
7
7
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _storybook_types from '@storybook/types';
|
|
2
|
-
import { Renderer, StoryId, LegacyStoryAnnotationsOrFn, NormalizedComponentAnnotations, NormalizedStoryAnnotations, StepRunner, ProjectAnnotations, Args, ComponentAnnotations,
|
|
2
|
+
import { Renderer, StoryId, LegacyStoryAnnotationsOrFn, NormalizedComponentAnnotations, NormalizedStoryAnnotations, StepRunner, ProjectAnnotations, Args, ComponentAnnotations, PreparedStoryFn, Store_CSFExports, ComposeStoryFn, Parameters, StrictArgTypes, ArgTypesEnhancer, LegacyStoryFn, DecoratorFunction, PartialStoryFn, StoryContextUpdate, ArgTypes, StoryContext, NormalizedStoriesSpecifier, IndexEntry, Addon_StorySortParameterV7, Path, PreparedStory, Addon_StorySortParameter } from '@storybook/types';
|
|
3
3
|
|
|
4
4
|
declare function normalizeStory<TRenderer extends Renderer>(key: StoryId, storyAnnotations: LegacyStoryAnnotationsOrFn<TRenderer>, meta: NormalizedComponentAnnotations<TRenderer>): NormalizedStoryAnnotations<TRenderer>;
|
|
5
5
|
|
|
@@ -24,13 +24,7 @@ declare function normalizeStory<TRenderer extends Renderer>(key: StoryId, storyA
|
|
|
24
24
|
declare function composeStepRunners<TRenderer extends Renderer>(stepRunners: StepRunner<TRenderer>[]): StepRunner<TRenderer>;
|
|
25
25
|
|
|
26
26
|
declare function setProjectAnnotations<TRenderer extends Renderer = Renderer>(projectAnnotations: ProjectAnnotations<TRenderer> | ProjectAnnotations<TRenderer>[]): void;
|
|
27
|
-
declare function composeStory<TRenderer extends Renderer = Renderer, TArgs extends Args = Args>(storyAnnotations: LegacyStoryAnnotationsOrFn<TRenderer>, componentAnnotations: ComponentAnnotations<TRenderer, TArgs>, projectAnnotations?: ProjectAnnotations<TRenderer>, defaultConfig?: ProjectAnnotations<TRenderer>, exportsName?: string):
|
|
28
|
-
(extraArgs: Partial<TArgs>): TRenderer["storyResult"];
|
|
29
|
-
storyName: string;
|
|
30
|
-
args: Args;
|
|
31
|
-
play: ComposedStoryPlayFn;
|
|
32
|
-
parameters: Parameters;
|
|
33
|
-
};
|
|
27
|
+
declare function composeStory<TRenderer extends Renderer = Renderer, TArgs extends Args = Args>(storyAnnotations: LegacyStoryAnnotationsOrFn<TRenderer>, componentAnnotations: ComponentAnnotations<TRenderer, TArgs>, projectAnnotations?: ProjectAnnotations<TRenderer>, defaultConfig?: ProjectAnnotations<TRenderer>, exportsName?: string): PreparedStoryFn<TRenderer, Partial<TArgs>>;
|
|
34
28
|
declare function composeStories<TModule extends Store_CSFExports>(storiesImport: TModule, globalConfig: ProjectAnnotations<Renderer>, composeStoryFn: ComposeStoryFn): {};
|
|
35
29
|
|
|
36
30
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Renderer, ProjectAnnotations, ArgsStoryFn } from '@storybook/types';
|
|
2
|
-
import { C as ClientApi } from './ClientApi-
|
|
2
|
+
import { C as ClientApi } from './ClientApi-5a0be40f.js';
|
|
3
3
|
|
|
4
4
|
interface CoreClient_RendererImplementation<TRenderer extends Renderer> {
|
|
5
5
|
decorateStory?: ProjectAnnotations<TRenderer>['applyDecorators'];
|
package/dist/store.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { S as StoryStore, a as prepareMeta, p as prepareStory,
|
|
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, a as prepareMeta, p as prepareStory, b as processCSFFile } from './StoryStore-a6898638.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-582c1134.js';
|
|
3
3
|
export { g as getValuesFromArgTypes, b as normalizeComponentAnnotations, n as normalizeInputType, a as normalizeInputTypes, c as normalizeProjectAnnotations, d as useAddonState, u as useSharedState } from './hooks-0a0ec0e3.js';
|
|
4
4
|
export { c as composeConfigs, a as getArrayField, g as getField, b as getObjectField, d as getSingletonField } from './composeConfigs-62a04721.js';
|
|
5
5
|
export { H as HooksContext, k as applyHooks, u as useArgs, a as useCallback, b as useChannel, c as useEffect, d as useGlobals, e as useMemo, f as useParameter, g as useReducer, h as useRef, i as useState, j as useStoryContext } from './hooks-55c56a89.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storybook/preview-api",
|
|
3
|
-
"version": "7.0.0-rc.
|
|
3
|
+
"version": "7.0.0-rc.4",
|
|
4
4
|
"description": "",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"storybook"
|
|
@@ -67,13 +67,13 @@
|
|
|
67
67
|
"prep": "../../../scripts/prepare/bundle.ts"
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
|
70
|
-
"@storybook/channel-postmessage": "7.0.0-rc.
|
|
71
|
-
"@storybook/channels": "7.0.0-rc.
|
|
72
|
-
"@storybook/client-logger": "7.0.0-rc.
|
|
73
|
-
"@storybook/core-events": "7.0.0-rc.
|
|
70
|
+
"@storybook/channel-postmessage": "7.0.0-rc.4",
|
|
71
|
+
"@storybook/channels": "7.0.0-rc.4",
|
|
72
|
+
"@storybook/client-logger": "7.0.0-rc.4",
|
|
73
|
+
"@storybook/core-events": "7.0.0-rc.4",
|
|
74
74
|
"@storybook/csf": "next",
|
|
75
75
|
"@storybook/global": "^5.0.0",
|
|
76
|
-
"@storybook/types": "7.0.0-rc.
|
|
76
|
+
"@storybook/types": "7.0.0-rc.4",
|
|
77
77
|
"@types/qs": "^6.9.5",
|
|
78
78
|
"dequal": "^2.0.2",
|
|
79
79
|
"lodash": "^4.17.21",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
},
|
|
87
87
|
"devDependencies": {
|
|
88
88
|
"@jest/globals": "^26.6.2",
|
|
89
|
-
"@storybook/core-common": "7.0.0-rc.
|
|
89
|
+
"@storybook/core-common": "7.0.0-rc.4",
|
|
90
90
|
"ansi-to-html": "^0.6.11",
|
|
91
91
|
"react": "^16.14.0"
|
|
92
92
|
},
|
|
@@ -103,5 +103,5 @@
|
|
|
103
103
|
"./src/store.ts"
|
|
104
104
|
]
|
|
105
105
|
},
|
|
106
|
-
"gitHead": "
|
|
106
|
+
"gitHead": "6fb713a2ca980fa241f82a076579889fcdf47ecc"
|
|
107
107
|
}
|