@storybook/preview-api 8.0.0-alpha.7 → 8.0.0-alpha.8

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
37
37
  Are you using a V6-style sort function in V7 mode?
38
38
 
39
39
  More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
40
- `)}},toIndexEntry=story=>{let{id,title,name,parameters,type}=story;return{id,title,name,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_ts_dedent7=require("ts-dedent"),import_global5=require("@storybook/global"),import_synchronous_promise2=require("synchronous-promise"),import_core_events3=require("@storybook/core-events"),import_client_logger10=require("@storybook/client-logger");var import_client_logger9=require("@storybook/client-logger"),import_core_events2=require("@storybook/core-events");var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return{name,message,stack}}catch{return{name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing")}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}))}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id})}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return["preparing"].includes(this.phase)}isPending(){return["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode})}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{})}),this.notYetRendered=!1,abortSignal.aborted)return;if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext)}),await this.runPhase(abortSignal,"played")}catch(error){if(import_client_logger9.logger.error(error),await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(import_core_events2.PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error))}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error}if(this.disableKeyListeners=!1,abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(import_core_events2.STORY_RENDERED,id))}catch(err){this.phase="errored",this.callbacks.showException(err)}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){this.abortController?.abort()}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0))}window.location.reload(),await new Promise(()=>{})}};var{fetch}=import_global5.global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(channel=addons.getChannel()){this.channel=channel;this.storyRenders=[];import_global5.global.FEATURES?.storyStoreV7&&addons.hasServerChannel()&&(this.serverChannel=addons.getServerChannel()),this.storyStore=new StoryStore}initialize({getStoryIndex,importFn,getProjectAnnotations}){return this.getStoryIndex=getStoryIndex,this.importFn=importFn,this.setupListeners(),this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(projectAnnotations=>this.initializeWithProjectAnnotations(projectAnnotations))}setupListeners(){this.channel.on(import_core_events3.STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(import_core_events3.UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(import_core_events3.UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(import_core_events3.RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(import_core_events3.FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(import_core_events3.FORCE_REMOUNT,this.onForceRemount.bind(this))}getProjectAnnotationsOrRenderError(getProjectAnnotations){return import_synchronous_promise2.SynchronousPromise.resolve().then(getProjectAnnotations).then(projectAnnotations=>{if(projectAnnotations.renderToDOM&&(0,import_client_logger10.deprecate)("`renderToDOM` is deprecated, please rename to `renderToCanvas`"),this.renderToCanvas=projectAnnotations.renderToCanvas||projectAnnotations.renderToDOM,!this.renderToCanvas)throw new Error(import_ts_dedent7.dedent`
40
+ `)}},toIndexEntry=story=>{let{id,title,name,parameters,type}=story;return{id,title,name,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_ts_dedent7=require("ts-dedent"),import_global5=require("@storybook/global"),import_synchronous_promise2=require("synchronous-promise"),import_core_events3=require("@storybook/core-events"),import_client_logger9=require("@storybook/client-logger");var import_core_events2=require("@storybook/core-events");var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return{name,message,stack}}catch{return{name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing")}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}))}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id})}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return["preparing"].includes(this.phase)}isPending(){return["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode})}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{})}),this.notYetRendered=!1,abortSignal.aborted)return;let ignoreUnhandledErrors=this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors===!0,unhandledErrors=new Set,onError=event=>unhandledErrors.add("error"in event?event.error:event.reason);if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){window.addEventListener("error",onError),window.addEventListener("unhandledrejection",onError),this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext)}),!ignoreUnhandledErrors&&unhandledErrors.size>0?await this.runPhase(abortSignal,"errored"):await this.runPhase(abortSignal,"played")}catch(error){if(await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(import_core_events2.PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error))}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error;console.error(error)}if(!ignoreUnhandledErrors&&unhandledErrors.size>0&&this.channel.emit(import_core_events2.UNHANDLED_ERRORS_WHILE_PLAYING,Array.from(unhandledErrors).map(serializeError)),this.disableKeyListeners=!1,window.removeEventListener("unhandledrejection",onError),window.removeEventListener("error",onError),abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(import_core_events2.STORY_RENDERED,id))}catch(err){this.phase="errored",this.callbacks.showException(err)}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){this.abortController?.abort()}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0))}window.location.reload(),await new Promise(()=>{})}};var{fetch}=import_global5.global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(channel=addons.getChannel()){this.channel=channel;this.storyRenders=[];import_global5.global.FEATURES?.storyStoreV7&&addons.hasServerChannel()&&(this.serverChannel=addons.getServerChannel()),this.storyStore=new StoryStore}initialize({getStoryIndex,importFn,getProjectAnnotations}){return this.getStoryIndex=getStoryIndex,this.importFn=importFn,this.setupListeners(),this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(projectAnnotations=>this.initializeWithProjectAnnotations(projectAnnotations))}setupListeners(){this.channel.on(import_core_events3.STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(import_core_events3.UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(import_core_events3.UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(import_core_events3.RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(import_core_events3.FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(import_core_events3.FORCE_REMOUNT,this.onForceRemount.bind(this))}getProjectAnnotationsOrRenderError(getProjectAnnotations){return import_synchronous_promise2.SynchronousPromise.resolve().then(getProjectAnnotations).then(projectAnnotations=>{if(projectAnnotations.renderToDOM&&(0,import_client_logger9.deprecate)("`renderToDOM` is deprecated, please rename to `renderToCanvas`"),this.renderToCanvas=projectAnnotations.renderToCanvas||projectAnnotations.renderToDOM,!this.renderToCanvas)throw new Error(import_ts_dedent7.dedent`
41
41
  Expected your framework's preset to export a \`renderToCanvas\` field.
42
42
 
43
43
  Perhaps it needs to be upgraded for Storybook 6.4?
@@ -45,7 +45,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
45
45
  More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
46
46
  `);return projectAnnotations}).catch(err=>{throw this.renderPreviewEntryError("Error reading preview.js:",err),err})}initializeWithProjectAnnotations(projectAnnotations){this.storyStore.setProjectAnnotations(projectAnnotations),this.setInitialGlobals();let storyIndexPromise;if(import_global5.global.FEATURES?.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){if(!this.importFn)throw new Error("Cannot call initializeWithStoryIndex before initialization");return this.storyStore.initialize({storyIndex,importFn:this.importFn,cache:!import_global5.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(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 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(import_ts_dedent7.dedent`Failed to initialize Storybook.
47
47
 
48
- Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return import_global5.global.FEATURES?.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 import_ts_dedent8=__toESM(require("ts-dedent")),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_dedent8.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(", ")}.
48
+ Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return import_global5.global.FEATURES?.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_dedent9=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_dedent8=__toESM(require("ts-dedent")),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_dedent8.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(", ")}.
49
49
  - Did you pass a component to the 'of' prop when the block only supports a story or a meta?
50
50
  - ... or vice versa?
51
51
  - 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:this.store.preparedMetaFromCSFFile({csfFile:resolved.csfFile})};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.subtype="csf";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}={}){this.teardownRender?.({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.subtype="mdx";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}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.composedPath&&event.composedPath()[0]||event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return!tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}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))}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(()=>(import_global6.global.FEATURES?.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.selection){await this.renderSelection();return}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`
@@ -59,14 +59,14 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
59
59
  - Also check the browser console and terminal for error messages.
60
60
  `));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}){await super.onStoriesChanged({importFn,storyIndex}),import_global6.global.FEATURES?.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){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storyStore.initializationPromise,this.channel.emit(import_core_events6.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(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,unmappedArgs}=this.storyStore.getStoryContext(render.story);import_global6.global.FEATURES?.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args:unmappedArgs})}else if(import_global6.global.FEATURES?.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}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(import_ts_dedent9.dedent`Failed to initialize Storybook.
61
61
 
62
- Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return import_global6.global.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(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){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}),error.message?.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_dedent10=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_dedent10.dedent`
62
+ Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return import_global6.global.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(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){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}),error.message?.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_dedent10=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_dedent10.dedent`
63
63
  Omitted potentially unsafe URL args.
64
64
 
65
65
  More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
66
- `),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_dedent11=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"),document2.documentElement.scrollTop=0,document2.documentElement.scrollLeft=0,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_dedent11.dedent`The desired layout: ${layout} is not a valid option.
66
+ `),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_dedent11=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"),document2.documentElement.scrollTop=0,document2.documentElement.scrollLeft=0,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_dedent11.dedent`The desired layout: ${layout} is not a valid option.
67
67
  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(`
68
68
  `);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
69
- `)),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),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_dedent13=require("ts-dedent"),import_global12=require("@storybook/global");var import_global11=require("@storybook/global"),import_ts_dedent12=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){let fileNameOrder=Object.keys(this.csfExports),storySortParameter=this.projectAnnotations.parameters?.options?.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:(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_dedent12.dedent`
69
+ `)),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),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_dedent13=require("ts-dedent"),import_global12=require("@storybook/global");var import_global11=require("@storybook/global"),import_ts_dedent12=require("ts-dedent"),import_synchronous_promise3=require("synchronous-promise"),import_csf7=require("@storybook/csf"),import_client_logger13=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){let fileNameOrder=Object.keys(this.csfExports),storySortParameter=this.projectAnnotations.parameters?.options?.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:(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_dedent12.dedent`
70
70
  Error sorting stories with sort parameter ${storySortParameter}:
71
71
 
72
72
  > ${err.message}
@@ -82,7 +82,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
82
82
  exclude it from your \`stories\` glob, or add <Meta isTemplate /> to it.
83
83
 
84
84
  If you wanted to index the file, you'll need to name it \`stories.mdx\` and stick to the
85
- 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])=>{let exportName=(0,import_csf7.storyNameFromExport)(key),id=storyExport.parameters?.__id||(0,import_csf7.toId)(componentId||title,exportName),name=typeof storyExport!="function"&&storyExport.name||storyExport.storyName||storyExport.story?.name||exportName;storyExport.parameters?.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=>{if(import_global12.global.FEATURES?.storyStoreV7)throw new Error(import_ts_dedent13.dedent`You cannot use \`${method}\` with the new Story Store.
85
+ 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_logger13.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])=>{let exportName=(0,import_csf7.storyNameFromExport)(key),id=storyExport.parameters?.__id||(0,import_csf7.toId)(componentId||title,exportName),name=typeof storyExport!="function"&&storyExport.name||storyExport.storyName||storyExport.story?.name||exportName;storyExport.parameters?.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=>{if(import_global12.global.FEATURES?.storyStoreV7)throw new Error(import_ts_dedent13.dedent`You cannot use \`${method}\` with the new Story Store.
86
86
 
87
- ${warningAlternatives[method]}`);if(!import_global12.global.__STORYBOOK_CLIENT_API__)throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`)},addDecorator=decorator=>{checkMethod("addDecorator"),import_global12.global.__STORYBOOK_CLIENT_API__?.addDecorator(decorator)},addParameters=parameters=>{checkMethod("addParameters"),import_global12.global.__STORYBOOK_CLIENT_API__?.addParameters(parameters)},addLoader=loader=>{checkMethod("addLoader"),import_global12.global.__STORYBOOK_CLIENT_API__?.addLoader(loader)},addArgs=args=>{checkMethod("addArgs"),import_global12.global.__STORYBOOK_CLIENT_API__?.addArgs(args)},addArgTypes=argTypes=>{checkMethod("addArgTypes"),import_global12.global.__STORYBOOK_CLIENT_API__?.addArgTypes(argTypes)},addArgsEnhancer=enhancer=>{checkMethod("addArgsEnhancer"),import_global12.global.__STORYBOOK_CLIENT_API__?.addArgsEnhancer(enhancer)},addArgTypesEnhancer=enhancer=>{checkMethod("addArgTypesEnhancer"),import_global12.global.__STORYBOOK_CLIENT_API__?.addArgTypesEnhancer(enhancer)},addStepRunner=stepRunner=>{checkMethod("addStepRunner"),import_global12.global.__STORYBOOK_CLIENT_API__?.addStepRunner(stepRunner)};var setGlobalRender=render=>{checkMethod("setGlobalRender"),import_global12.global.__STORYBOOK_CLIENT_API__&&(import_global12.global.__STORYBOOK_CLIENT_API__.facade.projectAnnotations.render=render)},ClientApi=class{constructor({storyStore}={}){this.addDecorator=decorator=>{this.facade.projectAnnotations.decorators?.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=>{this.facade.projectAnnotations.loaders?.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=>{this.facade.projectAnnotations.argsEnhancers?.push(enhancer)};this.addArgTypesEnhancer=enhancer=>{this.facade.projectAnnotations.argTypesEnhancers?.push(enhancer)};this._addedExports={};this.raw=()=>this.storyStore?.raw();this.facade=new StoryStoreFacade,this.storyStore=storyStore}importFn(path){return this.facade.importFn(path)}getStoryIndex(){if(!this.storyStore)throw new Error("Cannot get story index before setting storyStore");return this.facade.getStoryIndex(this.storyStore)}_loadAddedExports(){Object.entries(this._addedExports).forEach(([fileName,fileExports])=>this.facade.addStoriesFromExports(fileName,fileExports))}get _storyStore(){return this.storyStore}};var import_global13=require("@storybook/global"),import_qs4=require("qs"),getQueryParams=()=>{let{document:document4}=import_global13.global;return document4&&document4.location&&document4.location.search?(0,import_qs4.parse)(document4.location.search,{ignoreQueryPrefix:!0}):{}},getQueryParam=key=>getQueryParams()[key];var import_global14=require("@storybook/global"),import_channels2=require("@storybook/channels"),import_core_events7=require("@storybook/core-events");var import_client_logger15=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}
88
- ${error.stack}`:error.toString();import_client_logger15.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&&import_client_logger15.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}=import_global14.global,removedApi=name=>()=>{throw new Error(`@storybook/client-api:${name} was removed in storyStoreV7.`)};function start(renderToCanvas,{decorateStory:decorateStory2,render}={}){if(import_global14.global&&(import_global14.global.IS_STORYBOOK=!0),FEATURES?.storyStoreV7)return{forceReRender:removedApi("forceReRender"),configure:removedApi("configure"),clientApi:{raw:removedApi("raw")}};let channel=(0,import_channels2.createBrowserChannel)({page:"preview"});addons.setChannel(channel);let clientApi=import_global14.global?.__STORYBOOK_CLIENT_API__||new ClientApi,preview=import_global14.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,import_global14.global&&(import_global14.global.__STORYBOOK_CLIENT_API__=clientApi,import_global14.global.__STORYBOOK_ADDONS_CHANNEL__=channel,import_global14.global.__STORYBOOK_PREVIEW__=preview,import_global14.global.__STORYBOOK_STORY_STORE__=preview.storyStore),{forceReRender:()=>channel.emit(import_core_events7.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:decorateStory2}};initialized?(getProjectAnnotations(),onStoriesChanged()):(preview.initialize({getStoryIndex:()=>clientApi.getStoryIndex(),importFn,getProjectAnnotations}),initialized=!0)}}}0&&(module.exports={ClientApi,DocsContext,HooksContext,Preview,PreviewWeb,PreviewWithSelection,StoryStore,UrlStore,WebView,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});
87
+ ${warningAlternatives[method]}`);if(!import_global12.global.__STORYBOOK_CLIENT_API__)throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`)},addDecorator=decorator=>{checkMethod("addDecorator"),import_global12.global.__STORYBOOK_CLIENT_API__?.addDecorator(decorator)},addParameters=parameters=>{checkMethod("addParameters"),import_global12.global.__STORYBOOK_CLIENT_API__?.addParameters(parameters)},addLoader=loader=>{checkMethod("addLoader"),import_global12.global.__STORYBOOK_CLIENT_API__?.addLoader(loader)},addArgs=args=>{checkMethod("addArgs"),import_global12.global.__STORYBOOK_CLIENT_API__?.addArgs(args)},addArgTypes=argTypes=>{checkMethod("addArgTypes"),import_global12.global.__STORYBOOK_CLIENT_API__?.addArgTypes(argTypes)},addArgsEnhancer=enhancer=>{checkMethod("addArgsEnhancer"),import_global12.global.__STORYBOOK_CLIENT_API__?.addArgsEnhancer(enhancer)},addArgTypesEnhancer=enhancer=>{checkMethod("addArgTypesEnhancer"),import_global12.global.__STORYBOOK_CLIENT_API__?.addArgTypesEnhancer(enhancer)},addStepRunner=stepRunner=>{checkMethod("addStepRunner"),import_global12.global.__STORYBOOK_CLIENT_API__?.addStepRunner(stepRunner)};var setGlobalRender=render=>{checkMethod("setGlobalRender"),import_global12.global.__STORYBOOK_CLIENT_API__&&(import_global12.global.__STORYBOOK_CLIENT_API__.facade.projectAnnotations.render=render)},ClientApi=class{constructor({storyStore}={}){this.addDecorator=decorator=>{this.facade.projectAnnotations.decorators?.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=>{this.facade.projectAnnotations.loaders?.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=>{this.facade.projectAnnotations.argsEnhancers?.push(enhancer)};this.addArgTypesEnhancer=enhancer=>{this.facade.projectAnnotations.argTypesEnhancers?.push(enhancer)};this._addedExports={};this.raw=()=>this.storyStore?.raw();this.facade=new StoryStoreFacade,this.storyStore=storyStore}importFn(path){return this.facade.importFn(path)}getStoryIndex(){if(!this.storyStore)throw new Error("Cannot get story index before setting storyStore");return this.facade.getStoryIndex(this.storyStore)}_loadAddedExports(){Object.entries(this._addedExports).forEach(([fileName,fileExports])=>this.facade.addStoriesFromExports(fileName,fileExports))}get _storyStore(){return this.storyStore}};var import_global13=require("@storybook/global"),import_qs4=require("qs"),getQueryParams=()=>{let{document:document4}=import_global13.global;return document4&&document4.location&&document4.location.search?(0,import_qs4.parse)(document4.location.search,{ignoreQueryPrefix:!0}):{}},getQueryParam=key=>getQueryParams()[key];var import_global14=require("@storybook/global"),import_channels2=require("@storybook/channels"),import_core_events7=require("@storybook/core-events");var import_client_logger14=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}
88
+ ${error.stack}`:error.toString();import_client_logger14.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&&import_client_logger14.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}=import_global14.global,removedApi=name=>()=>{throw new Error(`@storybook/client-api:${name} was removed in storyStoreV7.`)};function start(renderToCanvas,{decorateStory:decorateStory2,render}={}){if(import_global14.global&&(import_global14.global.IS_STORYBOOK=!0),FEATURES?.storyStoreV7)return{forceReRender:removedApi("forceReRender"),configure:removedApi("configure"),clientApi:{raw:removedApi("raw")}};let channel=(0,import_channels2.createBrowserChannel)({page:"preview"});addons.setChannel(channel);let clientApi=import_global14.global?.__STORYBOOK_CLIENT_API__||new ClientApi,preview=import_global14.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,import_global14.global&&(import_global14.global.__STORYBOOK_CLIENT_API__=clientApi,import_global14.global.__STORYBOOK_ADDONS_CHANNEL__=channel,import_global14.global.__STORYBOOK_PREVIEW__=preview,import_global14.global.__STORYBOOK_STORY_STORE__=preview.storyStore),{forceReRender:()=>channel.emit(import_core_events7.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:decorateStory2}};initialized?(getProjectAnnotations(),onStoriesChanged()):(preview.initialize({getStoryIndex:()=>clientApi.getStoryIndex(),importFn,getProjectAnnotations}),initialized=!0)}}}0&&(module.exports={ClientApi,DocsContext,HooksContext,Preview,PreviewWeb,PreviewWithSelection,StoryStore,UrlStore,WebView,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/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { global } from '@storybook/global';
2
2
  import { Channel, createBrowserChannel } from '@storybook/channels';
3
3
  import { logger, once, deprecate as deprecate$1 } from '@storybook/client-logger';
4
- import { STORY_RENDERED, STORY_INDEX_INVALIDATED, UPDATE_GLOBALS, UPDATE_STORY_ARGS, RESET_STORY_ARGS, FORCE_RE_RENDER, FORCE_REMOUNT, SET_GLOBALS, GLOBALS_UPDATED, STORY_ARGS_UPDATED, CONFIG_ERROR, SET_CURRENT_STORY, UPDATE_QUERY_PARAMS, PRELOAD_ENTRIES, SET_INDEX, STORY_SPECIFIED, CURRENT_STORY_WAS_SET, PREVIEW_KEYDOWN, STORY_UNCHANGED, STORY_CHANGED, STORY_PREPARED, DOCS_PREPARED, STORY_MISSING, STORY_THREW_EXCEPTION, STORY_RENDER_PHASE_CHANGED, STORY_ERRORED, PLAY_FUNCTION_THREW_EXCEPTION, DOCS_RENDERED } from '@storybook/core-events';
4
+ import { STORY_RENDERED, STORY_INDEX_INVALIDATED, UPDATE_GLOBALS, UPDATE_STORY_ARGS, RESET_STORY_ARGS, FORCE_RE_RENDER, FORCE_REMOUNT, SET_GLOBALS, GLOBALS_UPDATED, STORY_ARGS_UPDATED, CONFIG_ERROR, SET_CURRENT_STORY, UPDATE_QUERY_PARAMS, PRELOAD_ENTRIES, SET_INDEX, STORY_SPECIFIED, CURRENT_STORY_WAS_SET, PREVIEW_KEYDOWN, STORY_UNCHANGED, STORY_CHANGED, STORY_PREPARED, DOCS_PREPARED, STORY_MISSING, STORY_THREW_EXCEPTION, STORY_RENDER_PHASE_CHANGED, STORY_ERRORED, PLAY_FUNCTION_THREW_EXCEPTION, UNHANDLED_ERRORS_WHILE_PLAYING, DOCS_RENDERED } from '@storybook/core-events';
5
5
  import memoize2 from 'memoizerific';
6
6
  import mapValues2 from 'lodash/mapValues.js';
7
7
  import pick from 'lodash/pick.js';
@@ -54,7 +54,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
54
54
  Are you using a V6-style sort function in V7 mode?
55
55
 
56
56
  More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
57
- `)}},toIndexEntry=story=>{let{id,title,name,parameters,type}=story;return {id,title,name,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return {name,message,stack}}catch{return {name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing");}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}));}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id});}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return !!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return ["preparing"].includes(this.phase)}isPending(){return ["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode});}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{});}),this.notYetRendered=!1,abortSignal.aborted)return;if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext);}),await this.runPhase(abortSignal,"played");}catch(error){if(logger.error(error),await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error));}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error}if(this.disableKeyListeners=!1,abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(STORY_RENDERED,id));}catch(err){this.phase="errored",this.callbacks.showException(err);}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){this.abortController?.abort();}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0));}window.location.reload(),await new Promise(()=>{});}};var {fetch}=global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(channel=addons.getChannel()){this.channel=channel;this.storyRenders=[];global.FEATURES?.storyStoreV7&&addons.hasServerChannel()&&(this.serverChannel=addons.getServerChannel()),this.storyStore=new StoryStore;}initialize({getStoryIndex,importFn,getProjectAnnotations}){return this.getStoryIndex=getStoryIndex,this.importFn=importFn,this.setupListeners(),this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(projectAnnotations=>this.initializeWithProjectAnnotations(projectAnnotations))}setupListeners(){this.channel.on(STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(FORCE_REMOUNT,this.onForceRemount.bind(this));}getProjectAnnotationsOrRenderError(getProjectAnnotations){return SynchronousPromise.resolve().then(getProjectAnnotations).then(projectAnnotations=>{if(projectAnnotations.renderToDOM&&deprecate$1("`renderToDOM` is deprecated, please rename to `renderToCanvas`"),this.renderToCanvas=projectAnnotations.renderToCanvas||projectAnnotations.renderToDOM,!this.renderToCanvas)throw new Error(dedent`
57
+ `)}},toIndexEntry=story=>{let{id,title,name,parameters,type}=story;return {id,title,name,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return {name,message,stack}}catch{return {name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing");}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}));}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id});}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return !!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return ["preparing"].includes(this.phase)}isPending(){return ["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode});}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{});}),this.notYetRendered=!1,abortSignal.aborted)return;let ignoreUnhandledErrors=this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors===!0,unhandledErrors=new Set,onError=event=>unhandledErrors.add("error"in event?event.error:event.reason);if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){window.addEventListener("error",onError),window.addEventListener("unhandledrejection",onError),this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext);}),!ignoreUnhandledErrors&&unhandledErrors.size>0?await this.runPhase(abortSignal,"errored"):await this.runPhase(abortSignal,"played");}catch(error){if(await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error));}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error;console.error(error);}if(!ignoreUnhandledErrors&&unhandledErrors.size>0&&this.channel.emit(UNHANDLED_ERRORS_WHILE_PLAYING,Array.from(unhandledErrors).map(serializeError)),this.disableKeyListeners=!1,window.removeEventListener("unhandledrejection",onError),window.removeEventListener("error",onError),abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(STORY_RENDERED,id));}catch(err){this.phase="errored",this.callbacks.showException(err);}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){this.abortController?.abort();}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0));}window.location.reload(),await new Promise(()=>{});}};var {fetch}=global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(channel=addons.getChannel()){this.channel=channel;this.storyRenders=[];global.FEATURES?.storyStoreV7&&addons.hasServerChannel()&&(this.serverChannel=addons.getServerChannel()),this.storyStore=new StoryStore;}initialize({getStoryIndex,importFn,getProjectAnnotations}){return this.getStoryIndex=getStoryIndex,this.importFn=importFn,this.setupListeners(),this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(projectAnnotations=>this.initializeWithProjectAnnotations(projectAnnotations))}setupListeners(){this.channel.on(STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(FORCE_REMOUNT,this.onForceRemount.bind(this));}getProjectAnnotationsOrRenderError(getProjectAnnotations){return SynchronousPromise.resolve().then(getProjectAnnotations).then(projectAnnotations=>{if(projectAnnotations.renderToDOM&&deprecate$1("`renderToDOM` is deprecated, please rename to `renderToCanvas`"),this.renderToCanvas=projectAnnotations.renderToCanvas||projectAnnotations.renderToDOM,!this.renderToCanvas)throw new Error(dedent`
58
58
  Expected your framework's preset to export a \`renderToCanvas\` field.
59
59
 
60
60
  Perhaps it needs to be upgraded for Storybook 6.4?
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/preview-api",
3
- "version": "8.0.0-alpha.7",
3
+ "version": "8.0.0-alpha.8",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "storybook"
@@ -43,12 +43,12 @@
43
43
  "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts"
44
44
  },
45
45
  "dependencies": {
46
- "@storybook/channels": "8.0.0-alpha.7",
47
- "@storybook/client-logger": "8.0.0-alpha.7",
48
- "@storybook/core-events": "8.0.0-alpha.7",
46
+ "@storybook/channels": "8.0.0-alpha.8",
47
+ "@storybook/client-logger": "8.0.0-alpha.8",
48
+ "@storybook/core-events": "8.0.0-alpha.8",
49
49
  "@storybook/csf": "^0.1.2",
50
50
  "@storybook/global": "^5.0.0",
51
- "@storybook/types": "8.0.0-alpha.7",
51
+ "@storybook/types": "8.0.0-alpha.8",
52
52
  "@types/qs": "^6.9.5",
53
53
  "dequal": "^2.0.2",
54
54
  "lodash": "^4.17.21",
@@ -60,7 +60,7 @@
60
60
  },
61
61
  "devDependencies": {
62
62
  "@jest/globals": "^29.5.0",
63
- "@storybook/core-common": "8.0.0-alpha.7",
63
+ "@storybook/core-common": "8.0.0-alpha.8",
64
64
  "ansi-to-html": "^0.6.11",
65
65
  "slash": "^5.0.0"
66
66
  },