-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
client_api.js
90 lines (73 loc) · 2.38 KB
/
client_api.js
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
import formatActionData from './ui/utils/formatActionData';
let idGenerator = 0;
export default class ClientApi {
constructor({ syncedStore, storyStore }) {
this._syncedStore = syncedStore;
this._storyStore = storyStore;
}
storiesOf(kind, m) {
if (m && m.hot) {
m.hot.dispose(() => {
this._storyStore.removeStoryKind(kind);
});
}
const decorators = [];
const api = {};
api.add = (storyName, getStory) => {
// Wrap the getStory function with each decorator. The first
// decorator will wrap the story function. The second will
// wrap the first decorator and so on.
const fn = decorators.reduce((decorated, decorator) => {
return () => decorator(decorated);
}, getStory);
// Add the fully decorated getStory function.
this._storyStore.addStory(kind, storyName, fn);
return api;
};
api.addDecorator = decorator => {
decorators.push(decorator);
return api;
};
return api;
}
action(name) {
const syncedStore = this._syncedStore;
return function (..._args) {
let args = Array.from(_args);
let { actions = [] } = syncedStore.getData();
// Remove events from the args. Otherwise, it creates a huge JSON string.
args = args.map(arg => {
if (typeof arg.preventDefault === 'function') {
return '[SyntheticEvent]';
}
return arg;
});
const id = ++idGenerator;
const data = { name, args };
actions = [{ data, id }].concat(actions);
// replace consecutive identical actions with single action having
// count equal to no. of those identical actions.
const formattedData = formatActionData(actions).slice(0, 10);
syncedStore.setData({ actions: formattedData });
};
}
linkTo(kind, story) {
const syncedStore = this._syncedStore;
return function (...args) {
const resolvedKind = typeof kind === 'function' ? kind(...args) : kind;
let resolvedStory;
if (story) {
resolvedStory = typeof story === 'function' ? story(...args) : story;
} else {
const { storyStore } = syncedStore.getData();
resolvedStory = storyStore
.find(item => item.kind === kind)
.stories[0];
}
syncedStore.setData({
selectedKind: resolvedKind,
selectedStory: resolvedStory,
});
};
}
}