@sit-onyx/storybook-utils 1.0.0-beta.9 → 1.0.0-beta.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -5
- package/package.json +18 -9
- package/src/actions.spec.ts +29 -0
- package/src/actions.ts +113 -54
- package/src/events.ts +777 -0
- package/src/index.ts +1 -0
- package/src/preview.spec.ts +3 -9
- package/src/preview.ts +34 -20
- package/src/required.ts +0 -1
- package/src/sbType.spec.ts +38 -0
- package/src/sbType.ts +104 -0
- package/src/style.css +161 -0
- package/src/theme.ts +33 -26
- package/src/types.ts +1 -49
- package/src/assets/logo-onyx.svg +0 -51
- package/src/index.css +0 -26
- package/src/source-code-generator.spec.ts +0 -258
- package/src/source-code-generator.ts +0 -539
|
@@ -1,539 +0,0 @@
|
|
|
1
|
-
//
|
|
2
|
-
// This file is only a temporary copy of the improved source code generation for Storybook.
|
|
3
|
-
// It is intended to be deleted once its officially released in Storybook itself, see:
|
|
4
|
-
// https://github.com/storybookjs/storybook/pull/27194
|
|
5
|
-
//
|
|
6
|
-
import type { Args, StoryContext } from "@storybook/vue3";
|
|
7
|
-
import { SourceType } from "storybook/internal/docs-tools";
|
|
8
|
-
import { isVNode, type VNode } from "vue";
|
|
9
|
-
import { replaceAll } from "./preview";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Context that is passed down to nested components/slots when generating the source code for a single story.
|
|
13
|
-
*/
|
|
14
|
-
export type SourceCodeGeneratorContext = {
|
|
15
|
-
/**
|
|
16
|
-
* Properties/variables that should be placed inside a `<script lang="ts" setup>` block.
|
|
17
|
-
* Usually contains complex property values like objects and arrays.
|
|
18
|
-
*/
|
|
19
|
-
scriptVariables: Record<string, string>;
|
|
20
|
-
/**
|
|
21
|
-
* Optional imports to add inside the `<script lang="ts" setup>` block.
|
|
22
|
-
* e.g. to add 'import { ref } from "vue";'
|
|
23
|
-
*
|
|
24
|
-
* key = package name, values = imports
|
|
25
|
-
*/
|
|
26
|
-
imports: Record<string, Set<string>>;
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Generate Vue source code for the given Story.
|
|
31
|
-
* @returns Source code or empty string if source code could not be generated.
|
|
32
|
-
*/
|
|
33
|
-
export const generateSourceCode = (
|
|
34
|
-
ctx: Pick<StoryContext, "title" | "component" | "args"> & {
|
|
35
|
-
component?: StoryContext["component"] & { __docgenInfo?: unknown };
|
|
36
|
-
},
|
|
37
|
-
): string => {
|
|
38
|
-
const sourceCodeContext: SourceCodeGeneratorContext = {
|
|
39
|
-
imports: {},
|
|
40
|
-
scriptVariables: {},
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
const { displayName, slotNames, eventNames } = parseDocgenInfo(ctx.component);
|
|
44
|
-
|
|
45
|
-
const props = generatePropsSourceCode(ctx.args, slotNames, eventNames, sourceCodeContext);
|
|
46
|
-
const slotSourceCode = generateSlotSourceCode(ctx.args, slotNames, sourceCodeContext);
|
|
47
|
-
const componentName = displayName || ctx.title.split("/").at(-1)!;
|
|
48
|
-
|
|
49
|
-
// prefer self closing tag if no slot content exists
|
|
50
|
-
const templateCode = slotSourceCode
|
|
51
|
-
? `<${componentName} ${props}> ${slotSourceCode} </${componentName}>`
|
|
52
|
-
: `<${componentName} ${props} />`;
|
|
53
|
-
|
|
54
|
-
const variablesCode = Object.entries(sourceCodeContext.scriptVariables)
|
|
55
|
-
.map(([name, value]) => `const ${name} = ${value};`)
|
|
56
|
-
.join("\n\n");
|
|
57
|
-
|
|
58
|
-
const importsCode = Object.entries(sourceCodeContext.imports)
|
|
59
|
-
.map(([packageName, imports]) => {
|
|
60
|
-
return `import { ${Array.from(imports.values()).sort().join(", ")} } from "${packageName}";`;
|
|
61
|
-
})
|
|
62
|
-
.join("\n");
|
|
63
|
-
|
|
64
|
-
const template = `<template>\n ${templateCode}\n</template>`;
|
|
65
|
-
|
|
66
|
-
if (!importsCode && !variablesCode) return template;
|
|
67
|
-
|
|
68
|
-
return `<script lang="ts" setup>
|
|
69
|
-
${importsCode ? `${importsCode}\n\n${variablesCode}` : variablesCode}
|
|
70
|
-
</script>
|
|
71
|
-
|
|
72
|
-
${template}`;
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Checks if the source code generation should be skipped for the given Story context.
|
|
77
|
-
* Will be true if one of the following is true:
|
|
78
|
-
* - view mode is not "docs"
|
|
79
|
-
* - story is no arg story
|
|
80
|
-
* - story has set custom source code via parameters.docs.source.code
|
|
81
|
-
* - story has set source type to "code" via parameters.docs.source.type
|
|
82
|
-
*/
|
|
83
|
-
export const shouldSkipSourceCodeGeneration = (context: StoryContext): boolean => {
|
|
84
|
-
const sourceParams = context?.parameters.docs?.source;
|
|
85
|
-
if (sourceParams?.type === SourceType.DYNAMIC) {
|
|
86
|
-
// always render if the user forces it
|
|
87
|
-
return false;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
const isArgsStory = context?.parameters.__isArgsStory;
|
|
91
|
-
const isDocsViewMode = context?.viewMode === "docs";
|
|
92
|
-
|
|
93
|
-
// never render if the user is forcing the block to render code, or
|
|
94
|
-
// if the user provides code, or if it's not an args story.
|
|
95
|
-
return (
|
|
96
|
-
!isDocsViewMode || !isArgsStory || sourceParams?.code || sourceParams?.type === SourceType.CODE
|
|
97
|
-
);
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Parses the __docgenInfo of the given component.
|
|
102
|
-
* Requires Storybook docs addon to be enabled.
|
|
103
|
-
* Default slot will always be sorted first, remaining slots are sorted alphabetically.
|
|
104
|
-
*/
|
|
105
|
-
export const parseDocgenInfo = (
|
|
106
|
-
component?: StoryContext["component"] & { __docgenInfo?: unknown },
|
|
107
|
-
) => {
|
|
108
|
-
// type check __docgenInfo to prevent errors
|
|
109
|
-
if (
|
|
110
|
-
!component ||
|
|
111
|
-
!("__docgenInfo" in component) ||
|
|
112
|
-
!component.__docgenInfo ||
|
|
113
|
-
typeof component.__docgenInfo !== "object"
|
|
114
|
-
) {
|
|
115
|
-
return {
|
|
116
|
-
displayName: component?.__name,
|
|
117
|
-
eventNames: [],
|
|
118
|
-
slotNames: [],
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const docgenInfo = component.__docgenInfo as Record<string, unknown>;
|
|
123
|
-
|
|
124
|
-
const displayName =
|
|
125
|
-
"displayName" in docgenInfo && typeof docgenInfo.displayName === "string"
|
|
126
|
-
? docgenInfo.displayName
|
|
127
|
-
: undefined;
|
|
128
|
-
|
|
129
|
-
const parseNames = (key: "slots" | "events") => {
|
|
130
|
-
if (!(key in docgenInfo) || !Array.isArray(docgenInfo[key])) return [];
|
|
131
|
-
|
|
132
|
-
const values = docgenInfo[key] as unknown[];
|
|
133
|
-
|
|
134
|
-
return values
|
|
135
|
-
.map((i) => (i && typeof i === "object" && "name" in i ? i.name : undefined))
|
|
136
|
-
.filter((i): i is string => typeof i === "string");
|
|
137
|
-
};
|
|
138
|
-
|
|
139
|
-
return {
|
|
140
|
-
displayName: displayName || component.__name,
|
|
141
|
-
slotNames: parseNames("slots").sort((a, b) => {
|
|
142
|
-
if (a === "default") return -1;
|
|
143
|
-
if (b === "default") return 1;
|
|
144
|
-
return a.localeCompare(b);
|
|
145
|
-
}),
|
|
146
|
-
eventNames: parseNames("events"),
|
|
147
|
-
};
|
|
148
|
-
};
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Generates the source code for the given Vue component properties.
|
|
152
|
-
* Props with complex values (objects and arrays) and v-models will be added to the ctx.scriptVariables because they should be
|
|
153
|
-
* generated in a `<script lang="ts" setup>` block.
|
|
154
|
-
*
|
|
155
|
-
* @param args Story args / property values.
|
|
156
|
-
* @param slotNames All slot names of the component. Needed to not generate code for args that are slots.
|
|
157
|
-
* Can be extracted using `parseDocgenInfo()`.
|
|
158
|
-
* @param eventNames All event names of the component. Needed to generate v-model properties. Can be extracted using `parseDocgenInfo()`.
|
|
159
|
-
*
|
|
160
|
-
* @example `:a="42" b="Hello World" v-model="modelValue" v-model:search="search"`
|
|
161
|
-
*/
|
|
162
|
-
export const generatePropsSourceCode = (
|
|
163
|
-
args: Record<string, unknown>,
|
|
164
|
-
slotNames: string[],
|
|
165
|
-
eventNames: string[],
|
|
166
|
-
ctx: SourceCodeGeneratorContext,
|
|
167
|
-
) => {
|
|
168
|
-
type Property = {
|
|
169
|
-
/** Property name */
|
|
170
|
-
name: string;
|
|
171
|
-
/** Stringified property value */
|
|
172
|
-
value: string;
|
|
173
|
-
/**
|
|
174
|
-
* Function that returns the source code when used inside the `<template>`.
|
|
175
|
-
* If unset, the property will be generated inside the `<script lang="ts" setup>` block.
|
|
176
|
-
*/
|
|
177
|
-
templateFn?: (name: string, value: string) => string;
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
const properties: Property[] = [];
|
|
181
|
-
|
|
182
|
-
Object.entries(args).forEach(([propName, value]) => {
|
|
183
|
-
// ignore slots
|
|
184
|
-
if (slotNames.includes(propName)) return;
|
|
185
|
-
if (value == undefined) return; // do not render undefined/null values
|
|
186
|
-
|
|
187
|
-
switch (typeof value) {
|
|
188
|
-
case "string":
|
|
189
|
-
if (value === "") return; // do not render empty strings
|
|
190
|
-
|
|
191
|
-
properties.push({
|
|
192
|
-
name: propName,
|
|
193
|
-
value: value.includes('"') ? `'${value}'` : `"${value}"`,
|
|
194
|
-
templateFn: (name, propValue) => `${name}=${propValue}`,
|
|
195
|
-
});
|
|
196
|
-
break;
|
|
197
|
-
case "number":
|
|
198
|
-
properties.push({
|
|
199
|
-
name: propName,
|
|
200
|
-
value: value.toString(),
|
|
201
|
-
templateFn: (name, propValue) => `:${name}="${propValue}"`,
|
|
202
|
-
});
|
|
203
|
-
break;
|
|
204
|
-
case "bigint":
|
|
205
|
-
properties.push({
|
|
206
|
-
name: propName,
|
|
207
|
-
value: `BigInt(${value.toString()})`,
|
|
208
|
-
templateFn: (name, propValue) => `:${name}="${propValue}"`,
|
|
209
|
-
});
|
|
210
|
-
break;
|
|
211
|
-
case "boolean":
|
|
212
|
-
properties.push({
|
|
213
|
-
name: propName,
|
|
214
|
-
value: value ? "true" : "false",
|
|
215
|
-
templateFn: (name, propValue) => (propValue === "true" ? name : `:${name}="false"`),
|
|
216
|
-
});
|
|
217
|
-
break;
|
|
218
|
-
case "symbol":
|
|
219
|
-
properties.push({
|
|
220
|
-
name: propName,
|
|
221
|
-
value: `Symbol(${value.description ? `'${value.description}'` : ""})`,
|
|
222
|
-
templateFn: (name, propValue) => `:${name}="${propValue}"`,
|
|
223
|
-
});
|
|
224
|
-
break;
|
|
225
|
-
case "object": {
|
|
226
|
-
properties.push({
|
|
227
|
-
name: propName,
|
|
228
|
-
value: formatObject(value),
|
|
229
|
-
// to follow Vue best practices, complex values like object and arrays are
|
|
230
|
-
// usually placed inside the <script setup> block instead of inlining them in the <template>
|
|
231
|
-
templateFn: undefined,
|
|
232
|
-
});
|
|
233
|
-
break;
|
|
234
|
-
}
|
|
235
|
-
case "function":
|
|
236
|
-
// TODO: check if functions should be rendered in source code
|
|
237
|
-
break;
|
|
238
|
-
}
|
|
239
|
-
});
|
|
240
|
-
|
|
241
|
-
properties.sort((a, b) => a.name.localeCompare(b.name));
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* List of generated source code for the props.
|
|
245
|
-
* @example [':a="42"', 'b="Hello World"']
|
|
246
|
-
*/
|
|
247
|
-
const props: string[] = [];
|
|
248
|
-
|
|
249
|
-
// now that we have all props parsed, we will generate them either inside the `<script lang="ts" setup>` block
|
|
250
|
-
// or inside the `<template>`.
|
|
251
|
-
// we also make sure to render v-model properties accordingly (see https://vuejs.org/guide/components/v-model)
|
|
252
|
-
properties.forEach((prop) => {
|
|
253
|
-
const isVModel = eventNames.includes(`update:${prop.name}`);
|
|
254
|
-
|
|
255
|
-
if (!isVModel && prop.templateFn) {
|
|
256
|
-
props.push(prop.templateFn(prop.name, prop.value));
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
let variableName = prop.name;
|
|
261
|
-
|
|
262
|
-
// a variable with the same name might already exist (e.g. from a parent component)
|
|
263
|
-
// so we need to make sure to use a unique name here to not generate multiple variables with the same name
|
|
264
|
-
if (variableName in ctx.scriptVariables) {
|
|
265
|
-
let index = 1;
|
|
266
|
-
do {
|
|
267
|
-
variableName = `${prop.name}${index}`;
|
|
268
|
-
index++;
|
|
269
|
-
} while (variableName in ctx.scriptVariables);
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
if (!isVModel) {
|
|
273
|
-
ctx.scriptVariables[variableName] = prop.value;
|
|
274
|
-
props.push(`:${prop.name}="${variableName}"`);
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// always generate v-models inside the `<script lang="ts" setup>` block
|
|
279
|
-
ctx.scriptVariables[variableName] = `ref(${prop.value})`;
|
|
280
|
-
|
|
281
|
-
if (!ctx.imports.vue) ctx.imports.vue = new Set();
|
|
282
|
-
ctx.imports.vue.add("ref");
|
|
283
|
-
|
|
284
|
-
if (prop.name === "modelValue") {
|
|
285
|
-
props.push(`v-model="${variableName}"`);
|
|
286
|
-
} else {
|
|
287
|
-
props.push(`v-model:${prop.name}="${variableName}"`);
|
|
288
|
-
}
|
|
289
|
-
});
|
|
290
|
-
|
|
291
|
-
return props.join(" ");
|
|
292
|
-
};
|
|
293
|
-
|
|
294
|
-
/**
|
|
295
|
-
* Generates the source code for the given Vue component slots.
|
|
296
|
-
* Supports primitive slot content (e.g. strings, numbers etc.) and nested components/VNodes (e.g. created using Vue's `h()` function).
|
|
297
|
-
*
|
|
298
|
-
* @param args Story args.
|
|
299
|
-
* @param slotNames All slot names of the component. Needed to only generate slots and ignore props etc.
|
|
300
|
-
* Can be extracted using `parseDocgenInfo()`.
|
|
301
|
-
* @param ctx Context so complex props of nested slot children will be set in the ctx.scriptVariables.
|
|
302
|
-
*
|
|
303
|
-
* @example `<template #slotName="{ foo }">Content {{ foo }}</template>`
|
|
304
|
-
*/
|
|
305
|
-
export const generateSlotSourceCode = (
|
|
306
|
-
args: Args,
|
|
307
|
-
slotNames: string[],
|
|
308
|
-
ctx: SourceCodeGeneratorContext,
|
|
309
|
-
): string => {
|
|
310
|
-
/** List of slot source codes (e.g. <template #slotName>Content</template>) */
|
|
311
|
-
const slotSourceCodes: string[] = [];
|
|
312
|
-
|
|
313
|
-
slotNames.forEach((slotName) => {
|
|
314
|
-
const arg = args[slotName];
|
|
315
|
-
if (!arg) return;
|
|
316
|
-
|
|
317
|
-
const slotContent = generateSlotChildrenSourceCode([arg], ctx);
|
|
318
|
-
if (!slotContent) return; // do not generate source code for empty slots
|
|
319
|
-
|
|
320
|
-
const slotBindings = typeof arg === "function" ? getFunctionParamNames(arg) : [];
|
|
321
|
-
|
|
322
|
-
if (slotName === "default" && !slotBindings.length) {
|
|
323
|
-
// do not add unnecessary "<template #default>" tag since the default slot content without bindings
|
|
324
|
-
// can be put directly into the slot without need of "<template #default>"
|
|
325
|
-
slotSourceCodes.push(slotContent);
|
|
326
|
-
} else {
|
|
327
|
-
slotSourceCodes.push(
|
|
328
|
-
`<template ${slotBindingsToString(slotName, slotBindings)}>${slotContent}</template>`,
|
|
329
|
-
);
|
|
330
|
-
}
|
|
331
|
-
});
|
|
332
|
-
|
|
333
|
-
return slotSourceCodes.join("\n\n");
|
|
334
|
-
};
|
|
335
|
-
|
|
336
|
-
/**
|
|
337
|
-
* Generates the source code for the given slot children (the code inside <template #slotName></template>).
|
|
338
|
-
*/
|
|
339
|
-
const generateSlotChildrenSourceCode = (
|
|
340
|
-
children: unknown[],
|
|
341
|
-
ctx: SourceCodeGeneratorContext,
|
|
342
|
-
): string => {
|
|
343
|
-
const slotChildrenSourceCodes: string[] = [];
|
|
344
|
-
|
|
345
|
-
/**
|
|
346
|
-
* Recursively generates the source code for a single slot child and all its children.
|
|
347
|
-
* @returns Source code for child and all nested children or empty string if child is of a non-supported type.
|
|
348
|
-
*/
|
|
349
|
-
const generateSingleChildSourceCode = (child: unknown): string => {
|
|
350
|
-
if (isVNode(child)) {
|
|
351
|
-
return generateVNodeSourceCode(child, ctx);
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
switch (typeof child) {
|
|
355
|
-
case "string":
|
|
356
|
-
case "number":
|
|
357
|
-
case "boolean":
|
|
358
|
-
return child.toString();
|
|
359
|
-
|
|
360
|
-
case "object":
|
|
361
|
-
if (child === null) return "";
|
|
362
|
-
if (Array.isArray(child)) {
|
|
363
|
-
// if child also has children, we generate them recursively
|
|
364
|
-
return child
|
|
365
|
-
.map(generateSingleChildSourceCode)
|
|
366
|
-
.filter((code) => code !== "")
|
|
367
|
-
.join("\n");
|
|
368
|
-
}
|
|
369
|
-
return JSON.stringify(child);
|
|
370
|
-
|
|
371
|
-
case "function": {
|
|
372
|
-
const paramNames = getFunctionParamNames(child).filter(
|
|
373
|
-
(param) => !["{", "}"].includes(param),
|
|
374
|
-
);
|
|
375
|
-
|
|
376
|
-
const parameters = paramNames.reduce<Record<string, string>>((obj, param) => {
|
|
377
|
-
obj[param] = `{{ ${param} }}`;
|
|
378
|
-
return obj;
|
|
379
|
-
}, {});
|
|
380
|
-
|
|
381
|
-
const returnValue = child(parameters);
|
|
382
|
-
let slotSourceCode = generateSlotChildrenSourceCode([returnValue], ctx);
|
|
383
|
-
|
|
384
|
-
// if slot bindings are used for properties of other components, our {{ paramName }} is incorrect because
|
|
385
|
-
// it would generate e.g. my-prop="{{ paramName }}", therefore, we replace it here to e.g. :my-prop="paramName"
|
|
386
|
-
paramNames.forEach((param) => {
|
|
387
|
-
slotSourceCode = replaceAll(
|
|
388
|
-
slotSourceCode,
|
|
389
|
-
new RegExp(` (\\S+)="{{ ${param} }}"`, "g"),
|
|
390
|
-
` :$1="${param}"`,
|
|
391
|
-
);
|
|
392
|
-
});
|
|
393
|
-
|
|
394
|
-
return slotSourceCode;
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
case "bigint":
|
|
398
|
-
return `{{ BigInt(${child.toString()}) }}`;
|
|
399
|
-
|
|
400
|
-
// the only missing case here is "symbol"
|
|
401
|
-
// because rendering a symbol as slot / HTML does not make sense and is not supported by Vue
|
|
402
|
-
default:
|
|
403
|
-
return "";
|
|
404
|
-
}
|
|
405
|
-
};
|
|
406
|
-
|
|
407
|
-
children.forEach((child) => {
|
|
408
|
-
const sourceCode = generateSingleChildSourceCode(child);
|
|
409
|
-
if (sourceCode !== "") slotChildrenSourceCodes.push(sourceCode);
|
|
410
|
-
});
|
|
411
|
-
|
|
412
|
-
return slotChildrenSourceCodes.join("\n");
|
|
413
|
-
};
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* Generates source code for the given VNode and all its children (e.g. created using `h(MyComponent)` or `h("div")`).
|
|
417
|
-
*/
|
|
418
|
-
const generateVNodeSourceCode = (vnode: VNode, ctx: SourceCodeGeneratorContext): string => {
|
|
419
|
-
const componentName = getVNodeName(vnode);
|
|
420
|
-
let childrenCode = "";
|
|
421
|
-
|
|
422
|
-
if (typeof vnode.children === "string") {
|
|
423
|
-
childrenCode = vnode.children;
|
|
424
|
-
} else if (Array.isArray(vnode.children)) {
|
|
425
|
-
childrenCode = generateSlotChildrenSourceCode(vnode.children, ctx);
|
|
426
|
-
} else if (vnode.children) {
|
|
427
|
-
// children are an object, just like if regular Story args where used
|
|
428
|
-
// so we can generate the source code with the regular "generateSlotSourceCode()".
|
|
429
|
-
childrenCode = generateSlotSourceCode(
|
|
430
|
-
vnode.children,
|
|
431
|
-
// $stable is a default property in vnode.children so we need to filter it out
|
|
432
|
-
// to not generate source code for it
|
|
433
|
-
Object.keys(vnode.children).filter((i) => i !== "$stable"),
|
|
434
|
-
ctx,
|
|
435
|
-
);
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
const props = vnode.props ? generatePropsSourceCode(vnode.props, [], [], ctx) : "";
|
|
439
|
-
|
|
440
|
-
// prefer self closing tag if no children exist
|
|
441
|
-
if (childrenCode) {
|
|
442
|
-
return `<${componentName}${props ? ` ${props}` : ""}>${childrenCode}</${componentName}>`;
|
|
443
|
-
}
|
|
444
|
-
return `<${componentName}${props ? ` ${props}` : ""} />`;
|
|
445
|
-
};
|
|
446
|
-
|
|
447
|
-
/**
|
|
448
|
-
* Gets the name for the given VNode.
|
|
449
|
-
* Will return "component" if name could not be extracted.
|
|
450
|
-
*
|
|
451
|
-
* @example "div" for `h("div")` or "MyComponent" for `h(MyComponent)`
|
|
452
|
-
*/
|
|
453
|
-
const getVNodeName = (vnode: VNode) => {
|
|
454
|
-
// this is e.g. the case when rendering native HTML elements like, h("div")
|
|
455
|
-
if (typeof vnode.type === "string") return vnode.type;
|
|
456
|
-
|
|
457
|
-
if (typeof vnode.type === "object") {
|
|
458
|
-
// this is the case when using custom Vue components like h(MyComponent)
|
|
459
|
-
if ("name" in vnode.type && vnode.type.name) {
|
|
460
|
-
// prefer custom component name set by the developer
|
|
461
|
-
return vnode.type.name;
|
|
462
|
-
} else if ("__name" in vnode.type && vnode.type.__name) {
|
|
463
|
-
// otherwise use name inferred by Vue from the file name
|
|
464
|
-
return vnode.type.__name;
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
return "component";
|
|
469
|
-
};
|
|
470
|
-
|
|
471
|
-
/**
|
|
472
|
-
* Gets a list of parameters for the given function since func.arguments can not be used since
|
|
473
|
-
* it throws a TypeError.
|
|
474
|
-
*
|
|
475
|
-
* If the arguments are destructured (e.g. "func({ foo, bar })"), the returned array will also
|
|
476
|
-
* include "{" and "}".
|
|
477
|
-
*
|
|
478
|
-
* @see Based on https://stackoverflow.com/a/9924463
|
|
479
|
-
*/
|
|
480
|
-
// eslint-disable-next-line @typescript-eslint/ban-types
|
|
481
|
-
export const getFunctionParamNames = (func: Function): string[] => {
|
|
482
|
-
const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;
|
|
483
|
-
const ARGUMENT_NAMES = /([^\s,]+)/g;
|
|
484
|
-
|
|
485
|
-
const fnStr = func.toString().replace(STRIP_COMMENTS, "");
|
|
486
|
-
const result = fnStr.slice(fnStr.indexOf("(") + 1, fnStr.indexOf(")")).match(ARGUMENT_NAMES);
|
|
487
|
-
if (!result) return [];
|
|
488
|
-
|
|
489
|
-
// when running "storybook build", the function will be minified, so result for e.g.
|
|
490
|
-
// `({ foo, bar }) => { // function body }` will be `["{foo:e", "bar:a}"]`
|
|
491
|
-
// therefore we need to remove the :e and :a mappings and extract the "{" and "}"" from the destructured object
|
|
492
|
-
// so the final result becomes `["{", "foo", "bar", "}"]`
|
|
493
|
-
return result.flatMap((param) => {
|
|
494
|
-
if (["{", "}"].includes(param)) return param;
|
|
495
|
-
const nonMinifiedName = param.split(":")[0].trim();
|
|
496
|
-
if (nonMinifiedName.startsWith("{")) {
|
|
497
|
-
return ["{", nonMinifiedName.substring(1)];
|
|
498
|
-
}
|
|
499
|
-
if (param.endsWith("}") && !nonMinifiedName.endsWith("}")) {
|
|
500
|
-
return [nonMinifiedName, "}"];
|
|
501
|
-
}
|
|
502
|
-
return nonMinifiedName;
|
|
503
|
-
});
|
|
504
|
-
};
|
|
505
|
-
|
|
506
|
-
/**
|
|
507
|
-
* Converts the given slot bindings/parameters to a string.
|
|
508
|
-
*
|
|
509
|
-
* @example
|
|
510
|
-
* If no params: '#slotName'
|
|
511
|
-
* If params: '#slotName="{ foo, bar }"'
|
|
512
|
-
*/
|
|
513
|
-
const slotBindingsToString = (
|
|
514
|
-
slotName: string,
|
|
515
|
-
params: string[],
|
|
516
|
-
): `#${string}` | `#${string}="${string}"` => {
|
|
517
|
-
if (!params.length) return `#${slotName}`;
|
|
518
|
-
if (params.length === 1) return `#${slotName}="${params[0]}"`;
|
|
519
|
-
|
|
520
|
-
// parameters might be destructured so remove duplicated brackets here
|
|
521
|
-
return `#${slotName}="{ ${params.filter((i) => !["{", "}"].includes(i)).join(", ")} }"`;
|
|
522
|
-
};
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* Formats the given object as string.
|
|
526
|
-
* Will format in single line if it only contains non-object values.
|
|
527
|
-
* Otherwise will format multiline.
|
|
528
|
-
*/
|
|
529
|
-
export const formatObject = (obj: object): string => {
|
|
530
|
-
const isPrimitive = Object.values(obj).every(
|
|
531
|
-
(value) => value == null || typeof value !== "object",
|
|
532
|
-
);
|
|
533
|
-
|
|
534
|
-
// if object/array only contains non-object values, we format all values in one line
|
|
535
|
-
if (isPrimitive) return JSON.stringify(obj);
|
|
536
|
-
|
|
537
|
-
// otherwise, we use a "pretty" formatting with newlines and spaces
|
|
538
|
-
return JSON.stringify(obj, null, 2);
|
|
539
|
-
};
|