@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,271 @@
1
+ /**
2
+ * ResizablePanel - A bottom-docked panel that can be resized by dragging
3
+ *
4
+ * Features:
5
+ * - Drag-to-resize from the top edge
6
+ * - Collapsible via chevron toggle
7
+ * - Persists size and open state to localStorage
8
+ */
9
+
10
+ import {
11
+ useState,
12
+ useEffect,
13
+ useCallback,
14
+ useRef,
15
+ type ReactNode,
16
+ type CSSProperties,
17
+ } from "react";
18
+ import { BRAND } from '@fragments-sdk/core';
19
+ import { ChevronDownIcon } from "./Icons.js";
20
+ import { Box, Stack, Button } from "@fragments-sdk/ui";
21
+
22
+ // Storage key for persisting panel state
23
+ const STORAGE_KEY = `${BRAND.storagePrefix}panel-state`;
24
+
25
+ interface PanelState {
26
+ height: number;
27
+ isOpen: boolean;
28
+ }
29
+
30
+ const DEFAULT_STATE: PanelState = {
31
+ height: 180,
32
+ isOpen: true,
33
+ };
34
+
35
+ const MIN_HEIGHT = 120;
36
+ const MAX_HEIGHT = 600;
37
+
38
+ function loadPanelState(): PanelState {
39
+ try {
40
+ const stored = localStorage.getItem(STORAGE_KEY);
41
+ if (stored) {
42
+ const parsed = JSON.parse(stored);
43
+ return { ...DEFAULT_STATE, ...parsed };
44
+ }
45
+ } catch {
46
+ // Ignore parse errors
47
+ }
48
+ return DEFAULT_STATE;
49
+ }
50
+
51
+ function savePanelState(state: PanelState): void {
52
+ try {
53
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
54
+ } catch {
55
+ // Ignore storage errors
56
+ }
57
+ }
58
+
59
+ interface ResizablePanelProps extends React.HTMLAttributes<HTMLDivElement> {
60
+ /** Panel header content (tabs, title, etc.) */
61
+ header: ReactNode;
62
+ /** Panel body content */
63
+ children: ReactNode;
64
+ /** Whether to show the panel at all */
65
+ visible?: boolean;
66
+ /** Additional class name for the panel container */
67
+ className?: string;
68
+ }
69
+
70
+ export function ResizablePanel({
71
+ header,
72
+ children,
73
+ visible = true,
74
+ className,
75
+ ...props
76
+ }: ResizablePanelProps) {
77
+ const [state, setState] = useState<PanelState>(loadPanelState);
78
+ const [isResizing, setIsResizing] = useState(false);
79
+ const panelRef = useRef<HTMLDivElement>(null);
80
+ const startYRef = useRef(0);
81
+ const startHeightRef = useRef(0);
82
+
83
+ // Save state changes to localStorage
84
+ useEffect(() => {
85
+ savePanelState(state);
86
+ }, [state]);
87
+
88
+ const handleMouseDown = useCallback(
89
+ (e: React.MouseEvent) => {
90
+ e.preventDefault();
91
+ setIsResizing(true);
92
+ startYRef.current = e.clientY;
93
+ startHeightRef.current = state.height;
94
+ },
95
+ [state.height]
96
+ );
97
+
98
+ const handleMouseMove = useCallback(
99
+ (e: MouseEvent) => {
100
+ if (!isResizing) return;
101
+
102
+ const deltaY = startYRef.current - e.clientY;
103
+ const newHeight = Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, startHeightRef.current + deltaY));
104
+ setState((s) => ({ ...s, height: newHeight }));
105
+ },
106
+ [isResizing]
107
+ );
108
+
109
+ const handleMouseUp = useCallback(() => {
110
+ setIsResizing(false);
111
+ }, []);
112
+
113
+ // Add global mouse event listeners during resize
114
+ useEffect(() => {
115
+ if (isResizing) {
116
+ document.addEventListener("mousemove", handleMouseMove);
117
+ document.addEventListener("mouseup", handleMouseUp);
118
+ document.body.style.cursor = "ns-resize";
119
+ document.body.style.userSelect = "none";
120
+
121
+ return () => {
122
+ document.removeEventListener("mousemove", handleMouseMove);
123
+ document.removeEventListener("mouseup", handleMouseUp);
124
+ document.body.style.cursor = "";
125
+ document.body.style.userSelect = "";
126
+ };
127
+ }
128
+ }, [isResizing, handleMouseMove, handleMouseUp]);
129
+
130
+ const toggleOpen = useCallback(() => {
131
+ setState((s) => ({ ...s, isOpen: !s.isOpen }));
132
+ }, []);
133
+
134
+ if (!visible) return null;
135
+
136
+ const isOpen = state.isOpen;
137
+
138
+ // Heights for layout calculation
139
+ const headerHeight = 40; // h-10 = 2.5rem = 40px
140
+ const grabHandleHeight = 12; // 6px top padding + 4px pill + 2px bottom padding
141
+
142
+ // Compute container styles — drawer appearance
143
+ const containerStyle: CSSProperties = {
144
+ flexShrink: 0,
145
+ backgroundColor: "var(--bg-secondary)",
146
+ // Only transition when NOT resizing (for smooth open/close animations)
147
+ transition: isResizing ? "none" : "height 300ms ease",
148
+ height: isOpen ? state.height : headerHeight,
149
+ // Prevent content from being selected during resize
150
+ ...(isResizing && { pointerEvents: "none" as const }),
151
+ position: "sticky",
152
+ bottom: 0,
153
+ // Drawer visual treatment
154
+ borderTopLeftRadius: "12px",
155
+ borderTopRightRadius: "12px",
156
+ boxShadow: "0 -4px 16px rgba(0, 0, 0, 0.08), 0 -1px 4px rgba(0, 0, 0, 0.04)",
157
+ borderTop: "1px solid var(--border)",
158
+ };
159
+
160
+ // Resize handle styles — extends above panel for easier grabbing
161
+ const resizeHandleStyle: CSSProperties = {
162
+ position: "absolute",
163
+ zIndex: 20,
164
+ top: "-8px",
165
+ left: 0,
166
+ right: 0,
167
+ height: "16px",
168
+ cursor: "ns-resize",
169
+ ...(isResizing && { backgroundColor: "rgba(var(--color-accent-rgb, 59, 130, 246), 0.2)" }),
170
+ };
171
+
172
+ // Grab handle pill — always visible in drawer style
173
+ const grabHandleStyle: CSSProperties = {
174
+ width: "100%",
175
+ display: "flex",
176
+ justifyContent: "center",
177
+ padding: "6px 0 2px",
178
+ cursor: "ns-resize",
179
+ };
180
+
181
+ const grabPillStyle: CSSProperties = {
182
+ width: "36px",
183
+ height: "4px",
184
+ borderRadius: "9999px",
185
+ backgroundColor: "var(--text-muted)",
186
+ opacity: isResizing ? 0.8 : 0.3,
187
+ transition: "opacity 150ms ease",
188
+ };
189
+
190
+ // Chevron icon rotation
191
+ const chevronStyle: CSSProperties = {
192
+ width: "16px",
193
+ height: "16px",
194
+ transition: "transform 150ms ease",
195
+ ...(!isOpen && { transform: "rotate(180deg)" }),
196
+ };
197
+
198
+ return (
199
+ <div ref={panelRef} className={className} style={containerStyle} {...props}>
200
+ {/* Full-viewport overlay during resize - prevents iframes from capturing events */}
201
+ {isResizing && (
202
+ <div
203
+ style={{
204
+ position: "fixed",
205
+ inset: 0,
206
+ zIndex: 50,
207
+ cursor: "ns-resize",
208
+ // Must explicitly enable pointer events since parent has pointerEvents: none
209
+ pointerEvents: "auto",
210
+ }}
211
+ />
212
+ )}
213
+
214
+ {/* Resize Handle - extends above panel for easier grabbing */}
215
+ {isOpen && (
216
+ <div
217
+ style={resizeHandleStyle}
218
+ onMouseDown={handleMouseDown}
219
+ />
220
+ )}
221
+
222
+ {/* Grab handle pill — always visible drawer indicator */}
223
+ {isOpen && (
224
+ <div
225
+ style={grabHandleStyle}
226
+ onMouseDown={handleMouseDown}
227
+ onMouseEnter={(e) => {
228
+ const pill = e.currentTarget.querySelector("[data-grab-pill]") as HTMLElement;
229
+ if (pill) pill.style.opacity = "0.6";
230
+ }}
231
+ onMouseLeave={(e) => {
232
+ const pill = e.currentTarget.querySelector("[data-grab-pill]") as HTMLElement;
233
+ if (pill) pill.style.opacity = isResizing ? "0.8" : "0.3";
234
+ }}
235
+ >
236
+ <div data-grab-pill style={grabPillStyle} />
237
+ </div>
238
+ )}
239
+
240
+ {/* Panel Header */}
241
+ <Stack direction="row" align="center" justify="between" style={{ padding: '0 16px', height: '40px', borderBottom: '1px solid var(--border-subtle)' }}>
242
+ <Stack direction="row" align="center" gap="xs" style={{ flex: 1, overflow: 'hidden' }}>
243
+ {header}
244
+ </Stack>
245
+ <Stack direction="row" align="center" gap="xs">
246
+ {/* Collapse toggle button */}
247
+ <Button
248
+ variant="ghost"
249
+ size="sm"
250
+ icon
251
+ onClick={toggleOpen}
252
+ aria-label={isOpen ? "Collapse panel" : "Expand panel"}
253
+ >
254
+ <span style={chevronStyle}>
255
+ <ChevronDownIcon />
256
+ </span>
257
+ </Button>
258
+ </Stack>
259
+ </Stack>
260
+
261
+ {/* Panel Content */}
262
+ {isOpen && (
263
+ <Box overflow="auto" style={{ height: `calc(100% - ${headerHeight}px)`, width: '100%' }}>
264
+ {children}
265
+ </Box>
266
+ )}
267
+ </div>
268
+ );
269
+ }
270
+
271
+ export default ResizablePanel;
@@ -0,0 +1,102 @@
1
+ import type { FragmentDefinition } from '@fragments-sdk/core';
2
+ import { useScrollSpy } from '../hooks/useScrollSpy.js';
3
+ import { Sidebar, Text } from '@fragments-sdk/ui';
4
+
5
+ interface RightSidebarProps {
6
+ fragment: FragmentDefinition;
7
+ }
8
+
9
+ interface TocItem {
10
+ id: string;
11
+ label: string;
12
+ children?: TocItem[];
13
+ }
14
+
15
+ export function RightSidebar({ fragment }: RightSidebarProps) {
16
+ // Build table of contents from fragment
17
+ const tocItems: TocItem[] = [];
18
+
19
+ // Overview section
20
+ tocItems.push({ id: 'overview', label: 'Overview' });
21
+
22
+ // Variants section with nested items
23
+ if (fragment.variants && fragment.variants.length > 0) {
24
+ tocItems.push({
25
+ id: 'variants',
26
+ label: 'Variants',
27
+ children: fragment.variants.map((variant, index) => ({
28
+ id: `variant-${index}`,
29
+ label: variant.name,
30
+ })),
31
+ });
32
+ }
33
+
34
+ // Usage section
35
+ if (fragment.usage) {
36
+ tocItems.push({ id: 'usage', label: 'Usage' });
37
+ }
38
+
39
+ // Props section
40
+ if (fragment.props && Object.keys(fragment.props).length > 0) {
41
+ tocItems.push({ id: 'props', label: 'Props' });
42
+ }
43
+
44
+ // Relations section
45
+ if (fragment.relations && fragment.relations.length > 0) {
46
+ tocItems.push({ id: 'relations', label: 'Relations' });
47
+ }
48
+
49
+ // Flatten for scroll spy
50
+ const allIds = tocItems.flatMap((item) => [
51
+ item.id,
52
+ ...(item.children?.map((child) => child.id) ?? []),
53
+ ]);
54
+
55
+ const { activeId, scrollToSection } = useScrollSpy({
56
+ sectionIds: allIds,
57
+ offset: 100,
58
+ });
59
+
60
+ return (
61
+ <Sidebar position="right" collapsible="none" style={{ padding: '8px 0' }}>
62
+ <Sidebar.Header>
63
+ <Text size="2xs" weight="medium" color="tertiary" style={{ textTransform: 'uppercase', letterSpacing: '0.05em' }}>
64
+ On this page
65
+ </Text>
66
+ </Sidebar.Header>
67
+ <Sidebar.Nav aria-label="On this page">
68
+ {tocItems.map((item) => {
69
+ const isActive = activeId === item.id;
70
+ const hasActiveChild = item.children?.some((child) => activeId === child.id);
71
+
72
+ return (
73
+ <Sidebar.Section key={item.id}>
74
+ <Sidebar.Item
75
+ active={isActive || !!hasActiveChild}
76
+ onClick={() => scrollToSection(item.id)}
77
+ >
78
+ {item.label}
79
+ </Sidebar.Item>
80
+ {item.children && item.children.length > 0 && (
81
+ <>
82
+ {item.children.map((child) => {
83
+ const isChildActive = activeId === child.id;
84
+ return (
85
+ <Sidebar.SubItem
86
+ key={child.id}
87
+ active={isChildActive}
88
+ onClick={() => scrollToSection(child.id)}
89
+ >
90
+ {child.label}
91
+ </Sidebar.SubItem>
92
+ );
93
+ })}
94
+ </>
95
+ )}
96
+ </Sidebar.Section>
97
+ );
98
+ })}
99
+ </Sidebar.Nav>
100
+ </Sidebar>
101
+ );
102
+ }
@@ -0,0 +1,17 @@
1
+ import { useMemo } from 'react';
2
+ import { useWebMCPTools } from '@fragments-sdk/webmcp/react';
3
+ import { useCompiledFragments } from '../hooks/useCompiledFragments.js';
4
+ import { createRuntimeWebMCPTools } from '../webmcp/runtime-tools.js';
5
+
6
+ export function RuntimeToolsRegistrar() {
7
+ const { data } = useCompiledFragments();
8
+
9
+ const tools = useMemo(() => {
10
+ if (!data) return [];
11
+ return createRuntimeWebMCPTools({ compiledData: data });
12
+ }, [data]);
13
+
14
+ useWebMCPTools(tools);
15
+
16
+ return null;
17
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * ScreenshotButton component - captures screenshots of the preview area.
3
+ * Saves directly to file.
4
+ */
5
+
6
+ import { useState, memo } from 'react';
7
+ import html2canvas from 'html2canvas';
8
+ import { Button, Tooltip } from '@fragments-sdk/ui';
9
+ import { CameraIcon } from './Icons.js';
10
+
11
+ interface ScreenshotButtonProps {
12
+ componentName: string;
13
+ variantName: string;
14
+ }
15
+
16
+ export const ScreenshotButton = memo(function ScreenshotButton({ componentName, variantName }: ScreenshotButtonProps) {
17
+ const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
18
+
19
+ const handleSaveToFile = async () => {
20
+ setStatus('loading');
21
+ try {
22
+ const previewContainer = document.querySelector('[data-preview-container="true"]');
23
+ if (!previewContainer) throw new Error('Preview container not found');
24
+
25
+ await document.fonts.ready;
26
+
27
+ const canvas = await html2canvas(previewContainer as HTMLElement, {
28
+ backgroundColor: null,
29
+ scale: 2,
30
+ logging: false,
31
+ useCORS: true,
32
+ allowTaint: true,
33
+ onclone: (clonedDoc) => {
34
+ const clonedElement = clonedDoc.querySelector('[data-preview-container="true"]');
35
+ if (clonedElement) {
36
+ const style = clonedDoc.createElement('style');
37
+ style.textContent = Array.from(document.styleSheets)
38
+ .map(sheet => {
39
+ try {
40
+ return Array.from(sheet.cssRules)
41
+ .map(rule => rule.cssText)
42
+ .join('\n');
43
+ } catch {
44
+ return '';
45
+ }
46
+ })
47
+ .join('\n');
48
+ clonedDoc.head.appendChild(style);
49
+ }
50
+ },
51
+ });
52
+
53
+ const blob = await new Promise<Blob>((resolve, reject) => {
54
+ canvas.toBlob((b) => {
55
+ if (b) resolve(b);
56
+ else reject(new Error('Failed to create blob'));
57
+ }, 'image/png');
58
+ });
59
+
60
+ const url = URL.createObjectURL(blob);
61
+ const a = document.createElement('a');
62
+ a.href = url;
63
+ a.download = `${componentName}-${variantName}.png`;
64
+ document.body.appendChild(a);
65
+ a.click();
66
+ document.body.removeChild(a);
67
+ URL.revokeObjectURL(url);
68
+ setStatus('success');
69
+ setTimeout(() => setStatus('idle'), 2000);
70
+ } catch (err) {
71
+ console.error('Screenshot save failed:', err);
72
+ setStatus('error');
73
+ setTimeout(() => setStatus('idle'), 2000);
74
+ }
75
+ };
76
+
77
+ return (
78
+ <Tooltip content="Save screenshot">
79
+ <Button
80
+ variant="ghost"
81
+ size="sm"
82
+ icon
83
+ disabled={status === 'loading'}
84
+ onClick={handleSaveToFile}
85
+ >
86
+ <CameraIcon style={{ width: '16px', height: '16px' }} />
87
+ </Button>
88
+ </Tooltip>
89
+ );
90
+ });
@@ -0,0 +1,204 @@
1
+ /**
2
+ * ShadowPreview - Shadow DOM based preview isolation
3
+ *
4
+ * Replaces IsolatedPreviewFrame as the default preview isolation mechanism.
5
+ * Same JS context (instant rendering) + shadow boundary (CSS encapsulation).
6
+ *
7
+ * Uses `createPortal` (not `createRoot`) to maintain the React context tree —
8
+ * ThemeProvider, ErrorBoundary, ActionCapture all propagate through the portal.
9
+ *
10
+ * Keyboard events are stopped at the shadow host boundary to prevent preview
11
+ * interactions from triggering app-level shortcuts (same isolation as iframes).
12
+ */
13
+
14
+ import {
15
+ useRef,
16
+ useEffect,
17
+ useState,
18
+ type ReactNode,
19
+ } from "react";
20
+ import { createPortal } from "react-dom";
21
+ import { useShadowStyles } from "../hooks/useShadowStyles.js";
22
+
23
+ export interface ShadowPreviewProps {
24
+ /** React elements to render (from renderContent()) */
25
+ children: ReactNode;
26
+ /** Theme for the preview */
27
+ theme: "light" | "dark";
28
+ /** Width of the preview (CSS value) */
29
+ width?: number | string;
30
+ /** Height of the preview (CSS value) */
31
+ height?: number | string;
32
+ /** Minimum height of the preview */
33
+ minHeight?: number | string;
34
+ /** Called when content size changes */
35
+ onContentSize?: (size: { width: number; height: number }) => void;
36
+ /** Additional class name for the host element */
37
+ className?: string;
38
+ /** Additional styles for the host element */
39
+ style?: React.CSSProperties;
40
+ /** Show size indicator on hover */
41
+ showSizeIndicator?: boolean;
42
+ }
43
+
44
+ function toCss(value: number | string | undefined): string | undefined {
45
+ if (value == null) return undefined;
46
+ return typeof value === "number" ? `${value}px` : value;
47
+ }
48
+
49
+ export function ShadowPreview({
50
+ children,
51
+ theme,
52
+ width = "100%",
53
+ height = "100%",
54
+ minHeight,
55
+ onContentSize,
56
+ className,
57
+ style,
58
+ showSizeIndicator = false,
59
+ }: ShadowPreviewProps) {
60
+ const hostRef = useRef<HTMLDivElement>(null);
61
+ const shadowRootRef = useRef<ShadowRoot | null>(null);
62
+ const renderTargetRef = useRef<HTMLDivElement | null>(null);
63
+ const [renderTarget, setRenderTarget] = useState<HTMLDivElement | null>(null);
64
+ const [isHovered, setIsHovered] = useState(false);
65
+ const [contentSize, setContentSize] = useState<{
66
+ width: number;
67
+ height: number;
68
+ } | null>(null);
69
+
70
+ // Initialize shadow root (once)
71
+ useEffect(() => {
72
+ const host = hostRef.current;
73
+ if (!host || shadowRootRef.current) return;
74
+
75
+ const shadow = host.attachShadow({ mode: "open" });
76
+ shadowRootRef.current = shadow;
77
+
78
+ // Base reset styles for the shadow root
79
+ const baseSheet = new CSSStyleSheet();
80
+ baseSheet.replaceSync(`
81
+ *, *::before, *::after {
82
+ box-sizing: border-box;
83
+ }
84
+ :host {
85
+ display: block;
86
+ -webkit-font-smoothing: antialiased;
87
+ }
88
+ #shadow-preview-root {
89
+ width: 100%;
90
+ height: 100%;
91
+ }
92
+ `);
93
+ shadow.adoptedStyleSheets = [baseSheet];
94
+
95
+ // Create render target inside shadow
96
+ const target = document.createElement("div");
97
+ target.id = "shadow-preview-root";
98
+ shadow.appendChild(target);
99
+
100
+ renderTargetRef.current = target;
101
+ setRenderTarget(target);
102
+ }, []);
103
+
104
+ // Mirror document styles into shadow root
105
+ useShadowStyles(shadowRootRef.current);
106
+
107
+ // Sync theme attribute on the render target
108
+ useEffect(() => {
109
+ if (renderTargetRef.current) {
110
+ renderTargetRef.current.setAttribute("data-theme", theme);
111
+ }
112
+ }, [theme]);
113
+
114
+ // ResizeObserver for content size reporting
115
+ // Uses requestAnimationFrame to avoid "ResizeObserver loop" browser warning
116
+ const lastSizeRef = useRef<string>("");
117
+ useEffect(() => {
118
+ const target = renderTargetRef.current;
119
+ if (!target) return;
120
+
121
+ let rafId = 0;
122
+ const observer = new ResizeObserver((entries) => {
123
+ // Defer state update to next frame to avoid ResizeObserver loop warning
124
+ cancelAnimationFrame(rafId);
125
+ rafId = requestAnimationFrame(() => {
126
+ for (const entry of entries) {
127
+ const { width: w, height: h } = entry.contentRect;
128
+ const rounded = { width: Math.round(w), height: Math.round(h) };
129
+ const key = `${rounded.width}x${rounded.height}`;
130
+ if (key === lastSizeRef.current) return;
131
+ lastSizeRef.current = key;
132
+ setContentSize(rounded);
133
+ onContentSize?.(rounded);
134
+ }
135
+ });
136
+ });
137
+
138
+ observer.observe(target);
139
+ return () => {
140
+ cancelAnimationFrame(rafId);
141
+ observer.disconnect();
142
+ };
143
+ }, [onContentSize, renderTarget]);
144
+
145
+ // Keyboard event isolation — prevent preview key events from reaching
146
+ // the document-level listener in useKeyboardShortcuts
147
+ useEffect(() => {
148
+ const host = hostRef.current;
149
+ if (!host) return;
150
+
151
+ const stopKeyboard = (e: Event) => {
152
+ e.stopPropagation();
153
+ };
154
+
155
+ host.addEventListener("keydown", stopKeyboard);
156
+ host.addEventListener("keyup", stopKeyboard);
157
+ return () => {
158
+ host.removeEventListener("keydown", stopKeyboard);
159
+ host.removeEventListener("keyup", stopKeyboard);
160
+ };
161
+ }, []);
162
+
163
+ return (
164
+ <div
165
+ ref={hostRef}
166
+ className={className}
167
+ onMouseEnter={() => setIsHovered(true)}
168
+ onMouseLeave={() => setIsHovered(false)}
169
+ style={{
170
+ position: "relative",
171
+ width: toCss(width),
172
+ height: toCss(height),
173
+ minHeight: toCss(minHeight),
174
+ ...style,
175
+ }}
176
+ >
177
+ {/* Portal children into shadow DOM — maintains React context tree */}
178
+ {renderTarget && createPortal(children, renderTarget)}
179
+
180
+ {/* Size indicator */}
181
+ {showSizeIndicator && contentSize && (
182
+ <div
183
+ style={{
184
+ position: "absolute",
185
+ bottom: 4,
186
+ right: 4,
187
+ padding: "2px 6px",
188
+ borderRadius: 4,
189
+ fontFamily: "monospace",
190
+ opacity: isHovered ? 1 : 0,
191
+ transition: "opacity 150ms",
192
+ background: "rgba(0, 0, 0, 0.5)",
193
+ color: "white",
194
+ fontSize: 10,
195
+ zIndex: 10,
196
+ pointerEvents: "none",
197
+ }}
198
+ >
199
+ {contentSize.width} x {contentSize.height}px
200
+ </div>
201
+ )}
202
+ </div>
203
+ );
204
+ }