@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,347 @@
1
+ /**
2
+ * usePreviewBridge - Communication hook for parent-iframe messaging
3
+ *
4
+ * This hook provides utilities for bidirectional communication between
5
+ * the parent viewer shell and the isolated iframe preview.
6
+ */
7
+
8
+ import { useRef, useEffect, useCallback, useState, type RefObject } from 'react';
9
+
10
+ /**
11
+ * Message types sent from parent to iframe
12
+ */
13
+ export type ParentMessage =
14
+ | { type: 'init'; frameId: string }
15
+ | { type: 'render'; fragmentPath: string; variantName: string; props?: Record<string, unknown> }
16
+ | { type: 'theme'; theme: 'light' | 'dark' }
17
+ | { type: 'resize'; width: number; height: number };
18
+
19
+ /**
20
+ * Message types sent from iframe to parent
21
+ */
22
+ export type FrameMessage =
23
+ | { type: 'ready'; frameId?: string }
24
+ | { type: 'rendered'; height: number; width: number; frameId?: string }
25
+ | { type: 'error'; message: string; stack?: string; frameId?: string };
26
+
27
+ /**
28
+ * Origin used for postMessage (same origin for Vite dev server)
29
+ */
30
+ const PREVIEW_ORIGIN = '*'; // In dev, we use * since it's same origin
31
+
32
+ /**
33
+ * Message channel ID to ensure we only respond to our own messages
34
+ */
35
+ export const PREVIEW_CHANNEL = 'fragments-preview';
36
+
37
+ /**
38
+ * Generate a unique frame ID
39
+ */
40
+ let frameIdCounter = 0;
41
+ function generateFrameId(): string {
42
+ return `frame-${++frameIdCounter}-${Date.now()}`;
43
+ }
44
+
45
+ /**
46
+ * Hook for the parent window to communicate with the iframe
47
+ */
48
+ export function usePreviewBridge(iframeRef: RefObject<HTMLIFrameElement | null>) {
49
+ const [isReady, setIsReady] = useState(false);
50
+ const [lastError, setLastError] = useState<string | null>(null);
51
+ const [contentSize, setContentSize] = useState<{ width: number; height: number } | null>(null);
52
+ const [isRendering, setIsRendering] = useState(false);
53
+ const pendingCallbacks = useRef<Map<string, (response: FrameMessage) => void>>(new Map());
54
+ const pendingTimeouts = useRef<Map<string, NodeJS.Timeout>>(new Map());
55
+ const messageId = useRef(0);
56
+ const frameIdRef = useRef<string>(generateFrameId());
57
+ const initSentRef = useRef(false);
58
+ const currentRenderIdRef = useRef<string | null>(null);
59
+
60
+ // Render timeout duration (30 seconds)
61
+ const RENDER_TIMEOUT = 30000;
62
+
63
+ // Listen for messages from iframe
64
+ useEffect(() => {
65
+ function handleMessage(event: MessageEvent) {
66
+ // Validate message structure
67
+ if (!event.data || event.data.channel !== PREVIEW_CHANNEL) {
68
+ return;
69
+ }
70
+
71
+ const message = event.data as FrameMessage & { channel: string; id?: string; frameId?: string };
72
+
73
+ // For "ready" messages (no frameId yet), check if it's from our iframe
74
+ if (message.type === 'ready' && !message.frameId) {
75
+ // Only process ready from our iframe by checking event.source
76
+ if (event.source !== iframeRef.current?.contentWindow) {
77
+ return;
78
+ }
79
+ // Send init message with our frameId
80
+ if (!initSentRef.current && iframeRef.current?.contentWindow) {
81
+ initSentRef.current = true;
82
+ iframeRef.current.contentWindow.postMessage(
83
+ { type: 'init', frameId: frameIdRef.current, channel: PREVIEW_CHANNEL },
84
+ PREVIEW_ORIGIN
85
+ );
86
+ }
87
+ setIsReady(true);
88
+ setLastError(null);
89
+ return;
90
+ }
91
+
92
+ // For all other messages, filter by frameId
93
+ if (message.frameId && message.frameId !== frameIdRef.current) {
94
+ return;
95
+ }
96
+
97
+ switch (message.type) {
98
+ case 'ready':
99
+ // Ready with frameId - just update state
100
+ setIsReady(true);
101
+ setLastError(null);
102
+ break;
103
+
104
+ case 'rendered':
105
+ setContentSize({ width: message.width, height: message.height });
106
+ setLastError(null);
107
+ setIsRendering(false);
108
+ // Clear any pending timeout for this render
109
+ if (currentRenderIdRef.current) {
110
+ const timeout = pendingTimeouts.current.get(currentRenderIdRef.current);
111
+ if (timeout) {
112
+ clearTimeout(timeout);
113
+ pendingTimeouts.current.delete(currentRenderIdRef.current);
114
+ }
115
+ currentRenderIdRef.current = null;
116
+ }
117
+ break;
118
+
119
+ case 'error':
120
+ setLastError(message.message);
121
+ break;
122
+ }
123
+
124
+ // Call any pending callbacks
125
+ if (message.id && pendingCallbacks.current.has(message.id)) {
126
+ const callback = pendingCallbacks.current.get(message.id);
127
+ pendingCallbacks.current.delete(message.id);
128
+ callback?.(message);
129
+ }
130
+ }
131
+
132
+ window.addEventListener('message', handleMessage);
133
+ return () => window.removeEventListener('message', handleMessage);
134
+ }, [iframeRef]);
135
+
136
+ // Reset ready state when iframe changes
137
+ useEffect(() => {
138
+ setIsReady(false);
139
+ setLastError(null);
140
+ setContentSize(null);
141
+ initSentRef.current = false;
142
+ }, [iframeRef.current]);
143
+
144
+ /**
145
+ * Send a message to the iframe
146
+ */
147
+ const sendMessage = useCallback((message: ParentMessage) => {
148
+ if (!iframeRef.current?.contentWindow) {
149
+ console.warn('[PreviewBridge] Cannot send message - iframe not ready');
150
+ return;
151
+ }
152
+
153
+ const id = `msg-${++messageId.current}`;
154
+ iframeRef.current.contentWindow.postMessage(
155
+ { ...message, channel: PREVIEW_CHANNEL, id, frameId: frameIdRef.current },
156
+ PREVIEW_ORIGIN
157
+ );
158
+ }, [iframeRef]);
159
+
160
+ /**
161
+ * Send a render request to the iframe
162
+ */
163
+ const render = useCallback((
164
+ fragmentPath: string,
165
+ variantName: string,
166
+ props?: Record<string, unknown>
167
+ ) => {
168
+ // Clear any existing timeout
169
+ if (currentRenderIdRef.current) {
170
+ const existingTimeout = pendingTimeouts.current.get(currentRenderIdRef.current);
171
+ if (existingTimeout) {
172
+ clearTimeout(existingTimeout);
173
+ pendingTimeouts.current.delete(currentRenderIdRef.current);
174
+ }
175
+ }
176
+
177
+ // Generate new render ID
178
+ const renderId = `render-${++messageId.current}`;
179
+ currentRenderIdRef.current = renderId;
180
+ setIsRendering(true);
181
+ setLastError(null);
182
+
183
+ sendMessage({ type: 'render', fragmentPath, variantName, props });
184
+
185
+ // Set timeout
186
+ const timeoutId = setTimeout(() => {
187
+ if (currentRenderIdRef.current === renderId) {
188
+ setLastError('Render timeout - component took too long to load');
189
+ setIsRendering(false);
190
+ currentRenderIdRef.current = null;
191
+ }
192
+ }, RENDER_TIMEOUT);
193
+
194
+ pendingTimeouts.current.set(renderId, timeoutId);
195
+ }, [sendMessage]);
196
+
197
+ /**
198
+ * Set the theme in the iframe
199
+ */
200
+ const setTheme = useCallback((theme: 'light' | 'dark') => {
201
+ sendMessage({ type: 'theme', theme });
202
+ }, [sendMessage]);
203
+
204
+ /**
205
+ * Resize the iframe viewport
206
+ */
207
+ const resize = useCallback((width: number, height: number) => {
208
+ sendMessage({ type: 'resize', width, height });
209
+ }, [sendMessage]);
210
+
211
+ /**
212
+ * Clear the last error
213
+ */
214
+ const clearError = useCallback(() => {
215
+ setLastError(null);
216
+ }, []);
217
+
218
+ // Cleanup timeouts on unmount
219
+ useEffect(() => {
220
+ return () => {
221
+ pendingTimeouts.current.forEach(timeout => clearTimeout(timeout));
222
+ pendingTimeouts.current.clear();
223
+ };
224
+ }, []);
225
+
226
+ return {
227
+ isReady,
228
+ isRendering,
229
+ lastError,
230
+ contentSize,
231
+ sendMessage,
232
+ render,
233
+ setTheme,
234
+ resize,
235
+ clearError,
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Hook for the iframe to communicate with the parent
241
+ * Used by PreviewFrameHost
242
+ */
243
+ export function useFrameBridge() {
244
+ const [renderRequest, setRenderRequest] = useState<{
245
+ fragmentPath: string;
246
+ variantName: string;
247
+ props?: Record<string, unknown>;
248
+ } | null>(null);
249
+ const [theme, setThemeState] = useState<'light' | 'dark'>('light');
250
+ const [viewportSize, setViewportSize] = useState<{ width: number; height: number } | null>(null);
251
+ const frameIdRef = useRef<string | null>(null);
252
+
253
+ // Listen for messages from parent
254
+ useEffect(() => {
255
+ function handleMessage(event: MessageEvent) {
256
+ // Validate message structure
257
+ if (!event.data || event.data.channel !== PREVIEW_CHANNEL) {
258
+ return;
259
+ }
260
+
261
+ const message = event.data as ParentMessage & { channel: string; id?: string; frameId?: string };
262
+
263
+ // Store frameId from init message or any message with frameId
264
+ if (message.frameId && !frameIdRef.current) {
265
+ frameIdRef.current = message.frameId;
266
+ }
267
+
268
+ // Skip init messages - they're just for setting frameId
269
+ if (message.type === 'init') {
270
+ return;
271
+ }
272
+
273
+ switch (message.type) {
274
+ case 'render':
275
+ setRenderRequest({
276
+ fragmentPath: message.fragmentPath,
277
+ variantName: message.variantName,
278
+ props: message.props,
279
+ });
280
+ break;
281
+
282
+ case 'theme':
283
+ setThemeState(message.theme);
284
+ // Apply theme class to document
285
+ if (message.theme === 'dark') {
286
+ document.documentElement.classList.add('dark');
287
+ } else {
288
+ document.documentElement.classList.remove('dark');
289
+ }
290
+ break;
291
+
292
+ case 'resize':
293
+ setViewportSize({ width: message.width, height: message.height });
294
+ break;
295
+ }
296
+ }
297
+
298
+ window.addEventListener('message', handleMessage);
299
+ return () => window.removeEventListener('message', handleMessage);
300
+ }, []);
301
+
302
+ /**
303
+ * Send a message to the parent window
304
+ */
305
+ const sendToParent = useCallback((message: FrameMessage) => {
306
+ if (!window.parent || window.parent === window) {
307
+ console.warn('[FrameBridge] Not running in iframe');
308
+ return;
309
+ }
310
+
311
+ window.parent.postMessage(
312
+ { ...message, channel: PREVIEW_CHANNEL, frameId: frameIdRef.current },
313
+ PREVIEW_ORIGIN
314
+ );
315
+ }, []);
316
+
317
+ /**
318
+ * Notify parent that the frame is ready
319
+ */
320
+ const notifyReady = useCallback(() => {
321
+ sendToParent({ type: 'ready' });
322
+ }, [sendToParent]);
323
+
324
+ /**
325
+ * Notify parent that rendering is complete
326
+ */
327
+ const notifyRendered = useCallback((width: number, height: number) => {
328
+ sendToParent({ type: 'rendered', width, height });
329
+ }, [sendToParent]);
330
+
331
+ /**
332
+ * Notify parent of a render error
333
+ */
334
+ const notifyError = useCallback((message: string, stack?: string) => {
335
+ sendToParent({ type: 'error', message, stack });
336
+ }, [sendToParent]);
337
+
338
+ return {
339
+ renderRequest,
340
+ theme,
341
+ viewportSize,
342
+ notifyReady,
343
+ notifyRendered,
344
+ notifyError,
345
+ setTheme: setThemeState,
346
+ };
347
+ }
@@ -0,0 +1,78 @@
1
+ import { useState, useEffect, useRef } from 'react';
2
+
3
+ interface UseScrollSpyOptions {
4
+ /** IDs of sections to observe */
5
+ sectionIds: string[];
6
+ /** Offset from top of viewport to consider section as active */
7
+ offset?: number;
8
+ /** Root element to observe within (default: document) */
9
+ root?: Element | null;
10
+ }
11
+
12
+ export function useScrollSpy({ sectionIds, offset = 100, root = null }: UseScrollSpyOptions) {
13
+ const [activeId, setActiveId] = useState<string | null>(sectionIds[0] ?? null);
14
+ const observerRef = useRef<IntersectionObserver | null>(null);
15
+
16
+ useEffect(() => {
17
+ const elements = sectionIds
18
+ .map((id) => document.getElementById(id))
19
+ .filter((el): el is HTMLElement => el !== null);
20
+
21
+ if (elements.length === 0) return;
22
+
23
+ // Track which sections are currently visible
24
+ const visibleSections = new Map<string, number>();
25
+
26
+ observerRef.current = new IntersectionObserver(
27
+ (entries) => {
28
+ entries.forEach((entry) => {
29
+ const id = entry.target.id;
30
+ if (entry.isIntersecting) {
31
+ // Store the top position of visible sections
32
+ visibleSections.set(id, entry.boundingClientRect.top);
33
+ } else {
34
+ visibleSections.delete(id);
35
+ }
36
+ });
37
+
38
+ // Find the section closest to the top
39
+ if (visibleSections.size > 0) {
40
+ let closestId = '';
41
+ let closestDistance = Infinity;
42
+
43
+ visibleSections.forEach((top, id) => {
44
+ const distance = Math.abs(top - offset);
45
+ if (distance < closestDistance) {
46
+ closestDistance = distance;
47
+ closestId = id;
48
+ }
49
+ });
50
+
51
+ if (closestId) {
52
+ setActiveId(closestId);
53
+ }
54
+ }
55
+ },
56
+ {
57
+ root,
58
+ rootMargin: `-${offset}px 0px -50% 0px`,
59
+ threshold: [0, 0.25, 0.5, 0.75, 1],
60
+ }
61
+ );
62
+
63
+ elements.forEach((el) => observerRef.current?.observe(el));
64
+
65
+ return () => {
66
+ observerRef.current?.disconnect();
67
+ };
68
+ }, [sectionIds, offset, root]);
69
+
70
+ const scrollToSection = (id: string) => {
71
+ const element = document.getElementById(id);
72
+ if (element) {
73
+ element.scrollIntoView({ behavior: 'smooth', block: 'start' });
74
+ }
75
+ };
76
+
77
+ return { activeId, scrollToSection };
78
+ }
@@ -0,0 +1,221 @@
1
+ /**
2
+ * useShadowStyles - Mirrors document stylesheets into shadow roots
3
+ *
4
+ * Uses a **singleton observer** — one MutationObserver total, not one per
5
+ * shadow root. CSSStyleSheet instances are shared across all registered
6
+ * shadow roots (5 variants = 1 shared set of sheets).
7
+ *
8
+ * Updates to `adoptedStyleSheets` are debounced via microtask so rapid
9
+ * Vite HMR bursts (many style tags added/removed in one tick) result in
10
+ * a single assignment per shadow root.
11
+ */
12
+
13
+ import { useEffect } from "react";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Module-level singleton state
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /** Shared CSSStyleSheet instances, keyed by data-vite-dev-id or href */
20
+ const sharedSheets = new Map<string, CSSStyleSheet>();
21
+
22
+ /** All currently registered shadow roots */
23
+ const registeredRoots = new Set<ShadowRoot>();
24
+
25
+ /** Head childList observer (singleton) */
26
+ let headObserver: MutationObserver | null = null;
27
+
28
+ /** Style textContent observer (singleton) */
29
+ let contentObserver: MutationObserver | null = null;
30
+
31
+ /** Microtask flush guard */
32
+ let flushScheduled = false;
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Helpers
36
+ // ---------------------------------------------------------------------------
37
+
38
+ function syncStyleTag(style: HTMLStyleElement): boolean {
39
+ const id = style.getAttribute("data-vite-dev-id");
40
+ if (!id || !style.textContent) return false;
41
+
42
+ const existing = sharedSheets.get(id);
43
+ if (existing) {
44
+ try {
45
+ existing.replaceSync(style.textContent);
46
+ } catch {
47
+ // CSS parse errors are non-fatal
48
+ }
49
+ return true;
50
+ }
51
+
52
+ const sheet = new CSSStyleSheet();
53
+ try {
54
+ sheet.replaceSync(style.textContent);
55
+ } catch {
56
+ return false;
57
+ }
58
+ sharedSheets.set(id, sheet);
59
+ return true;
60
+ }
61
+
62
+ function syncLinkTag(link: HTMLLinkElement): boolean {
63
+ const href = link.getAttribute("href");
64
+ if (!href) return false;
65
+ if (sharedSheets.has(href)) return false;
66
+
67
+ try {
68
+ if (link.sheet) {
69
+ const sheet = new CSSStyleSheet();
70
+ const rules: string[] = [];
71
+ for (const rule of link.sheet.cssRules) {
72
+ rules.push(rule.cssText);
73
+ }
74
+ sheet.replaceSync(rules.join("\n"));
75
+ sharedSheets.set(href, sheet);
76
+ return true;
77
+ }
78
+ } catch {
79
+ // Cross-origin or security restriction
80
+ }
81
+ return false;
82
+ }
83
+
84
+ /** Push current sheets to every registered shadow root (debounced) */
85
+ function scheduleFlush() {
86
+ if (flushScheduled) return;
87
+ flushScheduled = true;
88
+ queueMicrotask(() => {
89
+ flushScheduled = false;
90
+ const sheets = Array.from(sharedSheets.values());
91
+ for (const root of registeredRoots) {
92
+ root.adoptedStyleSheets = sheets;
93
+ }
94
+ });
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Observer lifecycle (starts with first root, stops when last root leaves)
99
+ // ---------------------------------------------------------------------------
100
+
101
+ function startObserving() {
102
+ if (headObserver) return;
103
+
104
+ // --- Initial sync ---
105
+ document.querySelectorAll<HTMLStyleElement>("style[data-vite-dev-id]").forEach(syncStyleTag);
106
+ document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]').forEach(syncLinkTag);
107
+
108
+ // Plain <style> without data-vite-dev-id (e.g., injected globals)
109
+ document.querySelectorAll<HTMLStyleElement>("style:not([data-vite-dev-id])").forEach((style) => {
110
+ if (!style.textContent) return;
111
+ const key = `__plain__${style.textContent.slice(0, 64)}`;
112
+ if (sharedSheets.has(key)) return;
113
+ const sheet = new CSSStyleSheet();
114
+ try {
115
+ sheet.replaceSync(style.textContent);
116
+ sharedSheets.set(key, sheet);
117
+ } catch {
118
+ // ignore
119
+ }
120
+ });
121
+
122
+ // --- Head childList observer ---
123
+ headObserver = new MutationObserver((mutations) => {
124
+ let changed = false;
125
+
126
+ for (const mutation of mutations) {
127
+ for (const node of mutation.addedNodes) {
128
+ if (node instanceof HTMLStyleElement && node.hasAttribute("data-vite-dev-id")) {
129
+ if (syncStyleTag(node)) changed = true;
130
+ // Also observe this new tag's text content for in-place HMR updates
131
+ if (node.firstChild) {
132
+ contentObserver?.observe(node.firstChild, { characterData: true });
133
+ }
134
+ }
135
+ if (node instanceof HTMLLinkElement && node.rel === "stylesheet") {
136
+ if (syncLinkTag(node)) changed = true;
137
+ }
138
+ }
139
+
140
+ for (const node of mutation.removedNodes) {
141
+ if (node instanceof HTMLStyleElement) {
142
+ const id = node.getAttribute("data-vite-dev-id");
143
+ if (id && sharedSheets.has(id)) {
144
+ sharedSheets.delete(id);
145
+ changed = true;
146
+ }
147
+ }
148
+ if (node instanceof HTMLLinkElement && node.rel === "stylesheet") {
149
+ const href = node.getAttribute("href");
150
+ if (href && sharedSheets.has(href)) {
151
+ sharedSheets.delete(href);
152
+ changed = true;
153
+ }
154
+ }
155
+ }
156
+ }
157
+
158
+ if (changed) scheduleFlush();
159
+ });
160
+
161
+ headObserver.observe(document.head, { childList: true });
162
+
163
+ // --- Content observer for in-place textContent mutations (Vite HMR) ---
164
+ contentObserver = new MutationObserver((mutations) => {
165
+ let changed = false;
166
+ for (const mutation of mutations) {
167
+ if (
168
+ mutation.type === "characterData" &&
169
+ mutation.target.parentElement instanceof HTMLStyleElement
170
+ ) {
171
+ if (syncStyleTag(mutation.target.parentElement)) {
172
+ changed = true;
173
+ }
174
+ }
175
+ }
176
+ if (changed) scheduleFlush();
177
+ });
178
+
179
+ // Observe existing style tag text nodes
180
+ document.querySelectorAll<HTMLStyleElement>("style[data-vite-dev-id]").forEach((style) => {
181
+ if (style.firstChild) {
182
+ contentObserver!.observe(style.firstChild, { characterData: true });
183
+ }
184
+ });
185
+ }
186
+
187
+ function stopObserving() {
188
+ if (registeredRoots.size > 0) return; // Still have consumers
189
+
190
+ headObserver?.disconnect();
191
+ headObserver = null;
192
+ contentObserver?.disconnect();
193
+ contentObserver = null;
194
+ sharedSheets.clear();
195
+ }
196
+
197
+ // ---------------------------------------------------------------------------
198
+ // Hook
199
+ // ---------------------------------------------------------------------------
200
+
201
+ export function useShadowStyles(shadowRoot: ShadowRoot | null) {
202
+ useEffect(() => {
203
+ if (!shadowRoot) return;
204
+
205
+ registeredRoots.add(shadowRoot);
206
+
207
+ // Start the singleton observer if this is the first root
208
+ if (registeredRoots.size === 1) {
209
+ startObserving();
210
+ }
211
+
212
+ // Apply current sheets to this root immediately
213
+ shadowRoot.adoptedStyleSheets = Array.from(sharedSheets.values());
214
+
215
+ return () => {
216
+ registeredRoots.delete(shadowRoot);
217
+ shadowRoot.adoptedStyleSheets = [];
218
+ stopObserving();
219
+ };
220
+ }, [shadowRoot]);
221
+ }