-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
preview.js
62 lines (53 loc) · 1.57 KB
/
preview.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
import { document } from 'global';
import qs from 'qs';
import addons from '@storybook/addons';
import { SELECT_STORY, STORY_CHANGED } from '@storybook/core-events';
import EVENTS from './constants';
export const navigate = params => addons.getChannel().emit(SELECT_STORY, params);
const generateUrl = id => {
const { location } = document;
const query = qs.parse(location.search, { ignoreQueryPrefix: true });
return `${location.origin + location.pathname}?${qs.stringify(
{ ...query, id },
{ encode: false }
)}`;
};
const valueOrCall = args => value => (typeof value === 'function' ? value(...args) : value);
export const linkTo = (kind, story) => (...args) => {
const resolver = valueOrCall(args);
navigate({
kind: resolver(kind),
story: resolver(story),
});
};
export const hrefTo = (kind, name) =>
new Promise(resolve => {
const channel = addons.getChannel();
channel.once(EVENTS.RECEIVE, id => resolve(generateUrl(id)));
channel.emit(EVENTS.REQUEST, { kind, name });
});
const linksListener = e => {
const { sbKind: kind, sbStory: story } = e.target.dataset;
if (kind || story) {
e.preventDefault();
navigate({ kind, story });
}
};
let hasListener = false;
const on = () => {
if (!hasListener) {
hasListener = true;
document.addEventListener('click', linksListener);
}
};
const off = () => {
if (hasListener) {
hasListener = false;
document.removeEventListener('click', linksListener);
}
};
export const withLinks = storyFn => {
on();
addons.getChannel().once(STORY_CHANGED, off);
return storyFn();
};