@storybook/preview-api 7.0.0-beta.16 → 7.0.0-beta.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DocsContext-b4bac20d.d.ts → DocsContext-917299b8.d.ts} +9 -8
- package/dist/{chunk-5OCY6AJW.mjs → chunk-HF5EPGVY.mjs} +2 -2
- package/dist/{chunk-GUZU4M6E.mjs → chunk-JHDSJNE7.mjs} +1 -1
- package/dist/{chunk-UBOQW2R4.mjs → chunk-UAUKVCSL.mjs} +2 -2
- package/dist/client-api.js +2 -2
- package/dist/client-api.mjs +1 -1
- package/dist/core-client.js +4 -4
- package/dist/core-client.mjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -4
- package/dist/index.mjs +1 -1
- package/dist/preview-web.d.ts +1 -1
- package/dist/preview-web.js +2 -2
- package/dist/preview-web.mjs +1 -1
- package/package.json +8 -8
|
@@ -62,18 +62,18 @@ declare class StoryRender<TRenderer extends Renderer> implements Render<TRendere
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
/**
|
|
65
|
-
* A
|
|
65
|
+
* A CsfDocsRender is a render of a docs entry that is rendered based on a CSF file.
|
|
66
66
|
*
|
|
67
67
|
* The expectation is the primary CSF file which is the `importPath` for the entry will
|
|
68
68
|
* define a story which may contain the actual rendered JSX code for the template in the
|
|
69
69
|
* `docs.page` parameter.
|
|
70
70
|
*
|
|
71
71
|
* Use cases:
|
|
72
|
-
* -
|
|
72
|
+
* - Autodocs, where there is no story, and we fall back to the globally defined template.
|
|
73
73
|
* - *.stories.mdx files, where the MDX compiler produces a CSF file with a `.parameter.docs.page`
|
|
74
74
|
* parameter containing the compiled content of the MDX file.
|
|
75
75
|
*/
|
|
76
|
-
declare class
|
|
76
|
+
declare class CsfDocsRender<TRenderer extends Renderer> implements Render<TRenderer> {
|
|
77
77
|
protected channel: Channel;
|
|
78
78
|
protected store: StoryStore<TRenderer>;
|
|
79
79
|
entry: IndexEntry;
|
|
@@ -99,14 +99,15 @@ declare class TemplateDocsRender<TRenderer extends Renderer> implements Render<T
|
|
|
99
99
|
}
|
|
100
100
|
|
|
101
101
|
/**
|
|
102
|
-
* A
|
|
102
|
+
* A MdxDocsRender is a render of a docs entry that comes from a true MDX file,
|
|
103
|
+
* that is a `.mdx` file that doesn't get compiled to a CSF file.
|
|
103
104
|
*
|
|
104
|
-
* A
|
|
105
|
+
* A MDX render can reference (import) zero or more CSF files that contain stories.
|
|
105
106
|
*
|
|
106
107
|
* Use cases:
|
|
107
108
|
* - *.mdx file that may or may not reference a specific CSF file with `<Meta of={} />`
|
|
108
109
|
*/
|
|
109
|
-
declare class
|
|
110
|
+
declare class MdxDocsRender<TRenderer extends Renderer> implements Render<TRenderer> {
|
|
110
111
|
protected channel: Channel;
|
|
111
112
|
protected store: StoryStore<TRenderer>;
|
|
112
113
|
entry: IndexEntry;
|
|
@@ -178,7 +179,7 @@ declare class Preview<TFramework extends Renderer> {
|
|
|
178
179
|
storyId: StoryId;
|
|
179
180
|
}): Promise<void>;
|
|
180
181
|
renderStoryToElement(story: PreparedStory<TFramework>, element: TFramework['canvasElement'], options: StoryRenderOptions): () => Promise<void>;
|
|
181
|
-
teardownRender(render: StoryRender<TFramework> |
|
|
182
|
+
teardownRender(render: StoryRender<TFramework> | CsfDocsRender<TFramework> | MdxDocsRender<TFramework>, { viewModeChanged }?: {
|
|
182
183
|
viewModeChanged?: boolean;
|
|
183
184
|
}): Promise<void>;
|
|
184
185
|
extract(options?: {
|
|
@@ -230,7 +231,7 @@ interface View<TStorybookRoot> {
|
|
|
230
231
|
showStoryDuringRender(): void;
|
|
231
232
|
}
|
|
232
233
|
|
|
233
|
-
type PossibleRender<TFramework extends Renderer> = StoryRender<TFramework> |
|
|
234
|
+
type PossibleRender<TFramework extends Renderer> = StoryRender<TFramework> | CsfDocsRender<TFramework> | MdxDocsRender<TFramework>;
|
|
234
235
|
declare class PreviewWithSelection<TFramework extends Renderer> extends Preview<TFramework> {
|
|
235
236
|
selectionStore: SelectionStore;
|
|
236
237
|
view: View<TFramework['canvasElement']>;
|
|
@@ -8,7 +8,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
8
8
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
9
9
|
`);return projectAnnotations}).catch(err=>{throw this.renderPreviewEntryError("Error reading preview.js:",err),err})}initializeWithProjectAnnotations(projectAnnotations){this.storyStore.setProjectAnnotations(projectAnnotations),this.setInitialGlobals();let storyIndexPromise;if(global.FEATURES?.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=SynchronousPromise.resolve().then(this.getStoryIndex)}return storyIndexPromise.then(storyIndex=>this.initializeWithStoryIndex(storyIndex)).catch(err=>{throw this.renderPreviewEntryError("Error loading story index:",err),err})}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStore.globals||!this.storyStore.projectAnnotations)throw new Error("Cannot emit before initialization");let payload={globals:this.storyStore.globals.get()||{},globalTypes:this.storyStore.projectAnnotations.globalTypes||{}};this.channel.emit(SET_GLOBALS,payload)}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new Error(await result.text())}initializeWithStoryIndex(storyIndex){if(!this.importFn)throw new Error("Cannot call initializeWithStoryIndex before initialization");return this.storyStore.initialize({storyIndex,importFn:this.importFn,cache:!global.FEATURES?.storyStoreV7})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError;let projectAnnotations=await this.getProjectAnnotationsOrRenderError(getProjectAnnotations);if(!this.storyStore.projectAnnotations){await this.initializeWithProjectAnnotations(projectAnnotations);return}await this.storyStore.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!!this.storyStore.projectAnnotations)try{let storyIndex=await this.getStoryIndexFromServer();this.storyStore.storyIndex||await this.initializeWithStoryIndex(storyIndex),await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){await this.storyStore.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(GLOBALS_UPDATED,{globals:this.storyStore.globals.get(),initialGlobals:this.storyStore.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){this.storyStore.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.rerender())),this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){let story=this.storyRenders.find(r=>r.id===storyId)?.story||await this.storyStore.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStore.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs})}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()))}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()))}renderStoryToElement(story,element,options){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,this.inlineStoryCallbacks(story.id),story.id,"docs",options,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render)}}async teardownRender(render,{viewModeChanged}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged})}async extract(options){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent`Failed to initialize Storybook.
|
|
10
10
|
|
|
11
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>logger2.error(`Error rendering docs story (${storyId})`,err),showException:err=>logger2.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger2.error(reason),logger2.error(err),this.channel.emit(CONFIG_ERROR,err)}};import{global as global5}from"@storybook/global";import{dedent as dedent2}from"ts-dedent";import{global as global2}from"@storybook/global";import{CURRENT_STORY_WAS_SET,PRELOAD_ENTRIES,PREVIEW_KEYDOWN,SET_CURRENT_STORY,SET_INDEX,STORY_ARGS_UPDATED as STORY_ARGS_UPDATED2,STORY_CHANGED,STORY_ERRORED,STORY_MISSING,STORY_PREPARED,STORY_RENDER_PHASE_CHANGED as STORY_RENDER_PHASE_CHANGED2,STORY_SPECIFIED,STORY_THREW_EXCEPTION,STORY_UNCHANGED,UPDATE_QUERY_PARAMS}from"@storybook/core-events";import{logger as logger3}from"@storybook/client-logger";import{DOCS_RENDERED}from"@storybook/core-events";var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}};var
|
|
11
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>logger2.error(`Error rendering docs story (${storyId})`,err),showException:err=>logger2.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger2.error(reason),logger2.error(err),this.channel.emit(CONFIG_ERROR,err)}};import{global as global5}from"@storybook/global";import{dedent as dedent2}from"ts-dedent";import{global as global2}from"@storybook/global";import{CURRENT_STORY_WAS_SET,PRELOAD_ENTRIES,PREVIEW_KEYDOWN,SET_CURRENT_STORY,SET_INDEX,STORY_ARGS_UPDATED as STORY_ARGS_UPDATED2,STORY_CHANGED,STORY_ERRORED,STORY_MISSING,STORY_PREPARED,STORY_RENDER_PHASE_CHANGED as STORY_RENDER_PHASE_CHANGED2,STORY_SPECIFIED,STORY_THREW_EXCEPTION,STORY_UNCHANGED,UPDATE_QUERY_PARAMS}from"@storybook/core-events";import{logger as logger3}from"@storybook/client-logger";import{DOCS_RENDERED}from"@storybook/core-events";var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}};var CsfDocsRender=class{constructor(channel,store,entry){this.channel=channel;this.store=store;this.entry=entry;this.type="docs";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!0),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};import{DOCS_RENDERED as DOCS_RENDERED2}from"@storybook/core-events";var MdxDocsRender=class{constructor(channel,store,entry){this.channel=channel;this.store=store;this.entry=entry;this.type="docs";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.exports&&this.exports===other.exports)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!1),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(DOCS_RENDERED2,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}function isStoryRender(r){return r.type==="story"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}initializeWithProjectAnnotations(projectAnnotations){return super.initializeWithProjectAnnotations(projectAnnotations).then(()=>this.setInitialGlobals())}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>(global2.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()))}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(dedent2`
|
|
12
12
|
Couldn't find any stories in your Storybook.
|
|
13
13
|
- Please check your stories field of your main.js config.
|
|
14
14
|
- Also check the browser console and terminal for error messages.
|
|
@@ -17,7 +17,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
17
17
|
- Are you sure a story with that id exists?
|
|
18
18
|
- Please check your stories field of your main.js config.
|
|
19
19
|
- Also check the browser console and terminal for error messages.
|
|
20
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),global2.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof
|
|
20
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),global2.FEATURES?.storyStoreV7||this.channel.emit(SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.()}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=this.currentSelection?.storyId!==storyId,viewModeChanged=this.currentRender?.type!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs(),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):render=new CsfDocsRender(this.channel,this.storyStore,entry);let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);global2.FEATURES?.storyStoreV7&&this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED2,{storyId,args})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged})}async extract(options){if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(dedent2`Failed to initialize Storybook.
|
|
21
21
|
|
|
22
22
|
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return global2.FEATURES?.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>logger3.error(`Error rendering docs story (${storyId})`,err),showException:err=>logger3.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){logger3.error(err),this.view.showErrorDisplay(err),this.channel.emit(STORY_MISSING,storySpecifier)}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(STORY_RENDER_PHASE_CHANGED2,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),logger3.error(`Error rendering story '${storyId}':`),logger3.error(error))}renderError(storyId,{title,description}){logger3.error(`Error rendering story ${title}: ${description}`),this.channel.emit(STORY_ERRORED,{title,description}),this.channel.emit(STORY_RENDER_PHASE_CHANGED2,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};import{global as global3}from"@storybook/global";import qs2 from"qs";import qs from"qs";import{dedent as dedent3}from"ts-dedent";import{once}from"@storybook/client-logger";import isPlainObject from"lodash/isPlainObject";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.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(qs.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(once.warn(dedent3`
|
|
23
23
|
Omitted potentially unsafe URL args.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ClientApi}from"./chunk-
|
|
1
|
+
import{ClientApi}from"./chunk-UAUKVCSL.mjs";import{PreviewWeb}from"./chunk-HF5EPGVY.mjs";import{addons}from"./chunk-RTGEOU4B.mjs";import{global}from"@storybook/global";import{createChannel}from"@storybook/channel-postmessage";import{FORCE_RE_RENDER}from"@storybook/core-events";import{logger}from"@storybook/client-logger";function executeLoadable(loadable){let reqs=null;Array.isArray(loadable)?reqs=loadable:loadable.keys&&(reqs=[loadable]);let exportsMap=new Map;if(reqs)reqs.forEach(req=>{req.keys().forEach(filename=>{try{let fileExports=req(filename);exportsMap.set(typeof req.resolve=="function"?req.resolve(filename):filename,fileExports)}catch(error){let errorString=error.message&&error.stack?`${error.message}
|
|
2
2
|
${error.stack}`:error.toString();logger.error(`Unexpected error while loading ${filename}: ${errorString}`)}})});else{let exported=loadable();Array.isArray(exported)&&exported.every(obj=>obj.default!=null)?exportsMap=new Map(exported.map((fileExports,index)=>[`exports-map-${index}`,fileExports])):exported&&logger.warn(`Loader function passed to 'configure' should return void or an array of module exports that all contain a 'default' export. Received: ${JSON.stringify(exported)}`)}return exportsMap}function executeLoadableForChanges(loadable,m){let lastExportsMap=m?.hot?.data?.lastExportsMap||new Map;m?.hot?.dispose&&(m.hot.accept(),m.hot.dispose(data=>{data.lastExportsMap=lastExportsMap}));let exportsMap=executeLoadable(loadable),added=new Map;Array.from(exportsMap.entries()).filter(([,fileExports])=>!!fileExports.default).filter(([fileName,fileExports])=>lastExportsMap.get(fileName)!==fileExports).forEach(([fileName,fileExports])=>added.set(fileName,fileExports));let removed=new Map;return Array.from(lastExportsMap.keys()).filter(fileName=>!exportsMap.has(fileName)).forEach(fileName=>{let value=lastExportsMap.get(fileName);value&&removed.set(fileName,value)}),lastExportsMap=exportsMap,{added,removed}}var{FEATURES}=global,removedApi=name=>()=>{throw new Error(`@storybook/client-api:${name} was removed in storyStoreV7.`)};function start(renderToCanvas,{decorateStory,render}={}){if(global&&(global.IS_STORYBOOK=!0),FEATURES?.storyStoreV7)return{forceReRender:removedApi("forceReRender"),configure:removedApi("configure"),clientApi:{storiesOf:removedApi("clientApi.storiesOf"),raw:removedApi("raw")}};let channel=createChannel({page:"preview"});addons.setChannel(channel);let clientApi=global?.__STORYBOOK_CLIENT_API__||new ClientApi,preview=global?.__STORYBOOK_PREVIEW__||new PreviewWeb,initialized=!1,importFn=path=>clientApi.importFn(path);function onStoriesChanged(){let storyIndex=clientApi.getStoryIndex();preview.onStoriesChanged({storyIndex,importFn})}return clientApi.onImportFnChanged=onStoriesChanged,clientApi.storyStore=preview.storyStore,global&&(global.__STORYBOOK_CLIENT_API__=clientApi,global.__STORYBOOK_ADDONS_CHANNEL__=channel,global.__STORYBOOK_PREVIEW__=preview,global.__STORYBOOK_STORY_STORE__=preview.storyStore),{forceReRender:()=>channel.emit(FORCE_RE_RENDER),clientApi,configure(framework,loadable,m,disableBackwardCompatibility=!0){if(disableBackwardCompatibility)throw new Error("unexpected configure() call");clientApi.addParameters({framework});let getProjectAnnotations=()=>{let{added,removed}=executeLoadableForChanges(loadable,m);return clientApi._loadAddedExports(),Array.from(added.entries()).forEach(([fileName,fileExports])=>clientApi.facade.addStoriesFromExports(fileName,fileExports)),Array.from(removed.entries()).forEach(([fileName])=>clientApi.facade.clearFilenameExports(fileName)),{render,...clientApi.facade.projectAnnotations,renderToCanvas,applyDecorators:decorateStory}};initialized?(getProjectAnnotations(),onStoriesChanged()):(preview.initialize({getStoryIndex:()=>clientApi.getStoryIndex(),importFn,getProjectAnnotations}),initialized=!0)}}}export{start};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{combineParameters,composeStepRunners,normalizeInputTypes,sortStoriesV6,userOrAutoTitle}from"./chunk-RRZ2SPWM.mjs";import{dedent as dedent2}from"ts-dedent";import{global as global2}from"@storybook/global";import{logger as logger2}from"@storybook/client-logger";import{toId as toId2,sanitize}from"@storybook/csf";import{global}from"@storybook/global";import{dedent}from"ts-dedent";import{SynchronousPromise}from"synchronous-promise";import{toId,isExportStory,storyNameFromExport}from"@storybook/csf";import{logger}from"@storybook/client-logger";var StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){let fileNameOrder=Object.keys(this.csfExports),storySortParameter=this.projectAnnotations.parameters?.options?.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:toId(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(dedent`
|
|
1
|
+
import{combineParameters,composeStepRunners,normalizeInputTypes,sortStoriesV6,userOrAutoTitle}from"./chunk-RRZ2SPWM.mjs";import{dedent as dedent2}from"ts-dedent";import{global as global2}from"@storybook/global";import{logger as logger2}from"@storybook/client-logger";import{toId as toId2,sanitize}from"@storybook/csf";import{global}from"@storybook/global";import{dedent}from"ts-dedent";import{SynchronousPromise}from"synchronous-promise";import{toId,isExportStory,storyNameFromExport}from"@storybook/csf";import{logger}from"@storybook/client-logger";var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){let fileNameOrder=Object.keys(this.csfExports),storySortParameter=this.projectAnnotations.parameters?.options?.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:toId(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(dedent`
|
|
2
2
|
Error sorting stories with sort parameter ${storySortParameter}:
|
|
3
3
|
|
|
4
4
|
> ${err.message}
|
|
@@ -6,7 +6,7 @@ import{combineParameters,composeStepRunners,normalizeInputTypes,sortStoriesV6,us
|
|
|
6
6
|
Are you using a V7-style sort function in V6 compatibility mode?
|
|
7
7
|
|
|
8
8
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
9
|
-
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>isExportStory(key,defaultExport)),docsOptions=global.DOCS_OPTIONS||{},
|
|
9
|
+
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>isExportStory(key,defaultExport)),docsOptions=global.DOCS_OPTIONS||{},{autodocs}=docsOptions,componentAutodocs=componentTags.includes(AUTODOCS_TAG),autodocsOptedIn=autodocs===!0||autodocs==="tag"&&componentAutodocs;if(!docsOptions.disable&&storyExports.length&&(componentTags.includes(STORIES_MDX_TAG)||autodocsOptedIn)){let name=docsOptions.defaultName,docsId=toId(componentId||title,name);this.entries[docsId]={type:"docs",id:docsId,title,name,importPath:fileName,...componentId&&{componentId},tags:[...componentTags,"docs",...autodocsOptedIn&&!componentAutodocs?[AUTODOCS_TAG]:[]],storiesImports:[]}}storyExports.forEach(([key,storyExport])=>{let exportName=storyNameFromExport(key),id=storyExport.parameters?.__id||toId(componentId||title,exportName),name=typeof storyExport!="function"&&storyExport.name||storyExport.storyName||storyExport.story?.name||exportName;storyExport.parameters?.docsOnly||(this.entries[id]={type:"story",id,name,title,importPath:fileName,...componentId&&{componentId},tags:[...storyExport.tags||componentTags,"story"]})})}};var warningAlternatives={addDecorator:"Instead, use `export const decorators = [];` in your `preview.js`.",addParameters:"Instead, use `export const parameters = {};` in your `preview.js`.",addLoader:"Instead, use `export const loaders = [];` in your `preview.js`.",addArgs:"",addArgTypes:"",addArgsEnhancer:"",addArgTypesEnhancer:"",addStepRunner:"",getGlobalRender:"",setGlobalRender:""},checkMethod=method=>{if(global2.FEATURES?.storyStoreV7)throw new Error(dedent2`You cannot use \`${method}\` with the new Story Store.
|
|
10
10
|
|
|
11
11
|
${warningAlternatives[method]}`);if(!global2.__STORYBOOK_CLIENT_API__)throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`)},addDecorator=decorator=>{checkMethod("addDecorator"),global2.__STORYBOOK_CLIENT_API__?.addDecorator(decorator)},addParameters=parameters=>{checkMethod("addParameters"),global2.__STORYBOOK_CLIENT_API__?.addParameters(parameters)},addLoader=loader=>{checkMethod("addLoader"),global2.__STORYBOOK_CLIENT_API__?.addLoader(loader)},addArgs=args=>{checkMethod("addArgs"),global2.__STORYBOOK_CLIENT_API__?.addArgs(args)},addArgTypes=argTypes=>{checkMethod("addArgTypes"),global2.__STORYBOOK_CLIENT_API__?.addArgTypes(argTypes)},addArgsEnhancer=enhancer=>{checkMethod("addArgsEnhancer"),global2.__STORYBOOK_CLIENT_API__?.addArgsEnhancer(enhancer)},addArgTypesEnhancer=enhancer=>{checkMethod("addArgTypesEnhancer"),global2.__STORYBOOK_CLIENT_API__?.addArgTypesEnhancer(enhancer)},addStepRunner=stepRunner=>{checkMethod("addStepRunner"),global2.__STORYBOOK_CLIENT_API__?.addStepRunner(stepRunner)};var setGlobalRender=render=>{checkMethod("setGlobalRender"),global2.__STORYBOOK_CLIENT_API__&&(global2.__STORYBOOK_CLIENT_API__.facade.projectAnnotations.render=render)},invalidStoryTypes=new Set(["string","number","boolean","symbol"]),ClientApi=class{constructor({storyStore}={}){this.lastFileName=0;this.addDecorator=decorator=>{this.facade.projectAnnotations.decorators?.push(decorator)};this.addParameters=({globals,globalTypes,...parameters})=>{this.facade.projectAnnotations.parameters=combineParameters(this.facade.projectAnnotations.parameters,parameters),globals&&(this.facade.projectAnnotations.globals={...this.facade.projectAnnotations.globals,...globals}),globalTypes&&(this.facade.projectAnnotations.globalTypes={...this.facade.projectAnnotations.globalTypes,...normalizeInputTypes(globalTypes)})};this.addStepRunner=stepRunner=>{this.facade.projectAnnotations.runStep=composeStepRunners([this.facade.projectAnnotations.runStep,stepRunner].filter(Boolean))};this.addLoader=loader=>{this.facade.projectAnnotations.loaders?.push(loader)};this.addArgs=args=>{this.facade.projectAnnotations.args={...this.facade.projectAnnotations.args,...args}};this.addArgTypes=argTypes=>{this.facade.projectAnnotations.argTypes={...this.facade.projectAnnotations.argTypes,...normalizeInputTypes(argTypes)}};this.addArgsEnhancer=enhancer=>{this.facade.projectAnnotations.argsEnhancers?.push(enhancer)};this.addArgTypesEnhancer=enhancer=>{this.facade.projectAnnotations.argTypesEnhancers?.push(enhancer)};this._addedExports={};this.storiesOf=(kind,m)=>{if(!kind&&typeof kind!="string")throw new Error("Invalid or missing kind provided for stories, should be a string");if(m||logger2.warn(`Missing 'module' parameter for story with a kind of '${kind}'. It will break your HMR`),m){let proto=Object.getPrototypeOf(m);proto.exports&&proto.exports.default&&logger2.error(`Illegal mix of CSF default export and storiesOf calls in a single file: ${proto.i}`)}let baseFilename=m&&m.id?`${m.id}`:(this.lastFileName++).toString(),fileName=baseFilename,i=1;for(;this._addedExports[fileName];)i+=1,fileName=`${baseFilename}-${i}`;m&&m.hot&&m.hot.accept&&(m.hot.accept(),m.hot.dispose(()=>{this.facade.clearFilenameExports(fileName),delete this._addedExports[fileName],setTimeout(()=>{this._loadAddedExports(),this.onImportFnChanged?.({importFn:this.importFn.bind(this)})},0)}));let hasAdded=!1,api={kind:kind.toString(),add:()=>api,addDecorator:()=>api,addLoader:()=>api,addParameters:()=>api};Object.keys(this.addons).forEach(name=>{let addon=this.addons[name];api[name]=(...args)=>(addon.apply(api,args),api)});let meta={id:sanitize(kind),title:kind,decorators:[],loaders:[],parameters:{}};this._addedExports[fileName]={default:meta};let counter=0;return api.add=(storyName,storyFn,parameters={})=>{if(hasAdded=!0,typeof storyName!="string")throw new Error(`Invalid or missing storyName provided for a "${kind}" story.`);if(!storyFn||Array.isArray(storyFn)||invalidStoryTypes.has(typeof storyFn))throw new Error(`Cannot load story "${storyName}" in "${kind}" due to invalid format. Storybook expected a function/object but received ${typeof storyFn} instead.`);let{decorators,loaders,component,args,argTypes,...storyParameters}=parameters,storyId=parameters.__id||toId2(kind,storyName),csfExports=this._addedExports[fileName];return csfExports[`story${counter}`]={name:storyName,parameters:{fileName,__id:storyId,...storyParameters},decorators,loaders,args,argTypes,component,render:storyFn},counter+=1,api},api.addDecorator=decorator=>{if(hasAdded)throw new Error(`You cannot add a decorator after the first story for a kind.
|
|
12
12
|
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);return meta.decorators?.push(decorator),api},api.addLoader=loader=>{if(hasAdded)throw new Error("You cannot add a loader after the first story for a kind.");return meta.loaders?.push(loader),api},api.addParameters=({component,args,argTypes,tags,...parameters})=>{if(hasAdded)throw new Error(`You cannot add parameters after the first story for a kind.
|
package/dist/client-api.js
CHANGED
|
@@ -38,7 +38,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
38
38
|
Are you using a V6-style sort function in V7 mode?
|
|
39
39
|
|
|
40
40
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
41
|
-
`)}},toIndexEntry=story=>{let{id,title,name,parameters,type}=story;return{id,title,name,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_global4=require("@storybook/global"),import_ts_dedent8=require("ts-dedent"),import_synchronous_promise2=require("synchronous-promise"),import_csf7=require("@storybook/csf"),import_client_logger9=require("@storybook/client-logger");var StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise2.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){var _a,_b;let fileNameOrder=Object.keys(this.csfExports),storySortParameter=(_b=(_a=this.projectAnnotations.parameters)==null?void 0:_a.options)==null?void 0:_b.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:(0,import_csf7.toId)(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(import_ts_dedent8.dedent`
|
|
41
|
+
`)}},toIndexEntry=story=>{let{id,title,name,parameters,type}=story;return{id,title,name,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_global4=require("@storybook/global"),import_ts_dedent8=require("ts-dedent"),import_synchronous_promise2=require("synchronous-promise"),import_csf7=require("@storybook/csf"),import_client_logger9=require("@storybook/client-logger");var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise2.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){var _a,_b;let fileNameOrder=Object.keys(this.csfExports),storySortParameter=(_b=(_a=this.projectAnnotations.parameters)==null?void 0:_a.options)==null?void 0:_b.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:(0,import_csf7.toId)(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(import_ts_dedent8.dedent`
|
|
42
42
|
Error sorting stories with sort parameter ${storySortParameter}:
|
|
43
43
|
|
|
44
44
|
> ${err.message}
|
|
@@ -46,7 +46,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
46
46
|
Are you using a V7-style sort function in V6 compatibility mode?
|
|
47
47
|
|
|
48
48
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
49
|
-
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(import_global4.global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger9.logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>(0,import_csf7.isExportStory)(key,defaultExport)),docsOptions=import_global4.global.DOCS_OPTIONS||{},
|
|
49
|
+
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(import_global4.global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger9.logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>(0,import_csf7.isExportStory)(key,defaultExport)),docsOptions=import_global4.global.DOCS_OPTIONS||{},{autodocs}=docsOptions,componentAutodocs=componentTags.includes(AUTODOCS_TAG),autodocsOptedIn=autodocs===!0||autodocs==="tag"&&componentAutodocs;if(!docsOptions.disable&&storyExports.length&&(componentTags.includes(STORIES_MDX_TAG)||autodocsOptedIn)){let name=docsOptions.defaultName,docsId=(0,import_csf7.toId)(componentId||title,name);this.entries[docsId]={type:"docs",id:docsId,title,name,importPath:fileName,...componentId&&{componentId},tags:[...componentTags,"docs",...autodocsOptedIn&&!componentAutodocs?[AUTODOCS_TAG]:[]],storiesImports:[]}}storyExports.forEach(([key,storyExport])=>{var _a,_b,_c;let exportName=(0,import_csf7.storyNameFromExport)(key),id=((_a=storyExport.parameters)==null?void 0:_a.__id)||(0,import_csf7.toId)(componentId||title,exportName),name=typeof storyExport!="function"&&storyExport.name||storyExport.storyName||((_b=storyExport.story)==null?void 0:_b.name)||exportName;(_c=storyExport.parameters)!=null&&_c.docsOnly||(this.entries[id]={type:"story",id,name,title,importPath:fileName,...componentId&&{componentId},tags:[...storyExport.tags||componentTags,"story"]})})}};var warningAlternatives={addDecorator:"Instead, use `export const decorators = [];` in your `preview.js`.",addParameters:"Instead, use `export const parameters = {};` in your `preview.js`.",addLoader:"Instead, use `export const loaders = [];` in your `preview.js`.",addArgs:"",addArgTypes:"",addArgsEnhancer:"",addArgTypesEnhancer:"",addStepRunner:"",getGlobalRender:"",setGlobalRender:""},checkMethod=method=>{var _a;if((_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7)throw new Error(import_ts_dedent9.dedent`You cannot use \`${method}\` with the new Story Store.
|
|
50
50
|
|
|
51
51
|
${warningAlternatives[method]}`);if(!import_global5.global.__STORYBOOK_CLIENT_API__)throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`)},addDecorator=decorator=>{var _a;checkMethod("addDecorator"),(_a=import_global5.global.__STORYBOOK_CLIENT_API__)==null||_a.addDecorator(decorator)},addParameters=parameters=>{var _a;checkMethod("addParameters"),(_a=import_global5.global.__STORYBOOK_CLIENT_API__)==null||_a.addParameters(parameters)},addLoader=loader=>{var _a;checkMethod("addLoader"),(_a=import_global5.global.__STORYBOOK_CLIENT_API__)==null||_a.addLoader(loader)},addArgs=args=>{var _a;checkMethod("addArgs"),(_a=import_global5.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgs(args)},addArgTypes=argTypes=>{var _a;checkMethod("addArgTypes"),(_a=import_global5.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgTypes(argTypes)},addArgsEnhancer=enhancer=>{var _a;checkMethod("addArgsEnhancer"),(_a=import_global5.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgsEnhancer(enhancer)},addArgTypesEnhancer=enhancer=>{var _a;checkMethod("addArgTypesEnhancer"),(_a=import_global5.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgTypesEnhancer(enhancer)},addStepRunner=stepRunner=>{var _a;checkMethod("addStepRunner"),(_a=import_global5.global.__STORYBOOK_CLIENT_API__)==null||_a.addStepRunner(stepRunner)};var setGlobalRender=render=>{checkMethod("setGlobalRender"),import_global5.global.__STORYBOOK_CLIENT_API__&&(import_global5.global.__STORYBOOK_CLIENT_API__.facade.projectAnnotations.render=render)},invalidStoryTypes=new Set(["string","number","boolean","symbol"]),ClientApi=class{constructor({storyStore}={}){this.lastFileName=0;this.addDecorator=decorator=>{var _a;(_a=this.facade.projectAnnotations.decorators)==null||_a.push(decorator)};this.addParameters=({globals,globalTypes,...parameters})=>{this.facade.projectAnnotations.parameters=combineParameters(this.facade.projectAnnotations.parameters,parameters),globals&&(this.facade.projectAnnotations.globals={...this.facade.projectAnnotations.globals,...globals}),globalTypes&&(this.facade.projectAnnotations.globalTypes={...this.facade.projectAnnotations.globalTypes,...normalizeInputTypes(globalTypes)})};this.addStepRunner=stepRunner=>{this.facade.projectAnnotations.runStep=composeStepRunners([this.facade.projectAnnotations.runStep,stepRunner].filter(Boolean))};this.addLoader=loader=>{var _a;(_a=this.facade.projectAnnotations.loaders)==null||_a.push(loader)};this.addArgs=args=>{this.facade.projectAnnotations.args={...this.facade.projectAnnotations.args,...args}};this.addArgTypes=argTypes=>{this.facade.projectAnnotations.argTypes={...this.facade.projectAnnotations.argTypes,...normalizeInputTypes(argTypes)}};this.addArgsEnhancer=enhancer=>{var _a;(_a=this.facade.projectAnnotations.argsEnhancers)==null||_a.push(enhancer)};this.addArgTypesEnhancer=enhancer=>{var _a;(_a=this.facade.projectAnnotations.argTypesEnhancers)==null||_a.push(enhancer)};this._addedExports={};this.storiesOf=(kind,m)=>{if(!kind&&typeof kind!="string")throw new Error("Invalid or missing kind provided for stories, should be a string");if(m||import_client_logger10.logger.warn(`Missing 'module' parameter for story with a kind of '${kind}'. It will break your HMR`),m){let proto=Object.getPrototypeOf(m);proto.exports&&proto.exports.default&&import_client_logger10.logger.error(`Illegal mix of CSF default export and storiesOf calls in a single file: ${proto.i}`)}let baseFilename=m&&m.id?`${m.id}`:(this.lastFileName++).toString(),fileName=baseFilename,i=1;for(;this._addedExports[fileName];)i+=1,fileName=`${baseFilename}-${i}`;m&&m.hot&&m.hot.accept&&(m.hot.accept(),m.hot.dispose(()=>{this.facade.clearFilenameExports(fileName),delete this._addedExports[fileName],setTimeout(()=>{var _a;this._loadAddedExports(),(_a=this.onImportFnChanged)==null||_a.call(this,{importFn:this.importFn.bind(this)})},0)}));let hasAdded=!1,api={kind:kind.toString(),add:()=>api,addDecorator:()=>api,addLoader:()=>api,addParameters:()=>api};Object.keys(this.addons).forEach(name=>{let addon=this.addons[name];api[name]=(...args)=>(addon.apply(api,args),api)});let meta={id:(0,import_csf8.sanitize)(kind),title:kind,decorators:[],loaders:[],parameters:{}};this._addedExports[fileName]={default:meta};let counter=0;return api.add=(storyName,storyFn,parameters={})=>{if(hasAdded=!0,typeof storyName!="string")throw new Error(`Invalid or missing storyName provided for a "${kind}" story.`);if(!storyFn||Array.isArray(storyFn)||invalidStoryTypes.has(typeof storyFn))throw new Error(`Cannot load story "${storyName}" in "${kind}" due to invalid format. Storybook expected a function/object but received ${typeof storyFn} instead.`);let{decorators,loaders,component,args,argTypes,...storyParameters}=parameters,storyId=parameters.__id||(0,import_csf8.toId)(kind,storyName),csfExports=this._addedExports[fileName];return csfExports[`story${counter}`]={name:storyName,parameters:{fileName,__id:storyId,...storyParameters},decorators,loaders,args,argTypes,component,render:storyFn},counter+=1,api},api.addDecorator=decorator=>{var _a;if(hasAdded)throw new Error(`You cannot add a decorator after the first story for a kind.
|
|
52
52
|
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);return(_a=meta.decorators)==null||_a.push(decorator),api},api.addLoader=loader=>{var _a;if(hasAdded)throw new Error("You cannot add a loader after the first story for a kind.");return(_a=meta.loaders)==null||_a.push(loader),api},api.addParameters=({component,args,argTypes,tags,...parameters})=>{if(hasAdded)throw new Error(`You cannot add parameters after the first story for a kind.
|
package/dist/client-api.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ClientApi,addArgTypes,addArgTypesEnhancer,addArgs,addArgsEnhancer,addDecorator,addLoader,addParameters,addStepRunner,getQueryParam,getQueryParams,setGlobalRender}from"./chunk-
|
|
1
|
+
import{ClientApi,addArgTypes,addArgTypesEnhancer,addArgs,addArgsEnhancer,addDecorator,addLoader,addParameters,addStepRunner,getQueryParam,getQueryParams,setGlobalRender}from"./chunk-UAUKVCSL.mjs";import{DEEPLY_EQUAL,NO_TARGET_NAME,StoryStore,combineArgs,combineParameters,composeConfigs,composeStepRunners,composeStories,composeStory,decorateStory,deepDiff,defaultDecorateStory,filterArgTypes,getArrayField,getField,getObjectField,getSingletonField,getValuesFromArgTypes,groupArgsByTarget,inferControls,mapArgsToTypes,noTargetArgs,normalizeComponentAnnotations,normalizeInputType,normalizeInputTypes,normalizeProjectAnnotations,normalizeStory,prepareStory,processCSFFile,sanitizeStoryContextUpdate,setProjectAnnotations,sortStoriesV6,sortStoriesV7,useAddonState,useSharedState,userOrAutoTitle,userOrAutoTitleFromSpecifier,validateOptions}from"./chunk-RRZ2SPWM.mjs";import{HooksContext,applyHooks,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext}from"./chunk-RTGEOU4B.mjs";export{ClientApi,DEEPLY_EQUAL,HooksContext,NO_TARGET_NAME,StoryStore,addArgTypes,addArgTypesEnhancer,addArgs,addArgsEnhancer,addDecorator,addLoader,addParameters,addStepRunner,applyHooks,combineArgs,combineParameters,composeConfigs,composeStepRunners,composeStories,composeStory,decorateStory,deepDiff,defaultDecorateStory,filterArgTypes,getArrayField,getField,getObjectField,getQueryParam,getQueryParams,getSingletonField,getValuesFromArgTypes,groupArgsByTarget,inferControls,mapArgsToTypes,noTargetArgs,normalizeComponentAnnotations,normalizeInputType,normalizeInputTypes,normalizeProjectAnnotations,normalizeStory,prepareStory,processCSFFile,sanitizeStoryContextUpdate,setGlobalRender,setProjectAnnotations,sortStoriesV6,sortStoriesV7,useAddonState,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useSharedState,useState,useStoryContext,userOrAutoTitle,userOrAutoTitleFromSpecifier,validateOptions};
|
package/dist/core-client.js
CHANGED
|
@@ -30,7 +30,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
30
30
|
CSF Auto-title received a numeric fileName. This typically happens when
|
|
31
31
|
webpack is mis-configured in production mode. To force webpack to produce
|
|
32
32
|
filenames, set optimization.moduleIds = "named" in your webpack config.
|
|
33
|
-
`);let normalizedFileName=(0,import_slash.default)(String(fileName));if(importPathMatcher.exec(normalizedFileName)){if(!userTitle){let suffix=normalizedFileName.replace(directory,""),path=(0,import_slash.default)(pathJoin([titlePrefix,suffix])).split("/");return path=stripExtension(path),path=removeRedundantFilename(path),path.join("/")}return titlePrefix?(0,import_slash.default)(pathJoin([titlePrefix,userTitle])):userTitle}},userOrAutoTitle=(fileName,storiesEntries,userTitle)=>{for(let i=0;i<storiesEntries.length;i+=1){let title=userOrAutoTitleFromSpecifier(fileName,storiesEntries[i],userTitle);if(title)return title}return userTitle||void 0};var import_ts_dedent7=require("ts-dedent");var STORY_KIND_PATH_SEPARATOR=/\s*\/\s*/,storySort=(options={})=>(a,b)=>{if(a.title===b.title&&!options.includeNames)return 0;let method=options.method||"configure",order=options.order||[],storyTitleA=a.title.trim().split(STORY_KIND_PATH_SEPARATOR),storyTitleB=b.title.trim().split(STORY_KIND_PATH_SEPARATOR);options.includeNames&&(storyTitleA.push(a.name),storyTitleB.push(b.name));let depth=0;for(;storyTitleA[depth]||storyTitleB[depth];){if(!storyTitleA[depth])return-1;if(!storyTitleB[depth])return 1;let nameA=storyTitleA[depth],nameB=storyTitleB[depth];if(nameA!==nameB){let indexA=order.indexOf(nameA),indexB=order.indexOf(nameB),indexWildcard=order.indexOf("*");return indexA!==-1||indexB!==-1?(indexA===-1&&(indexWildcard!==-1?indexA=indexWildcard:indexA=order.length),indexB===-1&&(indexWildcard!==-1?indexB=indexWildcard:indexB=order.length),indexA-indexB):method==="configure"?0:nameA.localeCompare(nameB,options.locales?options.locales:void 0,{numeric:!0,sensitivity:"accent"})}let index=order.indexOf(nameA);index===-1&&(index=order.indexOf("*")),order=index!==-1&&Array.isArray(order[index+1])?order[index+1]:[],depth+=1}return 0};var sortStoriesCommon=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter){let sortFn;typeof storySortParameter=="function"?sortFn=storySortParameter:sortFn=storySort(storySortParameter),stories.sort(sortFn)}else stories.sort((s1,s2)=>fileNameOrder.indexOf(s1.importPath)-fileNameOrder.indexOf(s2.importPath));return stories};var toIndexEntry=story=>{let{id,title,name,parameters,type}=story;return{id,title,name,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_global4=require("@storybook/global"),import_ts_dedent8=require("ts-dedent"),import_synchronous_promise2=require("synchronous-promise"),import_csf6=require("@storybook/csf"),import_client_logger9=require("@storybook/client-logger");var StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise2.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){var _a,_b;let fileNameOrder=Object.keys(this.csfExports),storySortParameter=(_b=(_a=this.projectAnnotations.parameters)==null?void 0:_a.options)==null?void 0:_b.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:(0,import_csf6.toId)(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(import_ts_dedent8.dedent`
|
|
33
|
+
`);let normalizedFileName=(0,import_slash.default)(String(fileName));if(importPathMatcher.exec(normalizedFileName)){if(!userTitle){let suffix=normalizedFileName.replace(directory,""),path=(0,import_slash.default)(pathJoin([titlePrefix,suffix])).split("/");return path=stripExtension(path),path=removeRedundantFilename(path),path.join("/")}return titlePrefix?(0,import_slash.default)(pathJoin([titlePrefix,userTitle])):userTitle}},userOrAutoTitle=(fileName,storiesEntries,userTitle)=>{for(let i=0;i<storiesEntries.length;i+=1){let title=userOrAutoTitleFromSpecifier(fileName,storiesEntries[i],userTitle);if(title)return title}return userTitle||void 0};var import_ts_dedent7=require("ts-dedent");var STORY_KIND_PATH_SEPARATOR=/\s*\/\s*/,storySort=(options={})=>(a,b)=>{if(a.title===b.title&&!options.includeNames)return 0;let method=options.method||"configure",order=options.order||[],storyTitleA=a.title.trim().split(STORY_KIND_PATH_SEPARATOR),storyTitleB=b.title.trim().split(STORY_KIND_PATH_SEPARATOR);options.includeNames&&(storyTitleA.push(a.name),storyTitleB.push(b.name));let depth=0;for(;storyTitleA[depth]||storyTitleB[depth];){if(!storyTitleA[depth])return-1;if(!storyTitleB[depth])return 1;let nameA=storyTitleA[depth],nameB=storyTitleB[depth];if(nameA!==nameB){let indexA=order.indexOf(nameA),indexB=order.indexOf(nameB),indexWildcard=order.indexOf("*");return indexA!==-1||indexB!==-1?(indexA===-1&&(indexWildcard!==-1?indexA=indexWildcard:indexA=order.length),indexB===-1&&(indexWildcard!==-1?indexB=indexWildcard:indexB=order.length),indexA-indexB):method==="configure"?0:nameA.localeCompare(nameB,options.locales?options.locales:void 0,{numeric:!0,sensitivity:"accent"})}let index=order.indexOf(nameA);index===-1&&(index=order.indexOf("*")),order=index!==-1&&Array.isArray(order[index+1])?order[index+1]:[],depth+=1}return 0};var sortStoriesCommon=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter){let sortFn;typeof storySortParameter=="function"?sortFn=storySortParameter:sortFn=storySort(storySortParameter),stories.sort(sortFn)}else stories.sort((s1,s2)=>fileNameOrder.indexOf(s1.importPath)-fileNameOrder.indexOf(s2.importPath));return stories};var toIndexEntry=story=>{let{id,title,name,parameters,type}=story;return{id,title,name,importPath:parameters.fileName,type}},sortStoriesV6=(stories,storySortParameter,fileNameOrder)=>{if(storySortParameter&&typeof storySortParameter=="function")return stories.sort(storySortParameter),stories.map(s=>toIndexEntry(s[1]));let storiesV7=stories.map(s=>toIndexEntry(s[1]));return sortStoriesCommon(storiesV7,storySortParameter,fileNameOrder)};var import_global4=require("@storybook/global"),import_ts_dedent8=require("ts-dedent"),import_synchronous_promise2=require("synchronous-promise"),import_csf6=require("@storybook/csf"),import_client_logger9=require("@storybook/client-logger");var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise2.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){var _a,_b;let fileNameOrder=Object.keys(this.csfExports),storySortParameter=(_b=(_a=this.projectAnnotations.parameters)==null?void 0:_a.options)==null?void 0:_b.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:(0,import_csf6.toId)(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(import_ts_dedent8.dedent`
|
|
34
34
|
Error sorting stories with sort parameter ${storySortParameter}:
|
|
35
35
|
|
|
36
36
|
> ${err.message}
|
|
@@ -38,7 +38,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
38
38
|
Are you using a V7-style sort function in V6 compatibility mode?
|
|
39
39
|
|
|
40
40
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
41
|
-
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(import_global4.global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger9.logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>(0,import_csf6.isExportStory)(key,defaultExport)),docsOptions=import_global4.global.DOCS_OPTIONS||{},
|
|
41
|
+
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(import_global4.global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger9.logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>(0,import_csf6.isExportStory)(key,defaultExport)),docsOptions=import_global4.global.DOCS_OPTIONS||{},{autodocs}=docsOptions,componentAutodocs=componentTags.includes(AUTODOCS_TAG),autodocsOptedIn=autodocs===!0||autodocs==="tag"&&componentAutodocs;if(!docsOptions.disable&&storyExports.length&&(componentTags.includes(STORIES_MDX_TAG)||autodocsOptedIn)){let name=docsOptions.defaultName,docsId=(0,import_csf6.toId)(componentId||title,name);this.entries[docsId]={type:"docs",id:docsId,title,name,importPath:fileName,...componentId&&{componentId},tags:[...componentTags,"docs",...autodocsOptedIn&&!componentAutodocs?[AUTODOCS_TAG]:[]],storiesImports:[]}}storyExports.forEach(([key,storyExport])=>{var _a,_b,_c;let exportName=(0,import_csf6.storyNameFromExport)(key),id=((_a=storyExport.parameters)==null?void 0:_a.__id)||(0,import_csf6.toId)(componentId||title,exportName),name=typeof storyExport!="function"&&storyExport.name||storyExport.storyName||((_b=storyExport.story)==null?void 0:_b.name)||exportName;(_c=storyExport.parameters)!=null&&_c.docsOnly||(this.entries[id]={type:"story",id,name,title,importPath:fileName,...componentId&&{componentId},tags:[...storyExport.tags||componentTags,"story"]})})}};var invalidStoryTypes=new Set(["string","number","boolean","symbol"]),ClientApi=class{constructor({storyStore}={}){this.lastFileName=0;this.addDecorator=decorator=>{var _a;(_a=this.facade.projectAnnotations.decorators)==null||_a.push(decorator)};this.addParameters=({globals,globalTypes,...parameters})=>{this.facade.projectAnnotations.parameters=combineParameters(this.facade.projectAnnotations.parameters,parameters),globals&&(this.facade.projectAnnotations.globals={...this.facade.projectAnnotations.globals,...globals}),globalTypes&&(this.facade.projectAnnotations.globalTypes={...this.facade.projectAnnotations.globalTypes,...normalizeInputTypes(globalTypes)})};this.addStepRunner=stepRunner=>{this.facade.projectAnnotations.runStep=composeStepRunners([this.facade.projectAnnotations.runStep,stepRunner].filter(Boolean))};this.addLoader=loader=>{var _a;(_a=this.facade.projectAnnotations.loaders)==null||_a.push(loader)};this.addArgs=args=>{this.facade.projectAnnotations.args={...this.facade.projectAnnotations.args,...args}};this.addArgTypes=argTypes=>{this.facade.projectAnnotations.argTypes={...this.facade.projectAnnotations.argTypes,...normalizeInputTypes(argTypes)}};this.addArgsEnhancer=enhancer=>{var _a;(_a=this.facade.projectAnnotations.argsEnhancers)==null||_a.push(enhancer)};this.addArgTypesEnhancer=enhancer=>{var _a;(_a=this.facade.projectAnnotations.argTypesEnhancers)==null||_a.push(enhancer)};this._addedExports={};this.storiesOf=(kind,m)=>{if(!kind&&typeof kind!="string")throw new Error("Invalid or missing kind provided for stories, should be a string");if(m||import_client_logger10.logger.warn(`Missing 'module' parameter for story with a kind of '${kind}'. It will break your HMR`),m){let proto=Object.getPrototypeOf(m);proto.exports&&proto.exports.default&&import_client_logger10.logger.error(`Illegal mix of CSF default export and storiesOf calls in a single file: ${proto.i}`)}let baseFilename=m&&m.id?`${m.id}`:(this.lastFileName++).toString(),fileName=baseFilename,i=1;for(;this._addedExports[fileName];)i+=1,fileName=`${baseFilename}-${i}`;m&&m.hot&&m.hot.accept&&(m.hot.accept(),m.hot.dispose(()=>{this.facade.clearFilenameExports(fileName),delete this._addedExports[fileName],setTimeout(()=>{var _a;this._loadAddedExports(),(_a=this.onImportFnChanged)==null||_a.call(this,{importFn:this.importFn.bind(this)})},0)}));let hasAdded=!1,api={kind:kind.toString(),add:()=>api,addDecorator:()=>api,addLoader:()=>api,addParameters:()=>api};Object.keys(this.addons).forEach(name=>{let addon=this.addons[name];api[name]=(...args)=>(addon.apply(api,args),api)});let meta={id:(0,import_csf7.sanitize)(kind),title:kind,decorators:[],loaders:[],parameters:{}};this._addedExports[fileName]={default:meta};let counter=0;return api.add=(storyName,storyFn,parameters={})=>{if(hasAdded=!0,typeof storyName!="string")throw new Error(`Invalid or missing storyName provided for a "${kind}" story.`);if(!storyFn||Array.isArray(storyFn)||invalidStoryTypes.has(typeof storyFn))throw new Error(`Cannot load story "${storyName}" in "${kind}" due to invalid format. Storybook expected a function/object but received ${typeof storyFn} instead.`);let{decorators,loaders,component,args,argTypes,...storyParameters}=parameters,storyId=parameters.__id||(0,import_csf7.toId)(kind,storyName),csfExports=this._addedExports[fileName];return csfExports[`story${counter}`]={name:storyName,parameters:{fileName,__id:storyId,...storyParameters},decorators,loaders,args,argTypes,component,render:storyFn},counter+=1,api},api.addDecorator=decorator=>{var _a;if(hasAdded)throw new Error(`You cannot add a decorator after the first story for a kind.
|
|
42
42
|
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);return(_a=meta.decorators)==null||_a.push(decorator),api},api.addLoader=loader=>{var _a;if(hasAdded)throw new Error("You cannot add a loader after the first story for a kind.");return(_a=meta.loaders)==null||_a.push(loader),api},api.addParameters=({component,args,argTypes,tags,...parameters})=>{if(hasAdded)throw new Error(`You cannot add parameters after the first story for a kind.
|
|
43
43
|
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);return meta.parameters=combineParameters(meta.parameters,parameters),component&&(meta.component=component),args&&(meta.args={...meta.args,...args}),argTypes&&(meta.argTypes={...meta.argTypes,...argTypes}),tags&&(meta.tags=tags),api},api};this.raw=()=>{var _a;return(_a=this.storyStore)==null?void 0:_a.raw()};this.facade=new StoryStoreFacade,this.addons={},this.storyStore=storyStore}importFn(path){return this.facade.importFn(path)}getStoryIndex(){if(!this.storyStore)throw new Error("Cannot get story index before setting storyStore");return this.facade.getStoryIndex(this.storyStore)}_loadAddedExports(){Object.entries(this._addedExports).forEach(([fileName,fileExports])=>this.facade.addStoriesFromExports(fileName,fileExports))}get _storyStore(){return this.storyStore}};var import_global11=require("@storybook/global"),import_channel_postmessage=require("@storybook/channel-postmessage"),import_core_events7=require("@storybook/core-events");var import_ts_dedent10=require("ts-dedent"),import_global6=require("@storybook/global"),import_synchronous_promise3=require("synchronous-promise"),import_core_events3=require("@storybook/core-events"),import_client_logger12=require("@storybook/client-logger");var import_client_logger11=require("@storybook/client-logger"),import_core_events2=require("@storybook/core-events");var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return{name,message,stack}}catch{return{name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing")}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}))}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id})}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return["preparing"].includes(this.phase)}isPending(){return["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");return this.store.getStoryContext(this.story)}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode})}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{})}),this.notYetRendered=!1,abortSignal.aborted)return;if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext)}),await this.runPhase(abortSignal,"played")}catch(error){if(import_client_logger11.logger.error(error),await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(import_core_events2.PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error))}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error}if(this.disableKeyListeners=!1,abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(import_core_events2.STORY_RENDERED,id))}catch(err){this.phase="errored",this.callbacks.showException(err)}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){var _a;(_a=this.abortController)==null||_a.abort()}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0))}window.location.reload(),await new Promise(()=>{})}};var{fetch}=import_global6.global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(channel=addons.getChannel()){this.channel=channel;this.storyRenders=[];var _a;(_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7&&addons.hasServerChannel()&&(this.serverChannel=addons.getServerChannel()),this.storyStore=new StoryStore}initialize({getStoryIndex,importFn,getProjectAnnotations}){return this.getStoryIndex=getStoryIndex,this.importFn=importFn,this.setupListeners(),this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(projectAnnotations=>this.initializeWithProjectAnnotations(projectAnnotations))}setupListeners(){var _a;(_a=this.serverChannel)==null||_a.on(import_core_events3.STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(import_core_events3.UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(import_core_events3.UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(import_core_events3.RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(import_core_events3.FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(import_core_events3.FORCE_REMOUNT,this.onForceRemount.bind(this))}getProjectAnnotationsOrRenderError(getProjectAnnotations){return import_synchronous_promise3.SynchronousPromise.resolve().then(getProjectAnnotations).then(projectAnnotations=>{if(projectAnnotations.renderToDOM&&(0,import_client_logger12.deprecate)("`renderToDOM` is deprecated, please rename to `renderToCanvas`"),this.renderToCanvas=projectAnnotations.renderToCanvas||projectAnnotations.renderToDOM,!this.renderToCanvas)throw new Error(import_ts_dedent10.dedent`
|
|
44
44
|
Expected your framework's preset to export a \`renderToCanvas\` field.
|
|
@@ -48,7 +48,7 @@ Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.m
|
|
|
48
48
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
49
49
|
`);return projectAnnotations}).catch(err=>{throw this.renderPreviewEntryError("Error reading preview.js:",err),err})}initializeWithProjectAnnotations(projectAnnotations){var _a;this.storyStore.setProjectAnnotations(projectAnnotations),this.setInitialGlobals();let storyIndexPromise;if((_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=import_synchronous_promise3.SynchronousPromise.resolve().then(this.getStoryIndex)}return storyIndexPromise.then(storyIndex=>this.initializeWithStoryIndex(storyIndex)).catch(err=>{throw this.renderPreviewEntryError("Error loading story index:",err),err})}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStore.globals||!this.storyStore.projectAnnotations)throw new Error("Cannot emit before initialization");let payload={globals:this.storyStore.globals.get()||{},globalTypes:this.storyStore.projectAnnotations.globalTypes||{}};this.channel.emit(import_core_events3.SET_GLOBALS,payload)}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new Error(await result.text())}initializeWithStoryIndex(storyIndex){var _a;if(!this.importFn)throw new Error("Cannot call initializeWithStoryIndex before initialization");return this.storyStore.initialize({storyIndex,importFn:this.importFn,cache:!((_a=import_global6.global.FEATURES)!=null&&_a.storyStoreV7)})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError;let projectAnnotations=await this.getProjectAnnotationsOrRenderError(getProjectAnnotations);if(!this.storyStore.projectAnnotations){await this.initializeWithProjectAnnotations(projectAnnotations);return}await this.storyStore.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!!this.storyStore.projectAnnotations)try{let storyIndex=await this.getStoryIndexFromServer();this.storyStore.storyIndex||await this.initializeWithStoryIndex(storyIndex),await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){await this.storyStore.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(import_core_events3.GLOBALS_UPDATED,{globals:this.storyStore.globals.get(),initialGlobals:this.storyStore.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){this.storyStore.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){let render=this.storyRenders.find(r=>r.id===storyId),story=(render==null?void 0:render.story)||await this.storyStore.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStore.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs})}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()))}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()))}renderStoryToElement(story,element,options){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,this.inlineStoryCallbacks(story.id),story.id,"docs",options,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render)}}async teardownRender(render,{viewModeChanged}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent10.dedent`Failed to initialize Storybook.
|
|
50
50
|
|
|
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)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger12.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger12.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger12.logger.error(reason),import_client_logger12.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global10=require("@storybook/global");var import_ts_dedent11=require("ts-dedent"),import_global7=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger13=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}};var
|
|
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)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger12.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger12.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger12.logger.error(reason),import_client_logger12.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global10=require("@storybook/global");var import_ts_dedent11=require("ts-dedent"),import_global7=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger13=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}};var CsfDocsRender=class{constructor(channel,store,entry){this.channel=channel;this.store=store;this.entry=entry;this.type="docs";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!0),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry){this.channel=channel;this.store=store;this.entry=entry;this.type="docs";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.exports&&this.exports===other.exports)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!1),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0)},renderDocs()}async teardown({viewModeChanged}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG2="autodocs",STORIES_MDX_TAG2="stories-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG2))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG2))}function isStoryRender(r){return r.type==="story"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}initializeWithProjectAnnotations(projectAnnotations){return super.initializeWithProjectAnnotations(projectAnnotations).then(()=>this.setInitialGlobals())}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent11.dedent`
|
|
52
52
|
Couldn't find any stories in your Storybook.
|
|
53
53
|
- Please check your stories field of your main.js config.
|
|
54
54
|
- Also check the browser console and terminal for error messages.
|
|
@@ -57,7 +57,7 @@ Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.m
|
|
|
57
57
|
- Are you sure a story with that id exists?
|
|
58
58
|
- Please check your stories field of your main.js config.
|
|
59
59
|
- Also check the browser console and terminal for error messages.
|
|
60
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){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
|
|
60
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global7.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs(),(_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):render=new CsfDocsRender(this.channel,this.storyStore,entry);let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global7.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent11.dedent`Failed to initialize Storybook.
|
|
61
61
|
|
|
62
62
|
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)}}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger13.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger13.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_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_dedent12=require("ts-dedent"),import_client_logger14=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject")),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.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_dedent12.dedent`
|
|
63
63
|
Omitted potentially unsafe URL args.
|
package/dist/core-client.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{start}from"./chunk-
|
|
1
|
+
import{start}from"./chunk-JHDSJNE7.mjs";import"./chunk-GRRYLBAT.mjs";import{ClientApi}from"./chunk-UAUKVCSL.mjs";import"./chunk-HF5EPGVY.mjs";import{StoryStore}from"./chunk-RRZ2SPWM.mjs";import"./chunk-RTGEOU4B.mjs";export{ClientApi,StoryStore,start};
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export { H as HooksContext, k as applyHooks, u as useArgs, a as useCallback, b a
|
|
|
3
3
|
export { S as StoryStore, p as prepareStory } from './StoryStore-e35dc2c4.js';
|
|
4
4
|
export { P as PropDescriptor, c as combineArgs, a as combineParameters, b as composeStepRunners, d as composeStories, e as composeStory, f as decorateStory, g as defaultDecorateStory, h as filterArgTypes, j as inferControls, n as normalizeStory, s as sanitizeStoryContextUpdate, i as setProjectAnnotations, l as sortStoriesV7, k as userOrAutoTitle, u as userOrAutoTitleFromSpecifier } from './sortStories-569e0e66.js';
|
|
5
5
|
export { c as composeConfigs } from './composeConfigs-7f62ebf7.js';
|
|
6
|
-
export { D as DocsContext, P as Preview, b as PreviewWeb, a as simulateDOMContentLoaded, s as simulatePageLoad } from './DocsContext-
|
|
6
|
+
export { D as DocsContext, P as Preview, b as PreviewWeb, a as simulateDOMContentLoaded, s as simulatePageLoad } from './DocsContext-917299b8.js';
|
|
7
7
|
export { C as ClientApi, a as addArgTypes, b as addArgTypesEnhancer, c as addArgs, d as addArgsEnhancer, e as addDecorator, f as addLoader, g as addParameters, h as addStepRunner, s as setGlobalRender } from './ClientApi-c264b450.js';
|
|
8
8
|
export { g as getQueryParam, a as getQueryParams } from './queryparams-d12445b8.js';
|
|
9
9
|
export { s as start } from './start-e15b4487.js';
|
package/dist/index.js
CHANGED
|
@@ -49,7 +49,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
49
49
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
50
50
|
`);return projectAnnotations}).catch(err=>{throw this.renderPreviewEntryError("Error reading preview.js:",err),err})}initializeWithProjectAnnotations(projectAnnotations){var _a;this.storyStore.setProjectAnnotations(projectAnnotations),this.setInitialGlobals();let storyIndexPromise;if((_a=import_global4.global.FEATURES)!=null&&_a.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=import_synchronous_promise2.SynchronousPromise.resolve().then(this.getStoryIndex)}return storyIndexPromise.then(storyIndex=>this.initializeWithStoryIndex(storyIndex)).catch(err=>{throw this.renderPreviewEntryError("Error loading story index:",err),err})}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStore.globals||!this.storyStore.projectAnnotations)throw new Error("Cannot emit before initialization");let payload={globals:this.storyStore.globals.get()||{},globalTypes:this.storyStore.projectAnnotations.globalTypes||{}};this.channel.emit(import_core_events3.SET_GLOBALS,payload)}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new Error(await result.text())}initializeWithStoryIndex(storyIndex){var _a;if(!this.importFn)throw new Error("Cannot call initializeWithStoryIndex before initialization");return this.storyStore.initialize({storyIndex,importFn:this.importFn,cache:!((_a=import_global4.global.FEATURES)!=null&&_a.storyStoreV7)})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError;let projectAnnotations=await this.getProjectAnnotationsOrRenderError(getProjectAnnotations);if(!this.storyStore.projectAnnotations){await this.initializeWithProjectAnnotations(projectAnnotations);return}await this.storyStore.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!!this.storyStore.projectAnnotations)try{let storyIndex=await this.getStoryIndexFromServer();this.storyStore.storyIndex||await this.initializeWithStoryIndex(storyIndex),await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){await this.storyStore.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(import_core_events3.GLOBALS_UPDATED,{globals:this.storyStore.globals.get(),initialGlobals:this.storyStore.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){this.storyStore.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){let render=this.storyRenders.find(r=>r.id===storyId),story=(render==null?void 0:render.story)||await this.storyStore.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStore.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs})}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()))}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()))}renderStoryToElement(story,element,options){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,this.inlineStoryCallbacks(story.id),story.id,"docs",options,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render)}}async teardownRender(render,{viewModeChanged}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent8.dedent`Failed to initialize Storybook.
|
|
51
51
|
|
|
52
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global4.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger10.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger10.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger10.logger.error(reason),import_client_logger10.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global8=require("@storybook/global");var import_ts_dedent9=require("ts-dedent"),import_global5=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger11=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}};var
|
|
52
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global4.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger10.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger10.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger10.logger.error(reason),import_client_logger10.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global8=require("@storybook/global");var import_ts_dedent9=require("ts-dedent"),import_global5=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger11=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}};var CsfDocsRender=class{constructor(channel,store,entry){this.channel=channel;this.store=store;this.entry=entry;this.type="docs";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!0),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry){this.channel=channel;this.store=store;this.entry=entry;this.type="docs";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.exports&&this.exports===other.exports)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!1),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0)},renderDocs()}async teardown({viewModeChanged}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}function isStoryRender(r){return r.type==="story"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}initializeWithProjectAnnotations(projectAnnotations){return super.initializeWithProjectAnnotations(projectAnnotations).then(()=>this.setInitialGlobals())}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent9.dedent`
|
|
53
53
|
Couldn't find any stories in your Storybook.
|
|
54
54
|
- Please check your stories field of your main.js config.
|
|
55
55
|
- Also check the browser console and terminal for error messages.
|
|
@@ -58,7 +58,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
58
58
|
- Are you sure a story with that id exists?
|
|
59
59
|
- Please check your stories field of your main.js config.
|
|
60
60
|
- Also check the browser console and terminal for error messages.
|
|
61
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global5.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
|
|
61
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs(),(_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):render=new CsfDocsRender(this.channel,this.storyStore,entry);let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global5.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent9.dedent`Failed to initialize Storybook.
|
|
62
62
|
|
|
63
63
|
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)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger11.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger11.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){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_global6=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent10=require("ts-dedent"),import_client_logger12=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject")),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.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(import_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger12.once.warn(import_ts_dedent10.dedent`
|
|
64
64
|
Omitted potentially unsafe URL args.
|
|
@@ -67,7 +67,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
67
67
|
`),acc),{})};var{history,document}=import_global6.global;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let{search=""}=document.location,{path,selectedKind,selectedStory,...rest}=import_qs2.default.parse(search,{ignoreQueryPrefix:!0});return import_qs2.default.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document.location;document.title=selection.storyId,history.replaceState({},"",`${document.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{let query=import_qs2.default.parse(document.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);return storyId?{storySpecifier:storyId,args,globals,viewMode}:null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document.location;history.replaceState({},"",`${document.location.pathname}${query}${hash}`)}};var import_global7=require("@storybook/global"),import_client_logger13=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),import_ts_dedent11=require("ts-dedent"),import_qs3=__toESM(require("qs")),{document:document2}=import_global7.global,PREPARING_DELAY=100,Mode=(Mode2=>(Mode2.MAIN="MAIN",Mode2.NOPREVIEW="NOPREVIEW",Mode2.PREPARING_STORY="PREPARING_STORY",Mode2.PREPARING_DOCS="PREPARING_DOCS",Mode2.ERROR="ERROR",Mode2))(Mode||{}),classes={PREPARING_STORY:"sb-show-preparing-story",PREPARING_DOCS:"sb-show-preparing-docs",MAIN:"sb-show-main",NOPREVIEW:"sb-show-nopreview",ERROR:"sb-show-errordisplay"},layoutClassMap={centered:"sb-main-centered",fullscreen:"sb-main-fullscreen",padded:"sb-main-padded"},ansiConverter=new import_ansi_to_html.default({escapeXML:!0}),WebView=class{constructor(){this.testing=!1;let{__SPECIAL_TEST_PARAMETER__}=import_qs3.default.parse(document2.location.search,{ignoreQueryPrefix:!0});switch(__SPECIAL_TEST_PARAMETER__){case"preparing-story":{this.showPreparingStory(),this.testing=!0;break}case"preparing-docs":{this.showPreparingDocs(),this.testing=!0;break}default:}}prepareForStory(story){return this.showStory(),this.applyLayout(story.parameters.layout),document2.documentElement.scrollTop=0,document2.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document2.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),this.docsRoot()}docsRoot(){return document2.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document2.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document2.body.classList.remove(this.currentLayoutClass),document2.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}checkIfLayoutExists(layout){layoutClassMap[layout]||import_client_logger13.logger.warn(import_ts_dedent11.dedent`The desired layout: ${layout} is not a valid option.
|
|
68
68
|
The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.`)}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document2.body.classList.add(classes[otherMode]):document2.body.classList.remove(classes[otherMode])})}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
|
|
69
69
|
`);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
|
|
70
|
-
`)),document2.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document2.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){var _a,_b;this.testing||(this.showMode("NOPREVIEW"),(_a=this.storyRoot())==null||_a.setAttribute("hidden","true"),(_b=this.docsRoot())==null||_b.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs(){clearTimeout(this.preparingTimeout),this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document2.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(){super(new UrlStore,new WebView),import_global8.global.__STORYBOOK_PREVIEW__=this}};var import_global9=require("@storybook/global"),{document:document3}=import_global9.global,runScriptTypes=["application/javascript","application/ecmascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript","module"],SCRIPT="script",SCRIPTS_ROOT_ID="scripts-root";function simulateDOMContentLoaded(){let DOMContentLoadedEvent=document3.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document3.dispatchEvent(DOMContentLoadedEvent)}function insertScript($script,callback,$scriptRoot){let scriptEl=document3.createElement("script");scriptEl.type=$script.type==="module"?"module":"text/javascript",$script.src?(scriptEl.onload=callback,scriptEl.onerror=callback,scriptEl.src=$script.src):scriptEl.textContent=$script.innerText,$scriptRoot?$scriptRoot.appendChild(scriptEl):document3.head.appendChild(scriptEl),$script.parentNode.removeChild($script),$script.src||callback()}function insertScriptsSequentially(scriptsToExecute,callback,index=0){scriptsToExecute[index](()=>{index++,index===scriptsToExecute.length?callback():insertScriptsSequentially(scriptsToExecute,callback,index)})}function simulatePageLoad($container){let $scriptsRoot=document3.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document3.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document3.body.appendChild($scriptsRoot));let $scripts=Array.from($container.querySelectorAll(SCRIPT));if($scripts.length){let scriptsToExecute=[];$scripts.forEach($script=>{let typeAttr=$script.getAttribute("type");(!typeAttr||runScriptTypes.includes(typeAttr))&&scriptsToExecute.push(callback=>insertScript($script,callback,$scriptsRoot))}),scriptsToExecute.length&&insertScriptsSequentially(scriptsToExecute,simulateDOMContentLoaded,void 0)}else simulateDOMContentLoaded()}var import_ts_dedent13=require("ts-dedent"),import_global11=require("@storybook/global"),import_client_logger15=require("@storybook/client-logger"),import_csf8=require("@storybook/csf");var import_global10=require("@storybook/global"),import_ts_dedent12=require("ts-dedent"),import_synchronous_promise3=require("synchronous-promise"),import_csf7=require("@storybook/csf"),import_client_logger14=require("@storybook/client-logger");var StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise3.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){var _a,_b;let fileNameOrder=Object.keys(this.csfExports),storySortParameter=(_b=(_a=this.projectAnnotations.parameters)==null?void 0:_a.options)==null?void 0:_b.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:(0,import_csf7.toId)(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(import_ts_dedent12.dedent`
|
|
70
|
+
`)),document2.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document2.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){var _a,_b;this.testing||(this.showMode("NOPREVIEW"),(_a=this.storyRoot())==null||_a.setAttribute("hidden","true"),(_b=this.docsRoot())==null||_b.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs(){clearTimeout(this.preparingTimeout),this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document2.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(){super(new UrlStore,new WebView),import_global8.global.__STORYBOOK_PREVIEW__=this}};var import_global9=require("@storybook/global"),{document:document3}=import_global9.global,runScriptTypes=["application/javascript","application/ecmascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript","module"],SCRIPT="script",SCRIPTS_ROOT_ID="scripts-root";function simulateDOMContentLoaded(){let DOMContentLoadedEvent=document3.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document3.dispatchEvent(DOMContentLoadedEvent)}function insertScript($script,callback,$scriptRoot){let scriptEl=document3.createElement("script");scriptEl.type=$script.type==="module"?"module":"text/javascript",$script.src?(scriptEl.onload=callback,scriptEl.onerror=callback,scriptEl.src=$script.src):scriptEl.textContent=$script.innerText,$scriptRoot?$scriptRoot.appendChild(scriptEl):document3.head.appendChild(scriptEl),$script.parentNode.removeChild($script),$script.src||callback()}function insertScriptsSequentially(scriptsToExecute,callback,index=0){scriptsToExecute[index](()=>{index++,index===scriptsToExecute.length?callback():insertScriptsSequentially(scriptsToExecute,callback,index)})}function simulatePageLoad($container){let $scriptsRoot=document3.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document3.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document3.body.appendChild($scriptsRoot));let $scripts=Array.from($container.querySelectorAll(SCRIPT));if($scripts.length){let scriptsToExecute=[];$scripts.forEach($script=>{let typeAttr=$script.getAttribute("type");(!typeAttr||runScriptTypes.includes(typeAttr))&&scriptsToExecute.push(callback=>insertScript($script,callback,$scriptsRoot))}),scriptsToExecute.length&&insertScriptsSequentially(scriptsToExecute,simulateDOMContentLoaded,void 0)}else simulateDOMContentLoaded()}var import_ts_dedent13=require("ts-dedent"),import_global11=require("@storybook/global"),import_client_logger15=require("@storybook/client-logger"),import_csf8=require("@storybook/csf");var import_global10=require("@storybook/global"),import_ts_dedent12=require("ts-dedent"),import_synchronous_promise3=require("synchronous-promise"),import_csf7=require("@storybook/csf"),import_client_logger14=require("@storybook/client-logger");var AUTODOCS_TAG2="autodocs",STORIES_MDX_TAG2="stories-mdx",StoryStoreFacade=class{constructor(){this.projectAnnotations={loaders:[],decorators:[],parameters:{},argsEnhancers:[],argTypesEnhancers:[],args:{},argTypes:{}},this.entries={},this.csfExports={}}importFn(path){return import_synchronous_promise3.SynchronousPromise.resolve().then(()=>{let moduleExports=this.csfExports[path];if(!moduleExports)throw new Error(`Unknown path: ${path}`);return moduleExports})}getStoryIndex(store){var _a,_b;let fileNameOrder=Object.keys(this.csfExports),storySortParameter=(_b=(_a=this.projectAnnotations.parameters)==null?void 0:_a.options)==null?void 0:_b.storySort,sortableV6=Object.entries(this.entries).map(([storyId,{type,importPath,...entry}])=>{let exports=this.csfExports[importPath],csfFile=store.processCSFFileWithCache(exports,importPath,exports.default.title),storyLike;return type==="story"?storyLike=store.storyFromCSFFile({storyId,csfFile}):storyLike={...entry,story:entry.name,kind:entry.title,componentId:(0,import_csf7.toId)(entry.componentId||entry.title),parameters:{fileName:importPath}},[storyId,storyLike,csfFile.meta.parameters,this.projectAnnotations.parameters||{}]}),sortedV7;try{sortedV7=sortStoriesV6(sortableV6,storySortParameter,fileNameOrder)}catch(err){throw typeof storySortParameter=="function"?new Error(import_ts_dedent12.dedent`
|
|
71
71
|
Error sorting stories with sort parameter ${storySortParameter}:
|
|
72
72
|
|
|
73
73
|
> ${err.message}
|
|
@@ -75,7 +75,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
75
75
|
Are you using a V7-style sort function in V6 compatibility mode?
|
|
76
76
|
|
|
77
77
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
|
78
|
-
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(import_global10.global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger14.logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>(0,import_csf7.isExportStory)(key,defaultExport)),docsOptions=import_global10.global.DOCS_OPTIONS||{},
|
|
78
|
+
`):err}return{v:4,entries:sortedV7.reduce((acc,s)=>(acc[s.id]=this.entries[s.id],acc),{})}}clearFilenameExports(fileName){this.csfExports[fileName]&&(Object.entries(this.entries).forEach(([id,{importPath}])=>{importPath===fileName&&delete this.entries[id]}),this.csfExports[fileName]={})}addStoriesFromExports(fileName,fileExports){if(fileName.match(/\.mdx$/)&&!fileName.match(/\.stories\.mdx$/)||this.csfExports[fileName]===fileExports)return;this.clearFilenameExports(fileName);let{default:defaultExport,__namedExportsOrder,...namedExports}=fileExports,{id:componentId,title,tags:componentTags=[]}=defaultExport||{},specifiers=(import_global10.global.STORIES||[]).map(specifier=>({...specifier,importPathMatcher:new RegExp(specifier.importPathMatcher)}));if(title=userOrAutoTitle(fileName,specifiers,title),!title){import_client_logger14.logger.info(`Unexpected default export without title in '${fileName}': ${JSON.stringify(fileExports.default)}`);return}this.csfExports[fileName]={...fileExports,default:{...defaultExport,title}};let sortedExports=namedExports;Array.isArray(__namedExportsOrder)&&(sortedExports={},__namedExportsOrder.forEach(name=>{let namedExport=namedExports[name];namedExport&&(sortedExports[name]=namedExport)}));let storyExports=Object.entries(sortedExports).filter(([key])=>(0,import_csf7.isExportStory)(key,defaultExport)),docsOptions=import_global10.global.DOCS_OPTIONS||{},{autodocs}=docsOptions,componentAutodocs=componentTags.includes(AUTODOCS_TAG2),autodocsOptedIn=autodocs===!0||autodocs==="tag"&&componentAutodocs;if(!docsOptions.disable&&storyExports.length&&(componentTags.includes(STORIES_MDX_TAG2)||autodocsOptedIn)){let name=docsOptions.defaultName,docsId=(0,import_csf7.toId)(componentId||title,name);this.entries[docsId]={type:"docs",id:docsId,title,name,importPath:fileName,...componentId&&{componentId},tags:[...componentTags,"docs",...autodocsOptedIn&&!componentAutodocs?[AUTODOCS_TAG2]:[]],storiesImports:[]}}storyExports.forEach(([key,storyExport])=>{var _a,_b,_c;let exportName=(0,import_csf7.storyNameFromExport)(key),id=((_a=storyExport.parameters)==null?void 0:_a.__id)||(0,import_csf7.toId)(componentId||title,exportName),name=typeof storyExport!="function"&&storyExport.name||storyExport.storyName||((_b=storyExport.story)==null?void 0:_b.name)||exportName;(_c=storyExport.parameters)!=null&&_c.docsOnly||(this.entries[id]={type:"story",id,name,title,importPath:fileName,...componentId&&{componentId},tags:[...storyExport.tags||componentTags,"story"]})})}};var warningAlternatives={addDecorator:"Instead, use `export const decorators = [];` in your `preview.js`.",addParameters:"Instead, use `export const parameters = {};` in your `preview.js`.",addLoader:"Instead, use `export const loaders = [];` in your `preview.js`.",addArgs:"",addArgTypes:"",addArgsEnhancer:"",addArgTypesEnhancer:"",addStepRunner:"",getGlobalRender:"",setGlobalRender:""},checkMethod=method=>{var _a;if((_a=import_global11.global.FEATURES)!=null&&_a.storyStoreV7)throw new Error(import_ts_dedent13.dedent`You cannot use \`${method}\` with the new Story Store.
|
|
79
79
|
|
|
80
80
|
${warningAlternatives[method]}`);if(!import_global11.global.__STORYBOOK_CLIENT_API__)throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`)},addDecorator=decorator=>{var _a;checkMethod("addDecorator"),(_a=import_global11.global.__STORYBOOK_CLIENT_API__)==null||_a.addDecorator(decorator)},addParameters=parameters=>{var _a;checkMethod("addParameters"),(_a=import_global11.global.__STORYBOOK_CLIENT_API__)==null||_a.addParameters(parameters)},addLoader=loader=>{var _a;checkMethod("addLoader"),(_a=import_global11.global.__STORYBOOK_CLIENT_API__)==null||_a.addLoader(loader)},addArgs=args=>{var _a;checkMethod("addArgs"),(_a=import_global11.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgs(args)},addArgTypes=argTypes=>{var _a;checkMethod("addArgTypes"),(_a=import_global11.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgTypes(argTypes)},addArgsEnhancer=enhancer=>{var _a;checkMethod("addArgsEnhancer"),(_a=import_global11.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgsEnhancer(enhancer)},addArgTypesEnhancer=enhancer=>{var _a;checkMethod("addArgTypesEnhancer"),(_a=import_global11.global.__STORYBOOK_CLIENT_API__)==null||_a.addArgTypesEnhancer(enhancer)},addStepRunner=stepRunner=>{var _a;checkMethod("addStepRunner"),(_a=import_global11.global.__STORYBOOK_CLIENT_API__)==null||_a.addStepRunner(stepRunner)};var setGlobalRender=render=>{checkMethod("setGlobalRender"),import_global11.global.__STORYBOOK_CLIENT_API__&&(import_global11.global.__STORYBOOK_CLIENT_API__.facade.projectAnnotations.render=render)},invalidStoryTypes=new Set(["string","number","boolean","symbol"]),ClientApi=class{constructor({storyStore}={}){this.lastFileName=0;this.addDecorator=decorator=>{var _a;(_a=this.facade.projectAnnotations.decorators)==null||_a.push(decorator)};this.addParameters=({globals,globalTypes,...parameters})=>{this.facade.projectAnnotations.parameters=combineParameters(this.facade.projectAnnotations.parameters,parameters),globals&&(this.facade.projectAnnotations.globals={...this.facade.projectAnnotations.globals,...globals}),globalTypes&&(this.facade.projectAnnotations.globalTypes={...this.facade.projectAnnotations.globalTypes,...normalizeInputTypes(globalTypes)})};this.addStepRunner=stepRunner=>{this.facade.projectAnnotations.runStep=composeStepRunners([this.facade.projectAnnotations.runStep,stepRunner].filter(Boolean))};this.addLoader=loader=>{var _a;(_a=this.facade.projectAnnotations.loaders)==null||_a.push(loader)};this.addArgs=args=>{this.facade.projectAnnotations.args={...this.facade.projectAnnotations.args,...args}};this.addArgTypes=argTypes=>{this.facade.projectAnnotations.argTypes={...this.facade.projectAnnotations.argTypes,...normalizeInputTypes(argTypes)}};this.addArgsEnhancer=enhancer=>{var _a;(_a=this.facade.projectAnnotations.argsEnhancers)==null||_a.push(enhancer)};this.addArgTypesEnhancer=enhancer=>{var _a;(_a=this.facade.projectAnnotations.argTypesEnhancers)==null||_a.push(enhancer)};this._addedExports={};this.storiesOf=(kind,m)=>{if(!kind&&typeof kind!="string")throw new Error("Invalid or missing kind provided for stories, should be a string");if(m||import_client_logger15.logger.warn(`Missing 'module' parameter for story with a kind of '${kind}'. It will break your HMR`),m){let proto=Object.getPrototypeOf(m);proto.exports&&proto.exports.default&&import_client_logger15.logger.error(`Illegal mix of CSF default export and storiesOf calls in a single file: ${proto.i}`)}let baseFilename=m&&m.id?`${m.id}`:(this.lastFileName++).toString(),fileName=baseFilename,i=1;for(;this._addedExports[fileName];)i+=1,fileName=`${baseFilename}-${i}`;m&&m.hot&&m.hot.accept&&(m.hot.accept(),m.hot.dispose(()=>{this.facade.clearFilenameExports(fileName),delete this._addedExports[fileName],setTimeout(()=>{var _a;this._loadAddedExports(),(_a=this.onImportFnChanged)==null||_a.call(this,{importFn:this.importFn.bind(this)})},0)}));let hasAdded=!1,api={kind:kind.toString(),add:()=>api,addDecorator:()=>api,addLoader:()=>api,addParameters:()=>api};Object.keys(this.addons).forEach(name=>{let addon=this.addons[name];api[name]=(...args)=>(addon.apply(api,args),api)});let meta={id:(0,import_csf8.sanitize)(kind),title:kind,decorators:[],loaders:[],parameters:{}};this._addedExports[fileName]={default:meta};let counter=0;return api.add=(storyName,storyFn,parameters={})=>{if(hasAdded=!0,typeof storyName!="string")throw new Error(`Invalid or missing storyName provided for a "${kind}" story.`);if(!storyFn||Array.isArray(storyFn)||invalidStoryTypes.has(typeof storyFn))throw new Error(`Cannot load story "${storyName}" in "${kind}" due to invalid format. Storybook expected a function/object but received ${typeof storyFn} instead.`);let{decorators,loaders,component,args,argTypes,...storyParameters}=parameters,storyId=parameters.__id||(0,import_csf8.toId)(kind,storyName),csfExports=this._addedExports[fileName];return csfExports[`story${counter}`]={name:storyName,parameters:{fileName,__id:storyId,...storyParameters},decorators,loaders,args,argTypes,component,render:storyFn},counter+=1,api},api.addDecorator=decorator=>{var _a;if(hasAdded)throw new Error(`You cannot add a decorator after the first story for a kind.
|
|
81
81
|
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);return(_a=meta.decorators)==null||_a.push(decorator),api},api.addLoader=loader=>{var _a;if(hasAdded)throw new Error("You cannot add a loader after the first story for a kind.");return(_a=meta.loaders)==null||_a.push(loader),api},api.addParameters=({component,args,argTypes,tags,...parameters})=>{if(hasAdded)throw new Error(`You cannot add parameters after the first story for a kind.
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{start}from"./chunk-
|
|
1
|
+
import{start}from"./chunk-JHDSJNE7.mjs";import{makeDecorator}from"./chunk-GRRYLBAT.mjs";import{ClientApi,addArgTypes,addArgTypesEnhancer,addArgs,addArgsEnhancer,addDecorator,addLoader,addParameters,addStepRunner,getQueryParam,getQueryParams,setGlobalRender}from"./chunk-UAUKVCSL.mjs";import{DocsContext,Preview,PreviewWeb,simulateDOMContentLoaded,simulatePageLoad}from"./chunk-HF5EPGVY.mjs";import{StoryStore,combineArgs,combineParameters,composeConfigs,composeStepRunners,composeStories,composeStory,decorateStory,defaultDecorateStory,filterArgTypes,inferControls,normalizeStory,prepareStory,sanitizeStoryContextUpdate,setProjectAnnotations,sortStoriesV7,userOrAutoTitle,userOrAutoTitleFromSpecifier}from"./chunk-RRZ2SPWM.mjs";import{HooksContext,addons,applyHooks,mockChannel,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext}from"./chunk-RTGEOU4B.mjs";export{ClientApi,DocsContext,HooksContext,Preview,PreviewWeb,StoryStore,addArgTypes,addArgTypesEnhancer,addArgs,addArgsEnhancer,addDecorator,addLoader,addParameters,addStepRunner,addons,applyHooks,combineArgs,combineParameters,composeConfigs,composeStepRunners,composeStories,composeStory,decorateStory,defaultDecorateStory,filterArgTypes,getQueryParam,getQueryParams,inferControls,makeDecorator,mockChannel,normalizeStory,prepareStory,sanitizeStoryContextUpdate,setGlobalRender,setProjectAnnotations,simulateDOMContentLoaded,simulatePageLoad,sortStoriesV7,start,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext,userOrAutoTitle,userOrAutoTitleFromSpecifier};
|
package/dist/preview-web.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { DocsContextProps, DocsRenderFunction, ProjectAnnotations as WebProjectAnnotations } from '@storybook/types';
|
|
2
2
|
export { c as composeConfigs } from './composeConfigs-7f62ebf7.js';
|
|
3
|
-
export { D as DocsContext, P as Preview, b as PreviewWeb, c as PreviewWithSelection, a as simulateDOMContentLoaded, s as simulatePageLoad } from './DocsContext-
|
|
3
|
+
export { D as DocsContext, P as Preview, b as PreviewWeb, c as PreviewWithSelection, a as simulateDOMContentLoaded, s as simulatePageLoad } from './DocsContext-917299b8.js';
|
|
4
4
|
import '@storybook/channels';
|
|
5
5
|
import './StoryStore-e35dc2c4.js';
|
|
6
6
|
import 'synchronous-promise';
|
package/dist/preview-web.js
CHANGED
|
@@ -34,7 +34,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
34
34
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
|
|
35
35
|
`);return projectAnnotations}).catch(err=>{throw this.renderPreviewEntryError("Error reading preview.js:",err),err})}initializeWithProjectAnnotations(projectAnnotations){var _a;this.storyStore.setProjectAnnotations(projectAnnotations),this.setInitialGlobals();let storyIndexPromise;if((_a=import_global4.global.FEATURES)!=null&&_a.storyStoreV7)storyIndexPromise=this.getStoryIndexFromServer();else{if(!this.getStoryIndex)throw new Error("No `getStoryIndex` passed defined in v6 mode");storyIndexPromise=import_synchronous_promise2.SynchronousPromise.resolve().then(this.getStoryIndex)}return storyIndexPromise.then(storyIndex=>this.initializeWithStoryIndex(storyIndex)).catch(err=>{throw this.renderPreviewEntryError("Error loading story index:",err),err})}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStore.globals||!this.storyStore.projectAnnotations)throw new Error("Cannot emit before initialization");let payload={globals:this.storyStore.globals.get()||{},globalTypes:this.storyStore.projectAnnotations.globalTypes||{}};this.channel.emit(import_core_events3.SET_GLOBALS,payload)}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new Error(await result.text())}initializeWithStoryIndex(storyIndex){var _a;if(!this.importFn)throw new Error("Cannot call initializeWithStoryIndex before initialization");return this.storyStore.initialize({storyIndex,importFn:this.importFn,cache:!((_a=import_global4.global.FEATURES)!=null&&_a.storyStoreV7)})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError;let projectAnnotations=await this.getProjectAnnotationsOrRenderError(getProjectAnnotations);if(!this.storyStore.projectAnnotations){await this.initializeWithProjectAnnotations(projectAnnotations);return}await this.storyStore.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!!this.storyStore.projectAnnotations)try{let storyIndex=await this.getStoryIndexFromServer();this.storyStore.storyIndex||await this.initializeWithStoryIndex(storyIndex),await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){await this.storyStore.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals}){if(!this.storyStore.globals)throw new Error("Cannot call onUpdateGlobals before initialization");this.storyStore.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(import_core_events3.GLOBALS_UPDATED,{globals:this.storyStore.globals.get(),initialGlobals:this.storyStore.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){this.storyStore.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStore.args.get(storyId)})}async onResetArgs({storyId,argNames}){let render=this.storyRenders.find(r=>r.id===storyId),story=(render==null?void 0:render.story)||await this.storyStore.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStore.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs})}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()))}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()))}renderStoryToElement(story,element,options){if(!this.renderToCanvas)throw new Error("Cannot call renderStoryToElement before initialization");let render=new StoryRender(this.channel,this.storyStore,this.renderToCanvas,this.inlineStoryCallbacks(story.id),story.id,"docs",options,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render)}}async teardownRender(render,{viewModeChanged}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent6.dedent`Failed to initialize Storybook.
|
|
36
36
|
|
|
37
|
-
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global4.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger9.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger9.logger.error(`Error rendering docs story (${storyId})`,err)}}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_global8=require("@storybook/global");var import_ts_dedent7=require("ts-dedent"),import_global5=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger10=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}};var
|
|
37
|
+
Do you have an error in your \`preview.js\`? Check your Storybook's browser console for errors.`);return(_a=import_global4.global.FEATURES)!=null&&_a.storyStoreV7&&await this.storyStore.cacheAllCSFFiles(),this.storyStore.extract(options)}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger9.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger9.logger.error(`Error rendering docs story (${storyId})`,err)}}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_global8=require("@storybook/global");var import_ts_dedent7=require("ts-dedent"),import_global5=require("@storybook/global"),import_core_events6=require("@storybook/core-events"),import_client_logger10=require("@storybook/client-logger");var import_core_events4=require("@storybook/core-events");var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles,componentStoriesFromAllCsfFiles=!0){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.storyIdToCSFFile=new Map,this.exportToStoryId=new Map,this.nameToStoryId=new Map,this.componentStoriesValue=[],csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile,componentStoriesFromAllCsfFiles||index===0)})}referenceCSFFile(csfFile,addToComponentStories){Object.values(csfFile.stories).forEach(annotation=>{this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStoryId.set(annotation.moduleExport,annotation.id)}),addToComponentStories&&this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}setMeta(metaExports){}storyIdByModuleExport(storyExport,metaExports){let storyId=this.exportToStoryId.get(storyExport);if(storyId)return storyId;throw new Error(`No story found with that export: ${storyExport}`)}};var CsfDocsRender=class{constructor(channel,store,entry){this.channel=channel;this.store=store;this.entry=entry;this.type="docs";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!0),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry){this.channel=channel;this.store=store;this.entry=entry;this.type="docs";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.exports&&this.exports===other.exports)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles,!1),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{await new Promise(r=>render(docsContext,docsParameter,canvasElement,r)),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0)},renderDocs()}async teardown({viewModeChanged}={}){var _a;(_a=this.teardownRender)==null||_a.call(this,{viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx";function isMdxEntry({tags}){return!(tags!=null&&tags.includes(AUTODOCS_TAG))&&!(tags!=null&&tags.includes(STORIES_MDX_TAG))}function isStoryRender(r){return r.type==="story"}var PreviewWithSelection=class extends Preview{constructor(selectionStore,view){super();this.selectionStore=selectionStore;this.view=view}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}initializeWithProjectAnnotations(projectAnnotations){return super.initializeWithProjectAnnotations(projectAnnotations).then(()=>this.setInitialGlobals())}async setInitialGlobals(){if(!this.storyStore.globals)throw new Error("Cannot call setInitialGlobals before initialization");let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStore.globals.updateFromPersisted(globals),this.emitGlobals()}initializeWithStoryIndex(storyIndex){return super.initializeWithStoryIndex(storyIndex).then(()=>{var _a;return(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,this.storyStore.getSetIndexPayload()),this.selectSpecifiedStory()})}async selectSpecifiedStory(){if(!this.storyStore.storyIndex)throw new Error("Cannot call selectSpecifiedStory before initialization");if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStore.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new Error(import_ts_dedent7.dedent`
|
|
38
38
|
Couldn't find any stories in your Storybook.
|
|
39
39
|
- Please check your stories field of your main.js config.
|
|
40
40
|
- Also check the browser console and terminal for error messages.
|
|
@@ -43,7 +43,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
|
43
43
|
- Are you sure a story with that id exists?
|
|
44
44
|
- Please check your stories field of your main.js config.
|
|
45
45
|
- Also check the browser console and terminal for error messages.
|
|
46
|
-
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global5.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
|
|
46
|
+
`));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){var _a;await super.onStoriesChanged({importFn,storyIndex}),(_a=import_global5.global.FEATURES)!=null&&_a.storyStoreV7||this.channel.emit(import_core_events6.SET_INDEX,await this.storyStore.getSetIndexPayload()),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){await this.storyStore.initializationPromise,this.selectionStore.setSelection({viewMode:"story",...selection}),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){var _a,_b;super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await((_b=(_a=this.currentRender).rerender)==null?void 0:_b.call(_a))}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await Promise.allSettled(ids.map(id=>this.storyStore.loadEntry(id)))}async renderSelection({persistedArgs}={}){var _a,_b,_c,_d;let{renderToCanvas}=this;if(!renderToCanvas)throw new Error("Cannot call renderSelection before initialization");let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStore.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=((_a=this.currentSelection)==null?void 0:_a.storyId)!==storyId,viewModeChanged=((_b=this.currentRender)==null?void 0:_b.type)!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs(),(_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):render=new CsfDocsRender(this.channel,this.storyStore,entry);let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyStore.args.updateFromPersisted(render.story,persistedArgs)}if(lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");let{parameters,initialArgs,argTypes,args}=this.storyStore.getStoryContext(render.story);(_d=import_global5.global.FEATURES)!=null&&_d.storyStoreV7&&this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args})}if(isStoryRender(render)){if(!render.story)throw new Error("Render has not been prepared!");this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))}else this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){var _a;this.storyRenders=this.storyRenders.filter(r=>r!==render),await((_a=render==null?void 0:render.teardown)==null?void 0:_a.call(render,{viewModeChanged}))}async extract(options){var _a;if(this.previewEntryError)throw this.previewEntryError;if(!this.storyStore.projectAnnotations)throw new Error(import_ts_dedent7.dedent`Failed to initialize Storybook.
|
|
47
47
|
|
|
48
48
|
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)}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}inlineStoryCallbacks(storyId){return{showMain:()=>{},showError:err=>import_client_logger10.logger.error(`Error rendering docs story (${storyId})`,err),showException:err=>import_client_logger10.logger.error(`Error rendering docs story (${storyId})`,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_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_global6=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent8=require("ts-dedent"),import_client_logger11=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject")),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.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_dedent8.dedent`
|
|
49
49
|
Omitted potentially unsafe URL args.
|
package/dist/preview-web.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DocsContext,Preview,PreviewWeb,PreviewWithSelection,simulateDOMContentLoaded,simulatePageLoad}from"./chunk-
|
|
1
|
+
import{DocsContext,Preview,PreviewWeb,PreviewWithSelection,simulateDOMContentLoaded,simulatePageLoad}from"./chunk-HF5EPGVY.mjs";import{composeConfigs}from"./chunk-RRZ2SPWM.mjs";import"./chunk-RTGEOU4B.mjs";export{DocsContext,Preview,PreviewWeb,PreviewWithSelection,composeConfigs,simulateDOMContentLoaded,simulatePageLoad};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storybook/preview-api",
|
|
3
|
-
"version": "7.0.0-beta.
|
|
3
|
+
"version": "7.0.0-beta.17",
|
|
4
4
|
"description": "",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"storybook"
|
|
@@ -67,13 +67,13 @@
|
|
|
67
67
|
"prep": "../../../scripts/prepare/bundle.ts"
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
|
70
|
-
"@storybook/channel-postmessage": "7.0.0-beta.
|
|
71
|
-
"@storybook/channels": "7.0.0-beta.
|
|
72
|
-
"@storybook/client-logger": "7.0.0-beta.
|
|
73
|
-
"@storybook/core-events": "7.0.0-beta.
|
|
70
|
+
"@storybook/channel-postmessage": "7.0.0-beta.17",
|
|
71
|
+
"@storybook/channels": "7.0.0-beta.17",
|
|
72
|
+
"@storybook/client-logger": "7.0.0-beta.17",
|
|
73
|
+
"@storybook/core-events": "7.0.0-beta.17",
|
|
74
74
|
"@storybook/csf": "next",
|
|
75
75
|
"@storybook/global": "^5.0.0",
|
|
76
|
-
"@storybook/types": "7.0.0-beta.
|
|
76
|
+
"@storybook/types": "7.0.0-beta.17",
|
|
77
77
|
"@types/qs": "^6.9.5",
|
|
78
78
|
"dequal": "^2.0.2",
|
|
79
79
|
"lodash": "^4.17.21",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
},
|
|
87
87
|
"devDependencies": {
|
|
88
88
|
"@jest/globals": "^26.6.2",
|
|
89
|
-
"@storybook/core-common": "7.0.0-beta.
|
|
89
|
+
"@storybook/core-common": "7.0.0-beta.17",
|
|
90
90
|
"ansi-to-html": "^0.6.11",
|
|
91
91
|
"react": "^16.14.0"
|
|
92
92
|
},
|
|
@@ -103,5 +103,5 @@
|
|
|
103
103
|
"./src/store.ts"
|
|
104
104
|
]
|
|
105
105
|
},
|
|
106
|
-
"gitHead": "
|
|
106
|
+
"gitHead": "6559b419625c2dcf76bad1a12fcf75e3dd7c4187"
|
|
107
107
|
}
|