@fragments-sdk/cli 0.8.1 → 0.9.1
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/dist/bin.js +517 -77
- package/dist/bin.js.map +1 -1
- package/dist/{chunk-WI6SLMSO.js → chunk-5GT62FCB.js} +2 -2
- package/dist/{chunk-CJEGT3WD.js → chunk-BW3ZATBW.js} +20 -3
- package/dist/chunk-BW3ZATBW.js.map +1 -0
- package/dist/{chunk-2JIKCJX3.js → chunk-D7372LQX.js} +13 -6
- package/dist/chunk-D7372LQX.js.map +1 -0
- package/dist/chunk-EZYXYWNF.js +131 -0
- package/dist/chunk-EZYXYWNF.js.map +1 -0
- package/dist/{chunk-NGIMCIK2.js → chunk-GF6OVPIN.js} +2 -2
- package/dist/{chunk-GOVI6COW.js → chunk-NVSPGSKB.js} +12 -4
- package/dist/chunk-NVSPGSKB.js.map +1 -0
- package/dist/core/index.d.ts +105 -3
- package/dist/core/index.js +12 -2
- package/dist/{defineFragment-D0UTve-I.d.ts → defineFragment-CBMS7Bab.d.ts} +21 -1
- package/dist/generate-LQA2R7FN.js +461 -0
- package/dist/generate-LQA2R7FN.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -4
- package/dist/index.js.map +1 -1
- package/dist/{init-KFYN37ZY.js → init-2GEGVIUQ.js} +14 -76
- package/dist/init-2GEGVIUQ.js.map +1 -0
- package/dist/mcp-bin.js +4 -3
- package/dist/mcp-bin.js.map +1 -1
- package/dist/{scan-65RH3QMM.js → scan-JGS65S7P.js} +6 -5
- package/dist/{service-A5GIGGGK.js → service-XP2EAJXD.js} +4 -3
- package/dist/{static-viewer-NSODM5VX.js → static-viewer-XCS7UJTO.js} +4 -3
- package/dist/storyFilters-3LUYAFZF.js +15 -0
- package/dist/storyFilters-3LUYAFZF.js.map +1 -0
- package/dist/{test-RPWZAYSJ.js → test-TD6TJNVY.js} +3 -3
- package/dist/{tokens-NIXSZRX7.js → tokens-2EXPCVP3.js} +5 -4
- package/dist/{tokens-NIXSZRX7.js.map → tokens-2EXPCVP3.js.map} +1 -1
- package/dist/{viewer-HZK4BSDK.js → viewer-RFA2KVBG.js} +249 -22
- package/dist/viewer-RFA2KVBG.js.map +1 -0
- package/package.json +2 -2
- package/src/bin.ts +26 -0
- package/src/build.ts +12 -2
- package/src/commands/build.ts +16 -2
- package/src/commands/doctor.ts +498 -0
- package/src/commands/generate.ts +383 -68
- package/src/commands/init-framework.ts +1 -1
- package/src/commands/init.ts +9 -51
- package/src/core/config.ts +15 -2
- package/src/core/generators/typescript-extractor.ts +10 -0
- package/src/core/index.ts +15 -0
- package/src/core/schema.ts +10 -2
- package/src/core/storyFilters.test.ts +350 -0
- package/src/core/storyFilters.ts +253 -0
- package/src/core/types.ts +22 -0
- package/src/migrate/converter.ts +9 -1
- package/src/migrate/parser.ts +2 -0
- package/src/migrate/types.ts +2 -0
- package/src/setup.ts +69 -24
- package/src/viewer/__tests__/viewer-integration.test.ts +1 -1
- package/src/viewer/components/AccessibilityPanel.tsx +305 -312
- package/src/viewer/components/ActionsPanel.tsx +31 -29
- package/src/viewer/components/AllVariantsPreview.tsx +78 -0
- package/src/viewer/components/App.tsx +187 -740
- package/src/viewer/components/BottomPanel.tsx +228 -132
- package/src/viewer/components/CodePanel.tsx +1 -1
- package/src/viewer/components/CommandPalette.tsx +7 -10
- package/src/viewer/components/ComponentDocView.tsx +164 -0
- package/src/viewer/components/ComponentGraph.tsx +111 -142
- package/src/viewer/components/ContractPanel.tsx +6 -6
- package/src/viewer/components/EmptyVariantMessage.tsx +54 -0
- package/src/viewer/components/FigmaEmbed.tsx +20 -18
- package/src/viewer/components/FragmentEditor.tsx +92 -115
- package/src/viewer/components/HeaderSearch.tsx +24 -0
- package/src/viewer/components/HealthDashboard.tsx +16 -2
- package/src/viewer/components/Icons.tsx +9 -0
- package/src/viewer/components/InteractionsPanel.tsx +101 -117
- package/src/viewer/components/IsolatedPreviewFrame.tsx +1 -0
- package/src/viewer/components/LandingPage.tsx +3 -3
- package/src/viewer/components/LeftSidebar.tsx +141 -63
- package/src/viewer/components/LoadErrorMessage.tsx +102 -0
- package/src/viewer/components/MultiViewportPreview.tsx +61 -142
- package/src/viewer/components/NoVariantsMessage.tsx +59 -0
- package/src/viewer/components/PanelShell.tsx +161 -0
- package/src/viewer/components/PerformancePanel.tsx +31 -28
- package/src/viewer/components/PreviewArea.tsx +1 -1
- package/src/viewer/components/PreviewAside.tsx +168 -0
- package/src/viewer/components/PreviewFrameHost.tsx +3 -3
- package/src/viewer/components/PropsEditor.tsx +70 -156
- package/src/viewer/components/ResizablePanel.tsx +103 -263
- package/src/viewer/components/RightSidebar.tsx +3 -9
- package/src/viewer/components/SkeletonLoader.tsx +13 -13
- package/src/viewer/components/TokenStylePanel.tsx +182 -209
- package/src/viewer/components/TopToolbar.tsx +159 -0
- package/src/viewer/components/VariantMatrix.tsx +42 -86
- package/src/viewer/components/VariantTabs.tsx +3 -3
- package/src/viewer/components/ViewerHeader.tsx +69 -0
- package/src/viewer/components/WebMCPDevTools.tsx +17 -23
- package/src/viewer/components/viewer-utils.ts +16 -0
- package/src/viewer/entry.tsx +5 -0
- package/src/viewer/hooks/useAppState.ts +27 -4
- package/src/viewer/hooks/usePreviewBridge.ts +2 -2
- package/src/viewer/preview-frame.html +6 -12
- package/src/viewer/server.ts +184 -6
- package/src/viewer/vendor/shared/src/ComponentDocContent.module.scss +10 -0
- package/src/viewer/vendor/shared/src/ComponentDocContent.module.scss.d.ts +2 -0
- package/src/viewer/vendor/shared/src/ComponentDocContent.tsx +274 -0
- package/src/viewer/vendor/shared/src/DocsPageShell.tsx +5 -0
- package/src/viewer/vendor/shared/src/PropsTable.module.scss +68 -0
- package/src/viewer/vendor/shared/src/PropsTable.module.scss.d.ts +2 -0
- package/src/viewer/vendor/shared/src/PropsTable.tsx +76 -0
- package/src/viewer/vendor/shared/src/VariantPreviewCard.module.scss +122 -0
- package/src/viewer/vendor/shared/src/VariantPreviewCard.module.scss.d.ts +2 -0
- package/src/viewer/vendor/shared/src/VariantPreviewCard.tsx +134 -0
- package/src/viewer/vendor/shared/src/docs-data/index.ts +32 -0
- package/src/viewer/vendor/shared/src/docs-data/mcp-configs.ts +72 -0
- package/src/viewer/vendor/shared/src/docs-data/palettes.ts +75 -0
- package/src/viewer/vendor/shared/src/docs-data/setup-examples.ts +55 -0
- package/src/viewer/vendor/shared/src/index.ts +8 -0
- package/src/viewer/vendor/shared/src/types.ts +12 -0
- package/src/viewer/vite-plugin.ts +109 -4
- package/dist/chunk-2JIKCJX3.js.map +0 -1
- package/dist/chunk-CJEGT3WD.js.map +0 -1
- package/dist/chunk-GOVI6COW.js.map +0 -1
- package/dist/generate-35OIMW4Y.js +0 -252
- package/dist/generate-35OIMW4Y.js.map +0 -1
- package/dist/init-KFYN37ZY.js.map +0 -1
- package/dist/viewer-HZK4BSDK.js.map +0 -1
- /package/dist/{chunk-WI6SLMSO.js.map → chunk-5GT62FCB.js.map} +0 -0
- /package/dist/{chunk-NGIMCIK2.js.map → chunk-GF6OVPIN.js.map} +0 -0
- /package/dist/{scan-65RH3QMM.js.map → scan-JGS65S7P.js.map} +0 -0
- /package/dist/{service-A5GIGGGK.js.map → service-XP2EAJXD.js.map} +0 -0
- /package/dist/{static-viewer-NSODM5VX.js.map → static-viewer-XCS7UJTO.js.map} +0 -0
- /package/dist/{test-RPWZAYSJ.js.map → test-TD6TJNVY.js.map} +0 -0
package/src/commands/generate.ts
CHANGED
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* fragments generate -
|
|
2
|
+
* fragments generate - Generate fragment files from component source code
|
|
3
3
|
*
|
|
4
|
-
* Analyzes component source code and generates
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* - Generated description
|
|
4
|
+
* Analyzes component source code and generates proper defineFragment() TSX files
|
|
5
|
+
* colocated next to the component source. These files are parseable by the
|
|
6
|
+
* build command and renderable by the dev viewer.
|
|
8
7
|
*/
|
|
9
8
|
|
|
10
|
-
import { readFile, writeFile,
|
|
11
|
-
import { resolve,
|
|
9
|
+
import { readFile, writeFile, access } from "node:fs/promises";
|
|
10
|
+
import { resolve, basename, dirname, relative, join } from "node:path";
|
|
12
11
|
import pc from "picocolors";
|
|
13
12
|
import fg from "fast-glob";
|
|
14
|
-
import { BRAND
|
|
13
|
+
import { BRAND } from "../core/index.js";
|
|
15
14
|
import { extractPropsFromFile } from "../core/node.js";
|
|
16
15
|
|
|
17
16
|
export interface GenerateOptions {
|
|
@@ -43,10 +42,6 @@ export async function generate(options: GenerateOptions = {}): Promise<GenerateR
|
|
|
43
42
|
|
|
44
43
|
console.log(pc.cyan(`\n${BRAND.name} Generate\n`));
|
|
45
44
|
|
|
46
|
-
// Ensure .fragments/components directory exists
|
|
47
|
-
const fragmentsDir = join(projectRoot, BRAND.dataDir, BRAND.componentsDir);
|
|
48
|
-
await mkdir(fragmentsDir, { recursive: true });
|
|
49
|
-
|
|
50
45
|
// Find component files
|
|
51
46
|
const componentPattern =
|
|
52
47
|
options.componentPattern ||
|
|
@@ -73,15 +68,15 @@ export async function generate(options: GenerateOptions = {}): Promise<GenerateR
|
|
|
73
68
|
absolute: true,
|
|
74
69
|
});
|
|
75
70
|
|
|
76
|
-
// Build story map for pattern inference
|
|
77
|
-
const storyMap = new Map<string,
|
|
71
|
+
// Build story map for pattern inference (names + args)
|
|
72
|
+
const storyMap = new Map<string, StoryVariant[]>();
|
|
78
73
|
for (const storyFile of storyFiles) {
|
|
79
74
|
try {
|
|
80
75
|
const content = await readFile(storyFile, "utf-8");
|
|
81
76
|
const componentName = extractComponentNameFromStory(content, storyFile);
|
|
82
77
|
if (componentName) {
|
|
83
|
-
const
|
|
84
|
-
storyMap.set(componentName,
|
|
78
|
+
const variants = extractStoryVariants(content);
|
|
79
|
+
storyMap.set(componentName, variants);
|
|
85
80
|
}
|
|
86
81
|
} catch {
|
|
87
82
|
// Ignore parsing errors
|
|
@@ -106,8 +101,11 @@ export async function generate(options: GenerateOptions = {}): Promise<GenerateR
|
|
|
106
101
|
continue;
|
|
107
102
|
}
|
|
108
103
|
|
|
109
|
-
//
|
|
110
|
-
const
|
|
104
|
+
// Write fragment file colocated next to the component source
|
|
105
|
+
const componentDir = dirname(filePath);
|
|
106
|
+
const componentBaseName = basename(filePath, ".tsx");
|
|
107
|
+
const fragmentPath = join(componentDir, `${componentBaseName}${BRAND.fileExtension}`);
|
|
108
|
+
|
|
111
109
|
let fragmentExists = false;
|
|
112
110
|
try {
|
|
113
111
|
await access(fragmentPath);
|
|
@@ -122,16 +120,18 @@ export async function generate(options: GenerateOptions = {}): Promise<GenerateR
|
|
|
122
120
|
continue;
|
|
123
121
|
}
|
|
124
122
|
|
|
125
|
-
// Generate
|
|
126
|
-
const
|
|
123
|
+
// Generate proper defineFragment() TSX content
|
|
124
|
+
const storyVariants = storyMap.get(componentName) || [];
|
|
125
|
+
const fragmentContent = generateFragmentTsx(
|
|
127
126
|
componentName,
|
|
127
|
+
componentBaseName,
|
|
128
128
|
extracted,
|
|
129
129
|
filePath,
|
|
130
|
-
|
|
130
|
+
storyVariants
|
|
131
131
|
);
|
|
132
132
|
|
|
133
133
|
// Write fragment file
|
|
134
|
-
await writeFile(fragmentPath,
|
|
134
|
+
await writeFile(fragmentPath, fragmentContent, "utf-8");
|
|
135
135
|
generated.push({ name: componentName, path: relative(projectRoot, fragmentPath) });
|
|
136
136
|
console.log(pc.green(` ✓ Generated ${componentName}${BRAND.fileExtension}`));
|
|
137
137
|
} catch (e) {
|
|
@@ -166,59 +166,235 @@ export async function generate(options: GenerateOptions = {}): Promise<GenerateR
|
|
|
166
166
|
}
|
|
167
167
|
|
|
168
168
|
/**
|
|
169
|
-
* Generate
|
|
169
|
+
* Generate proper defineFragment() TSX file content
|
|
170
170
|
*/
|
|
171
|
-
function
|
|
171
|
+
function generateFragmentTsx(
|
|
172
172
|
componentName: string,
|
|
173
|
+
componentBaseName: string,
|
|
173
174
|
extracted: ReturnType<typeof extractPropsFromFile> & { componentName: string },
|
|
174
175
|
filePath: string,
|
|
175
|
-
|
|
176
|
-
):
|
|
177
|
-
|
|
176
|
+
storyVariants: StoryVariant[]
|
|
177
|
+
): string {
|
|
178
|
+
const storyNames = storyVariants.map((v) => v.name);
|
|
178
179
|
const whenToUse = inferUsageFromStories(storyNames);
|
|
179
|
-
|
|
180
|
-
// Generate description from component name
|
|
181
180
|
const description = generateDescription(componentName, extracted.props);
|
|
182
|
-
|
|
183
|
-
// Infer accessibility from props
|
|
181
|
+
const status = inferStatus(filePath);
|
|
184
182
|
const accessibility = inferAccessibility(extracted.props);
|
|
185
183
|
|
|
186
|
-
//
|
|
187
|
-
const
|
|
184
|
+
// Build props object for defineFragment
|
|
185
|
+
const propsEntries = Object.entries(extracted.props || {});
|
|
186
|
+
|
|
187
|
+
// Format when array
|
|
188
|
+
const whenLines = whenToUse.length > 0
|
|
189
|
+
? whenToUse.map((w) => ` '${escapeQuotes(w)}',`).join("\n")
|
|
190
|
+
: ` 'TODO: describe when to use ${componentName}',`;
|
|
191
|
+
|
|
192
|
+
// Format props
|
|
193
|
+
let propsBlock = "{}";
|
|
194
|
+
if (propsEntries.length > 0) {
|
|
195
|
+
const propLines = propsEntries.map(([name, info]) => {
|
|
196
|
+
const propInfo = info as Record<string, unknown>;
|
|
197
|
+
const rawType = propInfo.type ? String(propInfo.type) : "";
|
|
198
|
+
const classified = classifyPropType(rawType);
|
|
199
|
+
const desc = propInfo.description ? String(propInfo.description).replace(/\n/g, " ") : "";
|
|
200
|
+
const required = propInfo.required ? "true" : "false";
|
|
201
|
+
const parts = [` type: '${classified.type}'`];
|
|
202
|
+
if (desc) parts.push(` description: '${escapeQuotes(desc)}'`);
|
|
203
|
+
parts.push(` required: ${required}`);
|
|
204
|
+
if (propInfo.default !== undefined) {
|
|
205
|
+
parts.push(` default: ${JSON.stringify(propInfo.default)}`);
|
|
206
|
+
}
|
|
207
|
+
// Use classified values (from string literal unions) or existing values
|
|
208
|
+
const values = classified.values || (propInfo.values && Array.isArray(propInfo.values) ? propInfo.values : null);
|
|
209
|
+
if (values && values.length > 0) {
|
|
210
|
+
parts.push(` values: ${JSON.stringify(values)}`);
|
|
211
|
+
}
|
|
212
|
+
return ` ${name}: {\n${parts.join(",\n")},\n }`;
|
|
213
|
+
});
|
|
214
|
+
propsBlock = `{\n${propLines.join(",\n")},\n }`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Build accessibility section
|
|
218
|
+
let accessibilityBlock = "";
|
|
219
|
+
if (accessibility.role || (accessibility.requirements && accessibility.requirements.length > 0)) {
|
|
220
|
+
const parts: string[] = [];
|
|
221
|
+
if (accessibility.role) {
|
|
222
|
+
parts.push(` role: '${accessibility.role}'`);
|
|
223
|
+
}
|
|
224
|
+
if (accessibility.requirements && accessibility.requirements.length > 0) {
|
|
225
|
+
const reqs = accessibility.requirements.map((r) => `'${escapeQuotes(r)}'`).join(", ");
|
|
226
|
+
parts.push(` requirements: [${reqs}]`);
|
|
227
|
+
}
|
|
228
|
+
accessibilityBlock = `
|
|
229
|
+
|
|
230
|
+
accessibility: {
|
|
231
|
+
${parts.join(",\n")},
|
|
232
|
+
},`;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Build variants from story args or fallback to bare render
|
|
236
|
+
const variants = buildVariants(componentName, storyVariants);
|
|
237
|
+
|
|
238
|
+
// Use default import when the source component uses export default
|
|
239
|
+
const componentImportStatement = extracted.isDefaultExport
|
|
240
|
+
? `import ${componentName} from './${componentBaseName}';`
|
|
241
|
+
: `import { ${componentName} } from './${componentBaseName}';`;
|
|
242
|
+
|
|
243
|
+
return `import React from 'react';
|
|
244
|
+
import { defineFragment } from '@fragments-sdk/cli/core';
|
|
245
|
+
${componentImportStatement}
|
|
246
|
+
|
|
247
|
+
export default defineFragment({
|
|
248
|
+
component: ${componentName},
|
|
249
|
+
|
|
250
|
+
meta: {
|
|
251
|
+
name: '${escapeQuotes(componentName)}',
|
|
252
|
+
description: '${escapeQuotes(description)}',
|
|
253
|
+
category: '${inferCategory(componentName, extracted.props)}',
|
|
254
|
+
status: '${status}',
|
|
255
|
+
},
|
|
256
|
+
|
|
257
|
+
usage: {
|
|
258
|
+
when: [
|
|
259
|
+
${whenLines}
|
|
260
|
+
],
|
|
261
|
+
whenNot: [],
|
|
262
|
+
},
|
|
263
|
+
|
|
264
|
+
props: ${propsBlock},${accessibilityBlock}
|
|
265
|
+
|
|
266
|
+
variants: [
|
|
267
|
+
${variants}
|
|
268
|
+
],
|
|
269
|
+
});
|
|
270
|
+
`;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Escape single quotes in strings
|
|
275
|
+
*/
|
|
276
|
+
function escapeQuotes(str: string): string {
|
|
277
|
+
return str.replace(/'/g, "\\'");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Classify a raw TypeScript type string into a valid fragment prop type enum value.
|
|
282
|
+
* Returns the classified type and optionally extracted enum values.
|
|
283
|
+
*/
|
|
284
|
+
function classifyPropType(rawType: string): { type: string; values?: string[] } {
|
|
285
|
+
const t = rawType.replace(/\s+/g, " ").trim();
|
|
286
|
+
const lower = t.toLowerCase();
|
|
287
|
+
|
|
288
|
+
// Direct primitive matches
|
|
289
|
+
if (lower === "string") return { type: "string" };
|
|
290
|
+
if (lower === "number") return { type: "number" };
|
|
291
|
+
if (lower === "boolean" || lower === "bool") return { type: "boolean" };
|
|
292
|
+
|
|
293
|
+
// String/number literal unions → enum with values
|
|
294
|
+
// e.g., '"primary" | "secondary"' or "'default' | 'modal'"
|
|
295
|
+
if (/^["'][^"']*["'](\s*\|\s*["'][^"']*["'])*$/.test(t)) {
|
|
296
|
+
const values = [...t.matchAll(/["']([^"']+)["']/g)].map((m) => m[1]);
|
|
297
|
+
if (values.length > 0) return { type: "enum", values };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Function types — arrow functions, callbacks, handlers, dispatchers
|
|
301
|
+
if (
|
|
302
|
+
lower.includes("=>") ||
|
|
303
|
+
lower.includes("handler") ||
|
|
304
|
+
lower.includes("callback") ||
|
|
305
|
+
lower.includes("dispatch") ||
|
|
306
|
+
lower.includes("listener") ||
|
|
307
|
+
/^\(/.test(t)
|
|
308
|
+
) {
|
|
309
|
+
return { type: "function" };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// React node types
|
|
313
|
+
if (
|
|
314
|
+
lower.includes("reactnode") ||
|
|
315
|
+
lower.includes("react.reactnode") ||
|
|
316
|
+
lower === "node"
|
|
317
|
+
) {
|
|
318
|
+
return { type: "node" };
|
|
319
|
+
}
|
|
188
320
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
321
|
+
// React element types
|
|
322
|
+
if (
|
|
323
|
+
lower.includes("reactelement") ||
|
|
324
|
+
lower.includes("react.reactelement") ||
|
|
325
|
+
lower.includes("jsx.element")
|
|
326
|
+
) {
|
|
327
|
+
return { type: "element" };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// Array types
|
|
331
|
+
if (lower.includes("[]") || lower.startsWith("array<") || lower.startsWith("readonly ")) {
|
|
332
|
+
return { type: "array" };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Object types (must come after array check since objects can contain [])
|
|
336
|
+
if (lower.startsWith("{") || lower.includes("record<") || lower === "object") {
|
|
337
|
+
return { type: "object" };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Union types (mixed types with |)
|
|
341
|
+
if (lower.includes("|")) {
|
|
342
|
+
// Check if it's a union of just string literals (enum)
|
|
343
|
+
const parts = t.split("|").map((p) => p.trim());
|
|
344
|
+
const allStringLiterals = parts.every((p) => /^["'].*["']$/.test(p));
|
|
345
|
+
if (allStringLiterals) {
|
|
346
|
+
const values = parts.map((p) => p.replace(/^["']|["']$/g, ""));
|
|
347
|
+
return { type: "enum", values };
|
|
348
|
+
}
|
|
349
|
+
return { type: "union" };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Anything else
|
|
353
|
+
return { type: "custom" };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Infer category from component name and props
|
|
358
|
+
*/
|
|
359
|
+
function inferCategory(componentName: string, props: Record<string, unknown>): string {
|
|
360
|
+
const lower = componentName.toLowerCase();
|
|
361
|
+
|
|
362
|
+
const categoryPatterns: Record<string, string[]> = {
|
|
363
|
+
"Actions": ["button", "action", "cta", "fab", "floatingaction"],
|
|
364
|
+
"Forms": ["form", "input", "select", "checkbox", "radio", "textarea", "field", "textfield", "datepicker", "switch", "slider", "segmented"],
|
|
365
|
+
"Layout": ["layout", "container", "grid", "flex", "stack", "box", "divider", "spacer", "sidebar"],
|
|
366
|
+
"Navigation": ["nav", "menu", "breadcrumb", "tab", "link", "pagination", "stepper", "topbar"],
|
|
367
|
+
"Feedback": ["alert", "toast", "notification", "message", "badge", "indicator", "progress", "spinner", "loading", "loader", "lozenge", "chip"],
|
|
368
|
+
"Data Display": ["table", "list", "card", "avatar", "stat", "timeline", "tree", "datalist", "datacard"],
|
|
369
|
+
"Overlays": ["modal", "dialog", "drawer", "popover", "tooltip", "dropdown", "slidepanel"],
|
|
370
|
+
"Typography": ["text", "heading", "title", "label", "paragraph"],
|
|
371
|
+
"Media": ["image", "video", "icon", "carousel"],
|
|
200
372
|
};
|
|
201
373
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
374
|
+
for (const [category, patterns] of Object.entries(categoryPatterns)) {
|
|
375
|
+
for (const pattern of patterns) {
|
|
376
|
+
if (lower.includes(pattern)) {
|
|
377
|
+
return category;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
205
380
|
}
|
|
206
381
|
|
|
207
|
-
return
|
|
382
|
+
if ("onClick" in props || "onPress" in props) return "Actions";
|
|
383
|
+
if ("value" in props || "defaultValue" in props) return "Forms";
|
|
384
|
+
if ("children" in props) return "Layout";
|
|
385
|
+
|
|
386
|
+
return "Components";
|
|
208
387
|
}
|
|
209
388
|
|
|
210
389
|
/**
|
|
211
390
|
* Extract component name from story file
|
|
212
391
|
*/
|
|
213
392
|
function extractComponentNameFromStory(content: string, filePath: string): string | null {
|
|
214
|
-
// Try to extract from title in default export
|
|
215
|
-
// e.g., export default { title: 'Components/Button' }
|
|
216
393
|
const titleMatch = content.match(/title:\s*['"](?:[^'"]+\/)?([^'"]+)['"]/);
|
|
217
394
|
if (titleMatch) {
|
|
218
395
|
return titleMatch[1];
|
|
219
396
|
}
|
|
220
397
|
|
|
221
|
-
// Try to extract from file name
|
|
222
398
|
const fileName = basename(filePath);
|
|
223
399
|
const componentName = fileName.replace(/\.stories\.(tsx?|jsx?)$/, "");
|
|
224
400
|
if (/^[A-Z]/.test(componentName)) {
|
|
@@ -228,26 +404,174 @@ function extractComponentNameFromStory(content: string, filePath: string): strin
|
|
|
228
404
|
return null;
|
|
229
405
|
}
|
|
230
406
|
|
|
407
|
+
interface StoryVariant {
|
|
408
|
+
name: string;
|
|
409
|
+
args: Record<string, unknown>;
|
|
410
|
+
}
|
|
411
|
+
|
|
231
412
|
/**
|
|
232
|
-
* Extract story names from story file content
|
|
413
|
+
* Extract story names and their args from story file content (CSF3 format).
|
|
414
|
+
* Parses patterns like:
|
|
415
|
+
* export const Primary: Story = { args: { variant: 'primary', children: 'Click me' } }
|
|
233
416
|
*/
|
|
234
|
-
function
|
|
235
|
-
const
|
|
417
|
+
function extractStoryVariants(content: string): StoryVariant[] {
|
|
418
|
+
const variants: StoryVariant[] = [];
|
|
236
419
|
|
|
237
|
-
// Match named exports that look like stories
|
|
238
|
-
// e.g., export const Primary = ...
|
|
239
420
|
const exportMatches = content.matchAll(
|
|
240
421
|
/export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/g
|
|
241
422
|
);
|
|
242
423
|
|
|
243
424
|
for (const match of exportMatches) {
|
|
244
425
|
const name = match[1];
|
|
245
|
-
if (name
|
|
246
|
-
|
|
426
|
+
if (name === "default" || name.endsWith("Args") || name.endsWith("Meta")) {
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const args = extractStoryArgs(content, name);
|
|
431
|
+
variants.push({ name, args });
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
return variants;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Extract the `args` object from a named story export.
|
|
439
|
+
* Uses balanced-brace matching to handle nested objects.
|
|
440
|
+
*/
|
|
441
|
+
function extractStoryArgs(content: string, storyName: string): Record<string, unknown> {
|
|
442
|
+
// Find the story export and look for an args block
|
|
443
|
+
const storyPattern = new RegExp(
|
|
444
|
+
`export\\s+const\\s+${storyName}[^=]*=\\s*\\{([\\s\\S]*?)\\n\\};`,
|
|
445
|
+
);
|
|
446
|
+
const storyMatch = content.match(storyPattern);
|
|
447
|
+
if (!storyMatch) return {};
|
|
448
|
+
|
|
449
|
+
const storyBody = storyMatch[1];
|
|
450
|
+
|
|
451
|
+
// Find the args block within the story body
|
|
452
|
+
const argsStart = storyBody.indexOf('args:');
|
|
453
|
+
if (argsStart === -1) return {};
|
|
454
|
+
|
|
455
|
+
// Find the opening brace after "args:"
|
|
456
|
+
const braceStart = storyBody.indexOf('{', argsStart);
|
|
457
|
+
if (braceStart === -1) return {};
|
|
458
|
+
|
|
459
|
+
// Balanced brace matching to find the full args object
|
|
460
|
+
let depth = 0;
|
|
461
|
+
let braceEnd = -1;
|
|
462
|
+
for (let i = braceStart; i < storyBody.length; i++) {
|
|
463
|
+
if (storyBody[i] === '{') depth++;
|
|
464
|
+
else if (storyBody[i] === '}') {
|
|
465
|
+
depth--;
|
|
466
|
+
if (depth === 0) {
|
|
467
|
+
braceEnd = i;
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (braceEnd === -1) return {};
|
|
473
|
+
|
|
474
|
+
const argsBlock = storyBody.slice(braceStart + 1, braceEnd).trim();
|
|
475
|
+
return parseArgsBlock(argsBlock);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Parse a simplified args block into key-value pairs.
|
|
480
|
+
* Handles string literals, numbers, booleans, and simple expressions.
|
|
481
|
+
*/
|
|
482
|
+
function parseArgsBlock(argsBlock: string): Record<string, unknown> {
|
|
483
|
+
const args: Record<string, unknown> = {};
|
|
484
|
+
|
|
485
|
+
// Match key: value pairs (handles string, number, boolean values)
|
|
486
|
+
const pairPattern = /(\w+)\s*:\s*(?:['"]([^'"]*?)['"]|(true|false)|(\d+(?:\.\d+)?))/g;
|
|
487
|
+
let pairMatch: RegExpExecArray | null;
|
|
488
|
+
|
|
489
|
+
while ((pairMatch = pairPattern.exec(argsBlock)) !== null) {
|
|
490
|
+
const key = pairMatch[1];
|
|
491
|
+
if (pairMatch[2] !== undefined) {
|
|
492
|
+
// String value
|
|
493
|
+
args[key] = pairMatch[2];
|
|
494
|
+
} else if (pairMatch[3] !== undefined) {
|
|
495
|
+
// Boolean
|
|
496
|
+
args[key] = pairMatch[3] === 'true';
|
|
497
|
+
} else if (pairMatch[4] !== undefined) {
|
|
498
|
+
// Number
|
|
499
|
+
args[key] = Number(pairMatch[4]);
|
|
247
500
|
}
|
|
248
501
|
}
|
|
249
502
|
|
|
250
|
-
return
|
|
503
|
+
return args;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Build variant entries from story args.
|
|
508
|
+
* If stories have args, generates JSX with those props.
|
|
509
|
+
* Falls back to a bare `<Component />` for the Default variant.
|
|
510
|
+
*/
|
|
511
|
+
function buildVariants(componentName: string, storyVariants: StoryVariant[]): string {
|
|
512
|
+
// Filter to variants with args, plus always include a Default
|
|
513
|
+
const hasDefault = storyVariants.some((v) => v.name === 'Default');
|
|
514
|
+
const entries: string[] = [];
|
|
515
|
+
|
|
516
|
+
if (!hasDefault) {
|
|
517
|
+
entries.push(formatVariantEntry(componentName, 'Default', `Default ${componentName}`, {}));
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
for (const variant of storyVariants) {
|
|
521
|
+
const description = variant.name
|
|
522
|
+
.replace(/([A-Z])/g, ' $1')
|
|
523
|
+
.trim();
|
|
524
|
+
entries.push(formatVariantEntry(componentName, variant.name, `${description} ${componentName}`, variant.args));
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Deduplicate: if stories provided a Default, don't double-add
|
|
528
|
+
return entries.join('\n');
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Format a single variant entry with JSX code and render function.
|
|
533
|
+
* Handles `children` as JSX children, all other args as props.
|
|
534
|
+
*/
|
|
535
|
+
function formatVariantEntry(
|
|
536
|
+
componentName: string,
|
|
537
|
+
name: string,
|
|
538
|
+
description: string,
|
|
539
|
+
args: Record<string, unknown>
|
|
540
|
+
): string {
|
|
541
|
+
const jsxCode = buildJsxString(componentName, args);
|
|
542
|
+
return ` {
|
|
543
|
+
name: '${escapeQuotes(name)}',
|
|
544
|
+
description: '${escapeQuotes(description)}',
|
|
545
|
+
code: \`${jsxCode}\`,
|
|
546
|
+
render: () => ${jsxCode},
|
|
547
|
+
},`;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Build a JSX string from component name and args.
|
|
552
|
+
* `children` string args become JSX children, others become props.
|
|
553
|
+
*/
|
|
554
|
+
function buildJsxString(componentName: string, args: Record<string, unknown>): string {
|
|
555
|
+
const { children, ...restArgs } = args;
|
|
556
|
+
const propParts: string[] = [];
|
|
557
|
+
|
|
558
|
+
for (const [key, value] of Object.entries(restArgs)) {
|
|
559
|
+
if (typeof value === 'string') {
|
|
560
|
+
propParts.push(`${key}="${escapeQuotes(value)}"`);
|
|
561
|
+
} else if (typeof value === 'boolean') {
|
|
562
|
+
propParts.push(value ? key : `${key}={false}`);
|
|
563
|
+
} else if (typeof value === 'number') {
|
|
564
|
+
propParts.push(`${key}={${value}}`);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const propsStr = propParts.length > 0 ? ' ' + propParts.join(' ') : '';
|
|
569
|
+
|
|
570
|
+
if (typeof children === 'string') {
|
|
571
|
+
return `<${componentName}${propsStr}>${children}</${componentName}>`;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
return `<${componentName}${propsStr} />`;
|
|
251
575
|
}
|
|
252
576
|
|
|
253
577
|
/**
|
|
@@ -257,13 +581,11 @@ function inferUsageFromStories(storyNames: string[]): string[] {
|
|
|
257
581
|
const usage: string[] = [];
|
|
258
582
|
|
|
259
583
|
for (const name of storyNames) {
|
|
260
|
-
// Convert PascalCase to sentence
|
|
261
584
|
const sentence = name
|
|
262
585
|
.replace(/([A-Z])/g, " $1")
|
|
263
586
|
.trim()
|
|
264
587
|
.toLowerCase();
|
|
265
588
|
|
|
266
|
-
// Skip generic names
|
|
267
589
|
if (
|
|
268
590
|
["default", "primary", "basic", "example", "playground"].includes(
|
|
269
591
|
sentence.toLowerCase()
|
|
@@ -272,7 +594,6 @@ function inferUsageFromStories(storyNames: string[]): string[] {
|
|
|
272
594
|
continue;
|
|
273
595
|
}
|
|
274
596
|
|
|
275
|
-
// Generate usage from story name
|
|
276
597
|
if (sentence.includes("loading")) {
|
|
277
598
|
usage.push("Showing loading states");
|
|
278
599
|
} else if (sentence.includes("disabled")) {
|
|
@@ -284,7 +605,6 @@ function inferUsageFromStories(storyNames: string[]): string[] {
|
|
|
284
605
|
} else if (sentence.includes("empty")) {
|
|
285
606
|
usage.push("Handling empty states");
|
|
286
607
|
} else if (sentence.includes("with")) {
|
|
287
|
-
// "WithIcon" -> "Adding icons"
|
|
288
608
|
const withPart = sentence.replace("with ", "");
|
|
289
609
|
usage.push(`Displaying with ${withPart}`);
|
|
290
610
|
}
|
|
@@ -300,13 +620,11 @@ function generateDescription(
|
|
|
300
620
|
componentName: string,
|
|
301
621
|
props: Record<string, unknown>
|
|
302
622
|
): string {
|
|
303
|
-
// Convert PascalCase to words
|
|
304
623
|
const words = componentName
|
|
305
624
|
.replace(/([A-Z])/g, " $1")
|
|
306
625
|
.trim()
|
|
307
626
|
.toLowerCase();
|
|
308
627
|
|
|
309
|
-
// Detect component type from name or props
|
|
310
628
|
const hasOnClick = "onClick" in props || "onPress" in props;
|
|
311
629
|
const hasValue = "value" in props || "defaultValue" in props;
|
|
312
630
|
const hasChildren = "children" in props;
|
|
@@ -337,18 +655,15 @@ function inferAccessibility(props: Record<string, unknown>): {
|
|
|
337
655
|
|
|
338
656
|
const hasOnClick = "onClick" in props || "onPress" in props;
|
|
339
657
|
const hasAriaLabel = "ariaLabel" in props || "aria-label" in props;
|
|
340
|
-
const hasRole = "role" in props;
|
|
341
658
|
const hasDisabled = "disabled" in props;
|
|
342
659
|
const hasHref = "href" in props;
|
|
343
660
|
|
|
344
|
-
// Infer role
|
|
345
661
|
if (hasOnClick && !hasHref) {
|
|
346
662
|
accessibility.role = "button";
|
|
347
663
|
} else if (hasHref) {
|
|
348
664
|
accessibility.role = "link";
|
|
349
665
|
}
|
|
350
666
|
|
|
351
|
-
// Infer requirements
|
|
352
667
|
const requirements: string[] = [];
|
|
353
668
|
|
|
354
669
|
if (hasOnClick && !hasAriaLabel) {
|
|
@@ -126,7 +126,7 @@ import { ThemeProvider } from '@fragments-sdk/ui';
|
|
|
126
126
|
|
|
127
127
|
export function Providers({ children }: { children: React.ReactNode }) {
|
|
128
128
|
return (
|
|
129
|
-
<ThemeProvider
|
|
129
|
+
<ThemeProvider defaultMode="system" attribute="data-theme">
|
|
130
130
|
{children}
|
|
131
131
|
</ThemeProvider>
|
|
132
132
|
);
|