/
render.js
94 lines (78 loc) · 2.06 KB
/
render.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
91
92
93
94
import { document } from 'global';
import { stripIndents } from 'common-tags';
let previousComponent = null;
function cleanUpPreviousStory() {
if (!previousComponent) {
return;
}
previousComponent.$destroy();
previousComponent = null;
}
function mountView({ Component, target, props, on, Wrapper, WrapperData }) {
let component;
if (Wrapper) {
const fragment = document.createDocumentFragment();
component = new Component({ target: fragment, props });
const wrapper = new Wrapper({
target,
slots: { default: fragment },
props: WrapperData || {},
});
component.$on('destroy', () => {
wrapper.$destroy(true);
});
} else {
component = new Component({ target, props });
}
if (on) {
// Attach svelte event listeners.
Object.keys(on).forEach(eventName => {
component.$on(eventName, on[eventName]);
});
}
previousComponent = component;
}
export default function render({
storyFn,
selectedKind,
selectedStory,
showMain,
showError,
// showException,
}) {
const {
/** @type {SvelteComponent} */
Component,
/** @type {any} */
props,
/** @type {{[string]: () => {}}} Attach svelte event handlers */
on,
Wrapper,
WrapperData,
} = storyFn();
cleanUpPreviousStory();
const DefaultCompatComponent = Component ? Component.default || Component : undefined;
const DefaultCompatWrapper = Wrapper ? Wrapper.default || Wrapper : undefined;
if (!DefaultCompatComponent) {
showError({
title: `Expecting a Svelte component from the story: "${selectedStory}" of "${selectedKind}".`,
description: stripIndents`
Did you forget to return the Svelte component configuration from the story?
Use "() => ({ Component: YourComponent, data: {} })"
when defining the story.
`,
});
return;
}
const target = document.getElementById('root');
target.innerHTML = '';
mountView({
Component: DefaultCompatComponent,
target,
props,
on,
Wrapper: DefaultCompatWrapper,
WrapperData,
});
showMain();
}