@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
package/src/entry.tsx ADDED
@@ -0,0 +1,335 @@
1
+ import { createRoot, type Root } from "react-dom/client";
2
+ import { Component, type ReactNode, type ErrorInfo } from "react";
3
+ import { App } from "./components/App.js";
4
+ import { ThemeProvider } from "./components/ThemeProvider.js";
5
+ import { ToastProvider } from "./components/Toast.js";
6
+ import { AppSkeleton } from "./components/SkeletonLoader.js";
7
+ import { WebMCPIntegration } from "./components/WebMCPIntegration.js";
8
+ // Fragments UI globals - base resets (box-sizing, body, scrollbars) + --fui-* CSS variables
9
+ import "@fragments-sdk/ui";
10
+ // Viewer-specific token aliases and utility classes
11
+ import "./styles/globals.css";
12
+
13
+ // App-level error boundary that catches any unhandled errors
14
+ class AppErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean; error: Error | null; errorInfo: ErrorInfo | null }> {
15
+ constructor(props: { children: ReactNode }) {
16
+ super(props);
17
+ this.state = { hasError: false, error: null, errorInfo: null };
18
+ }
19
+
20
+ static getDerivedStateFromError(error: Error) {
21
+ return { hasError: true, error };
22
+ }
23
+
24
+ componentDidCatch(error: Error, errorInfo: ErrorInfo) {
25
+ console.error('[Fragments] App Error:', error);
26
+ console.error('[Fragments] Component Stack:', errorInfo.componentStack);
27
+ this.setState({ errorInfo });
28
+ }
29
+
30
+ handleRetry = () => {
31
+ this.setState({ hasError: false, error: null, errorInfo: null });
32
+ window.location.reload();
33
+ };
34
+
35
+ render() {
36
+ if (this.state.hasError) {
37
+ const { error, errorInfo } = this.state;
38
+ return (
39
+ <div style={{
40
+ fontFamily: 'system-ui, -apple-system, sans-serif',
41
+ padding: '40px',
42
+ maxWidth: '800px',
43
+ margin: '0 auto',
44
+ }}>
45
+ <div style={{
46
+ background: '#fef2f2',
47
+ border: '1px solid #fecaca',
48
+ borderRadius: '12px',
49
+ padding: '24px',
50
+ }}>
51
+ <h1 style={{ color: '#dc2626', marginBottom: '16px', fontSize: '20px', fontWeight: 600 }}>
52
+ Application Error
53
+ </h1>
54
+ <p style={{ color: '#991b1b', marginBottom: '16px', fontSize: '14px' }}>
55
+ An error occurred while rendering the application:
56
+ </p>
57
+ <pre style={{
58
+ background: '#fee2e2',
59
+ border: '1px solid #fecaca',
60
+ borderRadius: '8px',
61
+ padding: '16px',
62
+ overflow: 'auto',
63
+ whiteSpace: 'pre-wrap',
64
+ wordBreak: 'break-word',
65
+ color: '#991b1b',
66
+ fontSize: '13px',
67
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
68
+ marginBottom: '16px',
69
+ }}>
70
+ {error?.message || 'Unknown error'}
71
+ </pre>
72
+ {errorInfo?.componentStack && (
73
+ <details style={{ marginBottom: '16px' }}>
74
+ <summary style={{
75
+ color: '#b91c1c',
76
+ cursor: 'pointer',
77
+ fontSize: '13px',
78
+ marginBottom: '8px',
79
+ }}>
80
+ Show component stack trace
81
+ </summary>
82
+ <pre style={{
83
+ background: '#fee2e2',
84
+ border: '1px solid #fecaca',
85
+ borderRadius: '8px',
86
+ padding: '12px',
87
+ overflow: 'auto',
88
+ whiteSpace: 'pre-wrap',
89
+ wordBreak: 'break-word',
90
+ color: '#7f1d1d',
91
+ fontSize: '11px',
92
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
93
+ maxHeight: '300px',
94
+ }}>
95
+ {error?.stack || errorInfo.componentStack}
96
+ </pre>
97
+ </details>
98
+ )}
99
+ <button
100
+ onClick={this.handleRetry}
101
+ style={{
102
+ background: '#dc2626',
103
+ color: 'white',
104
+ border: 'none',
105
+ borderRadius: '6px',
106
+ padding: '10px 16px',
107
+ fontSize: '14px',
108
+ fontWeight: 500,
109
+ cursor: 'pointer',
110
+ }}
111
+ >
112
+ Reload Application
113
+ </button>
114
+ </div>
115
+ <p style={{ marginTop: '16px', color: '#6b7280', fontSize: '13px' }}>
116
+ Check the browser console for more details. Common causes:
117
+ </p>
118
+ <ul style={{ color: '#6b7280', marginTop: '8px', paddingLeft: '20px', fontSize: '13px' }}>
119
+ <li>Syntax errors in fragment or component files</li>
120
+ <li>Missing or undefined imports</li>
121
+ <li>Components that crash during render</li>
122
+ <li>Invalid props passed to components</li>
123
+ </ul>
124
+ </div>
125
+ );
126
+ }
127
+
128
+ return this.props.children;
129
+ }
130
+ }
131
+
132
+ // Declare global types
133
+ declare global {
134
+ interface Window {
135
+ __FRAGMENTS__?: Array<{
136
+ path: string;
137
+ fragment: import("../core/index.js").FragmentDefinition;
138
+ }>;
139
+ __FRAGMENTS_CONFIG__?: import("../core/index.js").FragmentsConfig;
140
+ __FRAGMENTS_PACKAGE_NAME__?: string | null;
141
+ __FRAGMENTS_ERROR__?: string;
142
+ }
143
+ }
144
+
145
+ type FragmentItem = {
146
+ path: string;
147
+ fragment: import("../core/index.js").FragmentDefinition;
148
+ };
149
+
150
+ // Initialize fragments from window or empty array
151
+ let fragments: FragmentItem[] = window.__FRAGMENTS__ ?? [];
152
+ let loadError: string | null = window.__FRAGMENTS_ERROR__ ?? null;
153
+ let appRoot: Root | null = null;
154
+ const SKELETON_DELAY_MS = 120;
155
+ const MIN_SKELETON_DISPLAY_MS = 220;
156
+
157
+ // Filter helper
158
+ function filterValidFragments(items: FragmentItem[]): FragmentItem[] {
159
+ return items.filter(s => s && s.fragment && s.fragment.meta);
160
+ }
161
+
162
+ // Async loader for virtual module (runs after initial render)
163
+ async function loadFragmentsFromVirtualModule(): Promise<void> {
164
+ if (fragments.length > 0 || loadError) {
165
+ // Already have fragments or error from window
166
+ return;
167
+ }
168
+
169
+ try {
170
+ // @ts-expect-error Virtual module
171
+ const virtualModule = await import("virtual:fragments");
172
+ // Wait for lazy-loaded fragments
173
+ if (virtualModule.fragmentsPromise) {
174
+ fragments = await virtualModule.fragmentsPromise;
175
+ } else {
176
+ fragments = virtualModule.fragments;
177
+ }
178
+ fragments = filterValidFragments(fragments);
179
+ // Store consumer package name for import path display
180
+ if (virtualModule.projectPackageName) {
181
+ window.__FRAGMENTS_PACKAGE_NAME__ = virtualModule.projectPackageName;
182
+ }
183
+ } catch (e) {
184
+ const error = e as Error;
185
+ loadError = error.message || "Failed to load fragments";
186
+ console.error("[Fragments] Failed to load:", error);
187
+ }
188
+ }
189
+
190
+ // Filter initial fragments
191
+ fragments = filterValidFragments(fragments);
192
+
193
+ // Error display component
194
+ function ErrorDisplay({ error }: { error: string }) {
195
+ return (
196
+ <div style={{
197
+ fontFamily: 'system-ui, -apple-system, sans-serif',
198
+ padding: '40px',
199
+ maxWidth: '600px',
200
+ margin: '0 auto',
201
+ }}>
202
+ <h1 style={{ color: '#dc2626', marginBottom: '16px' }}>
203
+ Failed to Load Fragments
204
+ </h1>
205
+ <pre style={{
206
+ background: '#fef2f2',
207
+ border: '1px solid #fecaca',
208
+ borderRadius: '8px',
209
+ padding: '16px',
210
+ overflow: 'auto',
211
+ whiteSpace: 'pre-wrap',
212
+ wordBreak: 'break-word',
213
+ color: '#991b1b',
214
+ fontSize: '14px',
215
+ }}>
216
+ {error}
217
+ </pre>
218
+ <p style={{ marginTop: '16px', color: '#6b7280' }}>
219
+ Check the console for more details. Common issues:
220
+ </p>
221
+ <ul style={{ color: '#6b7280', marginTop: '8px', paddingLeft: '20px' }}>
222
+ <li>Fragment files have syntax errors</li>
223
+ <li>Components are not exported correctly</li>
224
+ <li>Missing dependencies</li>
225
+ </ul>
226
+ </div>
227
+ );
228
+ }
229
+
230
+ // Render the app
231
+ const rootElement = document.getElementById("root");
232
+ if (rootElement) {
233
+ appRoot = createRoot(rootElement);
234
+
235
+ const renderApp = (showSkeleton = false) => {
236
+ const currentFragments = window.__FRAGMENTS__ ?? fragments;
237
+ const currentError = loadError || window.__FRAGMENTS_ERROR__;
238
+
239
+ // Show skeleton while loading
240
+ if (showSkeleton && currentFragments.length === 0 && !currentError) {
241
+ appRoot?.render(
242
+ <ThemeProvider>
243
+ <AppSkeleton />
244
+ </ThemeProvider>
245
+ );
246
+ return;
247
+ }
248
+
249
+ // Show error if we have one and no valid fragments
250
+ if (currentError && currentFragments.length === 0) {
251
+ appRoot?.render(<ErrorDisplay error={currentError} />);
252
+ return;
253
+ }
254
+
255
+ appRoot?.render(
256
+ <ThemeProvider>
257
+ <ToastProvider position="bottom-right" duration={3000}>
258
+ <WebMCPIntegration>
259
+ <AppErrorBoundary>
260
+ <App fragments={currentFragments} />
261
+ </AppErrorBoundary>
262
+ </WebMCPIntegration>
263
+ </ToastProvider>
264
+ </ThemeProvider>
265
+ );
266
+ };
267
+
268
+ // Show skeleton immediately if no fragments yet
269
+ if (fragments.length === 0 && !loadError) {
270
+ const loadStartedAt = Date.now();
271
+ let skeletonShown = false;
272
+
273
+ const skeletonTimer = setTimeout(() => {
274
+ skeletonShown = true;
275
+ renderApp(true);
276
+ }, SKELETON_DELAY_MS);
277
+
278
+ // Load fragments asynchronously and re-render
279
+ loadFragmentsFromVirtualModule().then(() => {
280
+ clearTimeout(skeletonTimer);
281
+
282
+ if (!skeletonShown) {
283
+ renderApp(false);
284
+ return;
285
+ }
286
+
287
+ const elapsed = Date.now() - loadStartedAt;
288
+ const remaining = Math.max(MIN_SKELETON_DISPLAY_MS - elapsed, 0);
289
+ if (remaining === 0) {
290
+ renderApp(false);
291
+ return;
292
+ }
293
+
294
+ setTimeout(() => {
295
+ renderApp(false);
296
+ }, remaining);
297
+ });
298
+ } else {
299
+ // We have fragments from window, render immediately
300
+ renderApp(false);
301
+ }
302
+
303
+ // Listen for HMR updates from Fragments plugin
304
+ window.addEventListener("fragments:update", () => {
305
+ console.log("[Fragments] Refreshing viewer...");
306
+ // Re-render with updated fragments
307
+ renderApp(false);
308
+ });
309
+ }
310
+
311
+ // HMR support for entry file and a11y invalidation
312
+ // @ts-expect-error Vite HMR types
313
+ if (import.meta.hot) {
314
+ // @ts-expect-error Vite HMR types
315
+ import.meta.hot.accept();
316
+
317
+ // Subscribe to a11y invalidation events from Vite plugin
318
+ // @ts-expect-error Vite HMR types
319
+ import.meta.hot.on("fragments:a11y-invalidate", (data: {
320
+ components: string[];
321
+ file: string;
322
+ timestamp: number;
323
+ }) => {
324
+ console.log("[Fragments] A11y invalidation triggered for:", data.components.join(", "));
325
+
326
+ // Dispatch custom event for a11y service to handle
327
+ window.dispatchEvent(new CustomEvent("a11y-cache-invalidated", {
328
+ detail: {
329
+ components: data.components,
330
+ file: data.file,
331
+ timestamp: data.timestamp,
332
+ },
333
+ }));
334
+ });
335
+ }
@@ -0,0 +1,2 @@
1
+ export * from './useHmrStatus.js';
2
+ export * from './usePreviewBridge.js';