@storybook/preview-api 8.1.0-alpha.7 → 8.1.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +16 -3
- package/dist/index.js +15 -9
- package/dist/index.mjs +15 -9
- package/package.json +7 -7
package/dist/index.d.ts
CHANGED
@@ -1,6 +1,8 @@
|
|
1
1
|
import { Channel } from '@storybook/channels';
|
2
2
|
import * as _storybook_types from '@storybook/types';
|
3
3
|
import { Renderer, Args, StoryContext, StoryId, DecoratorApplicator, Addon_StoryWrapper, StoryName, ComponentTitle, StoryIndex, IndexEntry, Path, PreparedStory, Globals, GlobalTypes, LegacyStoryAnnotationsOrFn, NormalizedComponentAnnotations, NormalizedStoryAnnotations, ModuleExports, CSFFile, NormalizedProjectAnnotations, ModuleExport, PreparedMeta, ProjectAnnotations, StepRunner, NamedOrDefaultProjectAnnotations, ComponentAnnotations, ComposedStoryFn, Store_CSFExports, ComposeStoryFn, ModuleImportFn, StoryContextForLoaders, StoryContextForEnhancers, Parameters, StoryIndexV3, BoundStory, StrictArgTypes, ArgTypesEnhancer, LegacyStoryFn, DecoratorFunction, PartialStoryFn, StoryContextUpdate, NormalizedStoriesSpecifier, Addon_StorySortParameterV7, StoryRenderOptions, ViewMode, RenderToCanvas, RenderContextCallbacks, DocsContextProps, ResolvedModuleExportType, ResolvedModuleExportFromType } from '@storybook/types';
|
4
|
+
import { CleanupCallback } from '@storybook/csf';
|
5
|
+
import { RequestData, ArgTypesRequestPayload } from '@storybook/core-events';
|
4
6
|
import qs$1 from 'qs';
|
5
7
|
|
6
8
|
declare class AddonStore {
|
@@ -315,7 +317,7 @@ declare function composeConfigs<TRenderer extends Renderer>(moduleExportList: Mo
|
|
315
317
|
/**
|
316
318
|
* Compose step runners to create a single step runner that applies each step runner in order.
|
317
319
|
*
|
318
|
-
* A step runner is a
|
320
|
+
* A step runner is a function that takes a defined step: `step('label', () => { ... })`
|
319
321
|
* and runs it. The prototypical example is from `@storybook/addon-interactions` where the
|
320
322
|
* step runner will decorate all instrumented code inside the step with information about the
|
321
323
|
* label.
|
@@ -357,6 +359,7 @@ declare class StoryStore<TRenderer extends Renderer> {
|
|
357
359
|
globals: GlobalsStore;
|
358
360
|
args: ArgsStore;
|
359
361
|
hooks: Record<StoryId, HooksContext<TRenderer>>;
|
362
|
+
cleanupCallbacks: Record<StoryId, CleanupCallback[] | undefined>;
|
360
363
|
cachedCSFFiles?: Record<Path, CSFFile<TRenderer>>;
|
361
364
|
processCSFFileWithCache: typeof processCSFFile;
|
362
365
|
prepareMetaWithCache: typeof prepareMeta;
|
@@ -391,7 +394,8 @@ declare class StoryStore<TRenderer extends Renderer> {
|
|
391
394
|
getStoryContext(story: PreparedStory<TRenderer>, { forceInitialArgs }?: {
|
392
395
|
forceInitialArgs?: boolean | undefined;
|
393
396
|
}): Omit<StoryContextForLoaders, 'viewMode'>;
|
394
|
-
|
397
|
+
addCleanupCallbacks(story: PreparedStory<TRenderer>, callbacks: CleanupCallback[]): void;
|
398
|
+
cleanupStory(story: PreparedStory<TRenderer>): Promise<void>;
|
395
399
|
extract(options?: {
|
396
400
|
includeDocsOnly?: boolean;
|
397
401
|
}): Record<StoryId, StoryContextForEnhancers<TRenderer>>;
|
@@ -459,7 +463,7 @@ interface Render<TRenderer extends Renderer> {
|
|
459
463
|
renderToElement: (canvasElement: TRenderer['canvasElement'], renderStoryToElement?: any, options?: StoryRenderOptions) => Promise<void>;
|
460
464
|
}
|
461
465
|
|
462
|
-
type RenderPhase = 'preparing' | 'loading' | 'rendering' | 'playing' | 'played' | 'completed' | 'aborted' | 'errored';
|
466
|
+
type RenderPhase = 'preparing' | 'loading' | 'beforeEach' | 'rendering' | 'playing' | 'played' | 'completed' | 'aborted' | 'errored';
|
463
467
|
declare class StoryRender<TRenderer extends Renderer> implements Render<TRenderer> {
|
464
468
|
channel: Channel;
|
465
469
|
store: StoryStore<TRenderer>;
|
@@ -474,6 +478,7 @@ declare class StoryRender<TRenderer extends Renderer> implements Render<TRendere
|
|
474
478
|
private abortController?;
|
475
479
|
private canvasElement?;
|
476
480
|
private notYetRendered;
|
481
|
+
private rerenderEnqueued;
|
477
482
|
disableKeyListeners: boolean;
|
478
483
|
private teardownRender;
|
479
484
|
torndown: boolean;
|
@@ -489,6 +494,13 @@ declare class StoryRender<TRenderer extends Renderer> implements Render<TRendere
|
|
489
494
|
initial?: boolean;
|
490
495
|
forceRemount?: boolean;
|
491
496
|
}): Promise<void>;
|
497
|
+
/**
|
498
|
+
* Rerender the story.
|
499
|
+
* If the story is currently pending (loading/rendering), the rerender will be enqueued,
|
500
|
+
* and will be executed after the current render is completed.
|
501
|
+
* Rerendering while playing will not be enqueued, and will be executed immediately, to support
|
502
|
+
* rendering args changes while playing.
|
503
|
+
*/
|
492
504
|
rerender(): Promise<void>;
|
493
505
|
remount(): Promise<void>;
|
494
506
|
cancelRender(): void;
|
@@ -644,6 +656,7 @@ declare class Preview<TRenderer extends Renderer> {
|
|
644
656
|
storyId: StoryId;
|
645
657
|
updatedArgs: Args;
|
646
658
|
}): Promise<void>;
|
659
|
+
onRequestArgTypesInfo({ id, payload }: RequestData<ArgTypesRequestPayload>): Promise<void>;
|
647
660
|
onResetArgs({ storyId, argNames }: {
|
648
661
|
storyId: string;
|
649
662
|
argNames?: string[];
|
package/dist/index.js
CHANGED
@@ -3,7 +3,7 @@
|
|
3
3
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var it,normalCompletion=!0,didErr=!1,err;return{s:function(){it=o[Symbol.iterator]()},n:function(){var step=it.next();return normalCompletion=step.done,step},e:function(_e2){didErr=!0,err=_e2},f:function(){try{!normalCompletion&&it.return!=null&&it.return()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(o){if(typeof o=="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor&&(n=o.constructor.name),n==="Map"||n==="Set")return Array.from(n);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}}function _arrayLikeToArray(arr,len){(len==null||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}var entities=require_lib(),defaults={fg:"#FFF",bg:"#000",newline:!1,escapeXML:!1,stream:!1,colors:getDefaultColors()};function getDefaultColors(){var colors={0:"#000",1:"#A00",2:"#0A0",3:"#A50",4:"#00A",5:"#A0A",6:"#0AA",7:"#AAA",8:"#555",9:"#F55",10:"#5F5",11:"#FF5",12:"#55F",13:"#F5F",14:"#5FF",15:"#FFF"};return range(0,5).forEach(function(red){range(0,5).forEach(function(green){range(0,5).forEach(function(blue){return setStyleColor(red,green,blue,colors)})})}),range(0,23).forEach(function(gray){var c=gray+232,l=toHexString(gray*10+8);colors[c]="#"+l+l+l}),colors}function setStyleColor(red,green,blue,colors){var c=16+red*36+green*6+blue,r=red>0?red*40+55:0,g=green>0?green*40+55:0,b=blue>0?blue*40+55:0;colors[c]=toColorHexString([r,g,b])}function toHexString(num){for(var str=num.toString(16);str.length<2;)str="0"+str;return str}function toColorHexString(ref){var results=[],_iterator=_createForOfIteratorHelper(ref),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var r=_step.value;results.push(toHexString(r))}}catch(err){_iterator.e(err)}finally{_iterator.f()}return"#"+results.join("")}function generateOutput(stack,token,data,options){var result;return token==="text"?result=pushText(data,options):token==="display"?result=handleDisplay(stack,data,options):token==="xterm256"?result=pushForegroundColor(stack,options.colors[data]):token==="rgb"&&(result=handleRgb(stack,data)),result}function handleRgb(stack,data){data=data.substring(2).slice(0,-1);var operation=+data.substr(0,2),color=data.substring(5).split(";"),rgb=color.map(function(value){return("0"+Number(value).toString(16)).substr(-2)}).join("");return pushStyle(stack,(operation===38?"color:#":"background-color:#")+rgb)}function handleDisplay(stack,code,options){code=parseInt(code,10);var codeMap={"-1":function(){return"<br/>"},0:function(){return stack.length&&resetStyles(stack)},1:function(){return pushTag(stack,"b")},3:function(){return pushTag(stack,"i")},4:function(){return pushTag(stack,"u")},8:function(){return pushStyle(stack,"display:none")},9:function(){return pushTag(stack,"strike")},22:function(){return pushStyle(stack,"font-weight:normal;text-decoration:none;font-style:normal")},23:function(){return closeTag(stack,"i")},24:function(){return closeTag(stack,"u")},39:function(){return pushForegroundColor(stack,options.fg)},49:function(){return pushBackgroundColor(stack,options.bg)},53:function(){return pushStyle(stack,"text-decoration:overline")}},result;return codeMap[code]?result=codeMap[code]():4<code&&code<7?result=pushTag(stack,"blink"):29<code&&code<38?result=pushForegroundColor(stack,options.colors[code-30]):39<code&&code<48?result=pushBackgroundColor(stack,options.colors[code-40]):89<code&&code<98?result=pushForegroundColor(stack,options.colors[8+(code-90)]):99<code&&code<108&&(result=pushBackgroundColor(stack,options.colors[8+(code-100)])),result}function resetStyles(stack){var stackClone=stack.slice(0);return stack.length=0,stackClone.reverse().map(function(tag){return"</"+tag+">"}).join("")}function range(low,high){for(var results=[],j=low;j<=high;j++)results.push(j);return results}function notCategory(category){return function(e){return(category===null||e.category!==category)&&category!=="all"}}function categoryForCode(code){code=parseInt(code,10);var result=null;return code===0?result="all":code===1?result="bold":2<code&&code<5?result="underline":4<code&&code<7?result="blink":code===8?result="hide":code===9?result="strike":29<code&&code<38||code===39||89<code&&code<98?result="foreground-color":(39<code&&code<48||code===49||99<code&&code<108)&&(result="background-color"),result}function pushText(text,options){return options.escapeXML?entities.encodeXML(text):text}function pushTag(stack,tag,style){return style||(style=""),stack.push(tag),"<".concat(tag).concat(style?' style="'.concat(style,'"'):"",">")}function pushStyle(stack,style){return pushTag(stack,"span",style)}function pushForegroundColor(stack,color){return pushTag(stack,"span","color:"+color)}function pushBackgroundColor(stack,color){return pushTag(stack,"span","background-color:"+color)}function closeTag(stack,style){var last;if(stack.slice(-1)[0]===style&&(last=stack.pop()),last)return"</"+style+">"}function tokenize(text,options,callback){var ansiMatch=!1,ansiHandler=3;function remove(){return""}function removeXterm256(m,g1){return callback("xterm256",g1),""}function newline(m){return options.newline?callback("display",-1):callback("text",m),""}function ansiMess(m,g1){ansiMatch=!0,g1.trim().length===0&&(g1="0"),g1=g1.trimRight(";").split(";");var _iterator2=_createForOfIteratorHelper(g1),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var g=_step2.value;callback("display",g)}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}return""}function realText(m){return callback("text",m),""}function rgb(m){return callback("rgb",m),""}var tokens=[{pattern:/^\x08+/,sub:remove},{pattern:/^\x1b\[[012]?K/,sub:remove},{pattern:/^\x1b\[\(B/,sub:remove},{pattern:/^\x1b\[[34]8;2;\d+;\d+;\d+m/,sub:rgb},{pattern:/^\x1b\[38;5;(\d+)m/,sub:removeXterm256},{pattern:/^\n/,sub:newline},{pattern:/^\r+\n/,sub:newline},{pattern:/^\x1b\[((?:\d{1,3};?)+|)m/,sub:ansiMess},{pattern:/^\x1b\[\d?J/,sub:remove},{pattern:/^\x1b\[\d{0,3};\d{0,3}f/,sub:remove},{pattern:/^\x1b\[?[\d;]{0,3}/,sub:remove},{pattern:/^(([^\x1b\x08\r\n])+)/,sub:realText}];function process(handler2,i2){i2>ansiHandler&&ansiMatch||(ansiMatch=!1,text=text.replace(handler2.pattern,handler2.sub))}var results1=[],_text=text,length=_text.length;outer:for(;length>0;){for(var i=0,o=0,len=tokens.length;o<len;i=++o){var handler=tokens[i];if(process(handler,i),text.length!==length){length=text.length;continue outer}}if(text.length===length)break;results1.push(0),length=text.length}return results1}function updateStickyStack(stickyStack,token,data){return token!=="text"&&(stickyStack=stickyStack.filter(notCategory(categoryForCode(data))),stickyStack.push({token,data,category:categoryForCode(data)})),stickyStack}var Filter=function(){function Filter2(options){_classCallCheck(this,Filter2),options=options||{},options.colors&&(options.colors=Object.assign({},defaults.colors,options.colors)),this.options=Object.assign({},defaults,options),this.stack=[],this.stickyStack=[]}return _createClass(Filter2,[{key:"toHtml",value:function(input){var _this=this;input=typeof input=="string"?[input]:input;var stack=this.stack,options=this.options,buf=[];return this.stickyStack.forEach(function(element){var output=generateOutput(stack,element.token,element.data,options);output&&buf.push(output)}),tokenize(input.join(""),options,function(token,data){var output=generateOutput(stack,token,data,options);output&&buf.push(output),options.stream&&(_this.stickyStack=updateStickyStack(_this.stickyStack,token,data))}),stack.length&&buf.push(resetStyles(stack)),buf.join("")}}]),Filter2}();module2.exports=Filter}});var src_exports={};__export(src_exports,{DocsContext:()=>DocsContext,HooksContext:()=>HooksContext,Preview:()=>Preview,PreviewWeb:()=>PreviewWeb,PreviewWithSelection:()=>PreviewWithSelection,StoryStore:()=>StoryStore,UrlStore:()=>UrlStore,WebView:()=>WebView,addons:()=>addons,applyHooks:()=>applyHooks,combineArgs:()=>combineArgs,combineParameters:()=>combineParameters,composeConfigs:()=>composeConfigs,composeStepRunners:()=>composeStepRunners,composeStories:()=>composeStories,composeStory:()=>composeStory,createPlaywrightTest:()=>createPlaywrightTest,decorateStory:()=>decorateStory,defaultDecorateStory:()=>defaultDecorateStory,filterArgTypes:()=>filterArgTypes,inferControls:()=>inferControls,makeDecorator:()=>makeDecorator,mockChannel:()=>mockChannel,normalizeStory:()=>normalizeStory,prepareMeta:()=>prepareMeta,prepareStory:()=>prepareStory,sanitizeStoryContextUpdate:()=>sanitizeStoryContextUpdate,setProjectAnnotations:()=>setProjectAnnotations,simulateDOMContentLoaded:()=>simulateDOMContentLoaded,simulatePageLoad:()=>simulatePageLoad,sortStoriesV7:()=>sortStoriesV7,useArgs:()=>useArgs,useCallback:()=>useCallback,useChannel:()=>useChannel,useEffect:()=>useEffect,useGlobals:()=>useGlobals,useMemo:()=>useMemo,useParameter:()=>useParameter,useReducer:()=>useReducer,useRef:()=>useRef,useState:()=>useState,useStoryContext:()=>useStoryContext,userOrAutoTitle:()=>userOrAutoTitle,userOrAutoTitleFromSpecifier:()=>userOrAutoTitleFromSpecifier});module.exports=__toCommonJS(src_exports);var import_global=require("@storybook/global");var import_channels=require("@storybook/channels");function mockChannel(){let transport={setHandler:()=>{},send:()=>{}};return new import_channels.Channel({transport})}var AddonStore=class{constructor(){this.getChannel=()=>{if(!this.channel){let channel=mockChannel();return this.setChannel(channel),channel}return this.channel};this.ready=()=>this.promise;this.hasChannel=()=>!!this.channel;this.setChannel=channel=>{this.channel=channel,this.resolve()};this.promise=new Promise(res=>{this.resolve=()=>res(this.getChannel())})}},KEY="__STORYBOOK_ADDONS_PREVIEW";function getAddonsStore(){return import_global.global[KEY]||(import_global.global[KEY]=new AddonStore),import_global.global[KEY]}var addons=getAddonsStore();var import_global2=require("@storybook/global"),import_client_logger=require("@storybook/client-logger"),import_core_events=require("@storybook/core-events");var HooksContext=class{constructor(){this.hookListsMap=void 0;this.mountedDecorators=void 0;this.prevMountedDecorators=void 0;this.currentHooks=void 0;this.nextHookIndex=void 0;this.currentPhase=void 0;this.currentEffects=void 0;this.prevEffects=void 0;this.currentDecoratorName=void 0;this.hasUpdates=void 0;this.currentContext=void 0;this.renderListener=storyId=>{storyId===this.currentContext?.id&&(this.triggerEffects(),this.currentContext=null,this.removeRenderListeners())};this.init()}init(){this.hookListsMap=new WeakMap,this.mountedDecorators=new Set,this.prevMountedDecorators=new Set,this.currentHooks=[],this.nextHookIndex=0,this.currentPhase="NONE",this.currentEffects=[],this.prevEffects=[],this.currentDecoratorName=null,this.hasUpdates=!1,this.currentContext=null}clean(){this.prevEffects.forEach(effect=>{effect.destroy&&effect.destroy()}),this.init(),this.removeRenderListeners()}getNextHook(){let hook=this.currentHooks[this.nextHookIndex];return this.nextHookIndex+=1,hook}triggerEffects(){this.prevEffects.forEach(effect=>{!this.currentEffects.includes(effect)&&effect.destroy&&effect.destroy()}),this.currentEffects.forEach(effect=>{this.prevEffects.includes(effect)||(effect.destroy=effect.create())}),this.prevEffects=this.currentEffects,this.currentEffects=[]}addRenderListeners(){this.removeRenderListeners(),addons.getChannel().on(import_core_events.STORY_RENDERED,this.renderListener)}removeRenderListeners(){addons.getChannel().removeListener(import_core_events.STORY_RENDERED,this.renderListener)}};function hookify(fn){let hookified=(...args)=>{let{hooks}=typeof args[0]=="function"?args[1]:args[0],prevPhase=hooks.currentPhase,prevHooks=hooks.currentHooks,prevNextHookIndex=hooks.nextHookIndex,prevDecoratorName=hooks.currentDecoratorName;hooks.currentDecoratorName=fn.name,hooks.prevMountedDecorators.has(fn)?(hooks.currentPhase="UPDATE",hooks.currentHooks=hooks.hookListsMap.get(fn)||[]):(hooks.currentPhase="MOUNT",hooks.currentHooks=[],hooks.hookListsMap.set(fn,hooks.currentHooks),hooks.prevMountedDecorators.add(fn)),hooks.nextHookIndex=0;let prevContext=import_global2.global.STORYBOOK_HOOKS_CONTEXT;import_global2.global.STORYBOOK_HOOKS_CONTEXT=hooks;let result=fn(...args);if(import_global2.global.STORYBOOK_HOOKS_CONTEXT=prevContext,hooks.currentPhase==="UPDATE"&&hooks.getNextHook()!=null)throw new Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");return hooks.currentPhase=prevPhase,hooks.currentHooks=prevHooks,hooks.nextHookIndex=prevNextHookIndex,hooks.currentDecoratorName=prevDecoratorName,result};return hookified.originalFn=fn,hookified}var numberOfRenders=0,RENDER_LIMIT=25,applyHooks=applyDecorators=>(storyFn,decorators)=>{let decorated=applyDecorators(hookify(storyFn),decorators.map(decorator=>hookify(decorator)));return context=>{let{hooks}=context;hooks.prevMountedDecorators??=new Set,hooks.mountedDecorators=new Set([storyFn,...decorators]),hooks.currentContext=context,hooks.hasUpdates=!1;let result=decorated(context);for(numberOfRenders=1;hooks.hasUpdates;)if(hooks.hasUpdates=!1,hooks.currentEffects=[],result=decorated(context),numberOfRenders+=1,numberOfRenders>RENDER_LIMIT)throw new Error("Too many re-renders. Storybook limits the number of renders to prevent an infinite loop.");return hooks.addRenderListeners(),result}},areDepsEqual=(deps,nextDeps)=>deps.length===nextDeps.length&&deps.every((dep,i)=>dep===nextDeps[i]),invalidHooksError=()=>new Error("Storybook preview hooks can only be called inside decorators and story functions.");function getHooksContextOrNull(){return import_global2.global.STORYBOOK_HOOKS_CONTEXT||null}function getHooksContextOrThrow(){let hooks=getHooksContextOrNull();if(hooks==null)throw invalidHooksError();return hooks}function useHook(name,callback,deps){let hooks=getHooksContextOrThrow();if(hooks.currentPhase==="MOUNT"){deps!=null&&!Array.isArray(deps)&&import_client_logger.logger.warn(`${name} received a final argument that is not an array (instead, received ${deps}). When specified, the final argument must be an array.`);let hook={name,deps};return hooks.currentHooks.push(hook),callback(hook),hook}if(hooks.currentPhase==="UPDATE"){let hook=hooks.getNextHook();if(hook==null)throw new Error("Rendered more hooks than during the previous render.");return hook.name!==name&&import_client_logger.logger.warn(`Storybook has detected a change in the order of Hooks${hooks.currentDecoratorName?` called by ${hooks.currentDecoratorName}`:""}. This will lead to bugs and errors if not fixed.`),deps!=null&&hook.deps==null&&import_client_logger.logger.warn(`${name} received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.`),deps!=null&&hook.deps!=null&&deps.length!==hook.deps.length&&import_client_logger.logger.warn(`The final argument passed to ${name} changed size between renders. The order and size of this array must remain constant.
|
4
4
|
Previous: ${hook.deps}
|
5
5
|
Incoming: ${deps}`),(deps==null||hook.deps==null||!areDepsEqual(deps,hook.deps))&&(callback(hook),hook.deps=deps),hook}throw invalidHooksError()}function useMemoLike(name,nextCreate,deps){let{memoizedState}=useHook(name,hook=>{hook.memoizedState=nextCreate()},deps);return memoizedState}function useMemo(nextCreate,deps){return useMemoLike("useMemo",nextCreate,deps)}function useCallback(callback,deps){return useMemoLike("useCallback",()=>callback,deps)}function useRefLike(name,initialValue){return useMemoLike(name,()=>({current:initialValue}),[])}function useRef(initialValue){return useRefLike("useRef",initialValue)}function triggerUpdate(){let hooks=getHooksContextOrNull();if(hooks!=null&&hooks.currentPhase!=="NONE")hooks.hasUpdates=!0;else try{addons.getChannel().emit(import_core_events.FORCE_RE_RENDER)}catch{import_client_logger.logger.warn("State updates of Storybook preview hooks work only in browser")}}function useStateLike(name,initialState){let stateRef=useRefLike(name,typeof initialState=="function"?initialState():initialState),setState=update=>{stateRef.current=typeof update=="function"?update(stateRef.current):update,triggerUpdate()};return[stateRef.current,setState]}function useState(initialState){return useStateLike("useState",initialState)}function useReducer(reducer,initialArg,init){let initialState=init!=null?()=>init(initialArg):initialArg,[state,setState]=useStateLike("useReducer",initialState);return[state,action=>setState(prevState=>reducer(prevState,action))]}function useEffect(create,deps){let hooks=getHooksContextOrThrow(),effect=useMemoLike("useEffect",()=>({create}),deps);hooks.currentEffects.includes(effect)||hooks.currentEffects.push(effect)}function useChannel(eventMap,deps=[]){let channel=addons.getChannel();return useEffect(()=>(Object.entries(eventMap).forEach(([type,listener])=>channel.on(type,listener)),()=>{Object.entries(eventMap).forEach(([type,listener])=>channel.removeListener(type,listener))}),[...Object.keys(eventMap),...deps]),useCallback(channel.emit.bind(channel),[channel])}function useStoryContext(){let{currentContext}=getHooksContextOrThrow();if(currentContext==null)throw invalidHooksError();return currentContext}function useParameter(parameterKey,defaultValue){let{parameters}=useStoryContext();if(parameterKey)return parameters[parameterKey]??defaultValue}function useArgs(){let channel=addons.getChannel(),{id:storyId,args}=useStoryContext(),updateArgs=useCallback(updatedArgs=>channel.emit(import_core_events.UPDATE_STORY_ARGS,{storyId,updatedArgs}),[channel,storyId]),resetArgs=useCallback(argNames=>channel.emit(import_core_events.RESET_STORY_ARGS,{storyId,argNames}),[channel,storyId]);return[args,updateArgs,resetArgs]}function useGlobals(){let channel=addons.getChannel(),{globals}=useStoryContext(),updateGlobals=useCallback(newGlobals=>channel.emit(import_core_events.UPDATE_GLOBALS,{globals:newGlobals}),[channel]);return[globals,updateGlobals]}var makeDecorator=({name,parameterName,wrapper,skipIfNoParametersOrOptions=!1})=>{let decorator=options=>(storyFn,context)=>{let parameters=context.parameters&&context.parameters[parameterName];return parameters&¶meters.disable||skipIfNoParametersOrOptions&&!options&&!parameters?storyFn(context):wrapper(storyFn,context,{options,parameters})};return(...args)=>typeof args[0]=="function"?decorator()(...args):(...innerArgs)=>{if(innerArgs.length>1)return args.length>1?decorator(args)(...innerArgs):decorator(...args)(...innerArgs);throw new Error(`Passing stories directly into ${name}() is not allowed,
|
6
|
-
instead use addDecorator(${name}) and pass options with the '${parameterName}' parameter`)}};var import_memoizerific2=__toESM(require("memoizerific")),import_mapValues4=__toESM(require("lodash/mapValues.js")),import_pick=__toESM(require("lodash/pick.js")),import_preview_errors2=require("@storybook/core-events/preview-errors"),
|
6
|
+
instead use addDecorator(${name}) and pass options with the '${parameterName}' parameter`)}};var import_memoizerific2=__toESM(require("memoizerific")),import_mapValues4=__toESM(require("lodash/mapValues.js")),import_pick=__toESM(require("lodash/pick.js")),import_preview_errors2=require("@storybook/core-events/preview-errors"),import_client_logger9=require("@storybook/client-logger");var import_memoizerific=__toESM(require("memoizerific")),import_preview_errors=require("@storybook/core-events/preview-errors"),getImportPathMap=(0,import_memoizerific.default)(1)(entries=>Object.values(entries).reduce((acc,entry)=>(acc[entry.importPath]=acc[entry.importPath]||entry,acc),{})),StoryIndexStore=class{constructor({entries}={v:4,entries:{}}){this.entries=entries}entryFromSpecifier(specifier){let entries=Object.values(this.entries);if(specifier==="*")return entries[0];if(typeof specifier=="string")return this.entries[specifier]?this.entries[specifier]:entries.find(entry=>entry.id.startsWith(specifier));let{name,title}=specifier;return entries.find(entry=>entry.name===name&&entry.title===title)}storyIdToEntry(storyId){let storyEntry=this.entries[storyId];if(!storyEntry)throw new import_preview_errors.MissingStoryAfterHmrError({storyId});return storyEntry}importPathToEntry(importPath){return getImportPathMap(this.entries)[importPath]}};var import_dequal=require("dequal"),import_client_logger2=require("@storybook/client-logger"),import_isPlainObject=__toESM(require("lodash/isPlainObject.js")),import_ts_dedent=require("ts-dedent"),INCOMPATIBLE=Symbol("incompatible"),map=(arg,argType)=>{let type=argType.type;if(arg==null||!type||argType.mapping)return arg;switch(type.name){case"string":return String(arg);case"enum":return arg;case"number":return Number(arg);case"boolean":return String(arg)==="true";case"array":return!type.value||!Array.isArray(arg)?INCOMPATIBLE:arg.reduce((acc,item,index)=>{let mapped=map(item,{type:type.value});return mapped!==INCOMPATIBLE&&(acc[index]=mapped),acc},new Array(arg.length));case"object":return typeof arg=="string"||typeof arg=="number"?arg:!type.value||typeof arg!="object"?INCOMPATIBLE:Object.entries(arg).reduce((acc,[key,val])=>{let mapped=map(val,{type:type.value[key]});return mapped===INCOMPATIBLE?acc:Object.assign(acc,{[key]:mapped})},{});default:return INCOMPATIBLE}},mapArgsToTypes=(args,argTypes)=>Object.entries(args).reduce((acc,[key,value])=>{if(!argTypes[key])return acc;let mapped=map(value,argTypes[key]);return mapped===INCOMPATIBLE?acc:Object.assign(acc,{[key]:mapped})},{}),combineArgs=(value,update)=>Array.isArray(value)&&Array.isArray(update)?update.reduce((acc,upd,index)=>(acc[index]=combineArgs(value[index],update[index]),acc),[...value]).filter(v=>v!==void 0):!(0,import_isPlainObject.default)(value)||!(0,import_isPlainObject.default)(update)?update:Object.keys({...value,...update}).reduce((acc,key)=>{if(key in update){let combined=combineArgs(value[key],update[key]);combined!==void 0&&(acc[key]=combined)}else acc[key]=value[key];return acc},{}),validateOptions=(args,argTypes)=>Object.entries(argTypes).reduce((acc,[key,{options}])=>{function allowArg(){return key in args&&(acc[key]=args[key]),acc}if(!options)return allowArg();if(!Array.isArray(options))return import_client_logger2.once.error(import_ts_dedent.dedent`
|
7
7
|
Invalid argType: '${key}.options' should be an array.
|
8
8
|
|
9
9
|
More info: https://storybook.js.org/docs/react/api/argtypes
|
@@ -16,13 +16,19 @@ CSF .story annotations deprecated; annotate story functions directly:
|
|
16
16
|
- StoryFn.story.name => StoryFn.storyName
|
17
17
|
- StoryFn.story.(parameters|decorators) => StoryFn.(parameters|decorators)
|
18
18
|
See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-annotations for details and codemod.
|
19
|
-
`,deprecatedStoryAnnotationWarning=(0,import_util_deprecate.default)(()=>{},deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){let storyObject=storyAnnotations,userStoryFn=typeof storyAnnotations=="function"?storyAnnotations:null,{story}=storyObject;story&&(import_client_logger4.logger.debug("deprecated story",story),deprecatedStoryAnnotationWarning());let exportName=(0,import_csf.storyNameFromExport)(key),name=typeof storyObject!="function"&&storyObject.name||storyObject.storyName||story?.name||exportName,decorators=[...normalizeArrays(storyObject.decorators),...normalizeArrays(story?.decorators)],parameters={...story?.parameters,...storyObject.parameters},args={...story?.args,...storyObject.args},argTypes={...story?.argTypes,...storyObject.argTypes},loaders=[...normalizeArrays(storyObject.loaders),...normalizeArrays(story?.loaders)],{render,play,tags=[]}=storyObject,id=parameters.__id||(0,import_csf.toId)(meta.id,exportName);return{moduleExport:storyAnnotations,id,name,tags,decorators,parameters,args,argTypes:normalizeInputTypes(argTypes),loaders,...render&&{render},...userStoryFn&&{userStoryFn},...play&&{play}}}var import_csf3=require("@storybook/csf"),import_client_logger5=require("@storybook/client-logger");var import_csf2=require("@storybook/csf");function normalizeComponentAnnotations(defaultExport,title=defaultExport.title,importPath){let{id,argTypes}=defaultExport;return{id:(0,import_csf2.sanitize)(id||title),...defaultExport,title,...argTypes&&{argTypes:normalizeInputTypes(argTypes)},parameters:{fileName:importPath,...defaultExport.parameters}}}var checkGlobals=parameters=>{let{globals,globalTypes}=parameters;(globals||globalTypes)&&import_client_logger5.logger.error("Global args/argTypes can only be set globally",JSON.stringify({globals,globalTypes}))},checkStorySort=parameters=>{let{options}=parameters;options?.storySort&&import_client_logger5.logger.error("The storySort option parameter can only be set globally")},checkDisallowedParameters=parameters=>{parameters&&(checkGlobals(parameters),checkStorySort(parameters))};function processCSFFile(moduleExports,importPath,title){let{default:defaultExport,__namedExportsOrder,...namedExports}=moduleExports,meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters);let csfFile={meta,stories:{},moduleExports};return Object.keys(namedExports).forEach(key=>{if((0,import_csf3.isExportStory)(key,meta)){let storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta}}),csfFile}var import_global3=require("@storybook/global"),import_csf4=require("@storybook/csf");var import_isPlainObject2=__toESM(require("lodash/isPlainObject.js")),combineParameters=(...parameterSets)=>{let mergeKeys={},definedParametersSets=parameterSets.filter(Boolean),combined=definedParametersSets.reduce((acc,parameters)=>(Object.entries(parameters).forEach(([key,value])=>{let existing=acc[key];Array.isArray(value)||typeof existing>"u"?acc[key]=value:(0,import_isPlainObject2.default)(value)&&(0,import_isPlainObject2.default)(existing)?mergeKeys[key]=!0:typeof value<"u"&&(acc[key]=value)}),acc),{});return Object.keys(mergeKeys).forEach(key=>{let mergeValues=definedParametersSets.filter(Boolean).map(p=>p[key]).filter(value=>typeof value<"u");mergeValues.every(value=>(0,import_isPlainObject2.default)(value))?combined[key]=combineParameters(...mergeValues):combined[key]=mergeValues[mergeValues.length-1]}),combined};function decorateStory(storyFn,decorator,bindWithContext){let boundStoryFunction=bindWithContext(storyFn);return context=>decorator(boundStoryFunction,context)}function sanitizeStoryContextUpdate({componentId,title,kind,id,name,story,parameters,initialArgs,argTypes,...update}={}){return update}function defaultDecorateStory(storyFn,decorators){let contextStore={},bindWithContext=decoratedStoryFn=>update=>{if(!contextStore.value)throw new Error("Decorated function called without init");return contextStore.value={...contextStore.value,...sanitizeStoryContextUpdate(update)},decoratedStoryFn(contextStore.value)},decoratedWithContextStore=decorators.reduce((story,decorator)=>decorateStory(story,decorator,bindWithContext),storyFn);return context=>(contextStore.value=context,decoratedWithContextStore(context))}function prepareStory(storyAnnotations,componentAnnotations,projectAnnotations){let{moduleExport,id,name}=storyAnnotations||{},partialAnnotations=preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations),applyLoaders=async context=>{let updatedContext={...context,loaded:{}};for(let loaders of[..."__STORYBOOK_TEST_LOADERS__"in import_global3.global&&Array.isArray(import_global3.global.__STORYBOOK_TEST_LOADERS__)?[import_global3.global.__STORYBOOK_TEST_LOADERS__]:[],normalizeArrays(projectAnnotations.loaders),normalizeArrays(componentAnnotations.loaders),normalizeArrays(storyAnnotations.loaders)]){let loadResults=await Promise.all(loaders.map(loader=>loader(updatedContext))),loaded=Object.assign({},...loadResults);updatedContext={...updatedContext,loaded:{...updatedContext.loaded,...loaded}}}return updatedContext},undecoratedStoryFn=context=>render(context.args,context),{applyDecorators=defaultDecorateStory,runStep}=projectAnnotations,decorators=[...normalizeArrays(storyAnnotations?.decorators),...normalizeArrays(componentAnnotations?.decorators),...normalizeArrays(projectAnnotations?.decorators)],render=storyAnnotations?.userStoryFn||storyAnnotations?.render||componentAnnotations.render||projectAnnotations.render;if(!render)throw new Error(`No render function available for storyId '${id}'`);let decoratedStoryFn=applyHooks(applyDecorators)(undecoratedStoryFn,decorators),unboundStoryFn=context=>decoratedStoryFn(context),play=storyAnnotations?.play||componentAnnotations.play;return{...partialAnnotations,moduleExport,id,name,story:name,originalStoryFn:render,undecoratedStoryFn,unboundStoryFn,applyLoaders,playFunction:play&&(async storyContext=>{let playFunctionContext={...storyContext,step:(label,play2)=>runStep(label,play2,playFunctionContext)};return play(playFunctionContext)})}}function prepareMeta(componentAnnotations,projectAnnotations,moduleExport){return{...preparePartialAnnotations(void 0,componentAnnotations,projectAnnotations),moduleExport}}function preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations){let
|
19
|
+
`,deprecatedStoryAnnotationWarning=(0,import_util_deprecate.default)(()=>{},deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){let storyObject=storyAnnotations,userStoryFn=typeof storyAnnotations=="function"?storyAnnotations:null,{story}=storyObject;story&&(import_client_logger4.logger.debug("deprecated story",story),deprecatedStoryAnnotationWarning());let exportName=(0,import_csf.storyNameFromExport)(key),name=typeof storyObject!="function"&&storyObject.name||storyObject.storyName||story?.name||exportName,decorators=[...normalizeArrays(storyObject.decorators),...normalizeArrays(story?.decorators)],parameters={...story?.parameters,...storyObject.parameters},args={...story?.args,...storyObject.args},argTypes={...story?.argTypes,...storyObject.argTypes},loaders=[...normalizeArrays(storyObject.loaders),...normalizeArrays(story?.loaders)],beforeEach=[...normalizeArrays(storyObject.beforeEach),...normalizeArrays(story?.beforeEach)],{render,play,tags=[]}=storyObject,id=parameters.__id||(0,import_csf.toId)(meta.id,exportName);return{moduleExport:storyAnnotations,id,name,tags,decorators,parameters,args,argTypes:normalizeInputTypes(argTypes),loaders,beforeEach,...render&&{render},...userStoryFn&&{userStoryFn},...play&&{play}}}var import_csf3=require("@storybook/csf"),import_client_logger5=require("@storybook/client-logger");var import_csf2=require("@storybook/csf");function normalizeComponentAnnotations(defaultExport,title=defaultExport.title,importPath){let{id,argTypes}=defaultExport;return{id:(0,import_csf2.sanitize)(id||title),...defaultExport,title,...argTypes&&{argTypes:normalizeInputTypes(argTypes)},parameters:{fileName:importPath,...defaultExport.parameters}}}var checkGlobals=parameters=>{let{globals,globalTypes}=parameters;(globals||globalTypes)&&import_client_logger5.logger.error("Global args/argTypes can only be set globally",JSON.stringify({globals,globalTypes}))},checkStorySort=parameters=>{let{options}=parameters;options?.storySort&&import_client_logger5.logger.error("The storySort option parameter can only be set globally")},checkDisallowedParameters=parameters=>{parameters&&(checkGlobals(parameters),checkStorySort(parameters))};function processCSFFile(moduleExports,importPath,title){let{default:defaultExport,__namedExportsOrder,...namedExports}=moduleExports,meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters);let csfFile={meta,stories:{},moduleExports};return Object.keys(namedExports).forEach(key=>{if((0,import_csf3.isExportStory)(key,meta)){let storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta}}),csfFile}var import_ts_dedent3=require("ts-dedent"),import_global3=require("@storybook/global"),import_csf4=require("@storybook/csf"),import_global4=require("@storybook/global"),import_client_logger6=require("@storybook/client-logger");var import_isPlainObject2=__toESM(require("lodash/isPlainObject.js")),combineParameters=(...parameterSets)=>{let mergeKeys={},definedParametersSets=parameterSets.filter(Boolean),combined=definedParametersSets.reduce((acc,parameters)=>(Object.entries(parameters).forEach(([key,value])=>{let existing=acc[key];Array.isArray(value)||typeof existing>"u"?acc[key]=value:(0,import_isPlainObject2.default)(value)&&(0,import_isPlainObject2.default)(existing)?mergeKeys[key]=!0:typeof value<"u"&&(acc[key]=value)}),acc),{});return Object.keys(mergeKeys).forEach(key=>{let mergeValues=definedParametersSets.filter(Boolean).map(p=>p[key]).filter(value=>typeof value<"u");mergeValues.every(value=>(0,import_isPlainObject2.default)(value))?combined[key]=combineParameters(...mergeValues):combined[key]=mergeValues[mergeValues.length-1]}),combined};function decorateStory(storyFn,decorator,bindWithContext){let boundStoryFunction=bindWithContext(storyFn);return context=>decorator(boundStoryFunction,context)}function sanitizeStoryContextUpdate({componentId,title,kind,id,name,story,parameters,initialArgs,argTypes,...update}={}){return update}function defaultDecorateStory(storyFn,decorators){let contextStore={},bindWithContext=decoratedStoryFn=>update=>{if(!contextStore.value)throw new Error("Decorated function called without init");return contextStore.value={...contextStore.value,...sanitizeStoryContextUpdate(update)},decoratedStoryFn(contextStore.value)},decoratedWithContextStore=decorators.reduce((story,decorator)=>decorateStory(story,decorator,bindWithContext),storyFn);return context=>(contextStore.value=context,decoratedWithContextStore(context))}function prepareStory(storyAnnotations,componentAnnotations,projectAnnotations){let{moduleExport,id,name}=storyAnnotations||{},partialAnnotations=preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations),applyLoaders=async context=>{let updatedContext={...context,loaded:{}};for(let loaders of[..."__STORYBOOK_TEST_LOADERS__"in import_global3.global&&Array.isArray(import_global3.global.__STORYBOOK_TEST_LOADERS__)?[import_global3.global.__STORYBOOK_TEST_LOADERS__]:[],normalizeArrays(projectAnnotations.loaders),normalizeArrays(componentAnnotations.loaders),normalizeArrays(storyAnnotations.loaders)]){let loadResults=await Promise.all(loaders.map(loader=>loader(updatedContext))),loaded=Object.assign({},...loadResults);updatedContext={...updatedContext,loaded:{...updatedContext.loaded,...loaded}}}return updatedContext},applyBeforeEach=async context=>{let cleanupCallbacks=new Array;for(let beforeEach of[...normalizeArrays(projectAnnotations.beforeEach),...normalizeArrays(componentAnnotations.beforeEach),...normalizeArrays(storyAnnotations.beforeEach)]){let cleanup=await beforeEach(context);cleanup&&cleanupCallbacks.push(cleanup)}return cleanupCallbacks},undecoratedStoryFn=context=>render(context.args,context),{applyDecorators=defaultDecorateStory,runStep}=projectAnnotations,decorators=[...normalizeArrays(storyAnnotations?.decorators),...normalizeArrays(componentAnnotations?.decorators),...normalizeArrays(projectAnnotations?.decorators)],render=storyAnnotations?.userStoryFn||storyAnnotations?.render||componentAnnotations.render||projectAnnotations.render;if(!render)throw new Error(`No render function available for storyId '${id}'`);let decoratedStoryFn=applyHooks(applyDecorators)(undecoratedStoryFn,decorators),unboundStoryFn=context=>decoratedStoryFn(context),play=storyAnnotations?.play||componentAnnotations.play;return{...partialAnnotations,moduleExport,id,name,story:name,originalStoryFn:render,undecoratedStoryFn,unboundStoryFn,applyLoaders,applyBeforeEach,playFunction:play&&(async storyContext=>{let playFunctionContext={...storyContext,step:(label,play2)=>runStep(label,play2,playFunctionContext)};return play(playFunctionContext)})}}function prepareMeta(componentAnnotations,projectAnnotations,moduleExport){return{...preparePartialAnnotations(void 0,componentAnnotations,projectAnnotations),moduleExport}}function preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations){let defaultTags=["dev","test"];typeof import_global4.global.DOCS_OPTIONS?.autodocs<"u"&&import_client_logger6.once.warn(import_ts_dedent3.dedent`
|
20
|
+
The \`docs.autodocs\` setting in '.storybook/main.js' is deprecated. Use \`tags: ['autodocs']\` in \`.storybook/preview.js\` instead.
|
21
|
+
|
22
|
+
For more info see: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-docsautodocs-is-deprecated
|
23
|
+
`);let extraTags=import_global4.global.DOCS_OPTIONS?.autodocs===!0?["autodocs"]:[],tags=(0,import_csf4.combineTags)(...defaultTags,...extraTags,...projectAnnotations.tags??[],...componentAnnotations.tags??[],...storyAnnotations?.tags??[]),parameters=combineParameters(projectAnnotations.parameters,componentAnnotations.parameters,storyAnnotations?.parameters),{argTypesEnhancers=[],argsEnhancers=[]}=projectAnnotations,passedArgTypes=combineParameters(projectAnnotations.argTypes,componentAnnotations.argTypes,storyAnnotations?.argTypes);if(storyAnnotations){let render=storyAnnotations?.userStoryFn||storyAnnotations?.render||componentAnnotations.render||projectAnnotations.render;parameters.__isArgsStory=render&&render.length>0}let passedArgs={...projectAnnotations.args,...componentAnnotations.args,...storyAnnotations?.args},contextForEnhancers={componentId:componentAnnotations.id,title:componentAnnotations.title,kind:componentAnnotations.title,id:storyAnnotations?.id||componentAnnotations.id,name:storyAnnotations?.name||"__meta",story:storyAnnotations?.name||"__meta",component:componentAnnotations.component,subcomponents:componentAnnotations.subcomponents,tags,parameters,initialArgs:passedArgs,argTypes:passedArgTypes};contextForEnhancers.argTypes=argTypesEnhancers.reduce((accumulatedArgTypes,enhancer)=>enhancer({...contextForEnhancers,argTypes:accumulatedArgTypes}),contextForEnhancers.argTypes);let initialArgsBeforeEnhancers={...passedArgs};contextForEnhancers.initialArgs=argsEnhancers.reduce((accumulatedArgs,enhancer)=>({...accumulatedArgs,...enhancer({...contextForEnhancers,initialArgs:accumulatedArgs})}),initialArgsBeforeEnhancers);let{name,story,...withoutStoryIdentifiers}=contextForEnhancers;return withoutStoryIdentifiers}function prepareContext(context){let{args:unmappedArgs}=context,targetedContext={...context,allArgs:void 0,argsByTarget:void 0};if(import_global3.global.FEATURES?.argTypeTargetsV7){let argsByTarget=groupArgsByTarget(context);targetedContext={...context,allArgs:context.args,argsByTarget,args:argsByTarget[UNTARGETED]||{}}}let mappedArgs=Object.entries(targetedContext.args).reduce((acc,[key,val])=>{if(!targetedContext.argTypes[key]?.mapping)return acc[key]=val,acc;let mappingFn=originalValue=>{let mapping=targetedContext.argTypes[key].mapping;return mapping&&originalValue in mapping?mapping[originalValue]:originalValue};return acc[key]=Array.isArray(val)?val.map(mappingFn):mappingFn(val),acc},{}),includedArgs=Object.entries(mappedArgs).reduce((acc,[key,val])=>{let argType=targetedContext.argTypes[key]||{};return(0,import_csf4.includeConditionalArg)(argType,mappedArgs,targetedContext.globals)&&(acc[key]=val),acc},{});return{...targetedContext,unmappedArgs,args:includedArgs}}var import_mapValues2=__toESM(require("lodash/mapValues.js")),import_ts_dedent4=require("ts-dedent"),import_client_logger7=require("@storybook/client-logger");var inferType=(value,name,visited)=>{let type=typeof value;switch(type){case"boolean":case"string":case"number":case"function":case"symbol":return{name:type};default:break}return value?visited.has(value)?(import_client_logger7.logger.warn(import_ts_dedent4.dedent`
|
20
24
|
We've detected a cycle in arg '${name}'. Args should be JSON-serializable.
|
21
25
|
|
22
26
|
Consider using the mapping feature or fully custom args:
|
23
27
|
- Mapping: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
|
24
28
|
- Custom args: https://storybook.js.org/docs/react/essentials/controls#fully-custom-args
|
25
|
-
`),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:(0,import_mapValues2.default)(value,field=>inferType(field,name,new Set(visited)))}):{name:"object",value:{}}},inferArgTypes=context=>{let{id,argTypes:userArgTypes={},initialArgs={}}=context,argTypes=(0,import_mapValues2.default)(initialArgs,(arg,key)=>({name:key,type:inferType(arg,`${id}.${key}`,new Set)})),userArgTypesNames=(0,import_mapValues2.default)(userArgTypes,(argType,key)=>({name:key}));return combineParameters(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var import_mapValues3=__toESM(require("lodash/mapValues.js")),
|
29
|
+
`),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:(0,import_mapValues2.default)(value,field=>inferType(field,name,new Set(visited)))}):{name:"object",value:{}}},inferArgTypes=context=>{let{id,argTypes:userArgTypes={},initialArgs={}}=context,argTypes=(0,import_mapValues2.default)(initialArgs,(arg,key)=>({name:key,type:inferType(arg,`${id}.${key}`,new Set)})),userArgTypesNames=(0,import_mapValues2.default)(userArgTypes,(argType,key)=>({name:key}));return combineParameters(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var import_mapValues3=__toESM(require("lodash/mapValues.js")),import_client_logger8=require("@storybook/client-logger");var import_pickBy=__toESM(require("lodash/pickBy.js")),matches=(name,descriptor)=>Array.isArray(descriptor)?descriptor.includes(name):name.match(descriptor),filterArgTypes=(argTypes,include,exclude)=>!include&&!exclude?argTypes:argTypes&&(0,import_pickBy.default)(argTypes,(argType,key)=>{let name=argType.name||key;return(!include||matches(name,include))&&(!exclude||!matches(name,exclude))});var inferControl=(argType,name,matchers)=>{let{type,options}=argType;if(type){if(matchers.color&&matchers.color.test(name)){let controlType=type.name;if(controlType==="string")return{control:{type:"color"}};controlType!=="enum"&&import_client_logger8.logger.warn(`Addon controls: Control of type color only supports string, received "${controlType}" instead`)}if(matchers.date&&matchers.date.test(name))return{control:{type:"date"}};switch(type.name){case"array":return{control:{type:"object"}};case"boolean":return{control:{type:"boolean"}};case"string":return{control:{type:"text"}};case"number":return{control:{type:"number"}};case"enum":{let{value}=type;return{control:{type:value?.length<=5?"radio":"select"},options:value}}case"function":case"symbol":return null;default:return{control:{type:options?"select":"object"}}}}},inferControls=context=>{let{argTypes,parameters:{__isArgsStory,controls:{include=null,exclude=null,matchers={}}={}}}=context;if(!__isArgsStory)return argTypes;let filteredArgTypes=filterArgTypes(argTypes,include,exclude),withControls=(0,import_mapValues3.default)(filteredArgTypes,(argType,name)=>argType?.type&&inferControl(argType,name,matchers));return combineParameters(withControls,filteredArgTypes)};inferControls.secondPass=!0;function normalizeProjectAnnotations({argTypes,globalTypes,argTypesEnhancers,decorators,loaders,beforeEach,...annotations}){return{...argTypes&&{argTypes:normalizeInputTypes(argTypes)},...globalTypes&&{globalTypes:normalizeInputTypes(globalTypes)},decorators:normalizeArrays(decorators),loaders:normalizeArrays(loaders),beforeEach:normalizeArrays(beforeEach),argTypesEnhancers:[...argTypesEnhancers||[],inferArgTypes,inferControls],...annotations}}var import_global5=require("@storybook/global");function composeStepRunners(stepRunners){return async(label,play,playContext)=>{await stepRunners.reduceRight((innerPlay,stepRunner)=>async()=>stepRunner(label,innerPlay,playContext),async()=>play(playContext))()}}function getField(moduleExportList,field){return moduleExportList.map(xs=>xs.default?.[field]??xs[field]).filter(Boolean)}function getArrayField(moduleExportList,field,options={}){return getField(moduleExportList,field).reduce((prev,cur)=>{let normalized=normalizeArrays(cur);return options.reverseFileOrder?[...normalized,...prev]:[...prev,...normalized]},[])}function getObjectField(moduleExportList,field){return Object.assign({},...getField(moduleExportList,field))}function getSingletonField(moduleExportList,field){return getField(moduleExportList,field).pop()}function composeConfigs(moduleExportList){let allArgTypeEnhancers=getArrayField(moduleExportList,"argTypesEnhancers"),stepRunners=getField(moduleExportList,"runStep");return{parameters:combineParameters(...getField(moduleExportList,"parameters")),decorators:getArrayField(moduleExportList,"decorators",{reverseFileOrder:!(import_global5.global.FEATURES?.legacyDecoratorFileOrder??!1)}),args:getObjectField(moduleExportList,"args"),argsEnhancers:getArrayField(moduleExportList,"argsEnhancers"),argTypes:getObjectField(moduleExportList,"argTypes"),argTypesEnhancers:[...allArgTypeEnhancers.filter(e=>!e.secondPass),...allArgTypeEnhancers.filter(e=>e.secondPass)],globals:getObjectField(moduleExportList,"globals"),globalTypes:getObjectField(moduleExportList,"globalTypes"),loaders:getArrayField(moduleExportList,"loaders"),beforeEach:getArrayField(moduleExportList,"beforeEach"),render:getSingletonField(moduleExportList,"render"),renderToCanvas:getSingletonField(moduleExportList,"renderToCanvas"),renderToDOM:getSingletonField(moduleExportList,"renderToDOM"),applyDecorators:getSingletonField(moduleExportList,"applyDecorators"),runStep:composeStepRunners(stepRunners),tags:getArrayField(moduleExportList,"tags")}}var import_csf5=require("@storybook/csf"),import_ts_dedent5=__toESM(require("ts-dedent"));var globalProjectAnnotations={},DEFAULT_STORY_TITLE="ComposedStory",DEFAULT_STORY_NAME="Unnamed Story";function extractAnnotation(annotation){return"default"in annotation?annotation.default:annotation}function setProjectAnnotations(projectAnnotations){let annotations=Array.isArray(projectAnnotations)?projectAnnotations:[projectAnnotations];globalProjectAnnotations=composeConfigs(annotations.map(extractAnnotation))}var cleanups=[];function composeStory(storyAnnotations,componentAnnotations,projectAnnotations,defaultConfig,exportsName){if(storyAnnotations===void 0)throw new Error("Expected a story but received undefined.");componentAnnotations.title=componentAnnotations.title??DEFAULT_STORY_TITLE;let normalizedComponentAnnotations=normalizeComponentAnnotations(componentAnnotations),storyName=exportsName||storyAnnotations.storyName||storyAnnotations.story?.name||storyAnnotations.name||DEFAULT_STORY_NAME,normalizedStory=normalizeStory(storyName,storyAnnotations,normalizedComponentAnnotations),normalizedProjectAnnotations=normalizeProjectAnnotations(composeConfigs([defaultConfig??{},globalProjectAnnotations,projectAnnotations??{}])),story=prepareStory(normalizedStory,normalizedComponentAnnotations,normalizedProjectAnnotations),globalsFromGlobalTypes=getValuesFromArgTypes(normalizedProjectAnnotations.globalTypes),context={hooks:new HooksContext,globals:{...globalsFromGlobalTypes,...normalizedProjectAnnotations.globals},args:{...story.initialArgs},viewMode:"story",loaded:{},abortSignal:null,canvasElement:null,...story},playFunction=story.playFunction?async extraContext=>story.playFunction({...context,...extraContext,canvasElement:extraContext?.canvasElement??globalThis.document?.body}):void 0,previousCleanupsDone=!1;return Object.assign(function(extraArgs){if(context.args={...context.initialArgs,...extraArgs},cleanups.length>0&&!previousCleanupsDone){let humanReadableIdentifier=storyName;story.title!==DEFAULT_STORY_TITLE&&(humanReadableIdentifier=`${story.title} - ${humanReadableIdentifier}`),storyName===DEFAULT_STORY_NAME&&Object.keys(context.args).length>0&&(humanReadableIdentifier=`${humanReadableIdentifier} (${Object.keys(context.args).join(", ")})`),console.warn(import_ts_dedent5.default`Some stories were not cleaned up before rendering '${humanReadableIdentifier}'.
|
30
|
+
|
31
|
+
You should load the story with \`await Story.load()\` before rendering it.`)}return story.unboundStoryFn(prepareContext(context))},{id:story.id,storyName,load:async()=>{for(let{callback}of[...cleanups].reverse())await callback();cleanups.length=0,previousCleanupsDone=!0;let loadedContext=await story.applyLoaders(context);context.loaded=loadedContext.loaded,cleanups.push(...(await story.applyBeforeEach(context)).filter(Boolean).map(callback=>({storyName,callback})))},args:story.initialArgs,parameters:story.parameters,argTypes:story.argTypes,play:playFunction})}function composeStories(storiesImport,globalConfig,composeStoryFn){let{default:meta,__esModule,__namedExportsOrder,...stories}=storiesImport;return Object.entries(stories).reduce((storiesMap,[exportsName,story])=>(0,import_csf5.isExportStory)(exportsName,meta)?Object.assign(storiesMap,{[exportsName]:composeStoryFn(story,meta,globalConfig,exportsName)}):storiesMap,{})}function createPlaywrightTest(baseTest){return baseTest.extend({mount:async({mount,page},use)=>{await use(async(storyRef,...restArgs)=>{if(!("__pw_type"in storyRef)||"__pw_type"in storyRef&&storyRef.__pw_type!=="jsx")throw new Error(import_ts_dedent5.default`
|
26
32
|
Portable stories in Playwright CT only work when referencing JSX elements.
|
27
33
|
Please use JSX format for your components such as:
|
28
34
|
|
@@ -33,11 +39,11 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
33
39
|
await mount(<MyComponent foo="bar"/>)
|
34
40
|
|
35
41
|
More info: https://storybook.js.org/docs/api/portable-stories-playwright
|
36
|
-
`);await page.evaluate(async wrappedStoryRef=>{let unwrappedStoryRef=await globalThis.__pwUnwrapObject?.(wrappedStoryRef);return("__pw_type"in unwrappedStoryRef?unwrappedStoryRef.type:unwrappedStoryRef)?.load?.()},storyRef);let mountResult=await mount(storyRef,...restArgs);return await page.evaluate(async wrappedStoryRef=>{let unwrappedStoryRef=await globalThis.__pwUnwrapObject?.(wrappedStoryRef),story="__pw_type"in unwrappedStoryRef?unwrappedStoryRef.type:unwrappedStoryRef,canvasElement=document.querySelector("#root");return story?.play?.({canvasElement})},storyRef),mountResult})}})}var CSF_CACHE_SIZE=1e3,STORY_CACHE_SIZE=1e4,StoryStore=class{constructor(storyIndex,importFn,projectAnnotations){this.importFn=importFn;this.getStoriesJsonData=()=>{let value=this.getSetStoriesPayload(),allowedParameters=["fileName","docsOnly","framework","__id","__isArgsStory"];return{v:3,stories:(0,import_mapValues4.default)(value.stories,story=>{let{importPath}=this.storyIndex.entries[story.id];return{...(0,import_pick.default)(story,["id","name","title"]),importPath,kind:story.title,story:story.name,parameters:{...(0,import_pick.default)(story.parameters,allowedParameters),fileName:importPath}}})}};this.storyIndex=new StoryIndexStore(storyIndex),this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.args=new ArgsStore,this.globals=new GlobalsStore({globals,globalTypes}),this.hooks={},this.processCSFFileWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(processCSFFile),this.prepareMetaWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(prepareMeta),this.prepareStoryWithCache=(0,import_memoizerific2.default)(STORY_CACHE_SIZE)(prepareStory)}setProjectAnnotations(projectAnnotations){this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.globals.set({globals,globalTypes})}async onStoriesChanged({importFn,storyIndex}){importFn&&(this.importFn=importFn),storyIndex&&(this.storyIndex.entries=storyIndex.entries),this.cachedCSFFiles&&await this.cacheAllCSFFiles()}async storyIdToEntry(storyId){return this.storyIndex.storyIdToEntry(storyId)}async loadCSFFileByStoryId(storyId){let{importPath,title}=this.storyIndex.storyIdToEntry(storyId),moduleExports=await this.importFn(importPath);return this.processCSFFileWithCache(moduleExports,importPath,title)}async loadAllCSFFiles(){let importPaths={};return Object.entries(this.storyIndex.entries).forEach(([storyId,{importPath}])=>{importPaths[importPath]=storyId}),(await Promise.all(Object.entries(importPaths).map(async([importPath,storyId])=>({importPath,csfFile:await this.loadCSFFileByStoryId(storyId)})))).reduce((acc,{importPath,csfFile})=>(acc[importPath]=csfFile,acc),{})}async cacheAllCSFFiles(){this.cachedCSFFiles=await this.loadAllCSFFiles()}preparedMetaFromCSFFile({csfFile}){let componentAnnotations=csfFile.meta;return this.prepareMetaWithCache(componentAnnotations,this.projectAnnotations,csfFile.moduleExports.default)}async loadStory({storyId}){let csfFile=await this.loadCSFFileByStoryId(storyId);return this.storyFromCSFFile({storyId,csfFile})}storyFromCSFFile({storyId,csfFile}){let storyAnnotations=csfFile.stories[storyId];if(!storyAnnotations)throw new import_preview_errors2.MissingStoryFromCsfFileError({storyId});let componentAnnotations=csfFile.meta,story=this.prepareStoryWithCache(storyAnnotations,componentAnnotations,this.projectAnnotations);return this.args.setInitial(story),this.hooks[story.id]=this.hooks[story.id]||new HooksContext,story}componentStoriesFromCSFFile({csfFile}){return Object.keys(this.storyIndex.entries).filter(storyId=>!!csfFile.stories[storyId]).map(storyId=>this.storyFromCSFFile({storyId,csfFile}))}async loadEntry(id){let entry=await this.storyIdToEntry(id),storyImports=entry.type==="docs"?entry.storiesImports:[],[entryExports,...csfFiles]=await Promise.all([this.importFn(entry.importPath),...storyImports.map(storyImportPath=>{let firstStoryEntry=this.storyIndex.importPathToEntry(storyImportPath);return this.loadCSFFileByStoryId(firstStoryEntry.id)})]);return{entryExports,csfFiles}}getStoryContext(story,{forceInitialArgs=!1}={}){return prepareContext({...story,args:forceInitialArgs?story.initialArgs:this.args.get(story.id),globals:this.globals.get(),hooks:this.hooks[story.id]})}cleanupStory(story){this.hooks[story.id].clean()}extract(options={includeDocsOnly:!1}){let{cachedCSFFiles}=this;if(!cachedCSFFiles)throw new import_preview_errors2.CalledExtractOnStoreError;return Object.entries(this.storyIndex.entries).reduce((acc,[storyId,{type,importPath}])=>{if(type==="docs")return acc;let csfFile=cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return!options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((storyAcc,[key,value])=>key==="moduleExport"||typeof value=="function"?storyAcc:Array.isArray(value)?Object.assign(storyAcc,{[key]:value.slice().sort()}):Object.assign(storyAcc,{[key]:value}),{args:story.initialArgs})),acc},{})}getSetStoriesPayload(){let stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((acc,{title})=>(acc[title]={},acc),{});return{v:2,globals:this.globals.get(),globalParameters:{},kindParameters,stories}}raw(){return(0,
|
42
|
+
`);await page.evaluate(async wrappedStoryRef=>{let unwrappedStoryRef=await globalThis.__pwUnwrapObject?.(wrappedStoryRef);return("__pw_type"in unwrappedStoryRef?unwrappedStoryRef.type:unwrappedStoryRef)?.load?.()},storyRef);let mountResult=await mount(storyRef,...restArgs);return await page.evaluate(async wrappedStoryRef=>{let unwrappedStoryRef=await globalThis.__pwUnwrapObject?.(wrappedStoryRef),story="__pw_type"in unwrappedStoryRef?unwrappedStoryRef.type:unwrappedStoryRef,canvasElement=document.querySelector("#root");return story?.play?.({canvasElement})},storyRef),mountResult})}})}var CSF_CACHE_SIZE=1e3,STORY_CACHE_SIZE=1e4,StoryStore=class{constructor(storyIndex,importFn,projectAnnotations){this.importFn=importFn;this.getStoriesJsonData=()=>{let value=this.getSetStoriesPayload(),allowedParameters=["fileName","docsOnly","framework","__id","__isArgsStory"];return{v:3,stories:(0,import_mapValues4.default)(value.stories,story=>{let{importPath}=this.storyIndex.entries[story.id];return{...(0,import_pick.default)(story,["id","name","title"]),importPath,kind:story.title,story:story.name,parameters:{...(0,import_pick.default)(story.parameters,allowedParameters),fileName:importPath}}})}};this.storyIndex=new StoryIndexStore(storyIndex),this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.args=new ArgsStore,this.globals=new GlobalsStore({globals,globalTypes}),this.hooks={},this.cleanupCallbacks={},this.processCSFFileWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(processCSFFile),this.prepareMetaWithCache=(0,import_memoizerific2.default)(CSF_CACHE_SIZE)(prepareMeta),this.prepareStoryWithCache=(0,import_memoizerific2.default)(STORY_CACHE_SIZE)(prepareStory)}setProjectAnnotations(projectAnnotations){this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.globals.set({globals,globalTypes})}async onStoriesChanged({importFn,storyIndex}){importFn&&(this.importFn=importFn),storyIndex&&(this.storyIndex.entries=storyIndex.entries),this.cachedCSFFiles&&await this.cacheAllCSFFiles()}async storyIdToEntry(storyId){return this.storyIndex.storyIdToEntry(storyId)}async loadCSFFileByStoryId(storyId){let{importPath,title}=this.storyIndex.storyIdToEntry(storyId),moduleExports=await this.importFn(importPath);return this.processCSFFileWithCache(moduleExports,importPath,title)}async loadAllCSFFiles(){let importPaths={};return Object.entries(this.storyIndex.entries).forEach(([storyId,{importPath}])=>{importPaths[importPath]=storyId}),(await Promise.all(Object.entries(importPaths).map(async([importPath,storyId])=>({importPath,csfFile:await this.loadCSFFileByStoryId(storyId)})))).reduce((acc,{importPath,csfFile})=>(acc[importPath]=csfFile,acc),{})}async cacheAllCSFFiles(){this.cachedCSFFiles=await this.loadAllCSFFiles()}preparedMetaFromCSFFile({csfFile}){let componentAnnotations=csfFile.meta;return this.prepareMetaWithCache(componentAnnotations,this.projectAnnotations,csfFile.moduleExports.default)}async loadStory({storyId}){let csfFile=await this.loadCSFFileByStoryId(storyId);return this.storyFromCSFFile({storyId,csfFile})}storyFromCSFFile({storyId,csfFile}){let storyAnnotations=csfFile.stories[storyId];if(!storyAnnotations)throw new import_preview_errors2.MissingStoryFromCsfFileError({storyId});let componentAnnotations=csfFile.meta,story=this.prepareStoryWithCache(storyAnnotations,componentAnnotations,this.projectAnnotations);return this.args.setInitial(story),this.hooks[story.id]=this.hooks[story.id]||new HooksContext,story}componentStoriesFromCSFFile({csfFile}){return Object.keys(this.storyIndex.entries).filter(storyId=>!!csfFile.stories[storyId]).map(storyId=>this.storyFromCSFFile({storyId,csfFile}))}async loadEntry(id){let entry=await this.storyIdToEntry(id),storyImports=entry.type==="docs"?entry.storiesImports:[],[entryExports,...csfFiles]=await Promise.all([this.importFn(entry.importPath),...storyImports.map(storyImportPath=>{let firstStoryEntry=this.storyIndex.importPathToEntry(storyImportPath);return this.loadCSFFileByStoryId(firstStoryEntry.id)})]);return{entryExports,csfFiles}}getStoryContext(story,{forceInitialArgs=!1}={}){return prepareContext({...story,args:forceInitialArgs?story.initialArgs:this.args.get(story.id),globals:this.globals.get(),hooks:this.hooks[story.id]})}addCleanupCallbacks(story,callbacks){this.cleanupCallbacks[story.id]=callbacks}async cleanupStory(story){this.hooks[story.id].clean();let callbacks=this.cleanupCallbacks[story.id];if(callbacks)for(let callback of[...callbacks].reverse())await callback();delete this.cleanupCallbacks[story.id]}extract(options={includeDocsOnly:!1}){let{cachedCSFFiles}=this;if(!cachedCSFFiles)throw new import_preview_errors2.CalledExtractOnStoreError;return Object.entries(this.storyIndex.entries).reduce((acc,[storyId,{type,importPath}])=>{if(type==="docs")return acc;let csfFile=cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return!options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((storyAcc,[key,value])=>key==="moduleExport"||typeof value=="function"?storyAcc:Array.isArray(value)?Object.assign(storyAcc,{[key]:value.slice().sort()}):Object.assign(storyAcc,{[key]:value}),{args:story.initialArgs})),acc},{})}getSetStoriesPayload(){let stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((acc,{title})=>(acc[title]={},acc),{});return{v:2,globals:this.globals.get(),globalParameters:{},kindParameters,stories}}raw(){return(0,import_client_logger9.deprecate)("StoryStore.raw() is deprecated and will be removed in 9.0, please use extract() instead"),Object.values(this.extract()).map(({id})=>this.fromId(id)).filter(Boolean)}fromId(storyId){if((0,import_client_logger9.deprecate)("StoryStore.fromId() is deprecated and will be removed in 9.0, please use loadStory() instead"),!this.cachedCSFFiles)throw new Error("Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.");let importPath;try{({importPath}=this.storyIndex.storyIdToEntry(storyId))}catch{return null}let csfFile=this.cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return{...story,storyFn:update=>{let context={...this.getStoryContext(story),viewMode:"story"};return story.unboundStoryFn({...context,...update})}}}};function slash(path){return path.startsWith("\\\\?\\")?path:path.replace(/\\/g,"/")}var import_ts_dedent6=require("ts-dedent"),import_client_logger10=require("@storybook/client-logger"),sanitize2=parts=>{if(parts.length===0)return parts;let last=parts[parts.length-1],lastStripped=last?.replace(/(?:[.](?:story|stories))?([.][^.]+)$/i,"");if(parts.length===1)return[lastStripped];let nextToLast=parts[parts.length-2];return lastStripped&&nextToLast&&lastStripped.toLowerCase()===nextToLast.toLowerCase()?[...parts.slice(0,-2),lastStripped]:lastStripped&&(/^(story|stories)([.][^.]+)$/i.test(last)||/^index$/i.test(lastStripped))?parts.slice(0,-1):[...parts.slice(0,-1),lastStripped]};function pathJoin(paths){return paths.flatMap(p=>p.split("/")).filter(Boolean).join("/")}var userOrAutoTitleFromSpecifier=(fileName,entry,userTitle)=>{let{directory,importPathMatcher,titlePrefix=""}=entry||{};typeof fileName=="number"&&import_client_logger10.once.warn(import_ts_dedent6.dedent`
|
37
43
|
CSF Auto-title received a numeric fileName. This typically happens when
|
38
44
|
webpack is mis-configured in production mode. To force webpack to produce
|
39
45
|
filenames, set optimization.moduleIds = "named" in your webpack config.
|
40
|
-
`);let normalizedFileName=slash(String(fileName));if(importPathMatcher.exec(normalizedFileName)){if(!userTitle){let suffix=normalizedFileName.replace(directory,""),parts=pathJoin([titlePrefix,suffix]).split("/");return parts=sanitize2(parts),parts.join("/")}return titlePrefix?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
|
46
|
+
`);let normalizedFileName=slash(String(fileName));if(importPathMatcher.exec(normalizedFileName)){if(!userTitle){let suffix=normalizedFileName.replace(directory,""),parts=pathJoin([titlePrefix,suffix]).split("/");return parts=sanitize2(parts),parts.join("/")}return titlePrefix?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},sortStoriesV7=(stories,storySortParameter,fileNameOrder)=>{try{return sortStoriesCommon(stories,storySortParameter,fileNameOrder)}catch(err){throw new Error(import_ts_dedent7.dedent`
|
41
47
|
Error sorting stories with sort parameter ${storySortParameter}:
|
42
48
|
|
43
49
|
> ${err.message}
|
@@ -45,16 +51,16 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
45
51
|
Are you using a V6-style sort function in V7 mode?
|
46
52
|
|
47
53
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
48
|
-
`)}};var import_global5=require("@storybook/global"),import_client_logger10=require("@storybook/client-logger"),import_core_events3=require("@storybook/core-events"),import_preview_errors3=require("@storybook/core-events/preview-errors");var import_core_events2=require("@storybook/core-events");var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return{name,message,stack}}catch{return{name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing")}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(import_core_events2.STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}))}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id})}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return["preparing"].includes(this.phase)}isPending(){return["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode})}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{})}),this.notYetRendered=!1,abortSignal.aborted)return;let ignoreUnhandledErrors=this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors===!0,unhandledErrors=new Set,onError=event=>unhandledErrors.add("error"in event?event.error:event.reason);if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){window.addEventListener("error",onError),window.addEventListener("unhandledrejection",onError),this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext)}),!ignoreUnhandledErrors&&unhandledErrors.size>0?await this.runPhase(abortSignal,"errored"):await this.runPhase(abortSignal,"played")}catch(error){if(await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(import_core_events2.PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error))}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error;console.error(error)}if(!ignoreUnhandledErrors&&unhandledErrors.size>0&&this.channel.emit(import_core_events2.UNHANDLED_ERRORS_WHILE_PLAYING,Array.from(unhandledErrors).map(serializeError)),this.disableKeyListeners=!1,window.removeEventListener("unhandledrejection",onError),window.removeEventListener("error",onError),abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(import_core_events2.STORY_RENDERED,id))}catch(err){this.phase="errored",this.callbacks.showException(err)}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){this.abortController?.abort()}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0))}window.location.reload(),await new Promise(()=>{})}};var{fetch}=import_global5.global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(importFn,getProjectAnnotations,channel=addons.getChannel(),shouldInitialize=!0){this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.channel=channel;this.storyRenders=[];this.storeInitializationPromise=new Promise((resolve,reject)=>{this.resolveStoreInitializationPromise=resolve,this.rejectStoreInitializationPromise=reject}),shouldInitialize&&this.initialize()}get storyStore(){return new Proxy({},{get:(_,method)=>{if(this.storyStoreValue)return(0,import_client_logger10.deprecate)("Accessing the Story Store is deprecated and will be removed in 9.0"),this.storyStoreValue[method];throw new import_preview_errors3.StoryStoreAccessedBeforeInitializationError}})}async initialize(){this.setupListeners();try{let projectAnnotations=await this.getProjectAnnotationsOrRenderError();await this.initializeWithProjectAnnotations(projectAnnotations)}catch(err){this.rejectStoreInitializationPromise(err)}}ready(){return this.storeInitializationPromise}setupListeners(){this.channel.on(import_core_events3.STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(import_core_events3.UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(import_core_events3.UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(import_core_events3.RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(import_core_events3.FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(import_core_events3.FORCE_REMOUNT,this.onForceRemount.bind(this))}async getProjectAnnotationsOrRenderError(){try{let projectAnnotations=await this.getProjectAnnotations();if(this.renderToCanvas=projectAnnotations.renderToCanvas,!this.renderToCanvas)throw new import_preview_errors3.MissingRenderToCanvasError;return projectAnnotations}catch(err){throw this.renderPreviewEntryError("Error reading preview.js:",err),err}}async initializeWithProjectAnnotations(projectAnnotations){this.projectAnnotationsBeforeInitialization=projectAnnotations;try{let storyIndex=await this.getStoryIndexFromServer();return this.initializeWithStoryIndex(storyIndex)}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new import_preview_errors3.StoryIndexFetchError({text:await result.text()})}initializeWithStoryIndex(storyIndex){if(!this.projectAnnotationsBeforeInitialization)throw new Error("Cannot call initializeWithStoryIndex until project annotations resolve");this.storyStoreValue=new StoryStore(storyIndex,this.importFn,this.projectAnnotationsBeforeInitialization),delete this.projectAnnotationsBeforeInitialization,this.setInitialGlobals(),this.resolveStoreInitializationPromise()}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"emitGlobals"});let payload={globals:this.storyStoreValue.globals.get()||{},globalTypes:this.storyStoreValue.projectAnnotations.globalTypes||{}};this.channel.emit(import_core_events3.SET_GLOBALS,payload)}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError,this.getProjectAnnotations=getProjectAnnotations;let projectAnnotations=await this.getProjectAnnotationsOrRenderError();if(!this.storyStoreValue){await this.initializeWithProjectAnnotations(projectAnnotations);return}this.storyStoreValue.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!(!this.storyStoreValue&&!this.projectAnnotationsBeforeInitialization))try{let storyIndex=await this.getStoryIndexFromServer();if(this.projectAnnotationsBeforeInitialization){this.initializeWithStoryIndex(storyIndex);return}await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onStoriesChanged"});await this.storyStoreValue.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateGlobals"});this.storyStoreValue.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(import_core_events3.GLOBALS_UPDATED,{globals:this.storyStoreValue.globals.get(),initialGlobals:this.storyStoreValue.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateArgs"});this.storyStoreValue.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId&&!r.renderOptions.forceInitialArgs).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStoreValue.args.get(storyId)})}async onResetArgs({storyId,argNames}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onResetArgs"});let story=this.storyRenders.find(r=>r.id===storyId)?.story||await this.storyStoreValue.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStoreValue.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs})}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()))}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()))}renderStoryToElement(story,element,callbacks,options){if(!this.renderToCanvas||!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"renderStoryToElement"});let render=new StoryRender(this.channel,this.storyStoreValue,this.renderToCanvas,callbacks,story.id,"docs",options,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render)}}async teardownRender(render,{viewModeChanged}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged})}async loadStory({storyId}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"loadStory"});return this.storyStoreValue.loadStory({storyId})}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"getStoryContext"});return this.storyStoreValue.getStoryContext(story,{forceInitialArgs})}async extract(options){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"extract"});if(this.previewEntryError)throw this.previewEntryError;return await this.storyStoreValue.cacheAllCSFFiles(),this.storyStoreValue.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger10.logger.error(reason),import_client_logger10.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global8=require("@storybook/global");var import_tiny_invariant=__toESM(require("tiny-invariant")),import_core_events6=require("@storybook/core-events"),import_client_logger11=require("@storybook/client-logger"),import_preview_errors4=require("@storybook/core-events/preview-errors");var import_core_events4=require("@storybook/core-events");var import_ts_dedent7=__toESM(require("ts-dedent")),DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.componentStoriesFromCSFFile=csfFile=>this.store.componentStoriesFromCSFFile({csfFile});this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.componentStoriesValue=[],this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.attachedCSFFiles=new Set,csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");if(this.attachedCSFFiles.has(csfFile))return;this.attachedCSFFiles.add(csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(this.attachedCSFFiles.size===0)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");let firstAttachedCSFFile=Array.from(this.attachedCSFFiles)[0];if(moduleExportType==="meta")return{type:"meta",csfFile:firstAttachedCSFFile};let{component}=firstAttachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent7.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
|
54
|
+
`)}};var import_global6=require("@storybook/global"),import_client_logger11=require("@storybook/client-logger"),import_core_events3=require("@storybook/core-events"),import_preview_errors3=require("@storybook/core-events/preview-errors");var import_core_events2=require("@storybook/core-events");var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return{name,message,stack}}catch{return{name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.rerenderEnqueued=!1;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 await 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["loading","beforeEach","rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");let story=this.story;if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,applyBeforeEach,unboundStoryFn,playFunction}=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,canvasElement})}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement};if(await this.runPhase(abortSignal,"beforeEach",async()=>{let cleanupCallbacks=await applyBeforeEach(renderStoryContext);this.store.addCleanupCallbacks(story,cleanupCallbacks)}),abortSignal.aborted)return;let renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{})}),this.notYetRendered=!1,abortSignal.aborted)return;let ignoreUnhandledErrors=this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors===!0,unhandledErrors=new Set,onError=event=>unhandledErrors.add("error"in event?event.error:event.reason);if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){window.addEventListener("error",onError),window.addEventListener("unhandledrejection",onError),this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext)}),!ignoreUnhandledErrors&&unhandledErrors.size>0?await this.runPhase(abortSignal,"errored"):await this.runPhase(abortSignal,"played")}catch(error){if(await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(import_core_events2.PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error))}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error;console.error(error)}if(!ignoreUnhandledErrors&&unhandledErrors.size>0&&this.channel.emit(import_core_events2.UNHANDLED_ERRORS_WHILE_PLAYING,Array.from(unhandledErrors).map(serializeError)),this.disableKeyListeners=!1,window.removeEventListener("unhandledrejection",onError),window.removeEventListener("error",onError),abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(import_core_events2.STORY_RENDERED,id))}catch(err){this.phase="errored",this.callbacks.showException(err)}this.rerenderEnqueued&&(this.rerenderEnqueued=!1,this.render())}async rerender(){if(this.isPending()&&this.phase!=="playing")this.rerenderEnqueued=!0;else return this.render()}async remount(){return await this.teardown(),this.render({forceRemount:!0})}cancelRender(){this.abortController?.abort()}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&await 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(importFn,getProjectAnnotations,channel=addons.getChannel(),shouldInitialize=!0){this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.channel=channel;this.storyRenders=[];this.storeInitializationPromise=new Promise((resolve,reject)=>{this.resolveStoreInitializationPromise=resolve,this.rejectStoreInitializationPromise=reject}),shouldInitialize&&this.initialize()}get storyStore(){return new Proxy({},{get:(_,method)=>{if(this.storyStoreValue)return(0,import_client_logger11.deprecate)("Accessing the Story Store is deprecated and will be removed in 9.0"),this.storyStoreValue[method];throw new import_preview_errors3.StoryStoreAccessedBeforeInitializationError}})}async initialize(){this.setupListeners();try{let projectAnnotations=await this.getProjectAnnotationsOrRenderError();await this.initializeWithProjectAnnotations(projectAnnotations)}catch(err){this.rejectStoreInitializationPromise(err)}}ready(){return this.storeInitializationPromise}setupListeners(){this.channel.on(import_core_events3.STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(import_core_events3.UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(import_core_events3.UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(import_core_events3.ARGTYPES_INFO_REQUEST,this.onRequestArgTypesInfo.bind(this)),this.channel.on(import_core_events3.RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(import_core_events3.FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(import_core_events3.FORCE_REMOUNT,this.onForceRemount.bind(this))}async getProjectAnnotationsOrRenderError(){try{let projectAnnotations=await this.getProjectAnnotations();if(this.renderToCanvas=projectAnnotations.renderToCanvas,!this.renderToCanvas)throw new import_preview_errors3.MissingRenderToCanvasError;return projectAnnotations}catch(err){throw this.renderPreviewEntryError("Error reading preview.js:",err),err}}async initializeWithProjectAnnotations(projectAnnotations){this.projectAnnotationsBeforeInitialization=projectAnnotations;try{let storyIndex=await this.getStoryIndexFromServer();return this.initializeWithStoryIndex(storyIndex)}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new import_preview_errors3.StoryIndexFetchError({text:await result.text()})}initializeWithStoryIndex(storyIndex){if(!this.projectAnnotationsBeforeInitialization)throw new Error("Cannot call initializeWithStoryIndex until project annotations resolve");this.storyStoreValue=new StoryStore(storyIndex,this.importFn,this.projectAnnotationsBeforeInitialization),delete this.projectAnnotationsBeforeInitialization,this.setInitialGlobals(),this.resolveStoreInitializationPromise()}async setInitialGlobals(){this.emitGlobals()}emitGlobals(){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"emitGlobals"});let payload={globals:this.storyStoreValue.globals.get()||{},globalTypes:this.storyStoreValue.projectAnnotations.globalTypes||{}};this.channel.emit(import_core_events3.SET_GLOBALS,payload)}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError,this.getProjectAnnotations=getProjectAnnotations;let projectAnnotations=await this.getProjectAnnotationsOrRenderError();if(!this.storyStoreValue){await this.initializeWithProjectAnnotations(projectAnnotations);return}this.storyStoreValue.setProjectAnnotations(projectAnnotations),this.emitGlobals()}async onStoryIndexChanged(){if(delete this.previewEntryError,!(!this.storyStoreValue&&!this.projectAnnotationsBeforeInitialization))try{let storyIndex=await this.getStoryIndexFromServer();if(this.projectAnnotationsBeforeInitialization){this.initializeWithStoryIndex(storyIndex);return}await this.onStoriesChanged({storyIndex})}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onStoriesChanged"});await this.storyStoreValue.onStoriesChanged({importFn,storyIndex})}async onUpdateGlobals({globals}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateGlobals"});this.storyStoreValue.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(import_core_events3.GLOBALS_UPDATED,{globals:this.storyStoreValue.globals.get(),initialGlobals:this.storyStoreValue.globals.initialGlobals})}async onUpdateArgs({storyId,updatedArgs}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateArgs"});this.storyStoreValue.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId&&!r.renderOptions.forceInitialArgs).map(r=>r.rerender())),this.channel.emit(import_core_events3.STORY_ARGS_UPDATED,{storyId,args:this.storyStoreValue.args.get(storyId)})}async onRequestArgTypesInfo({id,payload}){try{await this.storeInitializationPromise;let story=await this.storyStoreValue?.loadStory(payload);this.channel.emit(import_core_events3.ARGTYPES_INFO_RESPONSE,{id,success:!0,payload:{argTypes:story?.argTypes||{}},error:null})}catch(e){this.channel.emit(import_core_events3.ARGTYPES_INFO_RESPONSE,{id,success:!1,error:e?.message})}}async onResetArgs({storyId,argNames}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"onResetArgs"});let story=this.storyRenders.find(r=>r.id===storyId)?.story||await this.storyStoreValue.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStoreValue.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs})}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()))}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()))}renderStoryToElement(story,element,callbacks,options){if(!this.renderToCanvas||!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"renderStoryToElement"});let render=new StoryRender(this.channel,this.storyStoreValue,this.renderToCanvas,callbacks,story.id,"docs",options,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render)}}async teardownRender(render,{viewModeChanged}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged})}async loadStory({storyId}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"loadStory"});return this.storyStoreValue.loadStory({storyId})}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"getStoryContext"});return this.storyStoreValue.getStoryContext(story,{forceInitialArgs})}async extract(options){if(!this.storyStoreValue)throw new import_preview_errors3.CalledPreviewMethodBeforeInitializationError({methodName:"extract"});if(this.previewEntryError)throw this.previewEntryError;return await this.storyStoreValue.cacheAllCSFFiles(),this.storyStoreValue.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,import_client_logger11.logger.error(reason),import_client_logger11.logger.error(err),this.channel.emit(import_core_events3.CONFIG_ERROR,err)}};var import_global9=require("@storybook/global");var import_tiny_invariant=__toESM(require("tiny-invariant")),import_core_events6=require("@storybook/core-events"),import_client_logger12=require("@storybook/client-logger"),import_preview_errors4=require("@storybook/core-events/preview-errors");var import_core_events4=require("@storybook/core-events");var import_ts_dedent8=__toESM(require("ts-dedent")),DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.componentStoriesFromCSFFile=csfFile=>this.store.componentStoriesFromCSFFile({csfFile});this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.componentStoriesValue=[],this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.attachedCSFFiles=new Set,csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile)})}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story)})}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");if(this.attachedCSFFiles.has(csfFile))return;this.attachedCSFFiles.add(csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story)})}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile)}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return{type:"story",story:this.primaryStory}}if(this.attachedCSFFiles.size===0)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");let firstAttachedCSFFile=Array.from(this.attachedCSFFiles)[0];if(moduleExportType==="meta")return{type:"meta",csfFile:firstAttachedCSFFile};let{component}=firstAttachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return{type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return{type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type)}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(import_ts_dedent8.default`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
|
49
55
|
- Did you pass a component to the 'of' prop when the block only supports a story or a meta?
|
50
56
|
- ... or vice versa?
|
51
|
-
- Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:this.store.preparedMetaFromCSFFile({csfFile:resolved.csfFile})};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.subtype="csf";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.subtype="mdx";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.exports&&this.exports===other.exports)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.composedPath&&event.composedPath()[0]||event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return!tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(importFn,getProjectAnnotations,selectionStore,view){super(importFn,getProjectAnnotations,void 0,!1);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.selectionStore=selectionStore;this.view=view;this.initialize()}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}async setInitialGlobals(){if(!this.storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"setInitialGlobals"});let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStoreValue.globals.updateFromPersisted(globals),this.emitGlobals()}async initializeWithStoryIndex(storyIndex){return await super.initializeWithStoryIndex(storyIndex),this.selectSpecifiedStory()}async selectSpecifiedStory(){if(!this.storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"selectSpecifiedStory"});if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new import_preview_errors4.EmptyIndexError):this.renderStoryLoadingException(storySpecifier,new import_preview_errors4.NoStoryMatchError({storySpecifier:storySpecifier.toString()}));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storeInitializationPromise,this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.()}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await this.storeInitializationPromise,this.storyStoreValue&&await Promise.allSettled(ids.map(id=>this.storyStoreValue?.loadEntry(id)))}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!this.storyStoreValue||!renderToCanvas)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"renderSelection"});let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStoreValue.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=this.currentSelection?.storyId!==storyId,viewModeChanged=this.currentRender?.type!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStoreValue,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)&&((0,import_tiny_invariant.default)(!!render.story),this.storyStoreValue.args.updateFromPersisted(render.story,persistedArgs)),lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){(0,import_tiny_invariant.default)(!!render.story);let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStoreValue.getStoryContext(render.story);this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(import_core_events6.STORY_ARGS_UPDATED,{storyId,args:unmappedArgs})}else{let{parameters}=this.storyStoreValue.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new import_preview_errors4.MdxFileWithNoCsfReferencesError({storyId});({parameters}=this.storyStoreValue.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}isStoryRender(render)?((0,import_tiny_invariant.default)(!!render.story),this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))):this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged})}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger11.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger11.logger.error(`Error rendering story '${storyId}':`),import_client_logger11.logger.error(error))}renderError(storyId,{title,description}){import_client_logger11.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global6=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent8=require("ts-dedent"),import_client_logger12=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject.js")),VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):(0,import_isPlainObject3.default)(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return!0;if(str==="!false")return!1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(import_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger12.once.warn(import_ts_dedent8.dedent`
|
57
|
+
- Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return{...resolved,projectAnnotations:this.projectAnnotations};case"meta":return{...resolved,preparedMeta:this.store.preparedMetaFromCSFFile({csfFile:resolved.csfFile})};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.subtype="csf";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.story&&this.story===other.story)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events4.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};var import_core_events5=require("@storybook/core-events");var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.subtype="mdx";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1}isEqual(other){return!!(this.id===other.id&&this.exports&&this.exports===other.exports)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(import_core_events5.DOCS_RENDERED,this.id)}catch(err){this.callbacks.showException(err)}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0)},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0}};var globalWindow=globalThis;function focusInInput(event){let target=event.composedPath&&event.composedPath()[0]||event.target;return/input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var ATTACHED_MDX_TAG="attached-mdx",UNATTACHED_MDX_TAG="unattached-mdx";function isMdxEntry({tags}){return tags?.includes(UNATTACHED_MDX_TAG)||tags?.includes(ATTACHED_MDX_TAG)}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(importFn,getProjectAnnotations,selectionStore,view){super(importFn,getProjectAnnotations,void 0,!1);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.selectionStore=selectionStore;this.view=view;this.initialize()}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(import_core_events6.SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(import_core_events6.UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(import_core_events6.PRELOAD_ENTRIES,this.onPreloadStories.bind(this))}async setInitialGlobals(){if(!this.storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"setInitialGlobals"});let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStoreValue.globals.updateFromPersisted(globals),this.emitGlobals()}async initializeWithStoryIndex(storyIndex){return await super.initializeWithStoryIndex(storyIndex),this.selectSpecifiedStory()}async selectSpecifiedStory(){if(!this.storyStoreValue)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"selectSpecifiedStory"});if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new import_preview_errors4.EmptyIndexError):this.renderStoryLoadingException(storySpecifier,new import_preview_errors4.NoStoryMatchError({storySpecifier:storySpecifier.toString()}));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(import_core_events6.STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args})}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection()}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory()}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(import_core_events6.PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}})}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storeInitializationPromise,this.channel.emit(import_core_events6.CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection()}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams)}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.()}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs})}async onPreloadStories({ids}){await this.storeInitializationPromise,this.storyStoreValue&&await Promise.allSettled(ids.map(id=>this.storyStoreValue?.loadEntry(id)))}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!this.storyStoreValue||!renderToCanvas)throw new import_preview_errors4.CalledPreviewMethodBeforeInitializationError({methodName:"renderSelection"});let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStoreValue.storyIdToEntry(storyId)}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=this.currentSelection?.storyId!==storyId,viewModeChanged=this.currentRender?.type!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStoreValue,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare()}catch(err){lastRender&&await this.teardownRender(lastRender),err!==PREPARE_ABORTED&&this.renderStoryLoadingException(storyId,err);return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)&&((0,import_tiny_invariant.default)(!!render.story),this.storyStoreValue.args.updateFromPersisted(render.story,persistedArgs)),lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(import_core_events6.STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(import_core_events6.STORY_CHANGED,storyId),isStoryRender(render)){(0,import_tiny_invariant.default)(!!render.story);let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStoreValue.getStoryContext(render.story);this.channel.emit(import_core_events6.STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs})}else{let{parameters}=this.storyStoreValue.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new import_preview_errors4.MdxFileWithNoCsfReferencesError({storyId});({parameters}=this.storyStoreValue.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}))}this.channel.emit(import_core_events6.DOCS_PREPARED,{id:storyId,parameters})}isStoryRender(render)?((0,import_tiny_invariant.default)(!!render.story),this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))):this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this))}async teardownRender(render,{viewModeChanged=!1}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged})}mainStoryCallbacks(storyId){return{showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err)}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(import_core_events6.STORY_MISSING)}renderStoryLoadingException(storySpecifier,err){import_client_logger12.logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(import_core_events6.STORY_MISSING,storySpecifier)}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(import_core_events6.STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),import_client_logger12.logger.error(`Error rendering story '${storyId}':`),import_client_logger12.logger.error(error))}renderError(storyId,{title,description}){import_client_logger12.logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(import_core_events6.STORY_ERRORED,{title,description}),this.channel.emit(import_core_events6.STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description})}};var import_global7=require("@storybook/global"),import_qs2=__toESM(require("qs"));var import_qs=__toESM(require("qs")),import_ts_dedent9=require("ts-dedent"),import_client_logger13=require("@storybook/client-logger"),import_isPlainObject3=__toESM(require("lodash/isPlainObject.js")),VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):(0,import_isPlainObject3.default)(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return!0;if(str==="!false")return!1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return`#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(import_qs.default.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(import_client_logger13.once.warn(import_ts_dedent9.dedent`
|
52
58
|
Omitted potentially unsafe URL args.
|
53
59
|
|
54
60
|
More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
|
55
|
-
`),acc),{})};var{history,document:document2}=
|
61
|
+
`),acc),{})};var{history,document:document2}=import_global7.global;function pathToId(path){let match=(path||"").match(/^\/story\/(.+)/);if(!match)throw new Error(`Invalid path '${path}', must start with '/story/'`);return match[1]}var getQueryString=({selection,extraParams})=>{let search=typeof document2<"u"?document2.location.search:"",{path,selectedKind,selectedStory,...rest}=import_qs2.default.parse(search,{ignoreQueryPrefix:!0});return import_qs2.default.stringify({...rest,...extraParams,...selection&&{id:selection.storyId,viewMode:selection.viewMode}},{encode:!1,addQueryPrefix:!0})},setPath=selection=>{if(!selection)return;let query=getQueryString({selection}),{hash=""}=document2.location;document2.title=selection.storyId,history.replaceState({},"",`${document2.location.pathname}${query}${hash}`)},isObject=val=>val!=null&&typeof val=="object"&&Array.isArray(val)===!1,getFirstString=v=>{if(v!==void 0){if(typeof v=="string")return v;if(Array.isArray(v))return getFirstString(v[0]);if(isObject(v))return getFirstString(Object.values(v).filter(Boolean))}},getSelectionSpecifierFromPath=()=>{if(typeof document2<"u"){let query=import_qs2.default.parse(document2.location.search,{ignoreQueryPrefix:!0}),args=typeof query.args=="string"?parseArgsParam(query.args):void 0,globals=typeof query.globals=="string"?parseArgsParam(query.globals):void 0,viewMode=getFirstString(query.viewMode);(typeof viewMode!="string"||!viewMode.match(/docs|story/))&&(viewMode="story");let path=getFirstString(query.path),storyId=path?pathToId(path):getFirstString(query.id);if(storyId)return{storySpecifier:storyId,args,globals,viewMode}}return null},UrlStore=class{constructor(){this.selectionSpecifier=getSelectionSpecifierFromPath()}setSelection(selection){this.selection=selection,setPath(this.selection)}setQueryParams(queryParams){let query=getQueryString({extraParams:queryParams}),{hash=""}=document2.location;history.replaceState({},"",`${document2.location.pathname}${query}${hash}`)}};var import_global8=require("@storybook/global"),import_client_logger14=require("@storybook/client-logger"),import_ansi_to_html=__toESM(require_ansi_to_html()),import_ts_dedent10=require("ts-dedent"),import_qs3=__toESM(require("qs")),{document:document3}=import_global8.global,PREPARING_DELAY=100,Mode=(Mode2=>(Mode2.MAIN="MAIN",Mode2.NOPREVIEW="NOPREVIEW",Mode2.PREPARING_STORY="PREPARING_STORY",Mode2.PREPARING_DOCS="PREPARING_DOCS",Mode2.ERROR="ERROR",Mode2))(Mode||{}),classes={PREPARING_STORY:"sb-show-preparing-story",PREPARING_DOCS:"sb-show-preparing-docs",MAIN:"sb-show-main",NOPREVIEW:"sb-show-nopreview",ERROR:"sb-show-errordisplay"},layoutClassMap={centered:"sb-main-centered",fullscreen:"sb-main-fullscreen",padded:"sb-main-padded"},ansiConverter=new import_ansi_to_html.default({escapeXML:!0}),WebView=class{constructor(){this.testing=!1;if(typeof document3<"u"){let{__SPECIAL_TEST_PARAMETER__}=import_qs3.default.parse(document3.location.search,{ignoreQueryPrefix:!0});switch(__SPECIAL_TEST_PARAMETER__){case"preparing-story":{this.showPreparingStory(),this.testing=!0;break}case"preparing-docs":{this.showPreparingDocs(),this.testing=!0;break}default:}}}prepareForStory(story){return this.showStory(),this.applyLayout(story.parameters.layout),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.storyRoot()}storyRoot(){return document3.getElementById("storybook-root")}prepareForDocs(){return this.showMain(),this.showDocs(),this.applyLayout("fullscreen"),document3.documentElement.scrollTop=0,document3.documentElement.scrollLeft=0,this.docsRoot()}docsRoot(){return document3.getElementById("storybook-docs")}applyLayout(layout="padded"){if(layout==="none"){document3.body.classList.remove(this.currentLayoutClass),this.currentLayoutClass=null;return}this.checkIfLayoutExists(layout);let layoutClass=layoutClassMap[layout];document3.body.classList.remove(this.currentLayoutClass),document3.body.classList.add(layoutClass),this.currentLayoutClass=layoutClass}checkIfLayoutExists(layout){layoutClassMap[layout]||import_client_logger14.logger.warn(import_ts_dedent10.dedent`
|
56
62
|
The desired layout: ${layout} is not a valid option.
|
57
63
|
The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.
|
58
64
|
`)}showMode(mode){clearTimeout(this.preparingTimeout),Object.keys(Mode).forEach(otherMode=>{otherMode===mode?document3.body.classList.add(classes[otherMode]):document3.body.classList.remove(classes[otherMode])})}showErrorDisplay({message="",stack=""}){let header=message,detail=stack,parts=message.split(`
|
59
65
|
`);parts.length>1&&([header]=parts,detail=parts.slice(1).join(`
|
60
|
-
`).replace(/^\n/,"")),document3.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document3.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){this.testing||(this.showMode("NOPREVIEW"),this.storyRoot()?.setAttribute("hidden","true"),this.docsRoot()?.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_DOCS"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document3.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(importFn,getProjectAnnotations){super(importFn,getProjectAnnotations,new UrlStore,new WebView);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;
|
66
|
+
`).replace(/^\n/,"")),document3.getElementById("error-message").innerHTML=ansiConverter.toHtml(header),document3.getElementById("error-stack").innerHTML=ansiConverter.toHtml(detail),this.showMode("ERROR")}showNoPreview(){this.testing||(this.showMode("NOPREVIEW"),this.storyRoot()?.setAttribute("hidden","true"),this.docsRoot()?.setAttribute("hidden","true"))}showPreparingStory({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_STORY"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_STORY"),PREPARING_DELAY)}showPreparingDocs({immediate=!1}={}){clearTimeout(this.preparingTimeout),immediate?this.showMode("PREPARING_DOCS"):this.preparingTimeout=setTimeout(()=>this.showMode("PREPARING_DOCS"),PREPARING_DELAY)}showMain(){this.showMode("MAIN")}showDocs(){this.storyRoot().setAttribute("hidden","true"),this.docsRoot().removeAttribute("hidden")}showStory(){this.docsRoot().setAttribute("hidden","true"),this.storyRoot().removeAttribute("hidden")}showStoryDuringRender(){document3.body.classList.add(classes.MAIN)}};var PreviewWeb=class extends PreviewWithSelection{constructor(importFn,getProjectAnnotations){super(importFn,getProjectAnnotations,new UrlStore,new WebView);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;import_global9.global.__STORYBOOK_PREVIEW__=this}};var import_global10=require("@storybook/global"),{document:document4}=import_global10.global,runScriptTypes=["application/javascript","application/ecmascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript","module"],SCRIPT="script",SCRIPTS_ROOT_ID="scripts-root";function simulateDOMContentLoaded(){let DOMContentLoadedEvent=document4.createEvent("Event");DOMContentLoadedEvent.initEvent("DOMContentLoaded",!0,!0),document4.dispatchEvent(DOMContentLoadedEvent)}function insertScript($script,callback,$scriptRoot){let scriptEl=document4.createElement("script");scriptEl.type=$script.type==="module"?"module":"text/javascript",$script.src?(scriptEl.onload=callback,scriptEl.onerror=callback,scriptEl.src=$script.src):scriptEl.textContent=$script.innerText,$scriptRoot?$scriptRoot.appendChild(scriptEl):document4.head.appendChild(scriptEl),$script.parentNode.removeChild($script),$script.src||callback()}function insertScriptsSequentially(scriptsToExecute,callback,index=0){scriptsToExecute[index](()=>{index++,index===scriptsToExecute.length?callback():insertScriptsSequentially(scriptsToExecute,callback,index)})}function simulatePageLoad($container){let $scriptsRoot=document4.getElementById(SCRIPTS_ROOT_ID);$scriptsRoot?$scriptsRoot.innerHTML="":($scriptsRoot=document4.createElement("div"),$scriptsRoot.id=SCRIPTS_ROOT_ID,document4.body.appendChild($scriptsRoot));let $scripts=Array.from($container.querySelectorAll(SCRIPT));if($scripts.length){let scriptsToExecute=[];$scripts.forEach($script=>{let typeAttr=$script.getAttribute("type");(!typeAttr||runScriptTypes.includes(typeAttr))&&scriptsToExecute.push(callback=>insertScript($script,callback,$scriptsRoot))}),scriptsToExecute.length&&insertScriptsSequentially(scriptsToExecute,simulateDOMContentLoaded,void 0)}else simulateDOMContentLoaded()}0&&(module.exports={DocsContext,HooksContext,Preview,PreviewWeb,PreviewWithSelection,StoryStore,UrlStore,WebView,addons,applyHooks,combineArgs,combineParameters,composeConfigs,composeStepRunners,composeStories,composeStory,createPlaywrightTest,decorateStory,defaultDecorateStory,filterArgTypes,inferControls,makeDecorator,mockChannel,normalizeStory,prepareMeta,prepareStory,sanitizeStoryContextUpdate,setProjectAnnotations,simulateDOMContentLoaded,simulatePageLoad,sortStoriesV7,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext,userOrAutoTitle,userOrAutoTitleFromSpecifier});
|
package/dist/index.mjs
CHANGED
@@ -1,15 +1,15 @@
|
|
1
1
|
import { global } from '@storybook/global';
|
2
2
|
import { Channel } from '@storybook/channels';
|
3
|
-
import { logger, deprecate as deprecate$1
|
4
|
-
import { STORY_RENDERED, STORY_INDEX_INVALIDATED, UPDATE_GLOBALS, UPDATE_STORY_ARGS, RESET_STORY_ARGS, FORCE_RE_RENDER, FORCE_REMOUNT, SET_GLOBALS, GLOBALS_UPDATED, STORY_ARGS_UPDATED, CONFIG_ERROR, SET_CURRENT_STORY, UPDATE_QUERY_PARAMS, PRELOAD_ENTRIES, STORY_SPECIFIED, CURRENT_STORY_WAS_SET, PREVIEW_KEYDOWN, STORY_UNCHANGED, STORY_CHANGED, STORY_PREPARED, DOCS_PREPARED, STORY_MISSING, STORY_THREW_EXCEPTION, STORY_RENDER_PHASE_CHANGED, STORY_ERRORED, PLAY_FUNCTION_THREW_EXCEPTION, UNHANDLED_ERRORS_WHILE_PLAYING, DOCS_RENDERED } from '@storybook/core-events';
|
3
|
+
import { logger, once, deprecate as deprecate$1 } from '@storybook/client-logger';
|
4
|
+
import { STORY_RENDERED, STORY_INDEX_INVALIDATED, UPDATE_GLOBALS, UPDATE_STORY_ARGS, ARGTYPES_INFO_REQUEST, RESET_STORY_ARGS, FORCE_RE_RENDER, FORCE_REMOUNT, SET_GLOBALS, GLOBALS_UPDATED, STORY_ARGS_UPDATED, ARGTYPES_INFO_RESPONSE, CONFIG_ERROR, SET_CURRENT_STORY, UPDATE_QUERY_PARAMS, PRELOAD_ENTRIES, STORY_SPECIFIED, CURRENT_STORY_WAS_SET, PREVIEW_KEYDOWN, STORY_UNCHANGED, STORY_CHANGED, STORY_PREPARED, DOCS_PREPARED, STORY_MISSING, STORY_THREW_EXCEPTION, STORY_RENDER_PHASE_CHANGED, STORY_ERRORED, PLAY_FUNCTION_THREW_EXCEPTION, UNHANDLED_ERRORS_WHILE_PLAYING, DOCS_RENDERED } from '@storybook/core-events';
|
5
5
|
import memoize2 from 'memoizerific';
|
6
6
|
import mapValues2 from 'lodash/mapValues.js';
|
7
7
|
import pick from 'lodash/pick.js';
|
8
8
|
import { MissingStoryFromCsfFileError, CalledExtractOnStoreError, StoryStoreAccessedBeforeInitializationError, MissingRenderToCanvasError, StoryIndexFetchError, CalledPreviewMethodBeforeInitializationError, EmptyIndexError, NoStoryMatchError, MdxFileWithNoCsfReferencesError, MissingStoryAfterHmrError } from '@storybook/core-events/preview-errors';
|
9
9
|
import { dequal } from 'dequal';
|
10
10
|
import isPlainObject from 'lodash/isPlainObject.js';
|
11
|
-
import
|
12
|
-
import { storyNameFromExport, toId, isExportStory, sanitize, includeConditionalArg } from '@storybook/csf';
|
11
|
+
import dedent5, { dedent } from 'ts-dedent';
|
12
|
+
import { storyNameFromExport, toId, combineTags, isExportStory, sanitize, includeConditionalArg } from '@storybook/csf';
|
13
13
|
import deprecate from 'util-deprecate';
|
14
14
|
import pickBy from 'lodash/pickBy.js';
|
15
15
|
import invariant from 'tiny-invariant';
|
@@ -33,13 +33,19 @@ CSF .story annotations deprecated; annotate story functions directly:
|
|
33
33
|
- StoryFn.story.name => StoryFn.storyName
|
34
34
|
- StoryFn.story.(parameters|decorators) => StoryFn.(parameters|decorators)
|
35
35
|
See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-annotations for details and codemod.
|
36
|
-
`,deprecatedStoryAnnotationWarning=deprecate(()=>{},deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){let storyObject=storyAnnotations,userStoryFn=typeof storyAnnotations=="function"?storyAnnotations:null,{story}=storyObject;story&&(logger.debug("deprecated story",story),deprecatedStoryAnnotationWarning());let exportName=storyNameFromExport(key),name=typeof storyObject!="function"&&storyObject.name||storyObject.storyName||story?.name||exportName,decorators=[...normalizeArrays(storyObject.decorators),...normalizeArrays(story?.decorators)],parameters={...story?.parameters,...storyObject.parameters},args={...story?.args,...storyObject.args},argTypes={...story?.argTypes,...storyObject.argTypes},loaders=[...normalizeArrays(storyObject.loaders),...normalizeArrays(story?.loaders)],{render,play,tags=[]}=storyObject,id=parameters.__id||toId(meta.id,exportName);return {moduleExport:storyAnnotations,id,name,tags,decorators,parameters,args,argTypes:normalizeInputTypes(argTypes),loaders,...render&&{render},...userStoryFn&&{userStoryFn},...play&&{play}}}function normalizeComponentAnnotations(defaultExport,title=defaultExport.title,importPath){let{id,argTypes}=defaultExport;return {id:sanitize(id||title),...defaultExport,title,...argTypes&&{argTypes:normalizeInputTypes(argTypes)},parameters:{fileName:importPath,...defaultExport.parameters}}}var checkGlobals=parameters=>{let{globals,globalTypes}=parameters;(globals||globalTypes)&&logger.error("Global args/argTypes can only be set globally",JSON.stringify({globals,globalTypes}));},checkStorySort=parameters=>{let{options}=parameters;options?.storySort&&logger.error("The storySort option parameter can only be set globally");},checkDisallowedParameters=parameters=>{parameters&&(checkGlobals(parameters),checkStorySort(parameters));};function processCSFFile(moduleExports,importPath,title){let{default:defaultExport,__namedExportsOrder,...namedExports}=moduleExports,meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters);let csfFile={meta,stories:{},moduleExports};return Object.keys(namedExports).forEach(key=>{if(isExportStory(key,meta)){let storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta;}}),csfFile}var combineParameters=(...parameterSets)=>{let mergeKeys={},definedParametersSets=parameterSets.filter(Boolean),combined=definedParametersSets.reduce((acc,parameters)=>(Object.entries(parameters).forEach(([key,value])=>{let existing=acc[key];Array.isArray(value)||typeof existing>"u"?acc[key]=value:isPlainObject(value)&&isPlainObject(existing)?mergeKeys[key]=!0:typeof value<"u"&&(acc[key]=value);}),acc),{});return Object.keys(mergeKeys).forEach(key=>{let mergeValues=definedParametersSets.filter(Boolean).map(p=>p[key]).filter(value=>typeof value<"u");mergeValues.every(value=>isPlainObject(value))?combined[key]=combineParameters(...mergeValues):combined[key]=mergeValues[mergeValues.length-1];}),combined};function decorateStory(storyFn,decorator,bindWithContext){let boundStoryFunction=bindWithContext(storyFn);return context=>decorator(boundStoryFunction,context)}function sanitizeStoryContextUpdate({componentId,title,kind,id,name,story,parameters,initialArgs,argTypes,...update}={}){return update}function defaultDecorateStory(storyFn,decorators){let contextStore={},bindWithContext=decoratedStoryFn=>update=>{if(!contextStore.value)throw new Error("Decorated function called without init");return contextStore.value={...contextStore.value,...sanitizeStoryContextUpdate(update)},decoratedStoryFn(contextStore.value)},decoratedWithContextStore=decorators.reduce((story,decorator)=>decorateStory(story,decorator,bindWithContext),storyFn);return context=>(contextStore.value=context,decoratedWithContextStore(context))}function prepareStory(storyAnnotations,componentAnnotations,projectAnnotations){let{moduleExport,id,name}=storyAnnotations||{},partialAnnotations=preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations),applyLoaders=async context=>{let updatedContext={...context,loaded:{}};for(let loaders of [..."__STORYBOOK_TEST_LOADERS__"in global&&Array.isArray(global.__STORYBOOK_TEST_LOADERS__)?[global.__STORYBOOK_TEST_LOADERS__]:[],normalizeArrays(projectAnnotations.loaders),normalizeArrays(componentAnnotations.loaders),normalizeArrays(storyAnnotations.loaders)]){let loadResults=await Promise.all(loaders.map(loader=>loader(updatedContext))),loaded=Object.assign({},...loadResults);updatedContext={...updatedContext,loaded:{...updatedContext.loaded,...loaded}};}return updatedContext},undecoratedStoryFn=context=>render(context.args,context),{applyDecorators=defaultDecorateStory,runStep}=projectAnnotations,decorators=[...normalizeArrays(storyAnnotations?.decorators),...normalizeArrays(componentAnnotations?.decorators),...normalizeArrays(projectAnnotations?.decorators)],render=storyAnnotations?.userStoryFn||storyAnnotations?.render||componentAnnotations.render||projectAnnotations.render;if(!render)throw new Error(`No render function available for storyId '${id}'`);let decoratedStoryFn=applyHooks(applyDecorators)(undecoratedStoryFn,decorators),unboundStoryFn=context=>decoratedStoryFn(context),play=storyAnnotations?.play||componentAnnotations.play;return {...partialAnnotations,moduleExport,id,name,story:name,originalStoryFn:render,undecoratedStoryFn,unboundStoryFn,applyLoaders,playFunction:play&&(async storyContext=>{let playFunctionContext={...storyContext,step:(label,play2)=>runStep(label,play2,playFunctionContext)};return play(playFunctionContext)})}}function prepareMeta(componentAnnotations,projectAnnotations,moduleExport){return {...preparePartialAnnotations(void 0,componentAnnotations,projectAnnotations),moduleExport}}function preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations){let
|
36
|
+
`,deprecatedStoryAnnotationWarning=deprecate(()=>{},deprecatedStoryAnnotation);function normalizeStory(key,storyAnnotations,meta){let storyObject=storyAnnotations,userStoryFn=typeof storyAnnotations=="function"?storyAnnotations:null,{story}=storyObject;story&&(logger.debug("deprecated story",story),deprecatedStoryAnnotationWarning());let exportName=storyNameFromExport(key),name=typeof storyObject!="function"&&storyObject.name||storyObject.storyName||story?.name||exportName,decorators=[...normalizeArrays(storyObject.decorators),...normalizeArrays(story?.decorators)],parameters={...story?.parameters,...storyObject.parameters},args={...story?.args,...storyObject.args},argTypes={...story?.argTypes,...storyObject.argTypes},loaders=[...normalizeArrays(storyObject.loaders),...normalizeArrays(story?.loaders)],beforeEach=[...normalizeArrays(storyObject.beforeEach),...normalizeArrays(story?.beforeEach)],{render,play,tags=[]}=storyObject,id=parameters.__id||toId(meta.id,exportName);return {moduleExport:storyAnnotations,id,name,tags,decorators,parameters,args,argTypes:normalizeInputTypes(argTypes),loaders,beforeEach,...render&&{render},...userStoryFn&&{userStoryFn},...play&&{play}}}function normalizeComponentAnnotations(defaultExport,title=defaultExport.title,importPath){let{id,argTypes}=defaultExport;return {id:sanitize(id||title),...defaultExport,title,...argTypes&&{argTypes:normalizeInputTypes(argTypes)},parameters:{fileName:importPath,...defaultExport.parameters}}}var checkGlobals=parameters=>{let{globals,globalTypes}=parameters;(globals||globalTypes)&&logger.error("Global args/argTypes can only be set globally",JSON.stringify({globals,globalTypes}));},checkStorySort=parameters=>{let{options}=parameters;options?.storySort&&logger.error("The storySort option parameter can only be set globally");},checkDisallowedParameters=parameters=>{parameters&&(checkGlobals(parameters),checkStorySort(parameters));};function processCSFFile(moduleExports,importPath,title){let{default:defaultExport,__namedExportsOrder,...namedExports}=moduleExports,meta=normalizeComponentAnnotations(defaultExport,title,importPath);checkDisallowedParameters(meta.parameters);let csfFile={meta,stories:{},moduleExports};return Object.keys(namedExports).forEach(key=>{if(isExportStory(key,meta)){let storyMeta=normalizeStory(key,namedExports[key],meta);checkDisallowedParameters(storyMeta.parameters),csfFile.stories[storyMeta.id]=storyMeta;}}),csfFile}var combineParameters=(...parameterSets)=>{let mergeKeys={},definedParametersSets=parameterSets.filter(Boolean),combined=definedParametersSets.reduce((acc,parameters)=>(Object.entries(parameters).forEach(([key,value])=>{let existing=acc[key];Array.isArray(value)||typeof existing>"u"?acc[key]=value:isPlainObject(value)&&isPlainObject(existing)?mergeKeys[key]=!0:typeof value<"u"&&(acc[key]=value);}),acc),{});return Object.keys(mergeKeys).forEach(key=>{let mergeValues=definedParametersSets.filter(Boolean).map(p=>p[key]).filter(value=>typeof value<"u");mergeValues.every(value=>isPlainObject(value))?combined[key]=combineParameters(...mergeValues):combined[key]=mergeValues[mergeValues.length-1];}),combined};function decorateStory(storyFn,decorator,bindWithContext){let boundStoryFunction=bindWithContext(storyFn);return context=>decorator(boundStoryFunction,context)}function sanitizeStoryContextUpdate({componentId,title,kind,id,name,story,parameters,initialArgs,argTypes,...update}={}){return update}function defaultDecorateStory(storyFn,decorators){let contextStore={},bindWithContext=decoratedStoryFn=>update=>{if(!contextStore.value)throw new Error("Decorated function called without init");return contextStore.value={...contextStore.value,...sanitizeStoryContextUpdate(update)},decoratedStoryFn(contextStore.value)},decoratedWithContextStore=decorators.reduce((story,decorator)=>decorateStory(story,decorator,bindWithContext),storyFn);return context=>(contextStore.value=context,decoratedWithContextStore(context))}function prepareStory(storyAnnotations,componentAnnotations,projectAnnotations){let{moduleExport,id,name}=storyAnnotations||{},partialAnnotations=preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations),applyLoaders=async context=>{let updatedContext={...context,loaded:{}};for(let loaders of [..."__STORYBOOK_TEST_LOADERS__"in global&&Array.isArray(global.__STORYBOOK_TEST_LOADERS__)?[global.__STORYBOOK_TEST_LOADERS__]:[],normalizeArrays(projectAnnotations.loaders),normalizeArrays(componentAnnotations.loaders),normalizeArrays(storyAnnotations.loaders)]){let loadResults=await Promise.all(loaders.map(loader=>loader(updatedContext))),loaded=Object.assign({},...loadResults);updatedContext={...updatedContext,loaded:{...updatedContext.loaded,...loaded}};}return updatedContext},applyBeforeEach=async context=>{let cleanupCallbacks=new Array;for(let beforeEach of [...normalizeArrays(projectAnnotations.beforeEach),...normalizeArrays(componentAnnotations.beforeEach),...normalizeArrays(storyAnnotations.beforeEach)]){let cleanup=await beforeEach(context);cleanup&&cleanupCallbacks.push(cleanup);}return cleanupCallbacks},undecoratedStoryFn=context=>render(context.args,context),{applyDecorators=defaultDecorateStory,runStep}=projectAnnotations,decorators=[...normalizeArrays(storyAnnotations?.decorators),...normalizeArrays(componentAnnotations?.decorators),...normalizeArrays(projectAnnotations?.decorators)],render=storyAnnotations?.userStoryFn||storyAnnotations?.render||componentAnnotations.render||projectAnnotations.render;if(!render)throw new Error(`No render function available for storyId '${id}'`);let decoratedStoryFn=applyHooks(applyDecorators)(undecoratedStoryFn,decorators),unboundStoryFn=context=>decoratedStoryFn(context),play=storyAnnotations?.play||componentAnnotations.play;return {...partialAnnotations,moduleExport,id,name,story:name,originalStoryFn:render,undecoratedStoryFn,unboundStoryFn,applyLoaders,applyBeforeEach,playFunction:play&&(async storyContext=>{let playFunctionContext={...storyContext,step:(label,play2)=>runStep(label,play2,playFunctionContext)};return play(playFunctionContext)})}}function prepareMeta(componentAnnotations,projectAnnotations,moduleExport){return {...preparePartialAnnotations(void 0,componentAnnotations,projectAnnotations),moduleExport}}function preparePartialAnnotations(storyAnnotations,componentAnnotations,projectAnnotations){let defaultTags=["dev","test"];typeof global.DOCS_OPTIONS?.autodocs<"u"&&once.warn(dedent`
|
37
|
+
The \`docs.autodocs\` setting in '.storybook/main.js' is deprecated. Use \`tags: ['autodocs']\` in \`.storybook/preview.js\` instead.
|
38
|
+
|
39
|
+
For more info see: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-docsautodocs-is-deprecated
|
40
|
+
`);let extraTags=global.DOCS_OPTIONS?.autodocs===!0?["autodocs"]:[],tags=combineTags(...defaultTags,...extraTags,...projectAnnotations.tags??[],...componentAnnotations.tags??[],...storyAnnotations?.tags??[]),parameters=combineParameters(projectAnnotations.parameters,componentAnnotations.parameters,storyAnnotations?.parameters),{argTypesEnhancers=[],argsEnhancers=[]}=projectAnnotations,passedArgTypes=combineParameters(projectAnnotations.argTypes,componentAnnotations.argTypes,storyAnnotations?.argTypes);if(storyAnnotations){let render=storyAnnotations?.userStoryFn||storyAnnotations?.render||componentAnnotations.render||projectAnnotations.render;parameters.__isArgsStory=render&&render.length>0;}let passedArgs={...projectAnnotations.args,...componentAnnotations.args,...storyAnnotations?.args},contextForEnhancers={componentId:componentAnnotations.id,title:componentAnnotations.title,kind:componentAnnotations.title,id:storyAnnotations?.id||componentAnnotations.id,name:storyAnnotations?.name||"__meta",story:storyAnnotations?.name||"__meta",component:componentAnnotations.component,subcomponents:componentAnnotations.subcomponents,tags,parameters,initialArgs:passedArgs,argTypes:passedArgTypes};contextForEnhancers.argTypes=argTypesEnhancers.reduce((accumulatedArgTypes,enhancer)=>enhancer({...contextForEnhancers,argTypes:accumulatedArgTypes}),contextForEnhancers.argTypes);let initialArgsBeforeEnhancers={...passedArgs};contextForEnhancers.initialArgs=argsEnhancers.reduce((accumulatedArgs,enhancer)=>({...accumulatedArgs,...enhancer({...contextForEnhancers,initialArgs:accumulatedArgs})}),initialArgsBeforeEnhancers);let{name,story,...withoutStoryIdentifiers}=contextForEnhancers;return withoutStoryIdentifiers}function prepareContext(context){let{args:unmappedArgs}=context,targetedContext={...context,allArgs:void 0,argsByTarget:void 0};if(global.FEATURES?.argTypeTargetsV7){let argsByTarget=groupArgsByTarget(context);targetedContext={...context,allArgs:context.args,argsByTarget,args:argsByTarget[UNTARGETED]||{}};}let mappedArgs=Object.entries(targetedContext.args).reduce((acc,[key,val])=>{if(!targetedContext.argTypes[key]?.mapping)return acc[key]=val,acc;let mappingFn=originalValue=>{let mapping=targetedContext.argTypes[key].mapping;return mapping&&originalValue in mapping?mapping[originalValue]:originalValue};return acc[key]=Array.isArray(val)?val.map(mappingFn):mappingFn(val),acc},{}),includedArgs=Object.entries(mappedArgs).reduce((acc,[key,val])=>{let argType=targetedContext.argTypes[key]||{};return includeConditionalArg(argType,mappedArgs,targetedContext.globals)&&(acc[key]=val),acc},{});return {...targetedContext,unmappedArgs,args:includedArgs}}var inferType=(value,name,visited)=>{let type=typeof value;switch(type){case"boolean":case"string":case"number":case"function":case"symbol":return {name:type};}return value?visited.has(value)?(logger.warn(dedent`
|
37
41
|
We've detected a cycle in arg '${name}'. Args should be JSON-serializable.
|
38
42
|
|
39
43
|
Consider using the mapping feature or fully custom args:
|
40
44
|
- Mapping: https://storybook.js.org/docs/react/writing-stories/args#mapping-to-complex-arg-values
|
41
45
|
- Custom args: https://storybook.js.org/docs/react/essentials/controls#fully-custom-args
|
42
|
-
`),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:mapValues2(value,field=>inferType(field,name,new Set(visited)))}):{name:"object",value:{}}},inferArgTypes=context=>{let{id,argTypes:userArgTypes={},initialArgs={}}=context,argTypes=mapValues2(initialArgs,(arg,key)=>({name:key,type:inferType(arg,`${id}.${key}`,new Set)})),userArgTypesNames=mapValues2(userArgTypes,(argType,key)=>({name:key}));return combineParameters(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var matches=(name,descriptor)=>Array.isArray(descriptor)?descriptor.includes(name):name.match(descriptor),filterArgTypes=(argTypes,include,exclude)=>!include&&!exclude?argTypes:argTypes&&pickBy(argTypes,(argType,key)=>{let name=argType.name||key;return (!include||matches(name,include))&&(!exclude||!matches(name,exclude))});var inferControl=(argType,name,matchers)=>{let{type,options}=argType;if(type){if(matchers.color&&matchers.color.test(name)){let controlType=type.name;if(controlType==="string")return {control:{type:"color"}};controlType!=="enum"&&logger.warn(`Addon controls: Control of type color only supports string, received "${controlType}" instead`);}if(matchers.date&&matchers.date.test(name))return {control:{type:"date"}};switch(type.name){case"array":return {control:{type:"object"}};case"boolean":return {control:{type:"boolean"}};case"string":return {control:{type:"text"}};case"number":return {control:{type:"number"}};case"enum":{let{value}=type;return {control:{type:value?.length<=5?"radio":"select"},options:value}}case"function":case"symbol":return null;default:return {control:{type:options?"select":"object"}}}}},inferControls=context=>{let{argTypes,parameters:{__isArgsStory,controls:{include=null,exclude=null,matchers={}}={}}}=context;if(!__isArgsStory)return argTypes;let filteredArgTypes=filterArgTypes(argTypes,include,exclude),withControls=mapValues2(filteredArgTypes,(argType,name)=>argType?.type&&inferControl(argType,name,matchers));return combineParameters(withControls,filteredArgTypes)};inferControls.secondPass=!0;function normalizeProjectAnnotations({argTypes,globalTypes,argTypesEnhancers,decorators,loaders,...annotations}){return {...argTypes&&{argTypes:normalizeInputTypes(argTypes)},...globalTypes&&{globalTypes:normalizeInputTypes(globalTypes)},decorators:normalizeArrays(decorators),loaders:normalizeArrays(loaders),argTypesEnhancers:[...argTypesEnhancers||[],inferArgTypes,inferControls],...annotations}}function composeStepRunners(stepRunners){return async(label,play,playContext)=>{await stepRunners.reduceRight((innerPlay,stepRunner)=>async()=>stepRunner(label,innerPlay,playContext),async()=>play(playContext))();}}function getField(moduleExportList,field){return moduleExportList.map(xs=>xs.default?.[field]??xs[field]).filter(Boolean)}function getArrayField(moduleExportList,field,options={}){return getField(moduleExportList,field).reduce((prev,cur)=>{let normalized=normalizeArrays(cur);return options.reverseFileOrder?[...normalized,...prev]:[...prev,...normalized]},[])}function getObjectField(moduleExportList,field){return Object.assign({},...getField(moduleExportList,field))}function getSingletonField(moduleExportList,field){return getField(moduleExportList,field).pop()}function composeConfigs(moduleExportList){let allArgTypeEnhancers=getArrayField(moduleExportList,"argTypesEnhancers"),stepRunners=getField(moduleExportList,"runStep");return {parameters:combineParameters(...getField(moduleExportList,"parameters")),decorators:getArrayField(moduleExportList,"decorators",{reverseFileOrder:!(global.FEATURES?.legacyDecoratorFileOrder??!1)}),args:getObjectField(moduleExportList,"args"),argsEnhancers:getArrayField(moduleExportList,"argsEnhancers"),argTypes:getObjectField(moduleExportList,"argTypes"),argTypesEnhancers:[...allArgTypeEnhancers.filter(e=>!e.secondPass),...allArgTypeEnhancers.filter(e=>e.secondPass)],globals:getObjectField(moduleExportList,"globals"),globalTypes:getObjectField(moduleExportList,"globalTypes"),loaders:getArrayField(moduleExportList,"loaders"),render:getSingletonField(moduleExportList,"render"),renderToCanvas:getSingletonField(moduleExportList,"renderToCanvas"),renderToDOM:getSingletonField(moduleExportList,"renderToDOM"),applyDecorators:getSingletonField(moduleExportList,"applyDecorators"),runStep:composeStepRunners(stepRunners)}}var globalProjectAnnotations={};function extractAnnotation(annotation){return "default"in annotation?annotation.default:annotation}function setProjectAnnotations(projectAnnotations){let annotations=Array.isArray(projectAnnotations)?projectAnnotations:[projectAnnotations];globalProjectAnnotations=composeConfigs(annotations.map(extractAnnotation));}function composeStory(storyAnnotations,componentAnnotations,projectAnnotations,defaultConfig,exportsName){if(storyAnnotations===void 0)throw new Error("Expected a story but received undefined.");componentAnnotations.title=componentAnnotations.title??
|
46
|
+
`),{name:"other",value:"cyclic object"}):(visited.add(value),Array.isArray(value)?{name:"array",value:value.length>0?inferType(value[0],name,new Set(visited)):{name:"other",value:"unknown"}}:{name:"object",value:mapValues2(value,field=>inferType(field,name,new Set(visited)))}):{name:"object",value:{}}},inferArgTypes=context=>{let{id,argTypes:userArgTypes={},initialArgs={}}=context,argTypes=mapValues2(initialArgs,(arg,key)=>({name:key,type:inferType(arg,`${id}.${key}`,new Set)})),userArgTypesNames=mapValues2(userArgTypes,(argType,key)=>({name:key}));return combineParameters(argTypes,userArgTypesNames,userArgTypes)};inferArgTypes.secondPass=!0;var matches=(name,descriptor)=>Array.isArray(descriptor)?descriptor.includes(name):name.match(descriptor),filterArgTypes=(argTypes,include,exclude)=>!include&&!exclude?argTypes:argTypes&&pickBy(argTypes,(argType,key)=>{let name=argType.name||key;return (!include||matches(name,include))&&(!exclude||!matches(name,exclude))});var inferControl=(argType,name,matchers)=>{let{type,options}=argType;if(type){if(matchers.color&&matchers.color.test(name)){let controlType=type.name;if(controlType==="string")return {control:{type:"color"}};controlType!=="enum"&&logger.warn(`Addon controls: Control of type color only supports string, received "${controlType}" instead`);}if(matchers.date&&matchers.date.test(name))return {control:{type:"date"}};switch(type.name){case"array":return {control:{type:"object"}};case"boolean":return {control:{type:"boolean"}};case"string":return {control:{type:"text"}};case"number":return {control:{type:"number"}};case"enum":{let{value}=type;return {control:{type:value?.length<=5?"radio":"select"},options:value}}case"function":case"symbol":return null;default:return {control:{type:options?"select":"object"}}}}},inferControls=context=>{let{argTypes,parameters:{__isArgsStory,controls:{include=null,exclude=null,matchers={}}={}}}=context;if(!__isArgsStory)return argTypes;let filteredArgTypes=filterArgTypes(argTypes,include,exclude),withControls=mapValues2(filteredArgTypes,(argType,name)=>argType?.type&&inferControl(argType,name,matchers));return combineParameters(withControls,filteredArgTypes)};inferControls.secondPass=!0;function normalizeProjectAnnotations({argTypes,globalTypes,argTypesEnhancers,decorators,loaders,beforeEach,...annotations}){return {...argTypes&&{argTypes:normalizeInputTypes(argTypes)},...globalTypes&&{globalTypes:normalizeInputTypes(globalTypes)},decorators:normalizeArrays(decorators),loaders:normalizeArrays(loaders),beforeEach:normalizeArrays(beforeEach),argTypesEnhancers:[...argTypesEnhancers||[],inferArgTypes,inferControls],...annotations}}function composeStepRunners(stepRunners){return async(label,play,playContext)=>{await stepRunners.reduceRight((innerPlay,stepRunner)=>async()=>stepRunner(label,innerPlay,playContext),async()=>play(playContext))();}}function getField(moduleExportList,field){return moduleExportList.map(xs=>xs.default?.[field]??xs[field]).filter(Boolean)}function getArrayField(moduleExportList,field,options={}){return getField(moduleExportList,field).reduce((prev,cur)=>{let normalized=normalizeArrays(cur);return options.reverseFileOrder?[...normalized,...prev]:[...prev,...normalized]},[])}function getObjectField(moduleExportList,field){return Object.assign({},...getField(moduleExportList,field))}function getSingletonField(moduleExportList,field){return getField(moduleExportList,field).pop()}function composeConfigs(moduleExportList){let allArgTypeEnhancers=getArrayField(moduleExportList,"argTypesEnhancers"),stepRunners=getField(moduleExportList,"runStep");return {parameters:combineParameters(...getField(moduleExportList,"parameters")),decorators:getArrayField(moduleExportList,"decorators",{reverseFileOrder:!(global.FEATURES?.legacyDecoratorFileOrder??!1)}),args:getObjectField(moduleExportList,"args"),argsEnhancers:getArrayField(moduleExportList,"argsEnhancers"),argTypes:getObjectField(moduleExportList,"argTypes"),argTypesEnhancers:[...allArgTypeEnhancers.filter(e=>!e.secondPass),...allArgTypeEnhancers.filter(e=>e.secondPass)],globals:getObjectField(moduleExportList,"globals"),globalTypes:getObjectField(moduleExportList,"globalTypes"),loaders:getArrayField(moduleExportList,"loaders"),beforeEach:getArrayField(moduleExportList,"beforeEach"),render:getSingletonField(moduleExportList,"render"),renderToCanvas:getSingletonField(moduleExportList,"renderToCanvas"),renderToDOM:getSingletonField(moduleExportList,"renderToDOM"),applyDecorators:getSingletonField(moduleExportList,"applyDecorators"),runStep:composeStepRunners(stepRunners),tags:getArrayField(moduleExportList,"tags")}}var globalProjectAnnotations={},DEFAULT_STORY_TITLE="ComposedStory",DEFAULT_STORY_NAME="Unnamed Story";function extractAnnotation(annotation){return "default"in annotation?annotation.default:annotation}function setProjectAnnotations(projectAnnotations){let annotations=Array.isArray(projectAnnotations)?projectAnnotations:[projectAnnotations];globalProjectAnnotations=composeConfigs(annotations.map(extractAnnotation));}var cleanups=[];function composeStory(storyAnnotations,componentAnnotations,projectAnnotations,defaultConfig,exportsName){if(storyAnnotations===void 0)throw new Error("Expected a story but received undefined.");componentAnnotations.title=componentAnnotations.title??DEFAULT_STORY_TITLE;let normalizedComponentAnnotations=normalizeComponentAnnotations(componentAnnotations),storyName=exportsName||storyAnnotations.storyName||storyAnnotations.story?.name||storyAnnotations.name||DEFAULT_STORY_NAME,normalizedStory=normalizeStory(storyName,storyAnnotations,normalizedComponentAnnotations),normalizedProjectAnnotations=normalizeProjectAnnotations(composeConfigs([defaultConfig??{},globalProjectAnnotations,projectAnnotations??{}])),story=prepareStory(normalizedStory,normalizedComponentAnnotations,normalizedProjectAnnotations),globalsFromGlobalTypes=getValuesFromArgTypes(normalizedProjectAnnotations.globalTypes),context={hooks:new HooksContext,globals:{...globalsFromGlobalTypes,...normalizedProjectAnnotations.globals},args:{...story.initialArgs},viewMode:"story",loaded:{},abortSignal:null,canvasElement:null,...story},playFunction=story.playFunction?async extraContext=>story.playFunction({...context,...extraContext,canvasElement:extraContext?.canvasElement??globalThis.document?.body}):void 0,previousCleanupsDone=!1;return Object.assign(function(extraArgs){if(context.args={...context.initialArgs,...extraArgs},cleanups.length>0&&!previousCleanupsDone){let humanReadableIdentifier=storyName;story.title!==DEFAULT_STORY_TITLE&&(humanReadableIdentifier=`${story.title} - ${humanReadableIdentifier}`),storyName===DEFAULT_STORY_NAME&&Object.keys(context.args).length>0&&(humanReadableIdentifier=`${humanReadableIdentifier} (${Object.keys(context.args).join(", ")})`),console.warn(dedent5`Some stories were not cleaned up before rendering '${humanReadableIdentifier}'.
|
47
|
+
|
48
|
+
You should load the story with \`await Story.load()\` before rendering it.`);}return story.unboundStoryFn(prepareContext(context))},{id:story.id,storyName,load:async()=>{for(let{callback}of [...cleanups].reverse())await callback();cleanups.length=0,previousCleanupsDone=!0;let loadedContext=await story.applyLoaders(context);context.loaded=loadedContext.loaded,cleanups.push(...(await story.applyBeforeEach(context)).filter(Boolean).map(callback=>({storyName,callback})));},args:story.initialArgs,parameters:story.parameters,argTypes:story.argTypes,play:playFunction})}function composeStories(storiesImport,globalConfig,composeStoryFn){let{default:meta,__esModule,__namedExportsOrder,...stories}=storiesImport;return Object.entries(stories).reduce((storiesMap,[exportsName,story])=>isExportStory(exportsName,meta)?Object.assign(storiesMap,{[exportsName]:composeStoryFn(story,meta,globalConfig,exportsName)}):storiesMap,{})}function createPlaywrightTest(baseTest){return baseTest.extend({mount:async({mount,page},use)=>{await use(async(storyRef,...restArgs)=>{if(!("__pw_type"in storyRef)||"__pw_type"in storyRef&&storyRef.__pw_type!=="jsx")throw new Error(dedent5`
|
43
49
|
Portable stories in Playwright CT only work when referencing JSX elements.
|
44
50
|
Please use JSX format for your components such as:
|
45
51
|
|
@@ -50,7 +56,7 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
50
56
|
await mount(<MyComponent foo="bar"/>)
|
51
57
|
|
52
58
|
More info: https://storybook.js.org/docs/api/portable-stories-playwright
|
53
|
-
`);await page.evaluate(async wrappedStoryRef=>{let unwrappedStoryRef=await globalThis.__pwUnwrapObject?.(wrappedStoryRef);return ("__pw_type"in unwrappedStoryRef?unwrappedStoryRef.type:unwrappedStoryRef)?.load?.()},storyRef);let mountResult=await mount(storyRef,...restArgs);return await page.evaluate(async wrappedStoryRef=>{let unwrappedStoryRef=await globalThis.__pwUnwrapObject?.(wrappedStoryRef),story="__pw_type"in unwrappedStoryRef?unwrappedStoryRef.type:unwrappedStoryRef,canvasElement=document.querySelector("#root");return story?.play?.({canvasElement})},storyRef),mountResult});}})}var CSF_CACHE_SIZE=1e3,STORY_CACHE_SIZE=1e4,StoryStore=class{constructor(storyIndex,importFn,projectAnnotations){this.importFn=importFn;this.getStoriesJsonData=()=>{let value=this.getSetStoriesPayload(),allowedParameters=["fileName","docsOnly","framework","__id","__isArgsStory"];return {v:3,stories:mapValues2(value.stories,story=>{let{importPath}=this.storyIndex.entries[story.id];return {...pick(story,["id","name","title"]),importPath,kind:story.title,story:story.name,parameters:{...pick(story.parameters,allowedParameters),fileName:importPath}}})}};this.storyIndex=new StoryIndexStore(storyIndex),this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.args=new ArgsStore,this.globals=new GlobalsStore({globals,globalTypes}),this.hooks={},this.processCSFFileWithCache=memoize2(CSF_CACHE_SIZE)(processCSFFile),this.prepareMetaWithCache=memoize2(CSF_CACHE_SIZE)(prepareMeta),this.prepareStoryWithCache=memoize2(STORY_CACHE_SIZE)(prepareStory);}setProjectAnnotations(projectAnnotations){this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.globals.set({globals,globalTypes});}async onStoriesChanged({importFn,storyIndex}){importFn&&(this.importFn=importFn),storyIndex&&(this.storyIndex.entries=storyIndex.entries),this.cachedCSFFiles&&await this.cacheAllCSFFiles();}async storyIdToEntry(storyId){return this.storyIndex.storyIdToEntry(storyId)}async loadCSFFileByStoryId(storyId){let{importPath,title}=this.storyIndex.storyIdToEntry(storyId),moduleExports=await this.importFn(importPath);return this.processCSFFileWithCache(moduleExports,importPath,title)}async loadAllCSFFiles(){let importPaths={};return Object.entries(this.storyIndex.entries).forEach(([storyId,{importPath}])=>{importPaths[importPath]=storyId;}),(await Promise.all(Object.entries(importPaths).map(async([importPath,storyId])=>({importPath,csfFile:await this.loadCSFFileByStoryId(storyId)})))).reduce((acc,{importPath,csfFile})=>(acc[importPath]=csfFile,acc),{})}async cacheAllCSFFiles(){this.cachedCSFFiles=await this.loadAllCSFFiles();}preparedMetaFromCSFFile({csfFile}){let componentAnnotations=csfFile.meta;return this.prepareMetaWithCache(componentAnnotations,this.projectAnnotations,csfFile.moduleExports.default)}async loadStory({storyId}){let csfFile=await this.loadCSFFileByStoryId(storyId);return this.storyFromCSFFile({storyId,csfFile})}storyFromCSFFile({storyId,csfFile}){let storyAnnotations=csfFile.stories[storyId];if(!storyAnnotations)throw new MissingStoryFromCsfFileError({storyId});let componentAnnotations=csfFile.meta,story=this.prepareStoryWithCache(storyAnnotations,componentAnnotations,this.projectAnnotations);return this.args.setInitial(story),this.hooks[story.id]=this.hooks[story.id]||new HooksContext,story}componentStoriesFromCSFFile({csfFile}){return Object.keys(this.storyIndex.entries).filter(storyId=>!!csfFile.stories[storyId]).map(storyId=>this.storyFromCSFFile({storyId,csfFile}))}async loadEntry(id){let entry=await this.storyIdToEntry(id),storyImports=entry.type==="docs"?entry.storiesImports:[],[entryExports,...csfFiles]=await Promise.all([this.importFn(entry.importPath),...storyImports.map(storyImportPath=>{let firstStoryEntry=this.storyIndex.importPathToEntry(storyImportPath);return this.loadCSFFileByStoryId(firstStoryEntry.id)})]);return {entryExports,csfFiles}}getStoryContext(story,{forceInitialArgs=!1}={}){return prepareContext({...story,args:forceInitialArgs?story.initialArgs:this.args.get(story.id),globals:this.globals.get(),hooks:this.hooks[story.id]})}cleanupStory(story){this.hooks[story.id].clean();}extract(options={includeDocsOnly:!1}){let{cachedCSFFiles}=this;if(!cachedCSFFiles)throw new CalledExtractOnStoreError;return Object.entries(this.storyIndex.entries).reduce((acc,[storyId,{type,importPath}])=>{if(type==="docs")return acc;let csfFile=cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return !options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((storyAcc,[key,value])=>key==="moduleExport"||typeof value=="function"?storyAcc:Array.isArray(value)?Object.assign(storyAcc,{[key]:value.slice().sort()}):Object.assign(storyAcc,{[key]:value}),{args:story.initialArgs})),acc},{})}getSetStoriesPayload(){let stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((acc,{title})=>(acc[title]={},acc),{});return {v:2,globals:this.globals.get(),globalParameters:{},kindParameters,stories}}raw(){return deprecate$1("StoryStore.raw() is deprecated and will be removed in 9.0, please use extract() instead"),Object.values(this.extract()).map(({id})=>this.fromId(id)).filter(Boolean)}fromId(storyId){if(deprecate$1("StoryStore.fromId() is deprecated and will be removed in 9.0, please use loadStory() instead"),!this.cachedCSFFiles)throw new Error("Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.");let importPath;try{({importPath}=this.storyIndex.storyIdToEntry(storyId));}catch{return null}let csfFile=this.cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return {...story,storyFn:update=>{let context={...this.getStoryContext(story),viewMode:"story"};return story.unboundStoryFn({...context,...update})}}}};function slash(path){return path.startsWith("\\\\?\\")?path:path.replace(/\\/g,"/")}var sanitize2=parts=>{if(parts.length===0)return parts;let last=parts[parts.length-1],lastStripped=last?.replace(/(?:[.](?:story|stories))?([.][^.]+)$/i,"");if(parts.length===1)return [lastStripped];let nextToLast=parts[parts.length-2];return lastStripped&&nextToLast&&lastStripped.toLowerCase()===nextToLast.toLowerCase()?[...parts.slice(0,-2),lastStripped]:lastStripped&&(/^(story|stories)([.][^.]+)$/i.test(last)||/^index$/i.test(lastStripped))?parts.slice(0,-1):[...parts.slice(0,-1),lastStripped]};function pathJoin(paths){return paths.flatMap(p=>p.split("/")).filter(Boolean).join("/")}var userOrAutoTitleFromSpecifier=(fileName,entry,userTitle)=>{let{directory,importPathMatcher,titlePrefix=""}=entry||{};typeof fileName=="number"&&once.warn(dedent`
|
59
|
+
`);await page.evaluate(async wrappedStoryRef=>{let unwrappedStoryRef=await globalThis.__pwUnwrapObject?.(wrappedStoryRef);return ("__pw_type"in unwrappedStoryRef?unwrappedStoryRef.type:unwrappedStoryRef)?.load?.()},storyRef);let mountResult=await mount(storyRef,...restArgs);return await page.evaluate(async wrappedStoryRef=>{let unwrappedStoryRef=await globalThis.__pwUnwrapObject?.(wrappedStoryRef),story="__pw_type"in unwrappedStoryRef?unwrappedStoryRef.type:unwrappedStoryRef,canvasElement=document.querySelector("#root");return story?.play?.({canvasElement})},storyRef),mountResult});}})}var CSF_CACHE_SIZE=1e3,STORY_CACHE_SIZE=1e4,StoryStore=class{constructor(storyIndex,importFn,projectAnnotations){this.importFn=importFn;this.getStoriesJsonData=()=>{let value=this.getSetStoriesPayload(),allowedParameters=["fileName","docsOnly","framework","__id","__isArgsStory"];return {v:3,stories:mapValues2(value.stories,story=>{let{importPath}=this.storyIndex.entries[story.id];return {...pick(story,["id","name","title"]),importPath,kind:story.title,story:story.name,parameters:{...pick(story.parameters,allowedParameters),fileName:importPath}}})}};this.storyIndex=new StoryIndexStore(storyIndex),this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.args=new ArgsStore,this.globals=new GlobalsStore({globals,globalTypes}),this.hooks={},this.cleanupCallbacks={},this.processCSFFileWithCache=memoize2(CSF_CACHE_SIZE)(processCSFFile),this.prepareMetaWithCache=memoize2(CSF_CACHE_SIZE)(prepareMeta),this.prepareStoryWithCache=memoize2(STORY_CACHE_SIZE)(prepareStory);}setProjectAnnotations(projectAnnotations){this.projectAnnotations=normalizeProjectAnnotations(projectAnnotations);let{globals,globalTypes}=projectAnnotations;this.globals.set({globals,globalTypes});}async onStoriesChanged({importFn,storyIndex}){importFn&&(this.importFn=importFn),storyIndex&&(this.storyIndex.entries=storyIndex.entries),this.cachedCSFFiles&&await this.cacheAllCSFFiles();}async storyIdToEntry(storyId){return this.storyIndex.storyIdToEntry(storyId)}async loadCSFFileByStoryId(storyId){let{importPath,title}=this.storyIndex.storyIdToEntry(storyId),moduleExports=await this.importFn(importPath);return this.processCSFFileWithCache(moduleExports,importPath,title)}async loadAllCSFFiles(){let importPaths={};return Object.entries(this.storyIndex.entries).forEach(([storyId,{importPath}])=>{importPaths[importPath]=storyId;}),(await Promise.all(Object.entries(importPaths).map(async([importPath,storyId])=>({importPath,csfFile:await this.loadCSFFileByStoryId(storyId)})))).reduce((acc,{importPath,csfFile})=>(acc[importPath]=csfFile,acc),{})}async cacheAllCSFFiles(){this.cachedCSFFiles=await this.loadAllCSFFiles();}preparedMetaFromCSFFile({csfFile}){let componentAnnotations=csfFile.meta;return this.prepareMetaWithCache(componentAnnotations,this.projectAnnotations,csfFile.moduleExports.default)}async loadStory({storyId}){let csfFile=await this.loadCSFFileByStoryId(storyId);return this.storyFromCSFFile({storyId,csfFile})}storyFromCSFFile({storyId,csfFile}){let storyAnnotations=csfFile.stories[storyId];if(!storyAnnotations)throw new MissingStoryFromCsfFileError({storyId});let componentAnnotations=csfFile.meta,story=this.prepareStoryWithCache(storyAnnotations,componentAnnotations,this.projectAnnotations);return this.args.setInitial(story),this.hooks[story.id]=this.hooks[story.id]||new HooksContext,story}componentStoriesFromCSFFile({csfFile}){return Object.keys(this.storyIndex.entries).filter(storyId=>!!csfFile.stories[storyId]).map(storyId=>this.storyFromCSFFile({storyId,csfFile}))}async loadEntry(id){let entry=await this.storyIdToEntry(id),storyImports=entry.type==="docs"?entry.storiesImports:[],[entryExports,...csfFiles]=await Promise.all([this.importFn(entry.importPath),...storyImports.map(storyImportPath=>{let firstStoryEntry=this.storyIndex.importPathToEntry(storyImportPath);return this.loadCSFFileByStoryId(firstStoryEntry.id)})]);return {entryExports,csfFiles}}getStoryContext(story,{forceInitialArgs=!1}={}){return prepareContext({...story,args:forceInitialArgs?story.initialArgs:this.args.get(story.id),globals:this.globals.get(),hooks:this.hooks[story.id]})}addCleanupCallbacks(story,callbacks){this.cleanupCallbacks[story.id]=callbacks;}async cleanupStory(story){this.hooks[story.id].clean();let callbacks=this.cleanupCallbacks[story.id];if(callbacks)for(let callback of [...callbacks].reverse())await callback();delete this.cleanupCallbacks[story.id];}extract(options={includeDocsOnly:!1}){let{cachedCSFFiles}=this;if(!cachedCSFFiles)throw new CalledExtractOnStoreError;return Object.entries(this.storyIndex.entries).reduce((acc,[storyId,{type,importPath}])=>{if(type==="docs")return acc;let csfFile=cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return !options.includeDocsOnly&&story.parameters.docsOnly||(acc[storyId]=Object.entries(story).reduce((storyAcc,[key,value])=>key==="moduleExport"||typeof value=="function"?storyAcc:Array.isArray(value)?Object.assign(storyAcc,{[key]:value.slice().sort()}):Object.assign(storyAcc,{[key]:value}),{args:story.initialArgs})),acc},{})}getSetStoriesPayload(){let stories=this.extract({includeDocsOnly:!0}),kindParameters=Object.values(stories).reduce((acc,{title})=>(acc[title]={},acc),{});return {v:2,globals:this.globals.get(),globalParameters:{},kindParameters,stories}}raw(){return deprecate$1("StoryStore.raw() is deprecated and will be removed in 9.0, please use extract() instead"),Object.values(this.extract()).map(({id})=>this.fromId(id)).filter(Boolean)}fromId(storyId){if(deprecate$1("StoryStore.fromId() is deprecated and will be removed in 9.0, please use loadStory() instead"),!this.cachedCSFFiles)throw new Error("Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.");let importPath;try{({importPath}=this.storyIndex.storyIdToEntry(storyId));}catch{return null}let csfFile=this.cachedCSFFiles[importPath],story=this.storyFromCSFFile({storyId,csfFile});return {...story,storyFn:update=>{let context={...this.getStoryContext(story),viewMode:"story"};return story.unboundStoryFn({...context,...update})}}}};function slash(path){return path.startsWith("\\\\?\\")?path:path.replace(/\\/g,"/")}var sanitize2=parts=>{if(parts.length===0)return parts;let last=parts[parts.length-1],lastStripped=last?.replace(/(?:[.](?:story|stories))?([.][^.]+)$/i,"");if(parts.length===1)return [lastStripped];let nextToLast=parts[parts.length-2];return lastStripped&&nextToLast&&lastStripped.toLowerCase()===nextToLast.toLowerCase()?[...parts.slice(0,-2),lastStripped]:lastStripped&&(/^(story|stories)([.][^.]+)$/i.test(last)||/^index$/i.test(lastStripped))?parts.slice(0,-1):[...parts.slice(0,-1),lastStripped]};function pathJoin(paths){return paths.flatMap(p=>p.split("/")).filter(Boolean).join("/")}var userOrAutoTitleFromSpecifier=(fileName,entry,userTitle)=>{let{directory,importPathMatcher,titlePrefix=""}=entry||{};typeof fileName=="number"&&once.warn(dedent`
|
54
60
|
CSF Auto-title received a numeric fileName. This typically happens when
|
55
61
|
webpack is mis-configured in production mode. To force webpack to produce
|
56
62
|
filenames, set optimization.moduleIds = "named" in your webpack config.
|
@@ -62,10 +68,10 @@ See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#hoisted-csf-
|
|
62
68
|
Are you using a V6-style sort function in V7 mode?
|
63
69
|
|
64
70
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
|
65
|
-
`)}};var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return {name,message,stack}}catch{return {name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing");}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}));}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id});}),this.abortController.signal.aborted)throw this.store.cleanupStory(this.story),PREPARE_ABORTED}isEqual(other){return !!(this.id===other.id&&this.story&&this.story===other.story)}isPreparing(){return ["preparing"].includes(this.phase)}isPending(){return ["rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,unboundStoryFn,playFunction}=this.story;forceRemount&&!initial&&(this.cancelRender(),this.abortController=new AbortController);let abortSignal=this.abortController.signal;try{let loadedContext;if(await this.runPhase(abortSignal,"loading",async()=>{loadedContext=await applyLoaders({...this.storyContext(),viewMode:this.viewMode});}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement},renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{});}),this.notYetRendered=!1,abortSignal.aborted)return;let ignoreUnhandledErrors=this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors===!0,unhandledErrors=new Set,onError=event=>unhandledErrors.add("error"in event?event.error:event.reason);if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){window.addEventListener("error",onError),window.addEventListener("unhandledrejection",onError),this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext);}),!ignoreUnhandledErrors&&unhandledErrors.size>0?await this.runPhase(abortSignal,"errored"):await this.runPhase(abortSignal,"played");}catch(error){if(await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error));}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error;console.error(error);}if(!ignoreUnhandledErrors&&unhandledErrors.size>0&&this.channel.emit(UNHANDLED_ERRORS_WHILE_PLAYING,Array.from(unhandledErrors).map(serializeError)),this.disableKeyListeners=!1,window.removeEventListener("unhandledrejection",onError),window.removeEventListener("error",onError),abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(STORY_RENDERED,id));}catch(err){this.phase="errored",this.callbacks.showException(err);}}async rerender(){return this.render()}async remount(){return this.render({forceRemount:!0})}cancelRender(){this.abortController?.abort();}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0));}window.location.reload(),await new Promise(()=>{});}};var {fetch}=global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(importFn,getProjectAnnotations,channel=addons.getChannel(),shouldInitialize=!0){this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.channel=channel;this.storyRenders=[];this.storeInitializationPromise=new Promise((resolve,reject)=>{this.resolveStoreInitializationPromise=resolve,this.rejectStoreInitializationPromise=reject;}),shouldInitialize&&this.initialize();}get storyStore(){return new Proxy({},{get:(_,method)=>{if(this.storyStoreValue)return deprecate$1("Accessing the Story Store is deprecated and will be removed in 9.0"),this.storyStoreValue[method];throw new StoryStoreAccessedBeforeInitializationError}})}async initialize(){this.setupListeners();try{let projectAnnotations=await this.getProjectAnnotationsOrRenderError();await this.initializeWithProjectAnnotations(projectAnnotations);}catch(err){this.rejectStoreInitializationPromise(err);}}ready(){return this.storeInitializationPromise}setupListeners(){this.channel.on(STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(FORCE_REMOUNT,this.onForceRemount.bind(this));}async getProjectAnnotationsOrRenderError(){try{let projectAnnotations=await this.getProjectAnnotations();if(this.renderToCanvas=projectAnnotations.renderToCanvas,!this.renderToCanvas)throw new MissingRenderToCanvasError;return projectAnnotations}catch(err){throw this.renderPreviewEntryError("Error reading preview.js:",err),err}}async initializeWithProjectAnnotations(projectAnnotations){this.projectAnnotationsBeforeInitialization=projectAnnotations;try{let storyIndex=await this.getStoryIndexFromServer();return this.initializeWithStoryIndex(storyIndex)}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new StoryIndexFetchError({text:await result.text()})}initializeWithStoryIndex(storyIndex){if(!this.projectAnnotationsBeforeInitialization)throw new Error("Cannot call initializeWithStoryIndex until project annotations resolve");this.storyStoreValue=new StoryStore(storyIndex,this.importFn,this.projectAnnotationsBeforeInitialization),delete this.projectAnnotationsBeforeInitialization,this.setInitialGlobals(),this.resolveStoreInitializationPromise();}async setInitialGlobals(){this.emitGlobals();}emitGlobals(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"emitGlobals"});let payload={globals:this.storyStoreValue.globals.get()||{},globalTypes:this.storyStoreValue.projectAnnotations.globalTypes||{}};this.channel.emit(SET_GLOBALS,payload);}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError,this.getProjectAnnotations=getProjectAnnotations;let projectAnnotations=await this.getProjectAnnotationsOrRenderError();if(!this.storyStoreValue){await this.initializeWithProjectAnnotations(projectAnnotations);return}this.storyStoreValue.setProjectAnnotations(projectAnnotations),this.emitGlobals();}async onStoryIndexChanged(){if(delete this.previewEntryError,!(!this.storyStoreValue&&!this.projectAnnotationsBeforeInitialization))try{let storyIndex=await this.getStoryIndexFromServer();if(this.projectAnnotationsBeforeInitialization){this.initializeWithStoryIndex(storyIndex);return}await this.onStoriesChanged({storyIndex});}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onStoriesChanged"});await this.storyStoreValue.onStoriesChanged({importFn,storyIndex});}async onUpdateGlobals({globals}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateGlobals"});this.storyStoreValue.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(GLOBALS_UPDATED,{globals:this.storyStoreValue.globals.get(),initialGlobals:this.storyStoreValue.globals.initialGlobals});}async onUpdateArgs({storyId,updatedArgs}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateArgs"});this.storyStoreValue.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId&&!r.renderOptions.forceInitialArgs).map(r=>r.rerender())),this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:this.storyStoreValue.args.get(storyId)});}async onResetArgs({storyId,argNames}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onResetArgs"});let story=this.storyRenders.find(r=>r.id===storyId)?.story||await this.storyStoreValue.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStoreValue.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs});}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()));}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()));}renderStoryToElement(story,element,callbacks,options){if(!this.renderToCanvas||!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"renderStoryToElement"});let render=new StoryRender(this.channel,this.storyStoreValue,this.renderToCanvas,callbacks,story.id,"docs",options,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render);}}async teardownRender(render,{viewModeChanged}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged});}async loadStory({storyId}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"loadStory"});return this.storyStoreValue.loadStory({storyId})}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"getStoryContext"});return this.storyStoreValue.getStoryContext(story,{forceInitialArgs})}async extract(options){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"extract"});if(this.previewEntryError)throw this.previewEntryError;return await this.storyStoreValue.cacheAllCSFFiles(),this.storyStoreValue.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger.error(reason),logger.error(err),this.channel.emit(CONFIG_ERROR,err);}};var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.componentStoriesFromCSFFile=csfFile=>this.store.componentStoriesFromCSFFile({csfFile});this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.componentStoriesValue=[],this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.attachedCSFFiles=new Set,csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile);});}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story);});}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");if(this.attachedCSFFiles.has(csfFile))return;this.attachedCSFFiles.add(csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story);});}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile);}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return {type:"story",story:this.primaryStory}}if(this.attachedCSFFiles.size===0)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");let firstAttachedCSFFile=Array.from(this.attachedCSFFiles)[0];if(moduleExportType==="meta")return {type:"meta",csfFile:firstAttachedCSFFile};let{component}=firstAttachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return {type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return {type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type);}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(dedent4`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
|
71
|
+
`)}};var PREPARE_ABORTED=new Error("prepareAborted");var{AbortController}=globalThis;function serializeError(error){try{let{name="Error",message=String(error),stack}=error;return {name,message,stack}}catch{return {name:"Error",message:String(error)}}}var StoryRender=class{constructor(channel,store,renderToScreen,callbacks,id,viewMode,renderOptions={autoplay:!0,forceInitialArgs:!1},story){this.channel=channel;this.store=store;this.renderToScreen=renderToScreen;this.callbacks=callbacks;this.id=id;this.viewMode=viewMode;this.renderOptions=renderOptions;this.type="story";this.notYetRendered=!0;this.rerenderEnqueued=!1;this.disableKeyListeners=!1;this.teardownRender=()=>{};this.torndown=!1;this.abortController=new AbortController,story&&(this.story=story,this.phase="preparing");}async runPhase(signal,phase,phaseFn){this.phase=phase,this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}),phaseFn&&await phaseFn(),signal.aborted&&(this.phase="aborted",this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:this.phase,storyId:this.id}));}async prepare(){if(await this.runPhase(this.abortController.signal,"preparing",async()=>{this.story=await this.store.loadStory({storyId:this.id});}),this.abortController.signal.aborted)throw await 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 ["loading","beforeEach","rendering","playing"].includes(this.phase)}async renderToElement(canvasElement){return this.canvasElement=canvasElement,this.render({initial:!0,forceRemount:!0})}storyContext(){if(!this.story)throw new Error("Cannot call storyContext before preparing");let{forceInitialArgs}=this.renderOptions;return this.store.getStoryContext(this.story,{forceInitialArgs})}async render({initial=!1,forceRemount=!1}={}){let{canvasElement}=this;if(!this.story)throw new Error("cannot render when not prepared");let story=this.story;if(!canvasElement)throw new Error("cannot render when canvasElement is unset");let{id,componentId,title,name,tags,applyLoaders,applyBeforeEach,unboundStoryFn,playFunction}=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,canvasElement});}),abortSignal.aborted)return;let renderStoryContext={...loadedContext,...this.storyContext(),abortSignal,canvasElement};if(await this.runPhase(abortSignal,"beforeEach",async()=>{let cleanupCallbacks=await applyBeforeEach(renderStoryContext);this.store.addCleanupCallbacks(story,cleanupCallbacks);}),abortSignal.aborted)return;let renderContext={componentId,title,kind:title,id,name,story:name,tags,...this.callbacks,showError:error=>(this.phase="errored",this.callbacks.showError(error)),showException:error=>(this.phase="errored",this.callbacks.showException(error)),forceRemount:forceRemount||this.notYetRendered,storyContext:renderStoryContext,storyFn:()=>unboundStoryFn(renderStoryContext),unboundStoryFn};if(await this.runPhase(abortSignal,"rendering",async()=>{let teardown=await this.renderToScreen(renderContext,canvasElement);this.teardownRender=teardown||(()=>{});}),this.notYetRendered=!1,abortSignal.aborted)return;let ignoreUnhandledErrors=this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors===!0,unhandledErrors=new Set,onError=event=>unhandledErrors.add("error"in event?event.error:event.reason);if(this.renderOptions.autoplay&&forceRemount&&playFunction&&this.phase!=="errored"){window.addEventListener("error",onError),window.addEventListener("unhandledrejection",onError),this.disableKeyListeners=!0;try{await this.runPhase(abortSignal,"playing",async()=>{await playFunction(renderContext.storyContext);}),!ignoreUnhandledErrors&&unhandledErrors.size>0?await this.runPhase(abortSignal,"errored"):await this.runPhase(abortSignal,"played");}catch(error){if(await this.runPhase(abortSignal,"errored",async()=>{this.channel.emit(PLAY_FUNCTION_THREW_EXCEPTION,serializeError(error));}),this.story.parameters.throwPlayFunctionExceptions!==!1)throw error;console.error(error);}if(!ignoreUnhandledErrors&&unhandledErrors.size>0&&this.channel.emit(UNHANDLED_ERRORS_WHILE_PLAYING,Array.from(unhandledErrors).map(serializeError)),this.disableKeyListeners=!1,window.removeEventListener("unhandledrejection",onError),window.removeEventListener("error",onError),abortSignal.aborted)return}await this.runPhase(abortSignal,"completed",async()=>this.channel.emit(STORY_RENDERED,id));}catch(err){this.phase="errored",this.callbacks.showException(err);}this.rerenderEnqueued&&(this.rerenderEnqueued=!1,this.render());}async rerender(){if(this.isPending()&&this.phase!=="playing")this.rerenderEnqueued=!0;else return this.render()}async remount(){return await this.teardown(),this.render({forceRemount:!0})}cancelRender(){this.abortController?.abort();}async teardown(){this.torndown=!0,this.cancelRender(),this.story&&await this.store.cleanupStory(this.story);for(let i=0;i<3;i+=1){if(!this.isPending()){await this.teardownRender();return}await new Promise(resolve=>setTimeout(resolve,0));}window.location.reload(),await new Promise(()=>{});}};var {fetch}=global,STORY_INDEX_PATH="./index.json",Preview=class{constructor(importFn,getProjectAnnotations,channel=addons.getChannel(),shouldInitialize=!0){this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.channel=channel;this.storyRenders=[];this.storeInitializationPromise=new Promise((resolve,reject)=>{this.resolveStoreInitializationPromise=resolve,this.rejectStoreInitializationPromise=reject;}),shouldInitialize&&this.initialize();}get storyStore(){return new Proxy({},{get:(_,method)=>{if(this.storyStoreValue)return deprecate$1("Accessing the Story Store is deprecated and will be removed in 9.0"),this.storyStoreValue[method];throw new StoryStoreAccessedBeforeInitializationError}})}async initialize(){this.setupListeners();try{let projectAnnotations=await this.getProjectAnnotationsOrRenderError();await this.initializeWithProjectAnnotations(projectAnnotations);}catch(err){this.rejectStoreInitializationPromise(err);}}ready(){return this.storeInitializationPromise}setupListeners(){this.channel.on(STORY_INDEX_INVALIDATED,this.onStoryIndexChanged.bind(this)),this.channel.on(UPDATE_GLOBALS,this.onUpdateGlobals.bind(this)),this.channel.on(UPDATE_STORY_ARGS,this.onUpdateArgs.bind(this)),this.channel.on(ARGTYPES_INFO_REQUEST,this.onRequestArgTypesInfo.bind(this)),this.channel.on(RESET_STORY_ARGS,this.onResetArgs.bind(this)),this.channel.on(FORCE_RE_RENDER,this.onForceReRender.bind(this)),this.channel.on(FORCE_REMOUNT,this.onForceRemount.bind(this));}async getProjectAnnotationsOrRenderError(){try{let projectAnnotations=await this.getProjectAnnotations();if(this.renderToCanvas=projectAnnotations.renderToCanvas,!this.renderToCanvas)throw new MissingRenderToCanvasError;return projectAnnotations}catch(err){throw this.renderPreviewEntryError("Error reading preview.js:",err),err}}async initializeWithProjectAnnotations(projectAnnotations){this.projectAnnotationsBeforeInitialization=projectAnnotations;try{let storyIndex=await this.getStoryIndexFromServer();return this.initializeWithStoryIndex(storyIndex)}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async getStoryIndexFromServer(){let result=await fetch(STORY_INDEX_PATH);if(result.status===200)return result.json();throw new StoryIndexFetchError({text:await result.text()})}initializeWithStoryIndex(storyIndex){if(!this.projectAnnotationsBeforeInitialization)throw new Error("Cannot call initializeWithStoryIndex until project annotations resolve");this.storyStoreValue=new StoryStore(storyIndex,this.importFn,this.projectAnnotationsBeforeInitialization),delete this.projectAnnotationsBeforeInitialization,this.setInitialGlobals(),this.resolveStoreInitializationPromise();}async setInitialGlobals(){this.emitGlobals();}emitGlobals(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"emitGlobals"});let payload={globals:this.storyStoreValue.globals.get()||{},globalTypes:this.storyStoreValue.projectAnnotations.globalTypes||{}};this.channel.emit(SET_GLOBALS,payload);}async onGetProjectAnnotationsChanged({getProjectAnnotations}){delete this.previewEntryError,this.getProjectAnnotations=getProjectAnnotations;let projectAnnotations=await this.getProjectAnnotationsOrRenderError();if(!this.storyStoreValue){await this.initializeWithProjectAnnotations(projectAnnotations);return}this.storyStoreValue.setProjectAnnotations(projectAnnotations),this.emitGlobals();}async onStoryIndexChanged(){if(delete this.previewEntryError,!(!this.storyStoreValue&&!this.projectAnnotationsBeforeInitialization))try{let storyIndex=await this.getStoryIndexFromServer();if(this.projectAnnotationsBeforeInitialization){this.initializeWithStoryIndex(storyIndex);return}await this.onStoriesChanged({storyIndex});}catch(err){throw this.renderPreviewEntryError("Error loading story index:",err),err}}async onStoriesChanged({importFn,storyIndex}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onStoriesChanged"});await this.storyStoreValue.onStoriesChanged({importFn,storyIndex});}async onUpdateGlobals({globals}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateGlobals"});this.storyStoreValue.globals.update(globals),await Promise.all(this.storyRenders.map(r=>r.rerender())),this.channel.emit(GLOBALS_UPDATED,{globals:this.storyStoreValue.globals.get(),initialGlobals:this.storyStoreValue.globals.initialGlobals});}async onUpdateArgs({storyId,updatedArgs}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onUpdateArgs"});this.storyStoreValue.args.update(storyId,updatedArgs),await Promise.all(this.storyRenders.filter(r=>r.id===storyId&&!r.renderOptions.forceInitialArgs).map(r=>r.rerender())),this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:this.storyStoreValue.args.get(storyId)});}async onRequestArgTypesInfo({id,payload}){try{await this.storeInitializationPromise;let story=await this.storyStoreValue?.loadStory(payload);this.channel.emit(ARGTYPES_INFO_RESPONSE,{id,success:!0,payload:{argTypes:story?.argTypes||{}},error:null});}catch(e){this.channel.emit(ARGTYPES_INFO_RESPONSE,{id,success:!1,error:e?.message});}}async onResetArgs({storyId,argNames}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"onResetArgs"});let story=this.storyRenders.find(r=>r.id===storyId)?.story||await this.storyStoreValue.loadStory({storyId}),updatedArgs=(argNames||[...new Set([...Object.keys(story.initialArgs),...Object.keys(this.storyStoreValue.args.get(storyId))])]).reduce((acc,argName)=>(acc[argName]=story.initialArgs[argName],acc),{});await this.onUpdateArgs({storyId,updatedArgs});}async onForceReRender(){await Promise.all(this.storyRenders.map(r=>r.rerender()));}async onForceRemount({storyId}){await Promise.all(this.storyRenders.filter(r=>r.id===storyId).map(r=>r.remount()));}renderStoryToElement(story,element,callbacks,options){if(!this.renderToCanvas||!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"renderStoryToElement"});let render=new StoryRender(this.channel,this.storyStoreValue,this.renderToCanvas,callbacks,story.id,"docs",options,story);return render.renderToElement(element),this.storyRenders.push(render),async()=>{await this.teardownRender(render);}}async teardownRender(render,{viewModeChanged}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged});}async loadStory({storyId}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"loadStory"});return this.storyStoreValue.loadStory({storyId})}getStoryContext(story,{forceInitialArgs=!1}={}){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"getStoryContext"});return this.storyStoreValue.getStoryContext(story,{forceInitialArgs})}async extract(options){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"extract"});if(this.previewEntryError)throw this.previewEntryError;return await this.storyStoreValue.cacheAllCSFFiles(),this.storyStoreValue.extract(options)}renderPreviewEntryError(reason,err){this.previewEntryError=err,logger.error(reason),logger.error(err),this.channel.emit(CONFIG_ERROR,err);}};var DocsContext=class{constructor(channel,store,renderStoryToElement,csfFiles){this.channel=channel;this.store=store;this.renderStoryToElement=renderStoryToElement;this.storyIdByName=storyName=>{let storyId=this.nameToStoryId.get(storyName);if(storyId)return storyId;throw new Error(`No story found with that name: ${storyName}`)};this.componentStories=()=>this.componentStoriesValue;this.componentStoriesFromCSFFile=csfFile=>this.store.componentStoriesFromCSFFile({csfFile});this.storyById=storyId=>{if(!storyId){if(!this.primaryStory)throw new Error("No primary story defined for docs entry. Did you forget to use `<Meta>`?");return this.primaryStory}let csfFile=this.storyIdToCSFFile.get(storyId);if(!csfFile)throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);return this.store.storyFromCSFFile({storyId,csfFile})};this.getStoryContext=story=>({...this.store.getStoryContext(story),viewMode:"docs"});this.loadStory=id=>this.store.loadStory({storyId:id});this.componentStoriesValue=[],this.storyIdToCSFFile=new Map,this.exportToStory=new Map,this.exportsToCSFFile=new Map,this.nameToStoryId=new Map,this.attachedCSFFiles=new Set,csfFiles.forEach((csfFile,index)=>{this.referenceCSFFile(csfFile);});}referenceCSFFile(csfFile){this.exportsToCSFFile.set(csfFile.moduleExports,csfFile),this.exportsToCSFFile.set(csfFile.moduleExports.default,csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{let annotation=csfFile.stories[story.id];this.storyIdToCSFFile.set(annotation.id,csfFile),this.exportToStory.set(annotation.moduleExport,story);});}attachCSFFile(csfFile){if(!this.exportsToCSFFile.has(csfFile.moduleExports))throw new Error("Cannot attach a CSF file that has not been referenced");if(this.attachedCSFFiles.has(csfFile))return;this.attachedCSFFiles.add(csfFile),this.store.componentStoriesFromCSFFile({csfFile}).forEach(story=>{this.nameToStoryId.set(story.name,story.id),this.componentStoriesValue.push(story),this.primaryStory||(this.primaryStory=story);});}referenceMeta(metaExports,attach){let resolved=this.resolveModuleExport(metaExports);if(resolved.type!=="meta")throw new Error("<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?");attach&&this.attachCSFFile(resolved.csfFile);}get projectAnnotations(){let{projectAnnotations}=this.store;if(!projectAnnotations)throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");return projectAnnotations}resolveAttachedModuleExportType(moduleExportType){if(moduleExportType==="story"){if(!this.primaryStory)throw new Error("No primary story attached to this docs file, did you forget to use <Meta of={} />?");return {type:"story",story:this.primaryStory}}if(this.attachedCSFFiles.size===0)throw new Error("No CSF file attached to this docs file, did you forget to use <Meta of={} />?");let firstAttachedCSFFile=Array.from(this.attachedCSFFiles)[0];if(moduleExportType==="meta")return {type:"meta",csfFile:firstAttachedCSFFile};let{component}=firstAttachedCSFFile.meta;if(!component)throw new Error("Attached CSF file does not defined a component, did you forget to export one?");return {type:"component",component}}resolveModuleExport(moduleExportOrType){let csfFile=this.exportsToCSFFile.get(moduleExportOrType);if(csfFile)return {type:"meta",csfFile};let story=this.exportToStory.get(moduleExportOrType);return story?{type:"story",story}:{type:"component",component:moduleExportOrType}}resolveOf(moduleExportOrType,validTypes=[]){let resolved;if(["component","meta","story"].includes(moduleExportOrType)){let type=moduleExportOrType;resolved=this.resolveAttachedModuleExportType(type);}else resolved=this.resolveModuleExport(moduleExportOrType);if(validTypes.length&&!validTypes.includes(resolved.type)){let prettyType=resolved.type==="component"?"component or unknown":resolved.type;throw new Error(dedent5`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(", ")}.
|
66
72
|
- Did you pass a component to the 'of' prop when the block only supports a story or a meta?
|
67
73
|
- ... or vice versa?
|
68
|
-
- Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return {...resolved,projectAnnotations:this.projectAnnotations};case"meta":return {...resolved,preparedMeta:this.store.preparedMetaFromCSFFile({csfFile:resolved.csfFile})};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.subtype="csf";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id;}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1;}isEqual(other){return !!(this.id===other.id&&this.story&&this.story===other.story)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(DOCS_RENDERED,this.id);}catch(err){this.callbacks.showException(err);}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement);},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0;}};var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.subtype="mdx";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id;}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1;}isEqual(other){return !!(this.id===other.id&&this.exports&&this.exports===other.exports)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(DOCS_RENDERED,this.id);}catch(err){this.callbacks.showException(err);}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0);},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0;}};var globalWindow=globalThis;function focusInInput(event){let target=event.composedPath&&event.composedPath()[0]||event.target;return /input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",ATTACHED_MDX_TAG="attached-mdx";function isMdxEntry({tags}){return !tags?.includes(AUTODOCS_TAG)&&!tags?.includes(STORIES_MDX_TAG)}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(importFn,getProjectAnnotations,selectionStore,view){super(importFn,getProjectAnnotations,void 0,!1);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.selectionStore=selectionStore;this.view=view;this.initialize();}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(PRELOAD_ENTRIES,this.onPreloadStories.bind(this));}async setInitialGlobals(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"setInitialGlobals"});let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStoreValue.globals.updateFromPersisted(globals),this.emitGlobals();}async initializeWithStoryIndex(storyIndex){return await super.initializeWithStoryIndex(storyIndex),this.selectSpecifiedStory()}async selectSpecifiedStory(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"selectSpecifiedStory"});if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new EmptyIndexError):this.renderStoryLoadingException(storySpecifier,new NoStoryMatchError({storySpecifier:storySpecifier.toString()}));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args});}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection();}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory();}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}});}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storeInitializationPromise,this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection();}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams);}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.();}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs});}async onPreloadStories({ids}){await this.storeInitializationPromise,this.storyStoreValue&&await Promise.allSettled(ids.map(id=>this.storyStoreValue?.loadEntry(id)));}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!this.storyStoreValue||!renderToCanvas)throw new CalledPreviewMethodBeforeInitializationError({methodName:"renderSelection"});let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStoreValue.storyIdToEntry(storyId);}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=this.currentSelection?.storyId!==storyId,viewModeChanged=this.currentRender?.type!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStoreValue,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare();}catch(err){err!==PREPARE_ABORTED&&(lastRender&&await this.teardownRender(lastRender),this.renderStoryLoadingException(storyId,err));return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)&&(invariant(!!render.story),this.storyStoreValue.args.updateFromPersisted(render.story,persistedArgs)),lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(STORY_CHANGED,storyId),isStoryRender(render)){invariant(!!render.story);let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStoreValue.getStoryContext(render.story);this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs}),(implementationChanged||persistedArgs)&&this.channel.emit(STORY_ARGS_UPDATED,{storyId,args:unmappedArgs});}else {let{parameters}=this.storyStoreValue.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new MdxFileWithNoCsfReferencesError({storyId});({parameters}=this.storyStoreValue.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}));}this.channel.emit(DOCS_PREPARED,{id:storyId,parameters});}isStoryRender(render)?(invariant(!!render.story),this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))):this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this));}async teardownRender(render,{viewModeChanged=!1}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged});}mainStoryCallbacks(storyId){return {showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err);}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(STORY_MISSING);}renderStoryLoadingException(storySpecifier,err){logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(STORY_MISSING,storySpecifier);}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),logger.error(`Error rendering story '${storyId}':`),logger.error(error));}renderError(storyId,{title,description}){logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(STORY_ERRORED,{title,description}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description});}};var VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):isPlainObject(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return !0;if(str==="!false")return !1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return `#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(qs2.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(once.warn(dedent`
|
74
|
+
- Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`)}switch(resolved.type){case"component":return {...resolved,projectAnnotations:this.projectAnnotations};case"meta":return {...resolved,preparedMeta:this.store.preparedMetaFromCSFFile({csfFile:resolved.csfFile})};case"story":default:return resolved}}};var CsfDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.subtype="csf";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id;}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;let{importPath,title}=this.entry,primaryCsfFile=this.store.processCSFFileWithCache(entryExports,importPath,title),primaryStoryId=Object.keys(primaryCsfFile.stories)[0];this.story=this.store.storyFromCSFFile({storyId:primaryStoryId,csfFile:primaryCsfFile}),this.csfFiles=[primaryCsfFile,...csfFiles],this.preparing=!1;}isEqual(other){return !!(this.id===other.id&&this.story&&this.story===other.story)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles);return this.csfFiles.forEach(csfFile=>docsContext.attachCSFFile(csfFile)),docsContext}async renderToElement(canvasElement,renderStoryToElement){if(!this.story||!this.csfFiles)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{docs:docsParameter}=this.story.parameters||{};if(!docsParameter)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let renderer=await docsParameter.renderer(),{render}=renderer,renderDocs=async()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(DOCS_RENDERED,this.id);}catch(err){this.callbacks.showException(err);}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged})=>{!viewModeChanged||!canvasElement||renderer.unmount(canvasElement);},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0;}};var MdxDocsRender=class{constructor(channel,store,entry,callbacks){this.channel=channel;this.store=store;this.entry=entry;this.callbacks=callbacks;this.type="docs";this.subtype="mdx";this.torndown=!1;this.disableKeyListeners=!1;this.preparing=!1;this.id=entry.id;}isPreparing(){return this.preparing}async prepare(){this.preparing=!0;let{entryExports,csfFiles=[]}=await this.store.loadEntry(this.id);if(this.torndown)throw PREPARE_ABORTED;this.csfFiles=csfFiles,this.exports=entryExports,this.preparing=!1;}isEqual(other){return !!(this.id===other.id&&this.exports&&this.exports===other.exports)}docsContext(renderStoryToElement){if(!this.csfFiles)throw new Error("Cannot render docs before preparing");return new DocsContext(this.channel,this.store,renderStoryToElement,this.csfFiles)}async renderToElement(canvasElement,renderStoryToElement){if(!this.exports||!this.csfFiles||!this.store.projectAnnotations)throw new Error("Cannot render docs before preparing");let docsContext=this.docsContext(renderStoryToElement),{docs}=this.store.projectAnnotations.parameters||{};if(!docs)throw new Error("Cannot render a story in viewMode=docs if `@storybook/addon-docs` is not installed");let docsParameter={...docs,page:this.exports.default},renderer=await docs.renderer(),{render}=renderer,renderDocs=async()=>{try{await render(docsContext,docsParameter,canvasElement),this.channel.emit(DOCS_RENDERED,this.id);}catch(err){this.callbacks.showException(err);}};return this.rerender=async()=>renderDocs(),this.teardownRender=async({viewModeChanged}={})=>{!viewModeChanged||!canvasElement||(renderer.unmount(canvasElement),this.torndown=!0);},renderDocs()}async teardown({viewModeChanged}={}){this.teardownRender?.({viewModeChanged}),this.torndown=!0;}};var globalWindow=globalThis;function focusInInput(event){let target=event.composedPath&&event.composedPath()[0]||event.target;return /input|textarea/i.test(target.tagName)||target.getAttribute("contenteditable")!==null}var ATTACHED_MDX_TAG="attached-mdx",UNATTACHED_MDX_TAG="unattached-mdx";function isMdxEntry({tags}){return tags?.includes(UNATTACHED_MDX_TAG)||tags?.includes(ATTACHED_MDX_TAG)}function isStoryRender(r){return r.type==="story"}function isDocsRender(r){return r.type==="docs"}function isCsfDocsRender(r){return isDocsRender(r)&&r.subtype==="csf"}var PreviewWithSelection=class extends Preview{constructor(importFn,getProjectAnnotations,selectionStore,view){super(importFn,getProjectAnnotations,void 0,!1);this.importFn=importFn;this.getProjectAnnotations=getProjectAnnotations;this.selectionStore=selectionStore;this.view=view;this.initialize();}setupListeners(){super.setupListeners(),globalWindow.onkeydown=this.onKeydown.bind(this),this.channel.on(SET_CURRENT_STORY,this.onSetCurrentStory.bind(this)),this.channel.on(UPDATE_QUERY_PARAMS,this.onUpdateQueryParams.bind(this)),this.channel.on(PRELOAD_ENTRIES,this.onPreloadStories.bind(this));}async setInitialGlobals(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"setInitialGlobals"});let{globals}=this.selectionStore.selectionSpecifier||{};globals&&this.storyStoreValue.globals.updateFromPersisted(globals),this.emitGlobals();}async initializeWithStoryIndex(storyIndex){return await super.initializeWithStoryIndex(storyIndex),this.selectSpecifiedStory()}async selectSpecifiedStory(){if(!this.storyStoreValue)throw new CalledPreviewMethodBeforeInitializationError({methodName:"selectSpecifiedStory"});if(this.selectionStore.selection){await this.renderSelection();return}if(!this.selectionStore.selectionSpecifier){this.renderMissingStory();return}let{storySpecifier,args}=this.selectionStore.selectionSpecifier,entry=this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);if(!entry){storySpecifier==="*"?this.renderStoryLoadingException(storySpecifier,new EmptyIndexError):this.renderStoryLoadingException(storySpecifier,new NoStoryMatchError({storySpecifier:storySpecifier.toString()}));return}let{id:storyId,type:viewMode}=entry;this.selectionStore.setSelection({storyId,viewMode}),this.channel.emit(STORY_SPECIFIED,this.selectionStore.selection),this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),await this.renderSelection({persistedArgs:args});}async onGetProjectAnnotationsChanged({getProjectAnnotations}){await super.onGetProjectAnnotationsChanged({getProjectAnnotations}),this.selectionStore.selection&&this.renderSelection();}async onStoriesChanged({importFn,storyIndex}){await super.onStoriesChanged({importFn,storyIndex}),this.selectionStore.selection?await this.renderSelection():await this.selectSpecifiedStory();}onKeydown(event){if(!this.storyRenders.find(r=>r.disableKeyListeners)&&!focusInInput(event)){let{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}=event;this.channel.emit(PREVIEW_KEYDOWN,{event:{altKey,ctrlKey,metaKey,shiftKey,key,code,keyCode}});}}async onSetCurrentStory(selection){this.selectionStore.setSelection({viewMode:"story",...selection}),await this.storeInitializationPromise,this.channel.emit(CURRENT_STORY_WAS_SET,this.selectionStore.selection),this.renderSelection();}onUpdateQueryParams(queryParams){this.selectionStore.setQueryParams(queryParams);}async onUpdateGlobals({globals}){super.onUpdateGlobals({globals}),(this.currentRender instanceof MdxDocsRender||this.currentRender instanceof CsfDocsRender)&&await this.currentRender.rerender?.();}async onUpdateArgs({storyId,updatedArgs}){super.onUpdateArgs({storyId,updatedArgs});}async onPreloadStories({ids}){await this.storeInitializationPromise,this.storyStoreValue&&await Promise.allSettled(ids.map(id=>this.storyStoreValue?.loadEntry(id)));}async renderSelection({persistedArgs}={}){let{renderToCanvas}=this;if(!this.storyStoreValue||!renderToCanvas)throw new CalledPreviewMethodBeforeInitializationError({methodName:"renderSelection"});let{selection}=this.selectionStore;if(!selection)throw new Error("Cannot call renderSelection as no selection was made");let{storyId}=selection,entry;try{entry=await this.storyStoreValue.storyIdToEntry(storyId);}catch(err){this.currentRender&&await this.teardownRender(this.currentRender),this.renderStoryLoadingException(storyId,err);return}let storyIdChanged=this.currentSelection?.storyId!==storyId,viewModeChanged=this.currentRender?.type!==entry.type;entry.type==="story"?this.view.showPreparingStory({immediate:viewModeChanged}):this.view.showPreparingDocs({immediate:viewModeChanged}),this.currentRender?.isPreparing()&&await this.teardownRender(this.currentRender);let render;entry.type==="story"?render=new StoryRender(this.channel,this.storyStoreValue,(...args)=>(this.view.showStoryDuringRender(),renderToCanvas(...args)),this.mainStoryCallbacks(storyId),storyId,"story"):isMdxEntry(entry)?render=new MdxDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId)):render=new CsfDocsRender(this.channel,this.storyStoreValue,entry,this.mainStoryCallbacks(storyId));let lastSelection=this.currentSelection;this.currentSelection=selection;let lastRender=this.currentRender;this.currentRender=render;try{await render.prepare();}catch(err){lastRender&&await this.teardownRender(lastRender),err!==PREPARE_ABORTED&&this.renderStoryLoadingException(storyId,err);return}let implementationChanged=!storyIdChanged&&lastRender&&!render.isEqual(lastRender);if(persistedArgs&&isStoryRender(render)&&(invariant(!!render.story),this.storyStoreValue.args.updateFromPersisted(render.story,persistedArgs)),lastRender&&!lastRender.torndown&&!storyIdChanged&&!implementationChanged&&!viewModeChanged){this.currentRender=lastRender,this.channel.emit(STORY_UNCHANGED,storyId),this.view.showMain();return}if(lastRender&&await this.teardownRender(lastRender,{viewModeChanged}),lastSelection&&(storyIdChanged||viewModeChanged)&&this.channel.emit(STORY_CHANGED,storyId),isStoryRender(render)){invariant(!!render.story);let{parameters,initialArgs,argTypes,unmappedArgs}=this.storyStoreValue.getStoryContext(render.story);this.channel.emit(STORY_PREPARED,{id:storyId,parameters,initialArgs,argTypes,args:unmappedArgs});}else {let{parameters}=this.storyStoreValue.projectAnnotations;if(isCsfDocsRender(render)||render.entry.tags?.includes(ATTACHED_MDX_TAG)){if(!render.csfFiles)throw new MdxFileWithNoCsfReferencesError({storyId});({parameters}=this.storyStoreValue.preparedMetaFromCSFFile({csfFile:render.csfFiles[0]}));}this.channel.emit(DOCS_PREPARED,{id:storyId,parameters});}isStoryRender(render)?(invariant(!!render.story),this.storyRenders.push(render),this.currentRender.renderToElement(this.view.prepareForStory(render.story))):this.currentRender.renderToElement(this.view.prepareForDocs(),this.renderStoryToElement.bind(this));}async teardownRender(render,{viewModeChanged=!1}={}){this.storyRenders=this.storyRenders.filter(r=>r!==render),await render?.teardown?.({viewModeChanged});}mainStoryCallbacks(storyId){return {showMain:()=>this.view.showMain(),showError:err=>this.renderError(storyId,err),showException:err=>this.renderException(storyId,err)}}renderPreviewEntryError(reason,err){super.renderPreviewEntryError(reason,err),this.view.showErrorDisplay(err);}renderMissingStory(){this.view.showNoPreview(),this.channel.emit(STORY_MISSING);}renderStoryLoadingException(storySpecifier,err){logger.error(err),this.view.showErrorDisplay(err),this.channel.emit(STORY_MISSING,storySpecifier);}renderException(storyId,error){let{name="Error",message=String(error),stack}=error;this.channel.emit(STORY_THREW_EXCEPTION,{name,message,stack}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),error.message?.startsWith("ignoredException")||(this.view.showErrorDisplay(error),logger.error(`Error rendering story '${storyId}':`),logger.error(error));}renderError(storyId,{title,description}){logger.error(`Error rendering story ${title}: ${description}`),this.channel.emit(STORY_ERRORED,{title,description}),this.channel.emit(STORY_RENDER_PHASE_CHANGED,{newPhase:"errored",storyId}),this.view.showErrorDisplay({message:title,stack:description});}};var VALIDATION_REGEXP=/^[a-zA-Z0-9 _-]*$/,NUMBER_REGEXP=/^-?[0-9]+(\.[0-9]+)?$/,HEX_REGEXP=/^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i,COLOR_REGEXP=/^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i,validateArgs=(key="",value)=>key===null||key===""||!VALIDATION_REGEXP.test(key)?!1:value==null||value instanceof Date||typeof value=="number"||typeof value=="boolean"?!0:typeof value=="string"?VALIDATION_REGEXP.test(value)||NUMBER_REGEXP.test(value)||HEX_REGEXP.test(value)||COLOR_REGEXP.test(value):Array.isArray(value)?value.every(v=>validateArgs(key,v)):isPlainObject(value)?Object.entries(value).every(([k,v])=>validateArgs(k,v)):!1,QS_OPTIONS={delimiter:";",allowDots:!0,allowSparse:!0,decoder(str,defaultDecoder,charset,type){if(type==="value"&&str.startsWith("!")){if(str==="!undefined")return;if(str==="!null")return null;if(str==="!true")return !0;if(str==="!false")return !1;if(str.startsWith("!date(")&&str.endsWith(")"))return new Date(str.slice(6,-1));if(str.startsWith("!hex(")&&str.endsWith(")"))return `#${str.slice(5,-1)}`;let color=str.slice(1).match(COLOR_REGEXP);if(color)return str.startsWith("!rgba")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})`:str.startsWith("!hsla")?`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})`:str.startsWith("!rgb")?`${color[1]}(${color[2]}, ${color[3]}, ${color[4]})`:`${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`}return type==="value"&&NUMBER_REGEXP.test(str)?Number(str):defaultDecoder(str,defaultDecoder,charset)}},parseArgsParam=argsString=>{let parts=argsString.split(";").map(part=>part.replace("=","~").replace(":","="));return Object.entries(qs2.parse(parts.join(";"),QS_OPTIONS)).reduce((acc,[key,value])=>validateArgs(key,value)?Object.assign(acc,{[key]:value}):(once.warn(dedent`
|
69
75
|
Omitted potentially unsafe URL args.
|
70
76
|
|
71
77
|
More info: https://storybook.js.org/docs/react/writing-stories/args#setting-args-through-the-url
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@storybook/preview-api",
|
3
|
-
"version": "8.1.0-
|
3
|
+
"version": "8.1.0-beta.0",
|
4
4
|
"description": "",
|
5
5
|
"keywords": [
|
6
6
|
"storybook"
|
@@ -44,12 +44,12 @@
|
|
44
44
|
"prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts"
|
45
45
|
},
|
46
46
|
"dependencies": {
|
47
|
-
"@storybook/channels": "8.1.0-
|
48
|
-
"@storybook/client-logger": "8.1.0-
|
49
|
-
"@storybook/core-events": "8.1.0-
|
50
|
-
"@storybook/csf": "^0.1.
|
47
|
+
"@storybook/channels": "8.1.0-beta.0",
|
48
|
+
"@storybook/client-logger": "8.1.0-beta.0",
|
49
|
+
"@storybook/core-events": "8.1.0-beta.0",
|
50
|
+
"@storybook/csf": "^0.1.7",
|
51
51
|
"@storybook/global": "^5.0.0",
|
52
|
-
"@storybook/types": "8.1.0-
|
52
|
+
"@storybook/types": "8.1.0-beta.0",
|
53
53
|
"@types/qs": "^6.9.5",
|
54
54
|
"dequal": "^2.0.2",
|
55
55
|
"lodash": "^4.17.21",
|
@@ -60,7 +60,7 @@
|
|
60
60
|
"util-deprecate": "^1.0.2"
|
61
61
|
},
|
62
62
|
"devDependencies": {
|
63
|
-
"@storybook/core-common": "8.1.0-
|
63
|
+
"@storybook/core-common": "8.1.0-beta.0",
|
64
64
|
"ansi-to-html": "^0.6.11",
|
65
65
|
"slash": "^5.0.0"
|
66
66
|
},
|