/
sourceDecorator.ts
236 lines (194 loc) · 6.71 KB
/
sourceDecorator.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
/* eslint no-underscore-dangle: ["error", { "allow": ["_vnode"] }] */
import { addons, StoryContext } from '@storybook/addons';
import { logger } from '@storybook/client-logger';
import prettier from 'prettier/standalone';
import prettierHtml from 'prettier/parser-html';
import Vue from 'vue';
import { SourceType, SNIPPET_RENDERED } from '../../shared';
export const skipSourceRender = (context: StoryContext) => {
const sourceParams = context?.parameters.docs?.source;
const isArgsStory = context?.parameters.__isArgsStory;
// always render if the user forces it
if (sourceParams?.type === SourceType.DYNAMIC) {
return false;
}
// never render if the user is forcing the block to render code, or
// if the user provides code, or if it's not an args story.
return !isArgsStory || sourceParams?.code || sourceParams?.type === SourceType.CODE;
};
export const sourceDecorator = (storyFn: any, context: StoryContext) => {
const story = storyFn();
// See ../react/jsxDecorator.tsx
if (skipSourceRender(context)) {
return story;
}
try {
// Creating a Vue instance each time is very costly. But we need to do it
// in order to access VNode, otherwise vm.$vnode will be undefined.
// Also, I couldn't see any notable difference from the implementation with
// per-story-cache.
// But if there is a more performant way, we should replace it with that ASAP.
const vm = new Vue({
data() {
return {
STORYBOOK_VALUES: context.args,
};
},
render(h) {
return h(story);
},
}).$mount();
const channel = addons.getChannel();
const storyComponent = getStoryComponent(story.options.STORYBOOK_WRAPS);
const storyNode = lookupStoryInstance(vm, storyComponent);
const code = vnodeToString(storyNode._vnode);
channel.emit(
SNIPPET_RENDERED,
(context || {}).id,
prettier.format(`<template>${code}</template>`, {
parser: 'vue',
plugins: [prettierHtml],
// Because the parsed vnode missing spaces right before/after the surround tag,
// we always get weird wrapped code without this option.
htmlWhitespaceSensitivity: 'ignore',
})
);
} catch (e) {
logger.warn(`Failed to generate dynamic story source: ${e}`);
}
return story;
};
export function vnodeToString(vnode: Vue.VNode): string {
const attrString = [
...(vnode.data?.slot ? ([['slot', vnode.data.slot]] as [string, any][]) : []),
['class', stringifyClassAttribute(vnode)],
...(vnode.componentOptions?.propsData ? Object.entries(vnode.componentOptions.propsData) : []),
...(vnode.data?.attrs ? Object.entries(vnode.data.attrs) : []),
]
.filter(([name], index, list) => list.findIndex((item) => item[0] === name) === index)
.map(([name, value]) => stringifyAttr(name, value))
.filter(Boolean)
.join(' ');
if (!vnode.componentOptions) {
// Non-component elements (div, span, etc...)
if (vnode.tag) {
if (!vnode.children) {
return `<${vnode.tag} ${attrString}/>`;
}
return `<${vnode.tag} ${attrString}>${vnode.children.map(vnodeToString).join('')}</${
vnode.tag
}>`;
}
// TextNode
if (vnode.text) {
if (/[<>"&]/.test(vnode.text)) {
return `{{\`${vnode.text.replace(/`/g, '\\`')}\`}}`;
}
return vnode.text;
}
// Unknown
return '';
}
// Probably users never see the "unknown-component". It seems that vnode.tag
// is always set.
const tag = vnode.componentOptions.tag || vnode.tag || 'unknown-component';
if (!vnode.componentOptions.children) {
return `<${tag} ${attrString}/>`;
}
return `<${tag} ${attrString}>${vnode.componentOptions.children
.map(vnodeToString)
.join('')}</${tag}>`;
}
function stringifyClassAttribute(vnode: Vue.VNode): string | undefined {
if (!vnode.data || (!vnode.data.staticClass && !vnode.data.class)) {
return undefined;
}
return (
[...(vnode.data.staticClass?.split(' ') ?? []), ...normalizeClassBinding(vnode.data.class)]
.filter(Boolean)
.join(' ') || undefined
);
}
// https://vuejs.org/v2/guide/class-and-style.html#Binding-HTML-Classes
function normalizeClassBinding(binding: unknown): readonly string[] {
if (!binding) {
return [];
}
if (typeof binding === 'string') {
return [binding];
}
if (binding instanceof Array) {
// To handle an object-in-array binding smartly, we use recursion
return binding.map(normalizeClassBinding).reduce((a, b) => [...a, ...b], []);
}
if (typeof binding === 'object') {
return Object.entries(binding)
.filter(([, active]) => !!active)
.map(([className]) => className);
}
// Unknown class binding
return [];
}
function stringifyAttr(attrName: string, value?: any): string | null {
if (typeof value === 'undefined' || typeof value === 'function') {
return null;
}
if (value === true) {
return attrName;
}
if (typeof value === 'string') {
return `${attrName}=${quote(value)}`;
}
// TODO: Better serialization (unquoted object key, Symbol/Classes, etc...)
// Seems like Prettier don't format JSON-look object (= when keys are quoted)
return `:${attrName}=${quote(JSON.stringify(value))}`;
}
function quote(value: string) {
return value.includes(`"`) && !value.includes(`'`)
? `'${value}'`
: `"${value.replace(/"/g, '"')}"`;
}
/**
* Skip decorators and grab a story component itself.
* https://github.com/pocka/storybook-addon-vue-info/pull/113
*/
function getStoryComponent(w: any) {
let matched = w;
while (
matched &&
matched.options &&
matched.options.components &&
matched.options.components.story &&
matched.options.components.story.options &&
matched.options.components.story.options.STORYBOOK_WRAPS
) {
matched = matched.options.components.story.options.STORYBOOK_WRAPS;
}
return matched;
}
interface VueInternal {
// We need to access this private property, in order to grab the vnode of the
// component instead of the "vnode of the parent of the component".
// Probably it's safe to rely on this because vm.$vnode is a reference for this.
// https://github.com/vuejs/vue/issues/6070#issuecomment-314389883
_vnode: Vue.VNode;
}
/**
* Find the story's instance from VNode tree.
*/
function lookupStoryInstance(instance: Vue, storyComponent: any): (Vue & VueInternal) | null {
if (
instance.$vnode &&
instance.$vnode.componentOptions &&
instance.$vnode.componentOptions.Ctor === storyComponent
) {
return instance as Vue & VueInternal;
}
for (let i = 0, l = instance.$children.length; i < l; i += 1) {
const found = lookupStoryInstance(instance.$children[i], storyComponent);
if (found) {
return found;
}
}
return null;
}