@storybook/preview-api 7.1.1-pr-22631-1689802540-351503cb.0 → 7.1.1-pr-23508-1689802571-5ec8c1c3.0

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/addons.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  export { makeDecorator } from './chunk-GRRYLBAT.mjs';
2
- export { AddonStore, HooksContext, addons, applyHooks, mockChannel, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-2WNKQWTL.mjs';
2
+ export { AddonStore, HooksContext, addons, applyHooks, mockChannel, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-SPTC5DZG.mjs';
@@ -1,6 +1,6 @@
1
- import { ClientApi } from './chunk-H5ZHWGYA.mjs';
2
- import { PreviewWeb } from './chunk-XDIJCHRW.mjs';
3
- import { addons } from './chunk-2WNKQWTL.mjs';
1
+ import { ClientApi } from './chunk-YYRSIG47.mjs';
2
+ import { PreviewWeb } from './chunk-RXJA4ZY6.mjs';
3
+ import { addons } from './chunk-SPTC5DZG.mjs';
4
4
  import { global } from '@storybook/global';
5
5
  import { createBrowserChannel } from '@storybook/channels';
6
6
  import { FORCE_RE_RENDER } from '@storybook/core-events';
@@ -1,4 +1,4 @@
1
- import { applyHooks, HooksContext, addons, useState, useMemo, useChannel, useEffect } from './chunk-2WNKQWTL.mjs';
1
+ import { applyHooks, HooksContext, addons, useState, useMemo, useChannel, useEffect } from './chunk-SPTC5DZG.mjs';
2
2
  import memoize2 from 'memoizerific';
3
3
  import mapValues2 from 'lodash/mapValues.js';
4
4
  import pick from 'lodash/pick.js';
@@ -1,5 +1,5 @@
1
- import { StoryStore } from './chunk-OAFZ2JF3.mjs';
2
- import { __commonJS, __toESM, addons } from './chunk-2WNKQWTL.mjs';
1
+ import { StoryStore } from './chunk-GVY4DZBB.mjs';
2
+ import { __commonJS, __toESM, addons } from './chunk-SPTC5DZG.mjs';
3
3
  import dedent2, { dedent } from 'ts-dedent';
4
4
  import { global } from '@storybook/global';
5
5
  import { SynchronousPromise } from 'synchronous-promise';
@@ -21,7 +21,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
21
21
  Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,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.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile);});}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story);});}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story);});}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile);}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return {type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return {type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return {type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return {type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type);}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(dedent2`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
22
22
  - Did you pass a component to the 'of' prop when the block only supports a story or a meta?
23
23
  - ... or vice versa?
24
- - 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.target;return /input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return !tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view;}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(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.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals();}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>(global.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()))}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(dedent`
24
+ - 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.target;return /input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return !tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view;}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(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.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals();}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>(global.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()))}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(dedent`
25
25
  Couldn't find any stories in your Storybook.
26
26
  - Please check your stories field of your main.js config.
27
27
  - Also check the browser console and terminal for error messages.
@@ -30,7 +30,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
30
30
  - Are you sure a story with that id exists?
31
31
  - Please check your stories field of your main.js config.
32
32
  - Also check the browser console and terminal for error messages.
33
- `));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}),global.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory();}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}});}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storyStore.initializationPromise,this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection();}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams);}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.();}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs});}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)));}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId);}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=this.currentSelection?.storyId!==storyId,viewModeChanged=this.currentRender?.type!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare();}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs);}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStore.getStoryContext(render.story);global.FEATURES?.storyStoreV7&&this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:unmappedArgs});}else if(global.FEATURES?.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}));}this.channel.emit(DOCS_PREPARED,{id:storyId,parameters});}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story));}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this));}async teardownRender(render,{viewModeChanged=!1}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged});}async extract(options){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent`Failed to initialize Storybook.
33
+ `));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}),global.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory();}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}});}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection();}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams);}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.();}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs});}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)));}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId);}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=this.currentSelection?.storyId!==storyId,viewModeChanged=this.currentRender?.type!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare();}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs);}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStore.getStoryContext(render.story);global.FEATURES?.storyStoreV7&&this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:unmappedArgs});}else if(global.FEATURES?.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}));}this.channel.emit(DOCS_PREPARED,{id:storyId,parameters});}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story));}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this));}async teardownRender(render,{viewModeChanged=!1}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged});}async extract(options){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent`Failed to initialize Storybook.
34
34
 
35
35
  Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}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`
36
36
  Omitted potentially unsafe URL args.
@@ -1,4 +1,4 @@
1
- import { combineParameters, normalizeInputTypes, composeStepRunners, sortStoriesV6, userOrAutoTitle } from './chunk-OAFZ2JF3.mjs';
1
+ import { combineParameters, normalizeInputTypes, composeStepRunners, sortStoriesV6, userOrAutoTitle } from './chunk-GVY4DZBB.mjs';
2
2
  import { dedent } from 'ts-dedent';
3
3
  import { global } from '@storybook/global';
4
4
  import { logger } from '@storybook/client-logger';
@@ -1,3 +1,3 @@
1
- export { ClientApi, addArgTypes, addArgTypesEnhancer, addArgs, addArgsEnhancer, addDecorator, addLoader, addParameters, addStepRunner, getQueryParam, getQueryParams, setGlobalRender } from './chunk-H5ZHWGYA.mjs';
2
- export { DEEPLY_EQUAL, StoryStore, UNTARGETED, combineArgs, combineParameters, composeConfigs, composeStepRunners, composeStories, composeStory, decorateStory, deepDiff, defaultDecorateStory, filterArgTypes, getArrayField, getField, getObjectField, getSingletonField, getValuesFromArgTypes, groupArgsByTarget, inferControls, mapArgsToTypes, noTargetArgs, normalizeComponentAnnotations, normalizeInputType, normalizeInputTypes, normalizeProjectAnnotations, normalizeStory, prepareContext, prepareMeta, prepareStory, processCSFFile, sanitizeStoryContextUpdate, setProjectAnnotations, sortStoriesV6, sortStoriesV7, useAddonState, useSharedState, userOrAutoTitle, userOrAutoTitleFromSpecifier, validateOptions } from './chunk-OAFZ2JF3.mjs';
3
- export { HooksContext, applyHooks, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-2WNKQWTL.mjs';
1
+ export { ClientApi, addArgTypes, addArgTypesEnhancer, addArgs, addArgsEnhancer, addDecorator, addLoader, addParameters, addStepRunner, getQueryParam, getQueryParams, setGlobalRender } from './chunk-YYRSIG47.mjs';
2
+ export { DEEPLY_EQUAL, StoryStore, UNTARGETED, combineArgs, combineParameters, composeConfigs, composeStepRunners, composeStories, composeStory, decorateStory, deepDiff, defaultDecorateStory, filterArgTypes, getArrayField, getField, getObjectField, getSingletonField, getValuesFromArgTypes, groupArgsByTarget, inferControls, mapArgsToTypes, noTargetArgs, normalizeComponentAnnotations, normalizeInputType, normalizeInputTypes, normalizeProjectAnnotations, normalizeStory, prepareContext, prepareMeta, prepareStory, processCSFFile, sanitizeStoryContextUpdate, setProjectAnnotations, sortStoriesV6, sortStoriesV7, useAddonState, useSharedState, userOrAutoTitle, userOrAutoTitleFromSpecifier, validateOptions } from './chunk-GVY4DZBB.mjs';
3
+ export { HooksContext, applyHooks, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-SPTC5DZG.mjs';
@@ -59,7 +59,7 @@ Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.m
59
59
  Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger12.logger.error(reason),import_client_logger12.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global10=require("@storybook/global");var import_ts_dedent12=require("ts-dedent"),import_global7=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger13=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var import_ts_dedent11=__toESM(require("ts-dedent")),DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent11.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
60
60
  - Did you pass a component to the 'of' prop when the block only supports a story or a meta?
61
61
  - ... or vice versa?
62
- - Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta: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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG2="autodocs",STORIES_MDX_TAG2="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG2))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG2))}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent12.dedent`
62
+ - Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta: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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG2="autodocs",STORIES_MDX_TAG2="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG2))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG2))}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent12.dedent`
63
63
  Couldn't find any stories in your Storybook.
64
64
  - Please check your stories field of your main.js config.
65
65
  - Also check the browser console and terminal for error messages.
@@ -68,7 +68,7 @@ Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.m
68
68
  - Are you sure a story with that id exists?
69
69
  - Please check your stories field of your main.js config.
70
70
  - Also check the browser console and terminal for error messages.
71
- `));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storyStore.initializationPromise,this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d,_e,_f;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStore.getStoryContext(render.story);(_d=import_global7.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args:unmappedArgs})}else if((_e=import_global7.global.FEATURES)!=null&&_e.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||(_f=render.entry.tags)!=null&&_f.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent12.dedent`Failed to initialize Storybook.
71
+ `));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d,_e,_f;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStore.getStoryContext(render.story);(_d=import_global7.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args:unmappedArgs})}else if((_e=import_global7.global.FEATURES)!=null&&_e.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||(_f=render.entry.tags)!=null&&_f.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent12.dedent`Failed to initialize Storybook.
72
72
 
73
73
  Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger13.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),(_a=error.message)!=null&&_a.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger13.logger.error(`Error rendering story '${storyId}':`),import_client_logger13.logger.error(error))}renderError(storyId,{title,description}){import_client_logger13.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global8=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent13=require("ts-dedent"),import_client_logger14=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject.js")),VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):(0,import_isPlainObject3.default)(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return!0;if(str==="!false")return!1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(import_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger14.once.warn(import_ts_dedent13.dedent`
74
74
  Omitted potentially unsafe URL args.
@@ -1,6 +1,6 @@
1
- export { start } from './chunk-D3HXM23F.mjs';
1
+ export { start } from './chunk-27FDX377.mjs';
2
2
  import './chunk-GRRYLBAT.mjs';
3
- export { ClientApi } from './chunk-H5ZHWGYA.mjs';
4
- import './chunk-XDIJCHRW.mjs';
5
- export { StoryStore } from './chunk-OAFZ2JF3.mjs';
6
- import './chunk-2WNKQWTL.mjs';
3
+ export { ClientApi } from './chunk-YYRSIG47.mjs';
4
+ import './chunk-RXJA4ZY6.mjs';
5
+ export { StoryStore } from './chunk-GVY4DZBB.mjs';
6
+ import './chunk-SPTC5DZG.mjs';
package/dist/index.js CHANGED
@@ -52,7 +52,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
52
52
  Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger10.logger.error(reason),import_client_logger10.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global9=require("@storybook/global");var import_ts_dedent10=require("ts-dedent"),import_global6=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger11=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var import_ts_dedent9=__toESM(require("ts-dedent")),DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent9.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
53
53
  - Did you pass a component to the 'of' prop when the block only supports a story or a meta?
54
54
  - ... or vice versa?
55
- - Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta: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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent10.dedent`
55
+ - Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta: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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent10.dedent`
56
56
  Couldn't find any stories in your Storybook.
57
57
  - Please check your stories field of your main.js config.
58
58
  - Also check the browser console and terminal for error messages.
@@ -61,7 +61,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
61
61
  - Are you sure a story with that id exists?
62
62
  - Please check your stories field of your main.js config.
63
63
  - Also check the browser console and terminal for error messages.
64
- `));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storyStore.initializationPromise,this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d,_e,_f;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStore.getStoryContext(render.story);(_d=import_global6.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args:unmappedArgs})}else if((_e=import_global6.global.FEATURES)!=null&&_e.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||(_f=render.entry.tags)!=null&&_f.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent10.dedent`Failed to initialize Storybook.
64
+ `));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d,_e,_f;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStore.getStoryContext(render.story);(_d=import_global6.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args:unmappedArgs})}else if((_e=import_global6.global.FEATURES)!=null&&_e.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||(_f=render.entry.tags)!=null&&_f.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent10.dedent`Failed to initialize Storybook.
65
65
 
66
66
  Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger11.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),(_a=error.message)!=null&&_a.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger11.logger.error(`Error rendering story '${storyId}':`),import_client_logger11.logger.error(error))}renderError(storyId,{title,description}){import_client_logger11.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global7=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent11=require("ts-dedent"),import_client_logger12=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject.js")),VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):(0,import_isPlainObject3.default)(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return!0;if(str==="!false")return!1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(import_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger12.once.warn(import_ts_dedent11.dedent`
67
67
  Omitted potentially unsafe URL args.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- export { start } from './chunk-D3HXM23F.mjs';
1
+ export { start } from './chunk-27FDX377.mjs';
2
2
  export { makeDecorator } from './chunk-GRRYLBAT.mjs';
3
- export { ClientApi, addArgTypes, addArgTypesEnhancer, addArgs, addArgsEnhancer, addDecorator, addLoader, addParameters, addStepRunner, getQueryParam, getQueryParams, setGlobalRender } from './chunk-H5ZHWGYA.mjs';
4
- export { DocsContext, Preview, PreviewWeb, simulateDOMContentLoaded, simulatePageLoad } from './chunk-XDIJCHRW.mjs';
5
- export { StoryStore, combineArgs, combineParameters, composeConfigs, composeStepRunners, composeStories, composeStory, decorateStory, defaultDecorateStory, filterArgTypes, inferControls, normalizeStory, prepareMeta, prepareStory, sanitizeStoryContextUpdate, setProjectAnnotations, sortStoriesV7, userOrAutoTitle, userOrAutoTitleFromSpecifier } from './chunk-OAFZ2JF3.mjs';
6
- export { HooksContext, addons, applyHooks, mockChannel, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-2WNKQWTL.mjs';
3
+ export { ClientApi, addArgTypes, addArgTypesEnhancer, addArgs, addArgsEnhancer, addDecorator, addLoader, addParameters, addStepRunner, getQueryParam, getQueryParams, setGlobalRender } from './chunk-YYRSIG47.mjs';
4
+ export { DocsContext, Preview, PreviewWeb, simulateDOMContentLoaded, simulatePageLoad } from './chunk-RXJA4ZY6.mjs';
5
+ export { StoryStore, combineArgs, combineParameters, composeConfigs, composeStepRunners, composeStories, composeStory, decorateStory, defaultDecorateStory, filterArgTypes, inferControls, normalizeStory, prepareMeta, prepareStory, sanitizeStoryContextUpdate, setProjectAnnotations, sortStoriesV7, userOrAutoTitle, userOrAutoTitleFromSpecifier } from './chunk-GVY4DZBB.mjs';
6
+ export { HooksContext, addons, applyHooks, mockChannel, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-SPTC5DZG.mjs';
@@ -37,7 +37,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
37
37
  Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger9.logger.error(reason),import_client_logger9.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global9=require("@storybook/global");var import_ts_dedent8=require("ts-dedent"),import_global6=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger10=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var import_ts_dedent7=__toESM(require("ts-dedent")),DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");this.attachedCSFFile=csfFile,this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(!this.attachedCSFFile)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");if(moduleExportType==="meta")return{type:"meta",csfFile:this.attachedCSFFile};let{component}=this.attachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent7.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
38
38
  - Did you pass a component to the 'of' prop when the block only supports a story or a meta?
39
39
  - ... or vice versa?
40
- - Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta: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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent8.dedent`
40
+ - Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta: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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.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}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent8.dedent`
41
41
  Couldn't find any stories in your Storybook.
42
42
  - Please check your stories field of your main.js config.
43
43
  - Also check the browser console and terminal for error messages.
@@ -46,7 +46,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
46
46
  - Are you sure a story with that id exists?
47
47
  - Please check your stories field of your main.js config.
48
48
  - Also check the browser console and terminal for error messages.
49
- `));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storyStore.initializationPromise,this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d,_e,_f;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStore.getStoryContext(render.story);(_d=import_global6.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args:unmappedArgs})}else if((_e=import_global6.global.FEATURES)!=null&&_e.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||(_f=render.entry.tags)!=null&&_f.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent8.dedent`Failed to initialize Storybook.
49
+ `));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d,_e,_f;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),(_c=this.currentRender)!=null&&_c.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStore,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStore,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStore.getStoryContext(render.story);(_d=import_global6.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args:unmappedArgs})}else if((_e=import_global6.global.FEATURES)!=null&&_e.storyStoreV7){if(!this.storyStore.projectAnnotations)throw new Error("Store not initialized");let{parameters}=this.storyStore.projectAnnotations;if(isCsfDocsRender(render)||(_f=render.entry.tags)!=null&&_f.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new Error("Render not prepared, or attached MDX file has no CSF references");({parameters}=this.storyStore.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent8.dedent`Failed to initialize Storybook.
50
50
 
51
51
  Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger10.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){var _a;let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),(_a=error.message)!=null&&_a.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger10.logger.error(`Error rendering story '${storyId}':`),import_client_logger10.logger.error(error))}renderError(storyId,{title,description}){import_client_logger10.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global7=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent9=require("ts-dedent"),import_client_logger11=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject.js")),VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):(0,import_isPlainObject3.default)(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return!0;if(str==="!false")return!1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(import_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger11.once.warn(import_ts_dedent9.dedent`
52
52
  Omitted potentially unsafe URL args.
@@ -1,3 +1,3 @@
1
- export { DocsContext, Preview, PreviewWeb, PreviewWithSelection, simulateDOMContentLoaded, simulatePageLoad } from './chunk-XDIJCHRW.mjs';
2
- export { composeConfigs } from './chunk-OAFZ2JF3.mjs';
3
- import './chunk-2WNKQWTL.mjs';
1
+ export { DocsContext, Preview, PreviewWeb, PreviewWithSelection, simulateDOMContentLoaded, simulatePageLoad } from './chunk-RXJA4ZY6.mjs';
2
+ export { composeConfigs } from './chunk-GVY4DZBB.mjs';
3
+ import './chunk-SPTC5DZG.mjs';
package/dist/store.mjs CHANGED
@@ -1,2 +1,2 @@
1
- export { DEEPLY_EQUAL, StoryStore, UNTARGETED, combineArgs, combineParameters, composeConfigs, composeStepRunners, composeStories, composeStory, decorateStory, deepDiff, defaultDecorateStory, filterArgTypes, getArrayField, getField, getObjectField, getSingletonField, getValuesFromArgTypes, groupArgsByTarget, inferControls, mapArgsToTypes, noTargetArgs, normalizeComponentAnnotations, normalizeInputType, normalizeInputTypes, normalizeProjectAnnotations, normalizeStory, prepareContext, prepareMeta, prepareStory, processCSFFile, sanitizeStoryContextUpdate, setProjectAnnotations, sortStoriesV6, sortStoriesV7, useAddonState, useSharedState, userOrAutoTitle, userOrAutoTitleFromSpecifier, validateOptions } from './chunk-OAFZ2JF3.mjs';
2
- export { HooksContext, applyHooks, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-2WNKQWTL.mjs';
1
+ export { DEEPLY_EQUAL, StoryStore, UNTARGETED, combineArgs, combineParameters, composeConfigs, composeStepRunners, composeStories, composeStory, decorateStory, deepDiff, defaultDecorateStory, filterArgTypes, getArrayField, getField, getObjectField, getSingletonField, getValuesFromArgTypes, groupArgsByTarget, inferControls, mapArgsToTypes, noTargetArgs, normalizeComponentAnnotations, normalizeInputType, normalizeInputTypes, normalizeProjectAnnotations, normalizeStory, prepareContext, prepareMeta, prepareStory, processCSFFile, sanitizeStoryContextUpdate, setProjectAnnotations, sortStoriesV6, sortStoriesV7, useAddonState, useSharedState, userOrAutoTitle, userOrAutoTitleFromSpecifier, validateOptions } from './chunk-GVY4DZBB.mjs';
2
+ export { HooksContext, applyHooks, useArgs, useCallback, useChannel, useEffect, useGlobals, useMemo, useParameter, useReducer, useRef, useState, useStoryContext } from './chunk-SPTC5DZG.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/preview-api",
3
- "version": "7.1.1-pr-22631-1689802540-351503cb.0",
3
+ "version": "7.1.1-pr-23508-1689802571-5ec8c1c3.0",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "storybook"
@@ -63,16 +63,17 @@
63
63
  "*.d.ts"
64
64
  ],
65
65
  "scripts": {
66
- "check": "../../../scripts/prepare/check.ts",
66
+ "check": "../../../scripts/node_modules/.bin/tsc --noEmit",
67
67
  "prep": "../../../scripts/prepare/bundle.ts"
68
68
  },
69
69
  "dependencies": {
70
- "@storybook/channels": "7.1.1-pr-22631-1689802540-351503cb.0",
71
- "@storybook/client-logger": "7.1.1-pr-22631-1689802540-351503cb.0",
72
- "@storybook/core-events": "7.1.1-pr-22631-1689802540-351503cb.0",
70
+ "@storybook/channel-postmessage": "7.1.1-pr-23508-1689802571-5ec8c1c3.0",
71
+ "@storybook/channels": "7.1.1-pr-23508-1689802571-5ec8c1c3.0",
72
+ "@storybook/client-logger": "7.1.1-pr-23508-1689802571-5ec8c1c3.0",
73
+ "@storybook/core-events": "7.1.1-pr-23508-1689802571-5ec8c1c3.0",
73
74
  "@storybook/csf": "^0.1.0",
74
75
  "@storybook/global": "^5.0.0",
75
- "@storybook/types": "7.1.1-pr-22631-1689802540-351503cb.0",
76
+ "@storybook/types": "7.1.1-pr-23508-1689802571-5ec8c1c3.0",
76
77
  "@types/qs": "^6.9.5",
77
78
  "dequal": "^2.0.2",
78
79
  "lodash": "^4.17.21",
@@ -84,7 +85,7 @@
84
85
  },
85
86
  "devDependencies": {
86
87
  "@jest/globals": "^29.5.0",
87
- "@storybook/core-common": "7.1.1-pr-22631-1689802540-351503cb.0",
88
+ "@storybook/core-common": "7.1.1-pr-23508-1689802571-5ec8c1c3.0",
88
89
  "ansi-to-html": "^0.6.11",
89
90
  "react": "^16.14.0",
90
91
  "slash": "^5.0.0"
File without changes