@storybook/preview-api 8.1.0-alpha.3 → 8.1.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -442,7 +442,7 @@ type RenderType = 'story' | 'docs';
442
442
  /**
443
443
  * A "Render" represents the rendering of a single entry to a single location
444
444
  *
445
- * The implemenations of render are used for two key purposes:
445
+ * The implementations of render are used for two key purposes:
446
446
  * - Tracking the state of the rendering as it moves between preparing, rendering and tearing down.
447
447
  * - Tracking what is rendered to know if a change requires re-rendering or teardown + recreation.
448
448
  */
package/dist/index.js CHANGED
@@ -48,11 +48,13 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
48
48
  `)}};var import_global5=require("@storybook/global"),import_client_logger10=require("@storybook/client-logger"),import_core_events3=require("@storybook/core-events"),import_preview_errors3=require("@storybook/core-events/preview-errors");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(importFn,getProjectAnnotations,channel=addons.getChannel(),shouldInitialize=!0){this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.channel=channel;this.storyRenders=[];this.storeInitializationPromise=new Promise((resolve,reject)=>{this.resolveStoreInitializationPromise=resolve,this.rejectStoreInitializationPromise=reject}),shouldInitialize&&this.initialize()}get storyStore(){return new Proxy({},{get:(_,method)=>{if(this.storyStoreValue)return(0,import_client_logger10.deprecate)("Accessing the Story Store is deprecated and will be removed in 9.0"),this.storyStoreValue[method];throw new import_preview_errors3.StoryStoreAccessedBeforeInitializationError}})}async initialize(){this.setupListeners();try{let projectAnnotations=await this.getProjectAnnotationsOrRenderError();await this.initializeWithProjectAnnotations(projectAnnotations)}catch(err){this.rejectStoreInitializationPromise(err)}}ready(){return this.storeInitializationPromise}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))}async getProjectAnnotationsOrRenderError(){try{let projectAnnotations=await this.getProjectAnnotations();if(this.renderToCanvas=projectAnnotations.renderToCanvas,!this.renderToCanvas)throw new import_preview_errors3.MissingRenderToCanvasError;return projectAnnotations}catch(err){throw this.renderPreviewEntryError("Error reading preview.js:",err),err}}async initializeWithProjectAnnotations(projectAnnotations){this.projectAnnotationsBeforeInitialization=projectAnnotations;try{let storyIndex=await this.getStoryIndexFromServer();return this.initializeWithStoryIndex(storyIndex)}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new import_preview_errors3.StoryIndexFetchError({text:await result.text()})}initializeWithStoryIndex(storyIndex){if(!this.projectAnnotationsBeforeInitialization)throw new Error("Cannot call initializeWithStoryIndex until project annotations resolve");this.storyStoreValue=new StoryStore(storyIndex,this.importFn,this.projectAnnotationsBeforeInitialization),delete this.projectAnnotationsBeforeInitialization,this.setInitialGlobals(),this.resolveStoreInitializationPromise()}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"emitGlobals"});let payload={globals:this.storyStoreValue.globals.get()||{},globalTypes:this.storyStoreValue.projectAnnotations.globalTypes||{}};this.channel.emit(import_core_events3.SET_GLOBALS,payload)}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError,this.getProjectAnnotations=getProjectAnnotations;let projectAnnotations=await this.getProjectAnnotationsOrRenderError();if(!this.storyStoreValue){await this.initializeWithProjectAnnotations(projectAnnotations);return}this.storyStoreValue.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!(!this.storyStoreValue&&!this.projectAnnotationsBeforeInitialization))try{let storyIndex=await this.getStoryIndexFromServer();if(this.projectAnnotationsBeforeInitialization){this.initializeWithStoryIndex(storyIndex);return}await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onStoriesChanged"});await this.storyStoreValue.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateGlobals"});this.storyStoreValue.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(import_core_events3.GLOBALS_UPDATED,{globals:this.storyStoreValue.globals.get(),initialGlobals:this.storyStoreValue.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateArgs"});this.storyStoreValue.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.storyStoreValue.args.get(storyId)})}async onResetArgs({storyId,argNames}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onResetArgs"});let story=this.storyRenders.find(r=>r.id===storyId)?.story||await this.storyStoreValue.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStoreValue.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||!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"renderStoryToElement"});let render=new StoryRender(this.channel,this.storyStoreValue,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 loadStory({storyId}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"loadStory"});return this.storyStoreValue.loadStory({storyId})}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"getStoryContext"});return this.storyStoreValue.getStoryContext(story,{forceInitialArgs})}async extract(options){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"extract"});if(this.previewEntryError)throw this.previewEntryError;return await this.storyStoreValue.cacheAllCSFFiles(),this.storyStoreValue.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_global8=require("@storybook/global");var import_tiny_invariant=__toESM(require("tiny-invariant")),import_core_events6=require("@storybook/core-events"),import_client_logger11=require("@storybook/client-logger"),import_preview_errors4=require("@storybook/core-events/preview-errors");var import_core_events4=require("@storybook/core-events");var import_ts_dedent7=__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.componentStoriesFromCSFFile=csfFile=>this.store.componentStoriesFromCSFFile({csfFile});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.componentStoriesValue=[],this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.attachedCSFFiles=new Set,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");if(this.attachedCSFFiles.has(csfFile))return;this.attachedCSFFiles.add(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.attachedCSFFiles.size===0)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");let firstAttachedCSFFile=Array.from(this.attachedCSFFiles)[0];if(moduleExportType==="meta")return{type:"meta",csfFile:firstAttachedCSFFile};let{component}=firstAttachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent7.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
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
- - 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(importFn,getProjectAnnotations,selectionStore,view){super(importFn,getProjectAnnotations,void 0,!1);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.selectionStore=selectionStore;this.view=view;this.initialize()}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.storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"setInitialGlobals"});let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStoreValue.globals.updateFromPersisted(globals),this.emitGlobals()}async initializeWithStoryIndex(storyIndex){return await super.initializeWithStoryIndex(storyIndex),this.selectSpecifiedStory()}async selectSpecifiedStory(){if(!this.storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"selectSpecifiedStory"});if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new import_preview_errors4.EmptyIndexError):this.renderStoryLoadingException(storySpecifier,new import_preview_errors4.NoStoryMatchError({storySpecifier:storySpecifier.toString()}));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}),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.storeInitializationPromise,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}){let{storyStoreValue}=this;if(!storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"onPreloadStories"});await Promise.allSettled(ids.map(id=>storyStoreValue.loadEntry(id)))}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!this.storyStoreValue||!renderToCanvas)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"renderSelection"});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.storyStoreValue.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.storyStoreValue,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStoreValue,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)&&((0,import_tiny_invariant.default)(!!render.story),this.storyStoreValue.args.updateFromPersisted(render.story,persistedArgs)),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)){(0,import_tiny_invariant.default)(!!render.story);let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStoreValue.getStoryContext(render.story);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{let{parameters}=this.storyStoreValue.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new import_preview_errors4.MdxFileWithNoCsfReferencesError({storyId});({parameters}=this.storyStoreValue.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}isStoryRender(render)?((0,import_tiny_invariant.default)(!!render.story),this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))):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})}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_global6=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent8=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_dedent8.dedent`
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(importFn,getProjectAnnotations,selectionStore,view){super(importFn,getProjectAnnotations,void 0,!1);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.selectionStore=selectionStore;this.view=view;this.initialize()}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.storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"setInitialGlobals"});let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStoreValue.globals.updateFromPersisted(globals),this.emitGlobals()}async initializeWithStoryIndex(storyIndex){return await super.initializeWithStoryIndex(storyIndex),this.selectSpecifiedStory()}async selectSpecifiedStory(){if(!this.storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"selectSpecifiedStory"});if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new import_preview_errors4.EmptyIndexError):this.renderStoryLoadingException(storySpecifier,new import_preview_errors4.NoStoryMatchError({storySpecifier:storySpecifier.toString()}));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}),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.storeInitializationPromise,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 this.storeInitializationPromise,this.storyStoreValue&&await Promise.allSettled(ids.map(id=>this.storyStoreValue?.loadEntry(id)))}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!this.storyStoreValue||!renderToCanvas)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"renderSelection"});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.storyStoreValue.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.storyStoreValue,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStoreValue,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)&&((0,import_tiny_invariant.default)(!!render.story),this.storyStoreValue.args.updateFromPersisted(render.story,persistedArgs)),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)){(0,import_tiny_invariant.default)(!!render.story);let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStoreValue.getStoryContext(render.story);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{let{parameters}=this.storyStoreValue.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new import_preview_errors4.MdxFileWithNoCsfReferencesError({storyId});({parameters}=this.storyStoreValue.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}isStoryRender(render)?((0,import_tiny_invariant.default)(!!render.story),this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))):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})}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_global6=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent8=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_dedent8.dedent`
52
52
  Omitted potentially unsafe URL args.
53
53
 
54
54
  More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
55
- `),acc),{})};var{history,document:document2}=import_global6.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=""}=document2.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=""}=document2.location;document2.title=selection.storyId,history.replaceState({},"",`${document2.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(document2.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=""}=document2.location;history.replaceState({},"",`${document2.location.pathname}${query}${hash}`)}};var import_global7=require("@storybook/global"),import_client_logger13=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),import_ts_dedent9=require("ts-dedent"),import_qs3=__toESM(require("qs")),{document:document3}=import_global7.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(document3.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),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document3.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.docsRoot()}docsRoot(){return document3.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document3.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document3.body.classList.remove(this.currentLayoutClass),document3.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}checkIfLayoutExists(layout){layoutClassMap[layout]||import_client_logger13.logger.warn(import_ts_dedent9.dedent`The desired layout: ${layout} is not a valid option.
56
- The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.`)}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document3.body.classList.add(classes[otherMode]):document3.body.classList.remove(classes[otherMode])})}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
55
+ `),acc),{})};var{history,document:document2}=import_global6.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=typeof document2<"u"?document2.location.search:"",{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=""}=document2.location;document2.title=selection.storyId,history.replaceState({},"",`${document2.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=()=>{if(typeof document2<"u"){let query=import_qs2.default.parse(document2.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);if(storyId)return{storySpecifier:storyId,args,globals,viewMode}}return null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document2.location;history.replaceState({},"",`${document2.location.pathname}${query}${hash}`)}};var import_global7=require("@storybook/global"),import_client_logger13=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),import_ts_dedent9=require("ts-dedent"),import_qs3=__toESM(require("qs")),{document:document3}=import_global7.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;if(typeof document3<"u"){let{__SPECIAL_TEST_PARAMETER__}=import_qs3.default.parse(document3.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),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document3.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.docsRoot()}docsRoot(){return document3.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document3.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document3.body.classList.remove(this.currentLayoutClass),document3.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}checkIfLayoutExists(layout){layoutClassMap[layout]||import_client_logger13.logger.warn(import_ts_dedent9.dedent`
56
+ The desired layout: ${layout} is not a valid option.
57
+ The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.
58
+ `)}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document3.body.classList.add(classes[otherMode]):document3.body.classList.remove(classes[otherMode])})}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
57
59
  `);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
58
60
  `).replace(/^\n/,"")),document3.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document3.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(){document3.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(importFn,getProjectAnnotations){super(importFn,getProjectAnnotations,new UrlStore,new WebView);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;import_global8.global.__STORYBOOK_PREVIEW__=this}};var import_global9=require("@storybook/global"),{document:document4}=import_global9.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=document4.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document4.dispatchEvent(DOMContentLoadedEvent)}function insertScript($script,callback,$scriptRoot){let scriptEl=document4.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):document4.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=document4.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document4.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document4.body.appendChild($scriptsRoot));let $scripts=Array.from($container.querySelectorAll(SCRIPT));if($scripts.length){let scriptsToExecute=[];$scripts.forEach($script=>{let typeAttr=$script.getAttribute("type");(!typeAttr||runScriptTypes.includes(typeAttr))&&scriptsToExecute.push(callback=>insertScript($script,callback,$scriptsRoot))}),scriptsToExecute.length&&insertScriptsSequentially(scriptsToExecute,simulateDOMContentLoaded,void 0)}else simulateDOMContentLoaded()}0&&(module.exports={DocsContext,HooksContext,Preview,PreviewWeb,PreviewWithSelection,StoryStore,UrlStore,WebView,addons,applyHooks,combineArgs,combineParameters,composeConfigs,composeStepRunners,composeStories,composeStory,createPlaywrightTest,decorateStory,defaultDecorateStory,filterArgTypes,inferControls,makeDecorator,mockChannel,normalizeStory,prepareMeta,prepareStory,sanitizeStoryContextUpdate,setProjectAnnotations,simulateDOMContentLoaded,simulatePageLoad,sortStoriesV7,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext,userOrAutoTitle,userOrAutoTitleFromSpecifier});
package/dist/index.mjs CHANGED
@@ -65,12 +65,14 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
65
65
  `)}};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(importFn,getProjectAnnotations,channel=addons.getChannel(),shouldInitialize=!0){this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.channel=channel;this.storyRenders=[];this.storeInitializationPromise=new Promise((resolve,reject)=>{this.resolveStoreInitializationPromise=resolve,this.rejectStoreInitializationPromise=reject;}),shouldInitialize&&this.initialize();}get storyStore(){return new Proxy({},{get:(_,method)=>{if(this.storyStoreValue)return deprecate$1("Accessing the Story Store is deprecated and will be removed in 9.0"),this.storyStoreValue[method];throw new StoryStoreAccessedBeforeInitializationError}})}async initialize(){this.setupListeners();try{let projectAnnotations=await this.getProjectAnnotationsOrRenderError();await this.initializeWithProjectAnnotations(projectAnnotations);}catch(err){this.rejectStoreInitializationPromise(err);}}ready(){return this.storeInitializationPromise}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));}async getProjectAnnotationsOrRenderError(){try{let projectAnnotations=await this.getProjectAnnotations();if(this.renderToCanvas=projectAnnotations.renderToCanvas,!this.renderToCanvas)throw new MissingRenderToCanvasError;return projectAnnotations}catch(err){throw this.renderPreviewEntryError("Error reading preview.js:",err),err}}async initializeWithProjectAnnotations(projectAnnotations){this.projectAnnotationsBeforeInitialization=projectAnnotations;try{let storyIndex=await this.getStoryIndexFromServer();return this.initializeWithStoryIndex(storyIndex)}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new StoryIndexFetchError({text:await result.text()})}initializeWithStoryIndex(storyIndex){if(!this.projectAnnotationsBeforeInitialization)throw new Error("Cannot call initializeWithStoryIndex until project annotations resolve");this.storyStoreValue=new StoryStore(storyIndex,this.importFn,this.projectAnnotationsBeforeInitialization),delete this.projectAnnotationsBeforeInitialization,this.setInitialGlobals(),this.resolveStoreInitializationPromise();}async setInitialGlobals(){this.emitGlobals();}emitGlobals(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"emitGlobals"});let payload={globals:this.storyStoreValue.globals.get()||{},globalTypes:this.storyStoreValue.projectAnnotations.globalTypes||{}};this.channel.emit(SET_GLOBALS,payload);}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError,this.getProjectAnnotations=getProjectAnnotations;let projectAnnotations=await this.getProjectAnnotationsOrRenderError();if(!this.storyStoreValue){await this.initializeWithProjectAnnotations(projectAnnotations);return}this.storyStoreValue.setProjectAnnotations(projectAnnotations),this.emitGlobals();}async onStoryIndexChanged(){if(delete this.previewEntryError,!(!this.storyStoreValue&&!this.projectAnnotationsBeforeInitialization))try{let storyIndex=await this.getStoryIndexFromServer();if(this.projectAnnotationsBeforeInitialization){this.initializeWithStoryIndex(storyIndex);return}await this.onStoriesChanged({storyIndex});}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onStoriesChanged"});await this.storyStoreValue.onStoriesChanged({importFn,storyIndex});}async onUpdateGlobals({globals}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateGlobals"});this.storyStoreValue.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(GLOBALS_UPDATED,{globals:this.storyStoreValue.globals.get(),initialGlobals:this.storyStoreValue.globals.initialGlobals});}async onUpdateArgs({storyId,updatedArgs}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateArgs"});this.storyStoreValue.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId&&!r.renderOptions.forceInitialArgs).map(r=>r.rerender())),this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:this.storyStoreValue.args.get(storyId)});}async onResetArgs({storyId,argNames}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onResetArgs"});let story=this.storyRenders.find(r=>r.id===storyId)?.story||await this.storyStoreValue.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStoreValue.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||!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"renderStoryToElement"});let render=new StoryRender(this.channel,this.storyStoreValue,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 loadStory({storyId}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"loadStory"});return this.storyStoreValue.loadStory({storyId})}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"getStoryContext"});return this.storyStoreValue.getStoryContext(story,{forceInitialArgs})}async extract(options){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"extract"});if(this.previewEntryError)throw this.previewEntryError;return await this.storyStoreValue.cacheAllCSFFiles(),this.storyStoreValue.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger.error(reason),logger.error(err),this.channel.emit(CONFIG_ERROR,err);}};var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.componentStoriesFromCSFFile=csfFile=>this.store.componentStoriesFromCSFFile({csfFile});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.componentStoriesValue=[],this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.attachedCSFFiles=new Set,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");if(this.attachedCSFFiles.has(csfFile))return;this.attachedCSFFiles.add(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.attachedCSFFiles.size===0)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");let firstAttachedCSFFile=Array.from(this.attachedCSFFiles)[0];if(moduleExportType==="meta")return {type:"meta",csfFile:firstAttachedCSFFile};let{component}=firstAttachedCSFFile.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(dedent4`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(", ")}.
66
66
  - Did you pass a component to the 'of' prop when the block only supports a story or a meta?
67
67
  - ... or vice versa?
68
- - 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(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 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(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(importFn,getProjectAnnotations,selectionStore,view){super(importFn,getProjectAnnotations,void 0,!1);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.selectionStore=selectionStore;this.view=view;this.initialize();}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(PRELOAD_ENTRIES,this.onPreloadStories.bind(this));}async setInitialGlobals(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"setInitialGlobals"});let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStoreValue.globals.updateFromPersisted(globals),this.emitGlobals();}async initializeWithStoryIndex(storyIndex){return await super.initializeWithStoryIndex(storyIndex),this.selectSpecifiedStory()}async selectSpecifiedStory(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"selectSpecifiedStory"});if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new EmptyIndexError):this.renderStoryLoadingException(storySpecifier,new NoStoryMatchError({storySpecifier:storySpecifier.toString()}));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args});}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection();}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory();}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}});}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storeInitializationPromise,this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection();}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams);}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.();}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs});}async onPreloadStories({ids}){let{storyStoreValue}=this;if(!storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onPreloadStories"});await Promise.allSettled(ids.map(id=>storyStoreValue.loadEntry(id)));}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!this.storyStoreValue||!renderToCanvas)throw new CalledPreviewMethodBeforeInitializationError({methodName:"renderSelection"});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.storyStoreValue.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.storyStoreValue,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStoreValue,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)&&(invariant(!!render.story),this.storyStoreValue.args.updateFromPersisted(render.story,persistedArgs)),lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(STORY_CHANGED,storyId),isStoryRender(render)){invariant(!!render.story);let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStoreValue.getStoryContext(render.story);this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:unmappedArgs});}else {let{parameters}=this.storyStoreValue.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new MdxFileWithNoCsfReferencesError({storyId});({parameters}=this.storyStoreValue.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}));}this.channel.emit(DOCS_PREPARED,{id:storyId,parameters});}isStoryRender(render)?(invariant(!!render.story),this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))):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});}mainStoryCallbacks(storyId){return {showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err);}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(STORY_MISSING);}renderStoryLoadingException(storySpecifier,err){logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(STORY_MISSING,storySpecifier);}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),logger.error(`Error rendering story '${storyId}':`),logger.error(error));}renderError(storyId,{title,description}){logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(STORY_ERRORED,{title,description}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description});}};var VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):isPlainObject(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return !0;if(str==="!false")return !1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return `#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(qs2.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(once.warn(dedent`
68
+ - 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(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 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(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(importFn,getProjectAnnotations,selectionStore,view){super(importFn,getProjectAnnotations,void 0,!1);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.selectionStore=selectionStore;this.view=view;this.initialize();}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(PRELOAD_ENTRIES,this.onPreloadStories.bind(this));}async setInitialGlobals(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"setInitialGlobals"});let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStoreValue.globals.updateFromPersisted(globals),this.emitGlobals();}async initializeWithStoryIndex(storyIndex){return await super.initializeWithStoryIndex(storyIndex),this.selectSpecifiedStory()}async selectSpecifiedStory(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"selectSpecifiedStory"});if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new EmptyIndexError):this.renderStoryLoadingException(storySpecifier,new NoStoryMatchError({storySpecifier:storySpecifier.toString()}));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args});}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection();}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory();}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}});}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storeInitializationPromise,this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection();}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams);}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.();}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs});}async onPreloadStories({ids}){await this.storeInitializationPromise,this.storyStoreValue&&await Promise.allSettled(ids.map(id=>this.storyStoreValue?.loadEntry(id)));}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!this.storyStoreValue||!renderToCanvas)throw new CalledPreviewMethodBeforeInitializationError({methodName:"renderSelection"});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.storyStoreValue.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.storyStoreValue,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStoreValue,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)&&(invariant(!!render.story),this.storyStoreValue.args.updateFromPersisted(render.story,persistedArgs)),lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(STORY_CHANGED,storyId),isStoryRender(render)){invariant(!!render.story);let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStoreValue.getStoryContext(render.story);this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:unmappedArgs});}else {let{parameters}=this.storyStoreValue.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new MdxFileWithNoCsfReferencesError({storyId});({parameters}=this.storyStoreValue.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}));}this.channel.emit(DOCS_PREPARED,{id:storyId,parameters});}isStoryRender(render)?(invariant(!!render.story),this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))):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});}mainStoryCallbacks(storyId){return {showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err);}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(STORY_MISSING);}renderStoryLoadingException(storySpecifier,err){logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(STORY_MISSING,storySpecifier);}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),logger.error(`Error rendering story '${storyId}':`),logger.error(error));}renderError(storyId,{title,description}){logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(STORY_ERRORED,{title,description}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description});}};var VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):isPlainObject(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return !0;if(str==="!false")return !1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return `#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(qs2.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(once.warn(dedent`
69
69
  Omitted potentially unsafe URL args.
70
70
 
71
71
  More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
72
- `),acc),{})};var{history,document:document2}=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=""}=document2.location,{path,selectedKind,selectedStory,...rest}=qs2.parse(search,{ignoreQueryPrefix:!0});return qs2.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document2.location;document2.title=selection.storyId,history.replaceState({},"",`${document2.location.pathname}${query}${hash}`);},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=qs2.parse(document2.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=""}=document2.location;history.replaceState({},"",`${document2.location.pathname}${query}${hash}`);}};var import_ansi_to_html=__toESM(require_ansi_to_html());var {document:document3}=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__}=qs2.parse(document3.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}}}prepareForStory(story){return this.showStory(),this.applyLayout(story.parameters.layout),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document3.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.docsRoot()}docsRoot(){return document3.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document3.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document3.body.classList.remove(this.currentLayoutClass),document3.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass;}checkIfLayoutExists(layout){layoutClassMap[layout]||logger.warn(dedent`The desired layout: ${layout} is not a valid option.
73
- The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.`);}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document3.body.classList.add(classes[otherMode]):document3.body.classList.remove(classes[otherMode]);});}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
72
+ `),acc),{})};var{history,document:document2}=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=typeof document2<"u"?document2.location.search:"",{path,selectedKind,selectedStory,...rest}=qs2.parse(search,{ignoreQueryPrefix:!0});return qs2.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document2.location;document2.title=selection.storyId,history.replaceState({},"",`${document2.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=()=>{if(typeof document2<"u"){let query=qs2.parse(document2.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);if(storyId)return {storySpecifier:storyId,args,globals,viewMode}}return null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath();}setSelection(selection){this.selection=selection,setPath(this.selection);}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document2.location;history.replaceState({},"",`${document2.location.pathname}${query}${hash}`);}};var import_ansi_to_html=__toESM(require_ansi_to_html());var {document:document3}=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;if(typeof document3<"u"){let{__SPECIAL_TEST_PARAMETER__}=qs2.parse(document3.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}}}}prepareForStory(story){return this.showStory(),this.applyLayout(story.parameters.layout),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document3.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.docsRoot()}docsRoot(){return document3.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document3.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document3.body.classList.remove(this.currentLayoutClass),document3.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass;}checkIfLayoutExists(layout){layoutClassMap[layout]||logger.warn(dedent`
73
+ The desired layout: ${layout} is not a valid option.
74
+ The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.
75
+ `);}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document3.body.classList.add(classes[otherMode]):document3.body.classList.remove(classes[otherMode]);});}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
74
76
  `);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
75
77
  `).replace(/^\n/,"")),document3.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document3.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(){document3.body.classList.add(classes.MAIN);}};var PreviewWeb=class extends PreviewWithSelection{constructor(importFn,getProjectAnnotations){super(importFn,getProjectAnnotations,new UrlStore,new WebView);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;global.__STORYBOOK_PREVIEW__=this;}};var{document:document4}=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=document4.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document4.dispatchEvent(DOMContentLoadedEvent);}function insertScript($script,callback,$scriptRoot){let scriptEl=document4.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):document4.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=document4.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document4.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document4.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();}
76
78
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/preview-api",
3
- "version": "8.1.0-alpha.3",
3
+ "version": "8.1.0-alpha.5",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "storybook"
@@ -44,12 +44,12 @@
44
44
  "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts"
45
45
  },
46
46
  "dependencies": {
47
- "@storybook/channels": "8.1.0-alpha.3",
48
- "@storybook/client-logger": "8.1.0-alpha.3",
49
- "@storybook/core-events": "8.1.0-alpha.3",
47
+ "@storybook/channels": "8.1.0-alpha.5",
48
+ "@storybook/client-logger": "8.1.0-alpha.5",
49
+ "@storybook/core-events": "8.1.0-alpha.5",
50
50
  "@storybook/csf": "^0.1.2",
51
51
  "@storybook/global": "^5.0.0",
52
- "@storybook/types": "8.1.0-alpha.3",
52
+ "@storybook/types": "8.1.0-alpha.5",
53
53
  "@types/qs": "^6.9.5",
54
54
  "dequal": "^2.0.2",
55
55
  "lodash": "^4.17.21",
@@ -60,7 +60,7 @@
60
60
  "util-deprecate": "^1.0.2"
61
61
  },
62
62
  "devDependencies": {
63
- "@storybook/core-common": "8.1.0-alpha.3",
63
+ "@storybook/core-common": "8.1.0-alpha.5",
64
64
  "ansi-to-html": "^0.6.11",
65
65
  "slash": "^5.0.0"
66
66
  },