@sit-onyx/storybook-utils 1.0.0-beta.43 → 1.0.0-beta.45

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sit-onyx/storybook-utils",
3
3
  "description": "Storybook utilities for Vue",
4
- "version": "1.0.0-beta.43",
4
+ "version": "1.0.0-beta.45",
5
5
  "type": "module",
6
6
  "author": "Schwarz IT KG",
7
7
  "license": "Apache-2.0",
@@ -23,11 +23,11 @@
23
23
  "url": "https://github.com/SchwarzIT/onyx/issues"
24
24
  },
25
25
  "peerDependencies": {
26
- "@storybook/vue3": ">= 8.2.0",
27
- "storybook": ">= 8.2.0",
26
+ "@storybook/vue3": ">= 8.3.0-alpha.5",
27
+ "storybook": ">= 8.3.0-alpha.5",
28
28
  "storybook-dark-mode": ">= 4",
29
- "@sit-onyx/icons": "^1.0.0-beta.1",
30
- "sit-onyx": "^1.0.0-beta.40"
29
+ "@sit-onyx/icons": "^1.0.0-beta.2",
30
+ "sit-onyx": "^1.0.0-beta.41"
31
31
  },
32
32
  "dependencies": {
33
33
  "deepmerge-ts": "^7.1.0"
@@ -1,25 +1,19 @@
1
1
  import bellRing from "@sit-onyx/icons/bell-ring.svg?raw";
2
2
  import calendar from "@sit-onyx/icons/calendar.svg?raw";
3
3
  import placeholder from "@sit-onyx/icons/placeholder.svg?raw";
4
- import { describe, expect, test, vi } from "vitest";
4
+ import { describe, expect, test } from "vitest";
5
5
  import { replaceAll, sourceCodeTransformer } from "./preview";
6
- import * as sourceCodeGenerator from "./source-code-generator";
7
6
 
8
7
  describe("preview.ts", () => {
9
8
  test("should transform source code and add icon/onyx imports", () => {
10
- // ARRANGE
11
- const generatorSpy = vi.spyOn(sourceCodeGenerator, "generateSourceCode")
12
- .mockReturnValue(`<template>
9
+ // ACT
10
+ const sourceCode = sourceCodeTransformer(`<template>
13
11
  <OnyxTest icon='${placeholder}' test='${bellRing}' :obj="{foo:'${replaceAll(calendar, '"', "\\'")}'}" />
14
12
  <OnyxOtherComponent />
15
13
  <OnyxComp>Test</OnyxComp>
16
14
  </template>`);
17
15
 
18
- // ACT
19
- const sourceCode = sourceCodeTransformer("", { title: "OnyxTest", args: {} });
20
-
21
16
  // ASSERT
22
- expect(generatorSpy).toHaveBeenCalledOnce();
23
17
  expect(sourceCode).toBe(`<script lang="ts" setup>
24
18
  import { OnyxComp, OnyxOtherComponent, OnyxTest } from "sit-onyx";
25
19
  import bellRing from "@sit-onyx/icons/bell-ring.svg?raw";
package/src/preview.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getIconImportName } from "@sit-onyx/icons";
2
- import { type Preview, type StoryContext } from "@storybook/vue3";
2
+ import type { Preview } from "@storybook/vue3";
3
3
  import { deepmerge } from "deepmerge-ts";
4
4
  import { DARK_MODE_EVENT_NAME } from "storybook-dark-mode";
5
5
  import { DOCS_RENDERED } from "storybook/internal/core-events";
@@ -7,7 +7,6 @@ import { addons } from "storybook/internal/preview-api";
7
7
  import type { ThemeVars } from "storybook/internal/theming";
8
8
  import { enhanceEventArgTypes } from "./actions";
9
9
  import { requiredGlobalType, withRequired } from "./required";
10
- import { generateSourceCode } from "./source-code-generator";
11
10
  import { ONYX_BREAKPOINTS, createTheme } from "./theme";
12
11
 
13
12
  const themes = {
@@ -126,16 +125,15 @@ export const createPreview = <T extends Preview = Preview>(overrides?: T) => {
126
125
  *
127
126
  * @see https://storybook.js.org/docs/react/api/doc-block-source
128
127
  */
129
- export const sourceCodeTransformer = (
130
- sourceCode: string,
131
- ctx: Pick<StoryContext, "title" | "component" | "args">,
132
- ): string => {
128
+ export const sourceCodeTransformer = (originalSourceCode: string): string => {
133
129
  const RAW_ICONS = import.meta.glob("../node_modules/@sit-onyx/icons/src/assets/*.svg", {
134
130
  query: "?raw",
135
131
  import: "default",
136
132
  eager: true,
137
133
  });
138
134
 
135
+ let code = originalSourceCode;
136
+
139
137
  /**
140
138
  * Mapping between icon SVG content (key) and icon name (value).
141
139
  * Needed to display a labelled dropdown list of all available icons.
@@ -148,8 +146,6 @@ export const sourceCodeTransformer = (
148
146
  {},
149
147
  );
150
148
 
151
- let code = generateSourceCode(ctx);
152
-
153
149
  const additionalImports: string[] = [];
154
150
 
155
151
  // add icon imports to the source code for all used onyx icons
@@ -1,262 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-unused-vars */
2
- //
3
- // This file is only a temporary copy of the improved source code generation for Storybook.
4
- // It is intended to be deleted once its officially released in Storybook itself, see:
5
- // https://github.com/storybookjs/storybook/pull/27194
6
- //
7
- import { expect, test } from "vitest";
8
- import { h } from "vue";
9
- import {
10
- generatePropsSourceCode,
11
- generateSlotSourceCode,
12
- generateSourceCode,
13
- getFunctionParamNames,
14
- parseDocgenInfo,
15
- type SourceCodeGeneratorContext,
16
- } from "./source-code-generator";
17
-
18
- test("should generate source code for props", () => {
19
- const ctx: SourceCodeGeneratorContext = {
20
- scriptVariables: {},
21
- imports: {},
22
- };
23
-
24
- const code = generatePropsSourceCode(
25
- {
26
- a: "foo",
27
- b: '"I am double quoted"',
28
- c: 42,
29
- d: true,
30
- e: false,
31
- f: [1, 2, 3],
32
- g: {
33
- g1: "foo",
34
- g2: 42,
35
- },
36
- h: undefined,
37
- i: null,
38
- j: "",
39
- k: BigInt(9007199254740991),
40
- l: Symbol(),
41
- m: Symbol("foo"),
42
- modelValue: "test-v-model",
43
- otherModelValue: 42,
44
- default: "default slot",
45
- testSlot: "test slot",
46
- },
47
- ["default", "testSlot"],
48
- ["update:modelValue", "update:otherModelValue"],
49
- ctx,
50
- );
51
-
52
- expect(code).toBe(
53
- `a="foo" b='"I am double quoted"' :c="42" d :e="false" :f="f" :g="g" :k="BigInt(9007199254740991)" :l="Symbol()" :m="Symbol('foo')" v-model="modelValue" v-model:otherModelValue="otherModelValue"`,
54
- );
55
-
56
- expect(ctx.scriptVariables).toStrictEqual({
57
- f: `[1,2,3]`,
58
- g: `{"g1":"foo","g2":42}`,
59
- modelValue: 'ref("test-v-model")',
60
- otherModelValue: "ref(42)",
61
- });
62
-
63
- expect(Array.from(ctx.imports.vue.values())).toStrictEqual(["ref"]);
64
- });
65
-
66
- test("should generate source code for slots", () => {
67
- // slot code generator should support primitive values (string, number etc.)
68
- // but also VNodes (e.g. created using h()) so custom Vue components can also be used
69
- // inside slots with proper generated code
70
-
71
- const slots = {
72
- default: "default content",
73
- a: "a content",
74
- b: 42,
75
- c: true,
76
- // single VNode without props
77
- d: h("div", "d content"),
78
- // VNode with props and single child
79
- e: h("div", { style: "color:red" }, "e content"),
80
- // VNode with props and single child returned as getter
81
- f: h("div", { style: "color:red" }, () => "f content"),
82
- // VNode with multiple children
83
- g: h("div", { style: "color:red" }, [
84
- "child 1",
85
- h("span", { style: "color:green" }, "child 2"),
86
- ]),
87
- // VNode multiple children but returned as getter
88
- h: h("div", { style: "color:red" }, () => [
89
- "child 1",
90
- h("span", { style: "color:green" }, "child 2"),
91
- ]),
92
- // VNode with multiple and nested children
93
- i: h("div", { style: "color:red" }, [
94
- "child 1",
95
- h("span", { style: "color:green" }, ["nested child 1", h("p", "nested child 2")]),
96
- ]),
97
- j: ["child 1", "child 2"],
98
- k: null,
99
- l: { foo: "bar" },
100
- m: BigInt(9007199254740991),
101
- };
102
-
103
- const expectedCode = `default content
104
-
105
- <template #a>a content</template>
106
-
107
- <template #b>42</template>
108
-
109
- <template #c>true</template>
110
-
111
- <template #d><div>d content</div></template>
112
-
113
- <template #e><div style="color:red">e content</div></template>
114
-
115
- <template #f><div style="color:red">f content</div></template>
116
-
117
- <template #g><div style="color:red">child 1
118
- <span style="color:green">child 2</span></div></template>
119
-
120
- <template #h><div style="color:red">child 1
121
- <span style="color:green">child 2</span></div></template>
122
-
123
- <template #i><div style="color:red">child 1
124
- <span style="color:green">nested child 1
125
- <p>nested child 2</p></span></div></template>
126
-
127
- <template #j>child 1
128
- child 2</template>
129
-
130
- <template #l>{"foo":"bar"}</template>
131
-
132
- <template #m>{{ BigInt(9007199254740991) }}</template>`;
133
-
134
- let actualCode = generateSlotSourceCode(slots, Object.keys(slots), {
135
- scriptVariables: {},
136
- imports: {},
137
- });
138
- expect(actualCode).toBe(expectedCode);
139
-
140
- // should generate the same code if getters/functions are used to return the slot content
141
- const slotsWithGetters = Object.entries(slots).reduce<
142
- Record<string, () => (typeof slots)[keyof typeof slots]>
143
- >((obj, [slotName, value]) => {
144
- obj[slotName] = () => value;
145
- return obj;
146
- }, {});
147
-
148
- actualCode = generateSlotSourceCode(slotsWithGetters, Object.keys(slotsWithGetters), {
149
- scriptVariables: {},
150
- imports: {},
151
- });
152
- expect(actualCode).toBe(expectedCode);
153
- });
154
-
155
- test("should generate source code for slots with bindings", () => {
156
- type TestBindings = {
157
- foo: string;
158
- bar?: number;
159
- boo: {
160
- mimeType: string;
161
- };
162
- };
163
-
164
- const slots = {
165
- a: ({ foo, bar, boo }: TestBindings) => `Slot with bindings ${foo}, ${bar} and ${boo.mimeType}`,
166
- b: ({ foo, boo }: TestBindings) =>
167
- h("a", { href: foo, target: foo, type: boo.mimeType, ...boo }, `Test link: ${foo}`),
168
- };
169
-
170
- const expectedCode = `<template #a="{ foo, bar, boo }">Slot with bindings {{ foo }}, {{ bar }} and {{ boo.mimeType }}</template>
171
-
172
- <template #b="{ foo, boo }"><a :href="foo" :target="foo" :type="boo.mimeType" v-bind="boo">Test link: {{ foo }}</a></template>`;
173
-
174
- const actualCode = generateSlotSourceCode(slots, Object.keys(slots), {
175
- imports: {},
176
- scriptVariables: {},
177
- });
178
- expect(actualCode).toBe(expectedCode);
179
- });
180
-
181
- test("should generate source code with <script setup> block", () => {
182
- const actualCode = generateSourceCode({
183
- title: "MyComponent",
184
- component: {
185
- __docgenInfo: {
186
- slots: [{ name: "mySlot" }],
187
- events: [{ name: "update:c" }],
188
- },
189
- },
190
- args: {
191
- a: 42,
192
- b: "foo",
193
- c: [1, 2, 3],
194
- d: { bar: "baz" },
195
- mySlot: () => h("div", { test: [1, 2], d: { nestedProp: "foo" } }),
196
- },
197
- });
198
-
199
- expect(actualCode).toBe(`<script lang="ts" setup>
200
- import { ref } from "vue";
201
-
202
- const c = ref([1,2,3]);
203
-
204
- const d = {"bar":"baz"};
205
-
206
- const d1 = {"nestedProp":"foo"};
207
-
208
- const test = [1,2];
209
- </script>
210
-
211
- <template>
212
- <MyComponent :a="42" b="foo" v-model:c="c" :d="d"> <template #mySlot><div :d="d1" :test="test" /></template> </MyComponent>
213
- </template>`);
214
- });
215
-
216
- test.each([
217
- { __docgenInfo: "invalid-value", slotNames: [] },
218
- { __docgenInfo: {}, slotNames: [] },
219
- { __docgenInfo: { slots: "invalid-value" }, slotNames: [] },
220
- { __docgenInfo: { slots: ["invalid-value"] }, slotNames: [] },
221
- {
222
- __docgenInfo: { slots: [{ name: "slot-1" }, { name: "slot-2" }, { notName: "slot-3" }] },
223
- slotNames: ["slot-1", "slot-2"],
224
- },
225
- ])("should parse slots names from __docgenInfo", ({ __docgenInfo, slotNames }) => {
226
- const docgenInfo = parseDocgenInfo({ __docgenInfo });
227
- expect(docgenInfo.slotNames).toStrictEqual(slotNames);
228
- });
229
-
230
- test.each([
231
- { __docgenInfo: "invalid-value", eventNames: [] },
232
- { __docgenInfo: {}, eventNames: [] },
233
- { __docgenInfo: { events: "invalid-value" }, eventNames: [] },
234
- { __docgenInfo: { events: ["invalid-value"] }, eventNames: [] },
235
- {
236
- __docgenInfo: { events: [{ name: "event-1" }, { name: "event-2" }, { notName: "event-3" }] },
237
- eventNames: ["event-1", "event-2"],
238
- },
239
- ])("should parse event names from __docgenInfo", ({ __docgenInfo, eventNames }) => {
240
- const docgenInfo = parseDocgenInfo({ __docgenInfo });
241
- expect(docgenInfo.eventNames).toStrictEqual(eventNames);
242
- });
243
-
244
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
245
- test.each<{ fn: (...args: any[]) => unknown; expectedNames: string[] }>([
246
- { fn: () => ({}), expectedNames: [] },
247
- { fn: (a) => ({}), expectedNames: ["a"] },
248
- { fn: (a, b) => ({}), expectedNames: ["a", "b"] },
249
- { fn: (a, b, { c }) => ({}), expectedNames: ["a", "b", "{", "c", "}"] },
250
- { fn: ({ a, b }) => ({}), expectedNames: ["{", "a", "b", "}"] },
251
- {
252
- fn: {
253
- // simulate minified function after running "storybook build"
254
- toString: () => "({a:foo,b:bar})=>({})",
255
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
256
- } as (...args: any[]) => unknown,
257
- expectedNames: ["{", "a", "b", "}"],
258
- },
259
- ])("should extract function parameter names", ({ fn, expectedNames }) => {
260
- const paramNames = getFunctionParamNames(fn);
261
- expect(paramNames).toStrictEqual(expectedNames);
262
- });
@@ -1,592 +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
- * Used to get the tracking data from the proxy.
13
- * A symbol is unique, so when using it as a key it can't be accidentally accessed.
14
- */
15
- const TRACKING_SYMBOL = Symbol("DEEP_ACCESS_SYMBOL");
16
-
17
- type TrackingProxy = {
18
- [TRACKING_SYMBOL]: true;
19
- toString: () => string;
20
- };
21
-
22
- const isProxy = (obj: unknown): obj is TrackingProxy =>
23
- !!(obj && typeof obj === "object" && TRACKING_SYMBOL in obj);
24
-
25
- /**
26
- * Context that is passed down to nested components/slots when generating the source code for a single story.
27
- */
28
- export type SourceCodeGeneratorContext = {
29
- /**
30
- * Properties/variables that should be placed inside a `<script lang="ts" setup>` block.
31
- * Usually contains complex property values like objects and arrays.
32
- */
33
- scriptVariables: Record<string, string>;
34
- /**
35
- * Optional imports to add inside the `<script lang="ts" setup>` block.
36
- * e.g. to add 'import { ref } from "vue";'
37
- *
38
- * key = package name, values = imports
39
- */
40
- imports: Record<string, Set<string>>;
41
- };
42
-
43
- /**
44
- * Generate Vue source code for the given Story.
45
- * @returns Source code or empty string if source code could not be generated.
46
- */
47
- export const generateSourceCode = (
48
- ctx: Pick<StoryContext, "title" | "component" | "args"> & {
49
- component?: StoryContext["component"] & { __docgenInfo?: unknown };
50
- },
51
- ): string => {
52
- const sourceCodeContext: SourceCodeGeneratorContext = {
53
- imports: {},
54
- scriptVariables: {},
55
- };
56
-
57
- const { displayName, slotNames, eventNames } = parseDocgenInfo(ctx.component);
58
-
59
- const props = generatePropsSourceCode(ctx.args, slotNames, eventNames, sourceCodeContext);
60
- const slotSourceCode = generateSlotSourceCode(ctx.args, slotNames, sourceCodeContext);
61
- const componentName = displayName || ctx.title.split("/").at(-1)!;
62
-
63
- // prefer self closing tag if no slot content exists
64
- const templateCode = slotSourceCode
65
- ? `<${componentName} ${props}> ${slotSourceCode} </${componentName}>`
66
- : `<${componentName} ${props} />`;
67
-
68
- const variablesCode = Object.entries(sourceCodeContext.scriptVariables)
69
- .map(([name, value]) => `const ${name} = ${value};`)
70
- .join("\n\n");
71
-
72
- const importsCode = Object.entries(sourceCodeContext.imports)
73
- .map(([packageName, imports]) => {
74
- return `import { ${Array.from(imports.values()).sort().join(", ")} } from "${packageName}";`;
75
- })
76
- .join("\n");
77
-
78
- const template = `<template>\n ${templateCode}\n</template>`;
79
-
80
- if (!importsCode && !variablesCode) return template;
81
-
82
- return `<script lang="ts" setup>
83
- ${importsCode ? `${importsCode}\n\n${variablesCode}` : variablesCode}
84
- </script>
85
-
86
- ${template}`;
87
- };
88
-
89
- /**
90
- * Checks if the source code generation should be skipped for the given Story context.
91
- * Will be true if one of the following is true:
92
- * - view mode is not "docs"
93
- * - story is no arg story
94
- * - story has set custom source code via parameters.docs.source.code
95
- * - story has set source type to "code" via parameters.docs.source.type
96
- */
97
- export const shouldSkipSourceCodeGeneration = (context: StoryContext): boolean => {
98
- const sourceParams = context?.parameters.docs?.source;
99
- if (sourceParams?.type === SourceType.DYNAMIC) {
100
- // always render if the user forces it
101
- return false;
102
- }
103
-
104
- const isArgsStory = context?.parameters.__isArgsStory;
105
- const isDocsViewMode = context?.viewMode === "docs";
106
-
107
- // never render if the user is forcing the block to render code, or
108
- // if the user provides code, or if it's not an args story.
109
- return (
110
- !isDocsViewMode || !isArgsStory || sourceParams?.code || sourceParams?.type === SourceType.CODE
111
- );
112
- };
113
-
114
- /**
115
- * Parses the __docgenInfo of the given component.
116
- * Requires Storybook docs addon to be enabled.
117
- * Default slot will always be sorted first, remaining slots are sorted alphabetically.
118
- */
119
- export const parseDocgenInfo = (
120
- component?: StoryContext["component"] & { __docgenInfo?: unknown },
121
- ) => {
122
- // type check __docgenInfo to prevent errors
123
- if (
124
- !component ||
125
- !("__docgenInfo" in component) ||
126
- !component.__docgenInfo ||
127
- typeof component.__docgenInfo !== "object"
128
- ) {
129
- return {
130
- displayName: component?.__name,
131
- eventNames: [],
132
- slotNames: [],
133
- };
134
- }
135
-
136
- const docgenInfo = component.__docgenInfo as Record<string, unknown>;
137
-
138
- const displayName =
139
- "displayName" in docgenInfo && typeof docgenInfo.displayName === "string"
140
- ? docgenInfo.displayName
141
- : undefined;
142
-
143
- const parseNames = (key: "slots" | "events") => {
144
- if (!(key in docgenInfo) || !Array.isArray(docgenInfo[key])) return [];
145
-
146
- const values = docgenInfo[key] as unknown[];
147
-
148
- return values
149
- .map((i) => (i && typeof i === "object" && "name" in i ? i.name : undefined))
150
- .filter((i): i is string => typeof i === "string");
151
- };
152
-
153
- return {
154
- displayName: displayName || component.__name,
155
- slotNames: parseNames("slots").sort((a, b) => {
156
- if (a === "default") return -1;
157
- if (b === "default") return 1;
158
- return a.localeCompare(b);
159
- }),
160
- eventNames: parseNames("events"),
161
- };
162
- };
163
-
164
- /**
165
- * Generates the source code for the given Vue component properties.
166
- * Props with complex values (objects and arrays) and v-models will be added to the ctx.scriptVariables because they should be
167
- * generated in a `<script lang="ts" setup>` block.
168
- *
169
- * @param args Story args / property values.
170
- * @param slotNames All slot names of the component. Needed to not generate code for args that are slots.
171
- * Can be extracted using `parseDocgenInfo()`.
172
- * @param eventNames All event names of the component. Needed to generate v-model properties. Can be extracted using `parseDocgenInfo()`.
173
- *
174
- * @example `:a="42" b="Hello World" v-model="modelValue" v-model:search="search"`
175
- */
176
- export const generatePropsSourceCode = (
177
- args: Record<string, unknown>,
178
- slotNames: string[],
179
- eventNames: string[],
180
- ctx: SourceCodeGeneratorContext,
181
- ) => {
182
- type Property = {
183
- /** Property name */
184
- name: string;
185
- /** Stringified property value */
186
- value: string;
187
- /**
188
- * Function that returns the source code when used inside the `<template>`.
189
- * If unset, the property will be generated inside the `<script lang="ts" setup>` block.
190
- */
191
- templateFn?: (name: string, value: string) => string;
192
- };
193
-
194
- const properties: Property[] = [];
195
-
196
- Object.entries(args).forEach(([propName, value]) => {
197
- // ignore slots
198
- if (slotNames.includes(propName)) return;
199
- if (value == undefined) return; // do not render undefined/null values
200
-
201
- if (isProxy(value)) {
202
- value = value!.toString();
203
- }
204
-
205
- switch (typeof value) {
206
- case "string":
207
- if (value === "") return; // do not render empty strings
208
-
209
- properties.push({
210
- name: propName,
211
- value: value.includes('"') ? `'${value}'` : `"${value}"`,
212
- templateFn: (name, propValue) => `${name}=${propValue}`,
213
- });
214
- break;
215
- case "number":
216
- properties.push({
217
- name: propName,
218
- value: value.toString(),
219
- templateFn: (name, propValue) => `:${name}="${propValue}"`,
220
- });
221
- break;
222
- case "bigint":
223
- properties.push({
224
- name: propName,
225
- value: `BigInt(${value.toString()})`,
226
- templateFn: (name, propValue) => `:${name}="${propValue}"`,
227
- });
228
- break;
229
- case "boolean":
230
- properties.push({
231
- name: propName,
232
- value: value ? "true" : "false",
233
- templateFn: (name, propValue) => (propValue === "true" ? name : `:${name}="false"`),
234
- });
235
- break;
236
- case "symbol":
237
- properties.push({
238
- name: propName,
239
- value: `Symbol(${value.description ? `'${value.description}'` : ""})`,
240
- templateFn: (name, propValue) => `:${name}="${propValue}"`,
241
- });
242
- break;
243
- case "object": {
244
- properties.push({
245
- name: propName,
246
- value: formatObject(value ?? {}),
247
- // to follow Vue best practices, complex values like object and arrays are
248
- // usually placed inside the <script setup> block instead of inlining them in the <template>
249
- templateFn: undefined,
250
- });
251
- break;
252
- }
253
- case "function":
254
- // TODO: check if functions should be rendered in source code
255
- break;
256
- }
257
- });
258
-
259
- properties.sort((a, b) => a.name.localeCompare(b.name));
260
-
261
- /**
262
- * List of generated source code for the props.
263
- * @example [':a="42"', 'b="Hello World"']
264
- */
265
- const props: string[] = [];
266
-
267
- // now that we have all props parsed, we will generate them either inside the `<script lang="ts" setup>` block
268
- // or inside the `<template>`.
269
- // we also make sure to render v-model properties accordingly (see https://vuejs.org/guide/components/v-model)
270
- properties.forEach((prop) => {
271
- const isVModel = eventNames.includes(`update:${prop.name}`);
272
-
273
- if (!isVModel && prop.templateFn) {
274
- props.push(prop.templateFn(prop.name, prop.value));
275
- return;
276
- }
277
-
278
- let variableName = prop.name;
279
-
280
- // a variable with the same name might already exist (e.g. from a parent component)
281
- // so we need to make sure to use a unique name here to not generate multiple variables with the same name
282
- if (variableName in ctx.scriptVariables) {
283
- let index = 1;
284
- do {
285
- variableName = `${prop.name}${index}`;
286
- index++;
287
- } while (variableName in ctx.scriptVariables);
288
- }
289
-
290
- if (!isVModel) {
291
- ctx.scriptVariables[variableName] = prop.value;
292
- props.push(`:${prop.name}="${variableName}"`);
293
- return;
294
- }
295
-
296
- // always generate v-models inside the `<script lang="ts" setup>` block
297
- ctx.scriptVariables[variableName] = `ref(${prop.value})`;
298
-
299
- if (!ctx.imports.vue) ctx.imports.vue = new Set();
300
- ctx.imports.vue.add("ref");
301
-
302
- if (prop.name === "modelValue") {
303
- props.push(`v-model="${variableName}"`);
304
- } else {
305
- props.push(`v-model:${prop.name}="${variableName}"`);
306
- }
307
- });
308
-
309
- return props.join(" ");
310
- };
311
-
312
- /**
313
- * Generates the source code for the given Vue component slots.
314
- * Supports primitive slot content (e.g. strings, numbers etc.) and nested components/VNodes (e.g. created using Vue's `h()` function).
315
- *
316
- * @param args Story args.
317
- * @param slotNames All slot names of the component. Needed to only generate slots and ignore props etc.
318
- * Can be extracted using `parseDocgenInfo()`.
319
- * @param ctx Context so complex props of nested slot children will be set in the ctx.scriptVariables.
320
- *
321
- * @example `<template #slotName="{ foo }">Content {{ foo }}</template>`
322
- */
323
- export const generateSlotSourceCode = (
324
- args: Args,
325
- slotNames: string[],
326
- ctx: SourceCodeGeneratorContext,
327
- ): string => {
328
- /** List of slot source codes (e.g. <template #slotName>Content</template>) */
329
- const slotSourceCodes: string[] = [];
330
-
331
- slotNames.forEach((slotName) => {
332
- const arg = args[slotName];
333
- if (!arg) return;
334
-
335
- const slotContent = generateSlotChildrenSourceCode([arg], ctx);
336
- if (!slotContent) return; // do not generate source code for empty slots
337
-
338
- const slotBindings = typeof arg === "function" ? getFunctionParamNames(arg) : [];
339
-
340
- if (slotName === "default" && !slotBindings.length) {
341
- // do not add unnecessary "<template #default>" tag since the default slot content without bindings
342
- // can be put directly into the slot without need of "<template #default>"
343
- slotSourceCodes.push(slotContent);
344
- } else {
345
- slotSourceCodes.push(
346
- `<template ${slotBindingsToString(slotName, slotBindings)}>${slotContent}</template>`,
347
- );
348
- }
349
- });
350
-
351
- return slotSourceCodes.join("\n\n");
352
- };
353
-
354
- /**
355
- * Generates the source code for the given slot children (the code inside <template #slotName></template>).
356
- */
357
- const generateSlotChildrenSourceCode = (
358
- children: unknown[],
359
- ctx: SourceCodeGeneratorContext,
360
- ): string => {
361
- const slotChildrenSourceCodes: string[] = [];
362
-
363
- /**
364
- * Recursively generates the source code for a single slot child and all its children.
365
- * @returns Source code for child and all nested children or empty string if child is of a non-supported type.
366
- */
367
- const generateSingleChildSourceCode = (child: unknown): string => {
368
- if (isVNode(child)) {
369
- return generateVNodeSourceCode(child, ctx);
370
- }
371
-
372
- switch (typeof child) {
373
- case "string":
374
- case "number":
375
- case "boolean":
376
- return child.toString();
377
-
378
- case "object":
379
- if (child === null) return "";
380
- if (Array.isArray(child)) {
381
- // if child also has children, we generate them recursively
382
- return child
383
- .map(generateSingleChildSourceCode)
384
- .filter((code) => code !== "")
385
- .join("\n");
386
- }
387
- return JSON.stringify(child);
388
-
389
- case "function": {
390
- const paramNames = getFunctionParamNames(child).filter(
391
- (param) => !["{", "}"].includes(param),
392
- );
393
-
394
- // We create proxy to track how and which properties of a parameter are accessed
395
- const parameters: Record<string, string> = {};
396
- const proxied: Record<string, TrackingProxy> = {};
397
- paramNames.forEach((param) => {
398
- parameters[param] = `{{ ${param} }}`;
399
- // TODO: we should be able to extend the proxy logic here and maybe get rid of the `generatePropsSourceCode` code
400
- proxied[param] = new Proxy(
401
- {
402
- // we use the symbol to identify the proxy
403
- [TRACKING_SYMBOL]: true,
404
- } as TrackingProxy,
405
- {
406
- // getter is called when any prop of the parameter is read
407
- get: (t, key) => {
408
- if (key === TRACKING_SYMBOL) {
409
- // allow retrieval of the tracking data
410
- return t[TRACKING_SYMBOL];
411
- }
412
- if ([Symbol.toPrimitive, Symbol.toStringTag, "toString"].includes(key)) {
413
- // when the parameter is used as a string we return the parameter name
414
- // we use the double brace notation as we don't know if the parameter is used in text or in a binding
415
- return () => `{{ ${param} }}`;
416
- }
417
- if (key === "v-bind") {
418
- // if this key is returned we just return the parameter name
419
- return `${param}`;
420
- }
421
- // otherwise a specific key of the parameter was accessed
422
- // we use the double brace notation as we don't know if the parameter is used in text or in a binding
423
- return `{{ ${param}.${key.toString()} }}`;
424
- },
425
- // ownKeys is called, among other uses, when an object is destructured
426
- // in this case we assume the parameter is supposed to be bound using "v-bind"
427
- // Therefore we only return one special key "v-bind" and the getter will be called afterwards with it
428
- ownKeys: () => {
429
- return [`v-bind`];
430
- },
431
- /** called when destructured */
432
- getOwnPropertyDescriptor: () => ({
433
- configurable: true,
434
- enumerable: true,
435
- value: param,
436
- writable: true,
437
- }),
438
- },
439
- );
440
- });
441
-
442
- const returnValue = child(proxied);
443
- const slotSourceCode = generateSlotChildrenSourceCode([returnValue], ctx);
444
-
445
- // if slot bindings are used for properties of other components, our {{ paramName }} is incorrect because
446
- // it would generate e.g. my-prop="{{ paramName }}", therefore, we replace it here to e.g. :my-prop="paramName"
447
- return replaceAll(slotSourceCode, / (\S+)="{{ (\S+) }}"/g, ` :$1="$2"`);
448
- }
449
-
450
- case "bigint":
451
- return `{{ BigInt(${child.toString()}) }}`;
452
-
453
- // the only missing case here is "symbol"
454
- // because rendering a symbol as slot / HTML does not make sense and is not supported by Vue
455
- default:
456
- return "";
457
- }
458
- };
459
-
460
- children.forEach((child) => {
461
- const sourceCode = generateSingleChildSourceCode(child);
462
- if (sourceCode !== "") slotChildrenSourceCodes.push(sourceCode);
463
- });
464
-
465
- return slotChildrenSourceCodes.join("\n");
466
- };
467
-
468
- /**
469
- * Generates source code for the given VNode and all its children (e.g. created using `h(MyComponent)` or `h("div")`).
470
- */
471
- const generateVNodeSourceCode = (vnode: VNode, ctx: SourceCodeGeneratorContext): string => {
472
- const componentName = getVNodeName(vnode);
473
- let childrenCode = "";
474
-
475
- if (typeof vnode.children === "string") {
476
- childrenCode = vnode.children;
477
- } else if (Array.isArray(vnode.children)) {
478
- childrenCode = generateSlotChildrenSourceCode(vnode.children, ctx);
479
- } else if (vnode.children) {
480
- // children are an object, just like if regular Story args where used
481
- // so we can generate the source code with the regular "generateSlotSourceCode()".
482
- childrenCode = generateSlotSourceCode(
483
- vnode.children,
484
- // $stable is a default property in vnode.children so we need to filter it out
485
- // to not generate source code for it
486
- Object.keys(vnode.children).filter((i) => i !== "$stable"),
487
- ctx,
488
- );
489
- }
490
-
491
- const props = vnode.props ? generatePropsSourceCode(vnode.props, [], [], ctx) : "";
492
-
493
- // prefer self closing tag if no children exist
494
- if (childrenCode) {
495
- return `<${componentName}${props ? ` ${props}` : ""}>${childrenCode}</${componentName}>`;
496
- }
497
- return `<${componentName}${props ? ` ${props}` : ""} />`;
498
- };
499
-
500
- /**
501
- * Gets the name for the given VNode.
502
- * Will return "component" if name could not be extracted.
503
- *
504
- * @example "div" for `h("div")` or "MyComponent" for `h(MyComponent)`
505
- */
506
- const getVNodeName = (vnode: VNode) => {
507
- // this is e.g. the case when rendering native HTML elements like, h("div")
508
- if (typeof vnode.type === "string") return vnode.type;
509
-
510
- if (typeof vnode.type === "object") {
511
- // this is the case when using custom Vue components like h(MyComponent)
512
- if ("name" in vnode.type && vnode.type.name) {
513
- // prefer custom component name set by the developer
514
- return vnode.type.name;
515
- } else if ("__name" in vnode.type && vnode.type.__name) {
516
- // otherwise use name inferred by Vue from the file name
517
- return vnode.type.__name;
518
- }
519
- }
520
-
521
- return "component";
522
- };
523
-
524
- /**
525
- * Gets a list of parameters for the given function since func.arguments can not be used since
526
- * it throws a TypeError.
527
- *
528
- * If the arguments are destructured (e.g. "func({ foo, bar })"), the returned array will also
529
- * include "{" and "}".
530
- *
531
- * @see Based on https://stackoverflow.com/a/9924463
532
- */
533
- // eslint-disable-next-line @typescript-eslint/ban-types
534
- export const getFunctionParamNames = (func: Function): string[] => {
535
- const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;
536
- const ARGUMENT_NAMES = /([^\s,]+)/g;
537
-
538
- const fnStr = func.toString().replace(STRIP_COMMENTS, "");
539
- const result = fnStr.slice(fnStr.indexOf("(") + 1, fnStr.indexOf(")")).match(ARGUMENT_NAMES);
540
- if (!result) return [];
541
-
542
- // when running "storybook build", the function will be minified, so result for e.g.
543
- // `({ foo, bar }) => { // function body }` will be `["{foo:e", "bar:a}"]`
544
- // therefore we need to remove the :e and :a mappings and extract the "{" and "}"" from the destructured object
545
- // so the final result becomes `["{", "foo", "bar", "}"]`
546
- return result.flatMap((param) => {
547
- if (["{", "}"].includes(param)) return param;
548
- const nonMinifiedName = param.split(":")[0].trim();
549
- if (nonMinifiedName.startsWith("{")) {
550
- return ["{", nonMinifiedName.substring(1)];
551
- }
552
- if (param.endsWith("}") && !nonMinifiedName.endsWith("}")) {
553
- return [nonMinifiedName, "}"];
554
- }
555
- return nonMinifiedName;
556
- });
557
- };
558
-
559
- /**
560
- * Converts the given slot bindings/parameters to a string.
561
- *
562
- * @example
563
- * If no params: '#slotName'
564
- * If params: '#slotName="{ foo, bar }"'
565
- */
566
- const slotBindingsToString = (
567
- slotName: string,
568
- params: string[],
569
- ): `#${string}` | `#${string}="${string}"` => {
570
- if (!params.length) return `#${slotName}`;
571
- if (params.length === 1) return `#${slotName}="${params[0]}"`;
572
-
573
- // parameters might be destructured so remove duplicated brackets here
574
- return `#${slotName}="{ ${params.filter((i) => !["{", "}"].includes(i)).join(", ")} }"`;
575
- };
576
-
577
- /**
578
- * Formats the given object as string.
579
- * Will format in single line if it only contains non-object values.
580
- * Otherwise will format multiline.
581
- */
582
- export const formatObject = (obj: object): string => {
583
- const isPrimitive = Object.values(obj).every(
584
- (value) => value == null || typeof value !== "object",
585
- );
586
-
587
- // if object/array only contains non-object values, we format all values in one line
588
- if (isPrimitive) return JSON.stringify(obj);
589
-
590
- // otherwise, we use a "pretty" formatting with newlines and spaces
591
- return JSON.stringify(obj, null, 2);
592
- };