@fragments-sdk/viewer 0.2.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.
Files changed (141) hide show
  1. package/LICENSE +84 -0
  2. package/index.html +28 -0
  3. package/package.json +71 -0
  4. package/src/__tests__/a11y-fixes.test.ts +358 -0
  5. package/src/__tests__/jsx-parser.test.ts +502 -0
  6. package/src/__tests__/render-utils.test.ts +232 -0
  7. package/src/__tests__/style-utils.test.ts +404 -0
  8. package/src/app/index.ts +1 -0
  9. package/src/assets/fragments-logo.ts +4 -0
  10. package/src/assets/fragments_logo.png +0 -0
  11. package/src/components/AccessibilityPanel.tsx +1457 -0
  12. package/src/components/ActionCapture.tsx +172 -0
  13. package/src/components/ActionsPanel.tsx +332 -0
  14. package/src/components/AllVariantsPreview.tsx +78 -0
  15. package/src/components/App.tsx +604 -0
  16. package/src/components/BottomPanel.tsx +288 -0
  17. package/src/components/CodePanel.naming.test.tsx +59 -0
  18. package/src/components/CodePanel.tsx +118 -0
  19. package/src/components/CommandPalette.tsx +392 -0
  20. package/src/components/ComponentDocView.tsx +164 -0
  21. package/src/components/ComponentGraph.tsx +380 -0
  22. package/src/components/ComponentHeader.tsx +88 -0
  23. package/src/components/ContractPanel.tsx +241 -0
  24. package/src/components/DeviceMockup.tsx +156 -0
  25. package/src/components/EmptyVariantMessage.tsx +54 -0
  26. package/src/components/ErrorBoundary.tsx +97 -0
  27. package/src/components/FigmaEmbed.tsx +238 -0
  28. package/src/components/FragmentEditor.tsx +525 -0
  29. package/src/components/FragmentRenderer.tsx +61 -0
  30. package/src/components/HeaderSearch.tsx +24 -0
  31. package/src/components/HealthDashboard.tsx +441 -0
  32. package/src/components/HmrStatusIndicator.tsx +61 -0
  33. package/src/components/Icons.tsx +479 -0
  34. package/src/components/InteractionsPanel.tsx +757 -0
  35. package/src/components/IsolatedPreviewFrame.tsx +390 -0
  36. package/src/components/IsolatedRender.tsx +113 -0
  37. package/src/components/KeyboardShortcutsHelp.tsx +53 -0
  38. package/src/components/LandingPage.tsx +420 -0
  39. package/src/components/Layout.tsx +27 -0
  40. package/src/components/LeftSidebar.tsx +472 -0
  41. package/src/components/LoadErrorMessage.tsx +102 -0
  42. package/src/components/MultiViewportPreview.tsx +527 -0
  43. package/src/components/NoVariantsMessage.tsx +59 -0
  44. package/src/components/PanelShell.tsx +161 -0
  45. package/src/components/PerformancePanel.tsx +304 -0
  46. package/src/components/PreviewArea.tsx +254 -0
  47. package/src/components/PreviewAside.tsx +168 -0
  48. package/src/components/PreviewFrameHost.tsx +304 -0
  49. package/src/components/PreviewToolbar.tsx +80 -0
  50. package/src/components/PropsEditor.tsx +506 -0
  51. package/src/components/PropsTable.tsx +111 -0
  52. package/src/components/RelationsSection.tsx +88 -0
  53. package/src/components/ResizablePanel.tsx +271 -0
  54. package/src/components/RightSidebar.tsx +102 -0
  55. package/src/components/RuntimeToolsRegistrar.tsx +17 -0
  56. package/src/components/ScreenshotButton.tsx +90 -0
  57. package/src/components/ShadowPreview.tsx +204 -0
  58. package/src/components/Sidebar.tsx +169 -0
  59. package/src/components/SkeletonLoader.tsx +161 -0
  60. package/src/components/ThemeProvider.tsx +42 -0
  61. package/src/components/Toast.tsx +3 -0
  62. package/src/components/TokenStylePanel.tsx +699 -0
  63. package/src/components/TopToolbar.tsx +159 -0
  64. package/src/components/Untitled +1 -0
  65. package/src/components/UsageSection.tsx +95 -0
  66. package/src/components/VariantMatrix.tsx +391 -0
  67. package/src/components/VariantRenderer.tsx +131 -0
  68. package/src/components/VariantTabs.tsx +40 -0
  69. package/src/components/ViewerHeader.tsx +69 -0
  70. package/src/components/ViewerStateSync.tsx +52 -0
  71. package/src/components/ViewportSelector.tsx +172 -0
  72. package/src/components/WebMCPDevTools.tsx +503 -0
  73. package/src/components/WebMCPIntegration.tsx +47 -0
  74. package/src/components/WebMCPStatusIndicator.tsx +60 -0
  75. package/src/components/_future/CreatePage.tsx +835 -0
  76. package/src/components/viewer-utils.ts +16 -0
  77. package/src/composition-renderer.ts +381 -0
  78. package/src/constants/index.ts +1 -0
  79. package/src/constants/ui.ts +166 -0
  80. package/src/entry.tsx +335 -0
  81. package/src/hooks/index.ts +2 -0
  82. package/src/hooks/useA11yCache.ts +383 -0
  83. package/src/hooks/useA11yService.ts +364 -0
  84. package/src/hooks/useActions.ts +138 -0
  85. package/src/hooks/useAppState.ts +147 -0
  86. package/src/hooks/useCompiledFragments.ts +42 -0
  87. package/src/hooks/useFigmaIntegration.ts +132 -0
  88. package/src/hooks/useHmrStatus.ts +109 -0
  89. package/src/hooks/useKeyboardShortcuts.ts +270 -0
  90. package/src/hooks/usePreviewBridge.ts +347 -0
  91. package/src/hooks/useScrollSpy.ts +78 -0
  92. package/src/hooks/useShadowStyles.ts +221 -0
  93. package/src/hooks/useUrlState.ts +318 -0
  94. package/src/hooks/useViewSettings.ts +111 -0
  95. package/src/intelligence/healthReport.ts +505 -0
  96. package/src/intelligence/styleDrift.ts +340 -0
  97. package/src/intelligence/usageScanner.ts +309 -0
  98. package/src/jsx-parser.ts +486 -0
  99. package/src/preview-frame-entry.tsx +25 -0
  100. package/src/preview-frame.html +148 -0
  101. package/src/render-template.html +68 -0
  102. package/src/render-utils.ts +311 -0
  103. package/src/shared/ComponentDocContent.module.scss +10 -0
  104. package/src/shared/ComponentDocContent.module.scss.d.ts +2 -0
  105. package/src/shared/ComponentDocContent.tsx +274 -0
  106. package/src/shared/DocsHeaderBar.tsx +129 -0
  107. package/src/shared/DocsPageAsideHost.tsx +89 -0
  108. package/src/shared/DocsPageShell.tsx +124 -0
  109. package/src/shared/DocsSearchCommand.tsx +99 -0
  110. package/src/shared/DocsSidebarNav.tsx +66 -0
  111. package/src/shared/PropsTable.module.scss +68 -0
  112. package/src/shared/PropsTable.module.scss.d.ts +2 -0
  113. package/src/shared/PropsTable.tsx +76 -0
  114. package/src/shared/VariantPreviewCard.module.scss +114 -0
  115. package/src/shared/VariantPreviewCard.module.scss.d.ts +2 -0
  116. package/src/shared/VariantPreviewCard.tsx +137 -0
  117. package/src/shared/docs-data/index.ts +32 -0
  118. package/src/shared/docs-data/mcp-configs.ts +72 -0
  119. package/src/shared/docs-data/palettes.ts +75 -0
  120. package/src/shared/docs-data/setup-examples.ts +55 -0
  121. package/src/shared/docs-layout.scss +28 -0
  122. package/src/shared/docs-layout.scss.d.ts +2 -0
  123. package/src/shared/index.ts +34 -0
  124. package/src/shared/types.ts +53 -0
  125. package/src/style-utils.ts +414 -0
  126. package/src/styles/globals.css +278 -0
  127. package/src/types/a11y.ts +197 -0
  128. package/src/utils/a11y-fixes.ts +509 -0
  129. package/src/utils/actionExport.ts +372 -0
  130. package/src/utils/colorSchemes.ts +201 -0
  131. package/src/utils/contrast.ts +246 -0
  132. package/src/utils/detectRelationships.ts +256 -0
  133. package/src/webmcp/__tests__/analytics.test.ts +108 -0
  134. package/src/webmcp/analytics.ts +165 -0
  135. package/src/webmcp/index.ts +3 -0
  136. package/src/webmcp/posthog-bridge.ts +39 -0
  137. package/src/webmcp/runtime-tools.ts +152 -0
  138. package/src/webmcp/scan-utils.ts +135 -0
  139. package/src/webmcp/use-tool-analytics.ts +69 -0
  140. package/src/webmcp/viewer-state.ts +45 -0
  141. package/tsconfig.json +20 -0
@@ -0,0 +1,288 @@
1
+ /**
2
+ * BottomPanel component - the tabbed panel at the bottom of the viewer.
3
+ * Uses the Drawer component from @fragments-sdk/ui as a non-modal bottom sheet.
4
+ * Contains Styles, Accessibility, Interactions, Graph, and Performance tabs.
5
+ */
6
+
7
+ import { memo, useCallback, useState, useEffect, useRef } from "react";
8
+ import type { FragmentDefinition, FragmentVariant } from '@fragments-sdk/core';
9
+ import { Drawer, Tabs, Button, Tooltip } from "@fragments-sdk/ui";
10
+ import { Terminal } from "@phosphor-icons/react";
11
+ import { BRAND } from '@fragments-sdk/core';
12
+ import { TokenStylePanel } from "./TokenStylePanel.js";
13
+ import { AccessibilityPanel } from "./AccessibilityPanel.js";
14
+ import { InteractionsPanel } from "./InteractionsPanel.js";
15
+ import { ComponentGraph } from "./ComponentGraph.js";
16
+ import { PerformancePanel } from "./PerformancePanel.js";
17
+ import type { ActivePanel } from "../hooks/useAppState.js";
18
+
19
+ // Persist panel height to localStorage
20
+ const HEIGHT_KEY = `${BRAND.storagePrefix}panel-height`;
21
+ const MIN_HEIGHT = 120;
22
+ const MAX_HEIGHT = 600;
23
+ const DEFAULT_HEIGHT = 240;
24
+
25
+ function loadHeight(): number {
26
+ try {
27
+ const v = localStorage.getItem(HEIGHT_KEY);
28
+ return v ? Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, Number(v))) : DEFAULT_HEIGHT;
29
+ } catch {
30
+ return DEFAULT_HEIGHT;
31
+ }
32
+ }
33
+
34
+ function saveHeight(h: number) {
35
+ try {
36
+ localStorage.setItem(HEIGHT_KEY, String(h));
37
+ } catch {
38
+ // Ignore storage errors
39
+ }
40
+ }
41
+
42
+ interface BottomPanelProps {
43
+ // Component data
44
+ fragment: FragmentDefinition;
45
+ variant: FragmentVariant;
46
+ fragments: Array<{ path: string; fragment: FragmentDefinition }>;
47
+
48
+ // Panel state
49
+ open: boolean;
50
+ onOpenChange: (open: boolean) => void;
51
+ activePanel: ActivePanel;
52
+ onPanelChange: (panel: ActivePanel) => void;
53
+
54
+ // Figma
55
+ figmaUrl?: string;
56
+ figmaStyles: Record<string, string> | null;
57
+ renderedStyles: Record<string, string> | null;
58
+ figmaLoading: boolean;
59
+ figmaError?: string;
60
+ onFetchFigma: () => void;
61
+ onRefreshRendered: () => void;
62
+
63
+ // Navigation
64
+ onNavigateToComponent: (name: string) => void;
65
+
66
+ // Keys
67
+ previewKey: number;
68
+ fragmentKey: string;
69
+ }
70
+
71
+ export const BottomPanel = memo(function BottomPanel({
72
+ fragment,
73
+ variant,
74
+ fragments,
75
+ open,
76
+ onOpenChange,
77
+ activePanel,
78
+ onPanelChange,
79
+ figmaUrl,
80
+ figmaStyles,
81
+ renderedStyles,
82
+ figmaLoading,
83
+ figmaError,
84
+ onFetchFigma,
85
+ onRefreshRendered,
86
+ onNavigateToComponent,
87
+ previewKey,
88
+ fragmentKey,
89
+ }: BottomPanelProps) {
90
+ // Resize state
91
+ const [height, setHeight] = useState(loadHeight);
92
+ const [isResizing, setIsResizing] = useState(false);
93
+ const startYRef = useRef(0);
94
+ const startHeightRef = useRef(0);
95
+
96
+ // Save height changes
97
+ useEffect(() => {
98
+ saveHeight(height);
99
+ }, [height]);
100
+
101
+ const handleMouseDown = useCallback(
102
+ (e: React.MouseEvent) => {
103
+ e.preventDefault();
104
+ setIsResizing(true);
105
+ startYRef.current = e.clientY;
106
+ startHeightRef.current = height;
107
+ },
108
+ [height]
109
+ );
110
+
111
+ useEffect(() => {
112
+ if (!isResizing) return;
113
+
114
+ const handleMouseMove = (e: MouseEvent) => {
115
+ const deltaY = startYRef.current - e.clientY;
116
+ setHeight(Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, startHeightRef.current + deltaY)));
117
+ };
118
+ const handleMouseUp = () => setIsResizing(false);
119
+
120
+ document.addEventListener("mousemove", handleMouseMove);
121
+ document.addEventListener("mouseup", handleMouseUp);
122
+ document.body.style.cursor = "ns-resize";
123
+ document.body.style.userSelect = "none";
124
+
125
+ return () => {
126
+ document.removeEventListener("mousemove", handleMouseMove);
127
+ document.removeEventListener("mouseup", handleMouseUp);
128
+ document.body.style.cursor = "";
129
+ document.body.style.userSelect = "";
130
+ };
131
+ }, [isResizing]);
132
+
133
+ // Tab change handler with Figma side effects
134
+ const handleStylesClick = useCallback(() => {
135
+ onPanelChange("styles");
136
+ onFetchFigma();
137
+ setTimeout(onRefreshRendered, 100);
138
+ }, [onPanelChange, onFetchFigma, onRefreshRendered]);
139
+
140
+ const handleTabChange = useCallback(
141
+ (value: string | number) => {
142
+ const panel = String(value);
143
+ if (panel === "styles") {
144
+ handleStylesClick();
145
+ } else {
146
+ onPanelChange(panel as ActivePanel);
147
+ }
148
+ },
149
+ [handleStylesClick, onPanelChange]
150
+ );
151
+
152
+ return (
153
+ <Drawer open={open} onOpenChange={onOpenChange} modal={false}>
154
+ {/* Floating trigger FAB — fixed bottom-right, moves up when drawer is open */}
155
+ <Tooltip content={open ? "Close dev tools" : "Open dev tools"} side="left">
156
+ <Drawer.Trigger asChild>
157
+ <Button
158
+ variant={open ? "secondary" : "primary"}
159
+ icon
160
+ size="md"
161
+ aria-label={open ? "Close dev tools" : "Open dev tools"}
162
+ style={{
163
+ position: "fixed",
164
+ bottom: open ? `${height + 16}px` : "16px",
165
+ right: "16px",
166
+ zIndex: 52,
167
+ borderRadius: "50%",
168
+ boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15), 0 2px 4px rgba(0, 0, 0, 0.1)",
169
+ transition: "bottom 300ms ease, box-shadow 200ms ease",
170
+ width: "44px",
171
+ height: "44px",
172
+ }}
173
+ >
174
+ <Terminal size={20} weight={open ? "fill" : "regular"} />
175
+ </Button>
176
+ </Drawer.Trigger>
177
+ </Tooltip>
178
+
179
+ <Drawer.Content
180
+ side="bottom"
181
+ backdrop={false}
182
+ id="bottom-panel"
183
+ aria-label="Bottom panel"
184
+ style={{
185
+ height: `${height}px`,
186
+ transition: isResizing ? "none" : undefined,
187
+ }}
188
+ >
189
+ {/* Full-viewport overlay during resize — prevents iframes from capturing events */}
190
+ {isResizing && (
191
+ <div
192
+ style={{
193
+ position: "fixed",
194
+ inset: 0,
195
+ zIndex: 52,
196
+ cursor: "ns-resize",
197
+ }}
198
+ />
199
+ )}
200
+
201
+ {/* Resize grab handle */}
202
+ <div
203
+ onMouseDown={handleMouseDown}
204
+ style={{
205
+ width: "100%",
206
+ display: "flex",
207
+ justifyContent: "center",
208
+ padding: "6px 0 2px",
209
+ cursor: "ns-resize",
210
+ flexShrink: 0,
211
+ }}
212
+ >
213
+ <div
214
+ style={{
215
+ width: "36px",
216
+ height: "4px",
217
+ borderRadius: "9999px",
218
+ backgroundColor: "var(--fui-text-muted, var(--text-muted))",
219
+ opacity: isResizing ? 0.8 : 0.3,
220
+ transition: "opacity 150ms ease",
221
+ }}
222
+ />
223
+ </div>
224
+
225
+ {/* Header with tabs */}
226
+ <Drawer.Header
227
+ style={{
228
+ padding: "0 16px",
229
+ borderBottom: "1px solid var(--fui-border-subtle, var(--border-subtle))",
230
+ }}
231
+ >
232
+ <Tabs value={activePanel} onValueChange={handleTabChange}>
233
+ <Tabs.List variant="pills">
234
+ {figmaUrl && <Tabs.Tab value="styles">Styles</Tabs.Tab>}
235
+ <Tabs.Tab value="accessibility">Accessibility</Tabs.Tab>
236
+ {variant?.hasPlayFunction && (
237
+ <Tabs.Tab value="interactions">Interactions</Tabs.Tab>
238
+ )}
239
+ <Tabs.Tab value="graph">Graph</Tabs.Tab>
240
+ <Tabs.Tab value="performance">Performance</Tabs.Tab>
241
+ </Tabs.List>
242
+ </Tabs>
243
+ </Drawer.Header>
244
+
245
+ {/* Panel Content */}
246
+ <Drawer.Body style={{ padding: 0 }}>
247
+ {activePanel === "styles" && figmaUrl && (
248
+ <TokenStylePanel
249
+ figmaUrl={figmaUrl}
250
+ figmaStyles={figmaStyles}
251
+ renderedStyles={renderedStyles}
252
+ figmaLoading={figmaLoading}
253
+ figmaError={figmaError}
254
+ onFetchFigma={onFetchFigma}
255
+ onRefreshRendered={onRefreshRendered}
256
+ />
257
+ )}
258
+
259
+ {activePanel === "accessibility" && (
260
+ <AccessibilityPanel
261
+ cacheKey={fragmentKey}
262
+ previewKey={previewKey}
263
+ autoScan={true}
264
+ componentName={fragment.meta.name}
265
+ variantName={variant.name}
266
+ />
267
+ )}
268
+
269
+ {activePanel === "interactions" && (
270
+ <InteractionsPanel key={fragmentKey} variant={variant} previewKey={previewKey} />
271
+ )}
272
+
273
+ {activePanel === "graph" && (
274
+ <ComponentGraph
275
+ fragment={fragment}
276
+ allFragments={fragments}
277
+ onNavigate={onNavigateToComponent}
278
+ />
279
+ )}
280
+
281
+ {activePanel === "performance" && (
282
+ <PerformancePanel componentName={fragment.meta.name} />
283
+ )}
284
+ </Drawer.Body>
285
+ </Drawer.Content>
286
+ </Drawer>
287
+ );
288
+ });
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import type { FragmentVariant } from '@fragments-sdk/core';
3
+
4
+ vi.mock('@fragments-sdk/ui', () => ({
5
+ CodeBlock: () => null,
6
+ }));
7
+
8
+ const {
9
+ __buildFallbackSnippetForTest,
10
+ __resolveDisplayedCodeForTest,
11
+ } = await import('./CodePanel.js');
12
+
13
+ function makeVariant(partial: Partial<FragmentVariant>): FragmentVariant {
14
+ return {
15
+ name: 'Default',
16
+ description: 'Default variant',
17
+ render: () => null,
18
+ ...partial,
19
+ };
20
+ }
21
+
22
+ describe('CodePanel authored code pipeline', () => {
23
+ it('prefers authored variant.code as-is', () => {
24
+ const variant = makeVariant({
25
+ code: `import { Button } from '@fragments-sdk/ui';\n\n<Button>Save</Button>`,
26
+ });
27
+
28
+ const resolved = __resolveDisplayedCodeForTest('Button', variant);
29
+
30
+ expect(resolved).toBe(`import { Button } from '@fragments-sdk/ui';\n\n<Button>Save</Button>`);
31
+ });
32
+
33
+ it('falls back to generated placeholder when variant.code is missing', () => {
34
+ const variant = makeVariant({
35
+ name: 'Primary',
36
+ args: {
37
+ variant: 'primary',
38
+ disabled: false,
39
+ children: 'Save Changes',
40
+ },
41
+ });
42
+
43
+ const code = __buildFallbackSnippetForTest('Button', variant);
44
+
45
+ expect(code).toContain("import { Button } from '@/components/Button';");
46
+ expect(code).toContain("<Button variant='primary' disabled={false}>Save Changes</Button>");
47
+ });
48
+
49
+ it('does not synthesize runtime JSX output', () => {
50
+ const variant = makeVariant({
51
+ code: '<Button icon={/* @__PURE__ */ jsxDEV(GearIcon, {}, void 0)} />',
52
+ });
53
+
54
+ const resolved = __resolveDisplayedCodeForTest('Button', variant);
55
+
56
+ // CodePanel now treats authored code as source-of-truth only.
57
+ expect(resolved).toContain('jsxDEV');
58
+ });
59
+ });
@@ -0,0 +1,118 @@
1
+ import { useMemo } from 'react';
2
+ import { CodeBlock } from '@fragments-sdk/ui';
3
+ import type { FragmentVariant, PropDefinition } from '@fragments-sdk/core';
4
+
5
+ interface CodePanelProps {
6
+ variant: FragmentVariant;
7
+ componentName: string;
8
+ compact?: boolean;
9
+ propDefs?: Record<string, PropDefinition>;
10
+ }
11
+
12
+ function quoteString(value: string): string {
13
+ return `'${value
14
+ .replace(/\\/g, '\\\\')
15
+ .replace(/'/g, "\\'")
16
+ .replace(/\n/g, '\\n')
17
+ }'`;
18
+ }
19
+
20
+ function serializeValue(value: unknown): string | null {
21
+ if (value === null) return '{null}';
22
+ if (value === undefined) return null;
23
+
24
+ if (typeof value === 'string') {
25
+ return quoteString(value);
26
+ }
27
+
28
+ if (typeof value === 'number' || typeof value === 'boolean') {
29
+ return `{${String(value)}}`;
30
+ }
31
+
32
+ if (Array.isArray(value)) {
33
+ const items = value
34
+ .map((item) => serializeValue(item))
35
+ .filter((item): item is string => item !== null)
36
+ .map((item) => (item.startsWith('{') && item.endsWith('}') ? item.slice(1, -1) : item));
37
+
38
+ if (items.length === 0) return '{[]}';
39
+ return `{[${items.join(', ')}]}`;
40
+ }
41
+
42
+ if (typeof value === 'object') {
43
+ return '{/* complex value */}';
44
+ }
45
+
46
+ return null;
47
+ }
48
+
49
+ function toSingleLine(code: string): string {
50
+ return code
51
+ .split('\n')
52
+ .map((line) => line.trim())
53
+ .filter(Boolean)
54
+ .join(' ')
55
+ .trim();
56
+ }
57
+
58
+ function buildFallbackSnippet(componentName: string, variant: FragmentVariant): string {
59
+ const args = variant.args ?? {};
60
+ const propEntries = Object.entries(args)
61
+ .filter(([name, value]) => name !== 'children' && typeof value !== 'function')
62
+ .map(([name, value]) => {
63
+ const serialized = serializeValue(value);
64
+ return serialized ? `${name}=${serialized}` : null;
65
+ })
66
+ .filter((entry): entry is string => entry !== null);
67
+
68
+ const children = typeof args.children === 'string' ? args.children : null;
69
+ const openTag = propEntries.length > 0
70
+ ? `<${componentName} ${propEntries.join(' ')}>`
71
+ : `<${componentName}>`;
72
+
73
+ const usage = children
74
+ ? `${openTag}${children}</${componentName}>`
75
+ : toSingleLine(`${openTag}</${componentName}>`);
76
+
77
+ return `import { ${componentName} } from '@/components/${componentName}';
78
+
79
+ ${usage}`;
80
+ }
81
+
82
+ function normalizeAuthoredSnippet(code: string): string {
83
+ const normalized = code.replace(/\r\n/g, '\n').trim();
84
+ return normalized.length > 0 ? normalized : '';
85
+ }
86
+
87
+ export function __buildFallbackSnippetForTest(componentName: string, variant: FragmentVariant): string {
88
+ return buildFallbackSnippet(componentName, variant);
89
+ }
90
+
91
+ export function resolveDisplayedCode(componentName: string, variant: FragmentVariant): string {
92
+ if (typeof variant.code === 'string') {
93
+ const normalized = normalizeAuthoredSnippet(variant.code);
94
+ if (normalized.length > 0) {
95
+ return normalized;
96
+ }
97
+ }
98
+
99
+ return buildFallbackSnippet(componentName, variant);
100
+ }
101
+
102
+ export function __resolveDisplayedCodeForTest(componentName: string, variant: FragmentVariant): string {
103
+ return resolveDisplayedCode(componentName, variant);
104
+ }
105
+
106
+ export function CodePanel({ variant, componentName, compact = false }: CodePanelProps) {
107
+ const code = useMemo(() => resolveDisplayedCode(componentName, variant), [componentName, variant]);
108
+
109
+ return (
110
+ <CodeBlock
111
+ code={code}
112
+ language="tsx"
113
+ showCopy
114
+ maxHeight={400}
115
+ compact={compact}
116
+ />
117
+ );
118
+ }