-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
withActions.ts
66 lines (56 loc) · 2.03 KB
/
withActions.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
// Based on http://backbonejs.org/docs/backbone.html#section-164
import { document, Element } from 'global';
import { isEqual } from 'lodash';
import { addons } from '@storybook/addons';
import Events from '@storybook/core-events';
import { actions } from './actions';
let lastSubscription: () => () => void;
let lastArgs: any[];
const delegateEventSplitter = /^(\S+)\s*(.*)$/;
const isIE = Element != null && !Element.prototype.matches;
const matchesMethod = isIE ? 'msMatchesSelector' : 'matches';
const root = document && document.getElementById('root');
const hasMatchInAncestry = (element: any, selector: any): boolean => {
if (element[matchesMethod](selector)) {
return true;
}
const parent = element.parentElement;
if (!parent) {
return false;
}
return hasMatchInAncestry(parent, selector);
};
const createHandlers = (actionsFn: (...arg: any[]) => object, ...args: any[]) => {
const actionsObject = actionsFn(...args);
return Object.entries(actionsObject).map(([key, action]) => {
// eslint-disable-next-line no-unused-vars
const [_, eventName, selector] = key.match(delegateEventSplitter);
return {
eventName,
handler: (e: { target: any }) => {
if (!selector || hasMatchInAncestry(e.target, selector)) {
action(e);
}
},
};
});
};
const actionsSubscription = (...args: any[]) => {
if (!isEqual(args, lastArgs)) {
lastArgs = args;
// @ts-ignore
const handlers = createHandlers(...args);
lastSubscription = () => {
handlers.forEach(({ eventName, handler }) => root.addEventListener(eventName, handler));
return () => handlers.forEach(({ eventName, handler }) => root.removeEventListener(eventName, handler));
};
}
return lastSubscription;
};
export const createDecorator = (actionsFn: any) => (...args: any[]) => (storyFn: () => any) => {
if (root != null) {
addons.getChannel().emit(Events.REGISTER_SUBSCRIPTION, actionsSubscription(actionsFn, ...args));
}
return storyFn();
};
export const withActions = createDecorator(actions);