-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathhooks.ts
471 lines (405 loc) · 14.2 KB
/
hooks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import { global } from '@storybook/global';
import { logger } from '@storybook/client-logger';
import type {
Renderer,
Args,
DecoratorApplicator,
DecoratorFunction,
LegacyStoryFn,
StoryContext,
StoryId,
} from '@storybook/types';
import {
FORCE_RE_RENDER,
STORY_RENDERED,
UPDATE_STORY_ARGS,
RESET_STORY_ARGS,
UPDATE_GLOBALS,
} from '@storybook/core-events';
import { addons } from './main';
interface Hook {
name: string;
memoizedState?: any;
deps?: any[] | undefined;
}
interface Effect {
create: () => (() => void) | void;
destroy?: (() => void) | void;
}
type AbstractFunction = (...args: any[]) => any;
export class HooksContext<TRenderer extends Renderer, TArgs extends Args = Args> {
hookListsMap: WeakMap<AbstractFunction, Hook[]> = undefined as any;
mountedDecorators: Set<AbstractFunction> = undefined as any;
prevMountedDecorators: Set<AbstractFunction> = undefined as any;
currentHooks: Hook[] = undefined as any;
nextHookIndex: number = undefined as any;
currentPhase: 'MOUNT' | 'UPDATE' | 'NONE' = undefined as any;
currentEffects: Effect[] = undefined as any;
prevEffects: Effect[] = undefined as any;
currentDecoratorName: string | null = undefined as any;
hasUpdates: boolean = undefined as any;
currentContext: StoryContext<TRenderer, TArgs> | null = undefined as any;
renderListener = (storyId: StoryId) => {
if (storyId !== this.currentContext?.id) {
return;
}
this.triggerEffects();
this.currentContext = null;
this.removeRenderListeners();
};
constructor() {
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 = false;
this.currentContext = null;
}
clean() {
this.prevEffects.forEach((effect) => {
if (effect.destroy) {
effect.destroy();
}
});
this.init();
this.removeRenderListeners();
}
getNextHook() {
const hook = this.currentHooks[this.nextHookIndex];
this.nextHookIndex += 1;
return hook;
}
triggerEffects() {
// destroy removed effects
this.prevEffects.forEach((effect) => {
if (!this.currentEffects.includes(effect) && effect.destroy) {
effect.destroy();
}
});
// trigger added effects
this.currentEffects.forEach((effect) => {
if (!this.prevEffects.includes(effect)) {
// eslint-disable-next-line no-param-reassign
effect.destroy = effect.create();
}
});
this.prevEffects = this.currentEffects;
this.currentEffects = [];
}
addRenderListeners() {
this.removeRenderListeners();
const channel = addons.getChannel();
channel.on(STORY_RENDERED, this.renderListener);
}
removeRenderListeners() {
const channel = addons.getChannel();
channel.removeListener(STORY_RENDERED, this.renderListener);
}
}
function hookify<TRenderer extends Renderer>(
storyFn: LegacyStoryFn<TRenderer>
): LegacyStoryFn<TRenderer>;
function hookify<TRenderer extends Renderer>(
decorator: DecoratorFunction<TRenderer>
): DecoratorFunction<TRenderer>;
function hookify<TRenderer extends Renderer>(fn: AbstractFunction) {
const hookified = (...args: any[]) => {
const { hooks }: { hooks: HooksContext<TRenderer> } =
typeof args[0] === 'function' ? args[1] : args[0];
const prevPhase = hooks.currentPhase;
const prevHooks = hooks.currentHooks;
const prevNextHookIndex = hooks.nextHookIndex;
const prevDecoratorName = hooks.currentDecoratorName;
hooks.currentDecoratorName = fn.name;
if (hooks.prevMountedDecorators.has(fn)) {
hooks.currentPhase = 'UPDATE';
hooks.currentHooks = hooks.hookListsMap.get(fn) || [];
} else {
hooks.currentPhase = 'MOUNT';
hooks.currentHooks = [];
hooks.hookListsMap.set(fn, hooks.currentHooks);
hooks.prevMountedDecorators.add(fn);
}
hooks.nextHookIndex = 0;
const prevContext = global.STORYBOOK_HOOKS_CONTEXT;
global.STORYBOOK_HOOKS_CONTEXT = hooks;
const result = fn(...args);
global.STORYBOOK_HOOKS_CONTEXT = prevContext;
if (hooks.currentPhase === 'UPDATE' && hooks.getNextHook() != null) {
throw new Error(
'Rendered fewer hooks than expected. This may be caused by an accidental early return statement.'
);
}
hooks.currentPhase = prevPhase;
hooks.currentHooks = prevHooks;
hooks.nextHookIndex = prevNextHookIndex;
hooks.currentDecoratorName = prevDecoratorName;
return result;
};
hookified.originalFn = fn;
return hookified;
}
// Counter to prevent infinite loops.
let numberOfRenders = 0;
const RENDER_LIMIT = 25;
export const applyHooks =
<TRenderer extends Renderer>(
applyDecorators: DecoratorApplicator<TRenderer>
): DecoratorApplicator<TRenderer> =>
(storyFn: LegacyStoryFn<TRenderer>, decorators: DecoratorFunction<TRenderer>[]) => {
const decorated = applyDecorators(
hookify(storyFn),
decorators.map((decorator) => hookify(decorator))
);
return (context) => {
const { hooks } = context as { hooks: HooksContext<TRenderer> };
hooks.prevMountedDecorators = hooks.mountedDecorators;
hooks.mountedDecorators = new Set([storyFn, ...decorators]);
hooks.currentContext = context;
hooks.hasUpdates = false;
let result = decorated(context);
numberOfRenders = 1;
while (hooks.hasUpdates) {
hooks.hasUpdates = false;
hooks.currentEffects = [];
result = decorated(context);
numberOfRenders += 1;
if (numberOfRenders > RENDER_LIMIT) {
throw new Error(
'Too many re-renders. Storybook limits the number of renders to prevent an infinite loop.'
);
}
}
hooks.addRenderListeners();
return result;
};
};
const areDepsEqual = (deps: any[], nextDeps: any[]) =>
deps.length === nextDeps.length && deps.every((dep, i) => dep === nextDeps[i]);
const invalidHooksError = () =>
new Error('Storybook preview hooks can only be called inside decorators and story functions.');
function getHooksContextOrNull<
TRenderer extends Renderer,
TArgs extends Args = Args
>(): HooksContext<TRenderer, TArgs> | null {
return global.STORYBOOK_HOOKS_CONTEXT || null;
}
function getHooksContextOrThrow<
TRenderer extends Renderer,
TArgs extends Args = Args
>(): HooksContext<TRenderer, TArgs> {
const hooks = getHooksContextOrNull<TRenderer, TArgs>();
if (hooks == null) {
throw invalidHooksError();
}
return hooks;
}
function useHook(name: string, callback: (hook: Hook) => void, deps?: any[] | undefined): Hook {
const hooks = getHooksContextOrThrow();
if (hooks.currentPhase === 'MOUNT') {
if (deps != null && !Array.isArray(deps)) {
logger.warn(
`${name} received a final argument that is not an array (instead, received ${deps}). When specified, the final argument must be an array.`
);
}
const hook: Hook = { name, deps };
hooks.currentHooks.push(hook);
callback(hook);
return hook;
}
if (hooks.currentPhase === 'UPDATE') {
const hook = hooks.getNextHook();
if (hook == null) {
throw new Error('Rendered more hooks than during the previous render.');
}
if (hook.name !== name) {
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.`
);
}
if (deps != null && hook.deps == null) {
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.`
);
}
if (deps != null && hook.deps != null && deps.length !== hook.deps.length) {
logger.warn(`The final argument passed to ${name} changed size between renders. The order and size of this array must remain constant.
Previous: ${hook.deps}
Incoming: ${deps}`);
}
if (deps == null || hook.deps == null || !areDepsEqual(deps, hook.deps)) {
callback(hook);
hook.deps = deps;
}
return hook;
}
throw invalidHooksError();
}
function useMemoLike<T>(name: string, nextCreate: () => T, deps: any[] | undefined): T {
const { memoizedState } = useHook(
name,
(hook) => {
// eslint-disable-next-line no-param-reassign
hook.memoizedState = nextCreate();
},
deps
);
return memoizedState;
}
/* Returns a memoized value, see https://reactjs.org/docs/hooks-reference.html#usememo */
export function useMemo<T>(nextCreate: () => T, deps?: any[]): T {
return useMemoLike('useMemo', nextCreate, deps);
}
/* Returns a memoized callback, see https://reactjs.org/docs/hooks-reference.html#usecallback */
export function useCallback<T>(callback: T, deps?: any[]): T {
return useMemoLike('useCallback', () => callback, deps);
}
function useRefLike<T>(name: string, initialValue: T): { current: T } {
return useMemoLike(name, () => ({ current: initialValue }), []);
}
/* Returns a mutable ref object, see https://reactjs.org/docs/hooks-reference.html#useref */
export function useRef<T>(initialValue: T): { current: T } {
return useRefLike('useRef', initialValue);
}
function triggerUpdate() {
const hooks = getHooksContextOrNull();
// Rerun storyFn if updates were triggered synchronously, force rerender otherwise
if (hooks != null && hooks.currentPhase !== 'NONE') {
hooks.hasUpdates = true;
} else {
try {
addons.getChannel().emit(FORCE_RE_RENDER);
} catch (e) {
logger.warn('State updates of Storybook preview hooks work only in browser');
}
}
}
function useStateLike<S>(
name: string,
initialState: (() => S) | S
): [S, (update: ((prevState: S) => S) | S) => void] {
const stateRef = useRefLike(
name,
// @ts-expect-error S type should never be function, but there's no way to tell that to TypeScript
typeof initialState === 'function' ? initialState() : initialState
);
const setState = (update: ((prevState: S) => S) | S) => {
// @ts-expect-error S type should never be function, but there's no way to tell that to TypeScript
stateRef.current = typeof update === 'function' ? update(stateRef.current) : update;
triggerUpdate();
};
return [stateRef.current, setState];
}
/* Returns a stateful value, and a function to update it, see https://reactjs.org/docs/hooks-reference.html#usestate */
export function useState<S>(
initialState: (() => S) | S
): [S, (update: ((prevState: S) => S) | S) => void] {
return useStateLike('useState', initialState);
}
/* A redux-like alternative to useState, see https://reactjs.org/docs/hooks-reference.html#usereducer */
export function useReducer<S, A>(
reducer: (state: S, action: A) => S,
initialState: S
): [S, (action: A) => void];
export function useReducer<S, I, A>(
reducer: (state: S, action: A) => S,
initialArg: I,
init: (initialArg: I) => S
): [S, (action: A) => void];
export function useReducer<S, A>(
reducer: (state: S, action: A) => S,
initialArg: any,
init?: any
): [S, (action: A) => void] {
const initialState: (() => S) | S = init != null ? () => init(initialArg) : initialArg;
const [state, setState] = useStateLike('useReducer', initialState);
const dispatch = (action: A) => setState((prevState) => reducer(prevState, action));
return [state, dispatch];
}
/*
Triggers a side effect, see https://reactjs.org/docs/hooks-reference.html#usestate
Effects are triggered synchronously after rendering the story
*/
export function useEffect(create: () => (() => void) | void, deps?: any[]): void {
const hooks = getHooksContextOrThrow();
const effect = useMemoLike('useEffect', () => ({ create }), deps);
if (!hooks.currentEffects.includes(effect)) {
hooks.currentEffects.push(effect);
}
}
export interface Listener {
(...args: any[]): void;
}
export interface EventMap {
[eventId: string]: Listener;
}
/* Accepts a map of Storybook channel event listeners, returns an emit function */
export function useChannel(eventMap: EventMap, deps: any[] = []) {
const channel = addons.getChannel();
useEffect(() => {
Object.entries(eventMap).forEach(([type, listener]) => channel.on(type, listener));
return () => {
Object.entries(eventMap).forEach(([type, listener]) =>
channel.removeListener(type, listener)
);
};
}, [...Object.keys(eventMap), ...deps]);
return useCallback(channel.emit.bind(channel), [channel]);
}
/* Returns current story context */
export function useStoryContext<
TRenderer extends Renderer,
TArgs extends Args = Args
>(): StoryContext<TRenderer> {
const { currentContext } = getHooksContextOrThrow<TRenderer, TArgs>();
if (currentContext == null) {
throw invalidHooksError();
}
return currentContext;
}
/* Returns current value of a story parameter */
export function useParameter<S>(parameterKey: string, defaultValue?: S): S | undefined {
const { parameters } = useStoryContext();
if (parameterKey) {
return parameters[parameterKey] ?? (defaultValue as S);
}
return undefined;
}
/* Returns current value of story args */
export function useArgs<TArgs extends Args = Args>(): [
TArgs,
(newArgs: Partial<TArgs>) => void,
(argNames?: (keyof TArgs)[]) => void
] {
const channel = addons.getChannel();
const { id: storyId, args } = useStoryContext<Renderer, TArgs>();
const updateArgs = useCallback(
(updatedArgs: Partial<TArgs>) => channel.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs }),
[channel, storyId]
);
const resetArgs = useCallback(
(argNames?: (keyof TArgs)[]) => channel.emit(RESET_STORY_ARGS, { storyId, argNames }),
[channel, storyId]
);
return [args as TArgs, updateArgs, resetArgs];
}
/* Returns current value of global args */
export function useGlobals(): [Args, (newGlobals: Args) => void] {
const channel = addons.getChannel();
const { globals } = useStoryContext();
const updateGlobals = useCallback(
(newGlobals: Args) => channel.emit(UPDATE_GLOBALS, { globals: newGlobals }),
[channel]
);
return [globals, updateGlobals];
}