@storybook/preview-api 7.0.0-beta.2 → 7.0.0-beta.20

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.
@@ -18,7 +18,6 @@ declare class StoryStoreFacade<TRenderer extends Renderer> {
18
18
  addStoriesFromExports(fileName: Path, fileExports: ModuleExports): void;
19
19
  }
20
20
 
21
- declare let singleton: ClientApi<Renderer>;
22
21
  declare const addDecorator: (decorator: DecoratorFunction<Renderer>) => void;
23
22
  declare const addParameters: (parameters: Parameters) => void;
24
23
  declare const addLoader: (loader: LoaderFunction<Renderer>) => void;
@@ -27,7 +26,7 @@ declare const addArgTypes: (argTypes: ArgTypes) => void;
27
26
  declare const addArgsEnhancer: (enhancer: ArgsEnhancer<Renderer>) => void;
28
27
  declare const addArgTypesEnhancer: (enhancer: ArgTypesEnhancer<Renderer>) => void;
29
28
  declare const addStepRunner: (stepRunner: StepRunner) => void;
30
- declare const setGlobalRender: (render: (typeof singleton)['facade']['projectAnnotations']['render']) => void;
29
+ declare const setGlobalRender: (render: StoryStoreFacade<any>['projectAnnotations']['render']) => void;
31
30
  declare class ClientApi<TRenderer extends Renderer> {
32
31
  facade: StoryStoreFacade<TRenderer>;
33
32
  storyStore?: StoryStore<TRenderer>;
@@ -62,18 +62,18 @@ declare class StoryRender<TRenderer extends Renderer> implements Render<TRendere
62
62
  }
63
63
 
64
64
  /**
65
- * A TemplateDocsRender is a render of a docs entry that is rendered with (an) attached CSF file(s).
65
+ * A CsfDocsRender is a render of a docs entry that is rendered based on a CSF file.
66
66
  *
67
67
  * The expectation is the primary CSF file which is the `importPath` for the entry will
68
68
  * define a story which may contain the actual rendered JSX code for the template in the
69
69
  * `docs.page` parameter.
70
70
  *
71
71
  * Use cases:
72
- * - Docs Page, where there is no parameter, and we fall back to the globally defined template.
72
+ * - Autodocs, where there is no story, and we fall back to the globally defined template.
73
73
  * - *.stories.mdx files, where the MDX compiler produces a CSF file with a `.parameter.docs.page`
74
74
  * parameter containing the compiled content of the MDX file.
75
75
  */
76
- declare class TemplateDocsRender<TRenderer extends Renderer> implements Render<TRenderer> {
76
+ declare class CsfDocsRender<TRenderer extends Renderer> implements Render<TRenderer> {
77
77
  protected channel: Channel;
78
78
  protected store: StoryStore<TRenderer>;
79
79
  entry: IndexEntry;
@@ -99,14 +99,15 @@ declare class TemplateDocsRender<TRenderer extends Renderer> implements Render<T
99
99
  }
100
100
 
101
101
  /**
102
- * A StandaloneDocsRender is a render of a docs entry that doesn't directly come from a CSF file.
102
+ * A MdxDocsRender is a render of a docs entry that comes from a true MDX file,
103
+ * that is a `.mdx` file that doesn't get compiled to a CSF file.
103
104
  *
104
- * A standalone render can reference zero or more CSF files that contain stories.
105
+ * A MDX render can reference (import) zero or more CSF files that contain stories.
105
106
  *
106
107
  * Use cases:
107
108
  * - *.mdx file that may or may not reference a specific CSF file with `<Meta of={} />`
108
109
  */
109
- declare class StandaloneDocsRender<TRenderer extends Renderer> implements Render<TRenderer> {
110
+ declare class MdxDocsRender<TRenderer extends Renderer> implements Render<TRenderer> {
110
111
  protected channel: Channel;
111
112
  protected store: StoryStore<TRenderer>;
112
113
  entry: IndexEntry;
@@ -178,7 +179,7 @@ declare class Preview<TFramework extends Renderer> {
178
179
  storyId: StoryId;
179
180
  }): Promise<void>;
180
181
  renderStoryToElement(story: PreparedStory<TFramework>, element: TFramework['canvasElement'], options: StoryRenderOptions): () => Promise<void>;
181
- teardownRender(render: StoryRender<TFramework> | TemplateDocsRender<TFramework> | StandaloneDocsRender<TFramework>, { viewModeChanged }?: {
182
+ teardownRender(render: StoryRender<TFramework> | CsfDocsRender<TFramework> | MdxDocsRender<TFramework>, { viewModeChanged }?: {
182
183
  viewModeChanged?: boolean;
183
184
  }): Promise<void>;
184
185
  extract(options?: {
@@ -230,7 +231,7 @@ interface View<TStorybookRoot> {
230
231
  showStoryDuringRender(): void;
231
232
  }
232
233
 
233
- type PossibleRender<TFramework extends Renderer> = StoryRender<TFramework> | TemplateDocsRender<TFramework> | StandaloneDocsRender<TFramework>;
234
+ type PossibleRender<TFramework extends Renderer> = StoryRender<TFramework> | CsfDocsRender<TFramework> | MdxDocsRender<TFramework>;
234
235
  declare class PreviewWithSelection<TFramework extends Renderer> extends Preview<TFramework> {
235
236
  selectionStore: SelectionStore;
236
237
  view: View<TFramework['canvasElement']>;
package/dist/addons.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var L=Object.create;var p=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var M=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty;var U=(r,e)=>{for(var n in e)p(r,n,{get:e[n],enumerable:!0})},C=(r,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of _(e))!I.call(r,t)&&t!==n&&p(r,t,{get:()=>e[t],enumerable:!(o=P(e,t))||o.enumerable});return r};var A=(r,e,n)=>(n=r!=null?L(M(r)):{},C(e||!r||!r.__esModule?p(n,"default",{value:r,enumerable:!0}):n,r)),F=r=>C(p({},"__esModule",{value:!0}),r);var re={};U(re,{AddonStore:()=>S,HooksContext:()=>T,addons:()=>d,applyHooks:()=>Y,makeDecorator:()=>ee,mockChannel:()=>g,useArgs:()=>Q,useCallback:()=>f,useChannel:()=>V,useEffect:()=>N,useGlobals:()=>Z,useMemo:()=>W,useParameter:()=>J,useReducer:()=>q,useRef:()=>z,useState:()=>X,useStoryContext:()=>k});module.exports=F(re);var y=A(require("global"));var O=require("@storybook/channels");function g(){let r={setHandler:()=>{},send:()=>{}};return new O.Channel({transport:r})}var S=class{constructor(){this.getChannel=()=>{if(!this.channel){let e=g();return this.setChannel(e),e}return this.channel};this.getServerChannel=()=>{if(!this.serverChannel)throw new Error("Accessing non-existent serverChannel");return this.serverChannel};this.ready=()=>this.promise;this.hasChannel=()=>!!this.channel;this.hasServerChannel=()=>!!this.serverChannel;this.setChannel=e=>{this.channel=e,this.resolve()};this.setServerChannel=e=>{this.serverChannel=e};this.promise=new Promise(e=>{this.resolve=()=>e(this.getChannel())})}},v="__STORYBOOK_ADDONS_PREVIEW";function $(){return y.default[v]||(y.default[v]=new S),y.default[v]}var d=$();var l=A(require("global")),h=require("@storybook/client-logger"),i=require("@storybook/core-events");var T=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=e=>{var n;e===((n=this.currentContext)==null?void 0:n.id)&&(this.triggerEffects(),this.currentContext=null,this.removeRenderListeners())};this.init()}init(){this.hookListsMap=new WeakMap,this.mountedDecorators=new Set,this.prevMountedDecorators=this.mountedDecorators,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(e=>{e.destroy&&e.destroy()}),this.init(),this.removeRenderListeners()}getNextHook(){let e=this.currentHooks[this.nextHookIndex];return this.nextHookIndex+=1,e}triggerEffects(){this.prevEffects.forEach(e=>{!this.currentEffects.includes(e)&&e.destroy&&e.destroy()}),this.currentEffects.forEach(e=>{this.prevEffects.includes(e)||(e.destroy=e.create())}),this.prevEffects=this.currentEffects,this.currentEffects=[]}addRenderListeners(){this.removeRenderListeners(),d.getChannel().on(i.STORY_RENDERED,this.renderListener)}removeRenderListeners(){d.getChannel().removeListener(i.STORY_RENDERED,this.renderListener)}};function b(r){return(...e)=>{let{hooks:n}=typeof e[0]=="function"?e[1]:e[0],o=n.currentPhase,t=n.currentHooks,s=n.nextHookIndex,a=n.currentDecoratorName;n.currentDecoratorName=r.name,n.prevMountedDecorators.has(r)?(n.currentPhase="UPDATE",n.currentHooks=n.hookListsMap.get(r)||[]):(n.currentPhase="MOUNT",n.currentHooks=[],n.hookListsMap.set(r,n.currentHooks),n.prevMountedDecorators.add(r)),n.nextHookIndex=0;let c=l.default.STORYBOOK_HOOKS_CONTEXT;l.default.STORYBOOK_HOOKS_CONTEXT=n;let u=r(...e);if(l.default.STORYBOOK_HOOKS_CONTEXT=c,n.currentPhase==="UPDATE"&&n.getNextHook()!=null)throw new Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");return n.currentPhase=o,n.currentHooks=t,n.nextHookIndex=s,n.currentDecoratorName=a,u}}var R=0,K=25,Y=r=>(e,n)=>{let o=r(b(e),n.map(t=>b(t)));return t=>{let{hooks:s}=t;s.prevMountedDecorators=s.mountedDecorators,s.mountedDecorators=new Set([e,...n]),s.currentContext=t,s.hasUpdates=!1;let a=o(t);for(R=1;s.hasUpdates;)if(s.hasUpdates=!1,s.currentEffects=[],a=o(t),R+=1,R>K)throw new Error("Too many re-renders. Storybook limits the number of renders to prevent an infinite loop.");return s.addRenderListeners(),a}},B=(r,e)=>r.length===e.length&&r.every((n,o)=>n===e[o]),E=()=>new Error("Storybook preview hooks can only be called inside decorators and story functions.");function D(){return l.default.STORYBOOK_HOOKS_CONTEXT||null}function x(){let r=D();if(r==null)throw E();return r}function G(r,e,n){let o=x();if(o.currentPhase==="MOUNT"){n!=null&&!Array.isArray(n)&&h.logger.warn(`${r} received a final argument that is not an array (instead, received ${n}). When specified, the final argument must be an array.`);let t={name:r,deps:n};return o.currentHooks.push(t),e(t),t}if(o.currentPhase==="UPDATE"){let t=o.getNextHook();if(t==null)throw new Error("Rendered more hooks than during the previous render.");return t.name!==r&&h.logger.warn(`Storybook has detected a change in the order of Hooks${o.currentDecoratorName?` called by ${o.currentDecoratorName}`:""}. This will lead to bugs and errors if not fixed.`),n!=null&&t.deps==null&&h.logger.warn(`${r} 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.`),n!=null&&t.deps!=null&&n.length!==t.deps.length&&h.logger.warn(`The final argument passed to ${r} changed size between renders. The order and size of this array must remain constant.
2
- Previous: ${t.deps}
3
- Incoming: ${n}`),(n==null||t.deps==null||!B(n,t.deps))&&(e(t),t.deps=n),t}throw E()}function m(r,e,n){let{memoizedState:o}=G(r,t=>{t.memoizedState=e()},n);return o}function W(r,e){return m("useMemo",r,e)}function f(r,e){return m("useCallback",()=>r,e)}function H(r,e){return m(r,()=>({current:e}),[])}function z(r){return H("useRef",r)}function j(){let r=D();if(r!=null&&r.currentPhase!=="NONE")r.hasUpdates=!0;else try{d.getChannel().emit(i.FORCE_RE_RENDER)}catch{h.logger.warn("State updates of Storybook preview hooks work only in browser")}}function w(r,e){let n=H(r,typeof e=="function"?e():e),o=t=>{n.current=typeof t=="function"?t(n.current):t,j()};return[n.current,o]}function X(r){return w("useState",r)}function q(r,e,n){let o=n!=null?()=>n(e):e,[t,s]=w("useReducer",o);return[t,c=>s(u=>r(u,c))]}function N(r,e){let n=x(),o=m("useEffect",()=>({create:r}),e);n.currentEffects.includes(o)||n.currentEffects.push(o)}function V(r,e=[]){let n=d.getChannel();return N(()=>(Object.entries(r).forEach(([o,t])=>n.on(o,t)),()=>{Object.entries(r).forEach(([o,t])=>n.removeListener(o,t))}),[...Object.keys(r),...e]),f(n.emit.bind(n),[n])}function k(){let{currentContext:r}=x();if(r==null)throw E();return r}function J(r,e){let{parameters:n}=k();if(r)return n[r]??e}function Q(){let r=d.getChannel(),{id:e,args:n}=k(),o=f(s=>r.emit(i.UPDATE_STORY_ARGS,{storyId:e,updatedArgs:s}),[r,e]),t=f(s=>r.emit(i.RESET_STORY_ARGS,{storyId:e,argNames:s}),[r,e]);return[n,o,t]}function Z(){let r=d.getChannel(),{globals:e}=k(),n=f(o=>r.emit(i.UPDATE_GLOBALS,{globals:o}),[r]);return[e,n]}var ee=({name:r,parameterName:e,wrapper:n,skipIfNoParametersOrOptions:o=!1})=>{let t=s=>(a,c)=>{let u=c.parameters&&c.parameters[e];return u&&u.disable||o&&!s&&!u?a(c):n(a,c,{options:s,parameters:u})};return(...s)=>typeof s[0]=="function"?t()(...s):(...a)=>{if(a.length>1)return s.length>1?t(s)(...a):t(...s)(...a);throw new Error(`Passing stories directly into ${r}() is not allowed,
4
- instead use addDecorator(${r}) and pass options with the '${e}' parameter`)}};0&&(module.exports={AddonStore,HooksContext,addons,applyHooks,makeDecorator,mockChannel,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext});
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var addons_exports={};__export(addons_exports,{AddonStore:()=>AddonStore,HooksContext:()=>HooksContext,addons:()=>addons,applyHooks:()=>applyHooks,makeDecorator:()=>makeDecorator,mockChannel:()=>mockChannel,useArgs:()=>useArgs,useCallback:()=>useCallback,useChannel:()=>useChannel,useEffect:()=>useEffect,useGlobals:()=>useGlobals,useMemo:()=>useMemo,useParameter:()=>useParameter,useReducer:()=>useReducer,useRef:()=>useRef,useState:()=>useState,useStoryContext:()=>useStoryContext});module.exports=__toCommonJS(addons_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.getServerChannel=()=>{if(!this.serverChannel)throw new Error("Accessing non-existent serverChannel");return this.serverChannel};this.ready=()=>this.promise;this.hasChannel=()=>!!this.channel;this.hasServerChannel=()=>!!this.serverChannel;this.setChannel=channel=>{this.channel=channel,this.resolve()};this.setServerChannel=channel=>{this.serverChannel=channel};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=>{var _a;storyId===((_a=this.currentContext)==null?void 0:_a.id)&&(this.triggerEffects(),this.currentContext=null,this.removeRenderListeners())};this.init()}init(){this.hookListsMap=new WeakMap,this.mountedDecorators=new Set,this.prevMountedDecorators=this.mountedDecorators,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){return(...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}}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=hooks.mountedDecorators,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.
2
+ Previous: ${hook.deps}
3
+ 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&&parameters.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,
4
+ instead use addDecorator(${name}) and pass options with the '${parameterName}' parameter`)}};0&&(module.exports={AddonStore,HooksContext,addons,applyHooks,makeDecorator,mockChannel,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext});
package/dist/addons.mjs CHANGED
@@ -1 +1 @@
1
- import{makeDecorator}from"./chunk-GRRYLBAT.mjs";import{AddonStore,HooksContext,addons,applyHooks,mockChannel,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext}from"./chunk-QSH26RWA.mjs";export{AddonStore,HooksContext,addons,applyHooks,makeDecorator,mockChannel,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext};
1
+ import{makeDecorator}from"./chunk-GRRYLBAT.mjs";import{AddonStore,HooksContext,addons,applyHooks,mockChannel,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext}from"./chunk-RTGEOU4B.mjs";export{AddonStore,HooksContext,addons,applyHooks,makeDecorator,mockChannel,useArgs,useCallback,useChannel,useEffect,useGlobals,useMemo,useParameter,useReducer,useRef,useState,useStoryContext};