@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,364 @@
1
+ /**
2
+ * A11y Service Hook
3
+ *
4
+ * Central service for triggering accessibility scans with:
5
+ * - Debouncing logic to prevent excessive scans during rapid changes
6
+ * - Scan queue with concurrency limit
7
+ * - Automatic re-scanning on HMR invalidation
8
+ */
9
+
10
+ import { useCallback, useEffect, useRef, useState } from 'react';
11
+ import type {
12
+ A11yServiceConfig,
13
+ ComponentScanState,
14
+ ScanStatus,
15
+ } from '../types/a11y.js';
16
+ import {
17
+ updateComponentA11yResult,
18
+ getComponentA11yResult,
19
+ invalidateComponents,
20
+ isComponentStale,
21
+ getA11ySummary,
22
+ } from './useA11yCache.js';
23
+ import { runAxeScan, type ScanResult } from '../webmcp/scan-utils.js';
24
+
25
+ // Default configuration
26
+ const DEFAULT_CONFIG: A11yServiceConfig = {
27
+ hmrDebounceMs: 500,
28
+ navigationDebounceMs: 200,
29
+ scanCooldownMs: 1000,
30
+ maxConcurrentScans: 2,
31
+ };
32
+
33
+ // Global state for the service (singleton pattern)
34
+ interface A11yServiceState {
35
+ activeScanCount: number;
36
+ scanQueue: Array<{
37
+ componentName: string;
38
+ targetSelector: string;
39
+ variant?: string;
40
+ resolve: (result: ScanResult | null) => void;
41
+ reject: (error: Error) => void;
42
+ }>;
43
+ debounceTimers: Map<string, NodeJS.Timeout>;
44
+ lastScanTimes: Map<string, number>;
45
+ componentStates: Map<string, ComponentScanState>;
46
+ }
47
+
48
+ const serviceState: A11yServiceState = {
49
+ activeScanCount: 0,
50
+ scanQueue: [],
51
+ debounceTimers: new Map(),
52
+ lastScanTimes: new Map(),
53
+ componentStates: new Map(),
54
+ };
55
+
56
+ /**
57
+ * Process the scan queue
58
+ */
59
+ async function processQueue(config: A11yServiceConfig): Promise<void> {
60
+ while (
61
+ serviceState.scanQueue.length > 0 &&
62
+ serviceState.activeScanCount < config.maxConcurrentScans
63
+ ) {
64
+ const item = serviceState.scanQueue.shift();
65
+ if (!item) break;
66
+
67
+ serviceState.activeScanCount++;
68
+
69
+ // Update component state
70
+ serviceState.componentStates.set(item.componentName, {
71
+ status: 'scanning',
72
+ lastScanAt: Date.now(),
73
+ });
74
+
75
+ // Dispatch scanning event
76
+ window.dispatchEvent(new CustomEvent('a11y-scan-started', {
77
+ detail: { componentName: item.componentName },
78
+ }));
79
+
80
+ try {
81
+ const result = await runAxeScan(item.targetSelector);
82
+
83
+ if (result) {
84
+ // Update cache with full results
85
+ updateComponentA11yResult(item.componentName, {
86
+ violations: result.violations,
87
+ passes: result.passes,
88
+ incomplete: result.incomplete,
89
+ counts: result.counts,
90
+ variant: item.variant,
91
+ });
92
+
93
+ serviceState.componentStates.set(item.componentName, {
94
+ status: 'completed',
95
+ lastScanAt: Date.now(),
96
+ });
97
+ } else {
98
+ serviceState.componentStates.set(item.componentName, {
99
+ status: 'error',
100
+ error: 'Target element not found',
101
+ });
102
+ }
103
+
104
+ serviceState.lastScanTimes.set(item.componentName, Date.now());
105
+ item.resolve(result);
106
+ } catch (error) {
107
+ serviceState.componentStates.set(item.componentName, {
108
+ status: 'error',
109
+ error: error instanceof Error ? error.message : 'Scan failed',
110
+ });
111
+ item.reject(error instanceof Error ? error : new Error('Scan failed'));
112
+ } finally {
113
+ serviceState.activeScanCount--;
114
+
115
+ // Dispatch scan complete event
116
+ window.dispatchEvent(new CustomEvent('a11y-scan-completed', {
117
+ detail: { componentName: item.componentName },
118
+ }));
119
+
120
+ // Process next item in queue
121
+ processQueue(config);
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Options for the useA11yService hook
128
+ */
129
+ export interface UseA11yServiceOptions {
130
+ /** Override default configuration */
131
+ config?: Partial<A11yServiceConfig>;
132
+ /** Component name being scanned */
133
+ componentName?: string;
134
+ /** Target selector for scanning */
135
+ targetSelector?: string;
136
+ /** Current variant name */
137
+ variant?: string;
138
+ /** Auto-scan when component changes */
139
+ autoScan?: boolean;
140
+ }
141
+
142
+ /**
143
+ * A11y Service Hook
144
+ *
145
+ * Provides methods for triggering and managing accessibility scans.
146
+ */
147
+ export function useA11yService(options: UseA11yServiceOptions = {}) {
148
+ const {
149
+ config: configOverrides = {},
150
+ componentName,
151
+ targetSelector = '[data-preview-container="true"]',
152
+ variant,
153
+ autoScan = true,
154
+ } = options;
155
+
156
+ const config: A11yServiceConfig = { ...DEFAULT_CONFIG, ...configOverrides };
157
+ const configRef = useRef(config);
158
+ configRef.current = config;
159
+
160
+ const [scanStatus, setScanStatus] = useState<ScanStatus>('idle');
161
+ const [lastResult, setLastResult] = useState<ScanResult | null>(null);
162
+
163
+ /**
164
+ * Queue a scan for a component
165
+ */
166
+ const scanComponent = useCallback(
167
+ (
168
+ targetComponentName: string = componentName || '',
169
+ targetSel: string = targetSelector,
170
+ targetVariant?: string
171
+ ): Promise<ScanResult | null> => {
172
+ if (!targetComponentName) {
173
+ return Promise.resolve(null);
174
+ }
175
+
176
+ // Check cooldown
177
+ const lastScan = serviceState.lastScanTimes.get(targetComponentName);
178
+ if (lastScan && Date.now() - lastScan < configRef.current.scanCooldownMs) {
179
+ // Return cached result if available
180
+ const cached = getComponentA11yResult(targetComponentName);
181
+ if (cached) {
182
+ return Promise.resolve({
183
+ violations: cached.violations,
184
+ passes: cached.passes,
185
+ incomplete: cached.incomplete,
186
+ counts: cached.counts,
187
+ });
188
+ }
189
+ }
190
+
191
+ return new Promise((resolve, reject) => {
192
+ serviceState.scanQueue.push({
193
+ componentName: targetComponentName,
194
+ targetSelector: targetSel,
195
+ variant: targetVariant || variant,
196
+ resolve,
197
+ reject,
198
+ });
199
+
200
+ serviceState.componentStates.set(targetComponentName, { status: 'pending' });
201
+ setScanStatus('pending');
202
+
203
+ // Start processing
204
+ processQueue(configRef.current);
205
+ });
206
+ },
207
+ [componentName, targetSelector, variant]
208
+ );
209
+
210
+ /**
211
+ * Scan with debouncing (for HMR or rapid changes)
212
+ */
213
+ const scanDebounced = useCallback(
214
+ (
215
+ debounceMs: number = configRef.current.hmrDebounceMs,
216
+ targetComponentName: string = componentName || ''
217
+ ) => {
218
+ if (!targetComponentName) return;
219
+
220
+ // Clear existing timer
221
+ const existingTimer = serviceState.debounceTimers.get(targetComponentName);
222
+ if (existingTimer) {
223
+ clearTimeout(existingTimer);
224
+ }
225
+
226
+ // Set new timer
227
+ const timer = setTimeout(() => {
228
+ serviceState.debounceTimers.delete(targetComponentName);
229
+ scanComponent(targetComponentName);
230
+ }, debounceMs);
231
+
232
+ serviceState.debounceTimers.set(targetComponentName, timer);
233
+ },
234
+ [componentName, scanComponent]
235
+ );
236
+
237
+ /**
238
+ * Invalidate cache for components and optionally trigger re-scan
239
+ */
240
+ const invalidate = useCallback(
241
+ (componentNames: string[], rescan: boolean = true) => {
242
+ invalidateComponents(componentNames);
243
+
244
+ if (rescan) {
245
+ // Debounce each component's re-scan
246
+ for (const name of componentNames) {
247
+ scanDebounced(configRef.current.hmrDebounceMs, name);
248
+ }
249
+ }
250
+ },
251
+ [scanDebounced]
252
+ );
253
+
254
+ /**
255
+ * Get current scan state for a component
256
+ */
257
+ const getComponentState = useCallback(
258
+ (name: string = componentName || ''): ComponentScanState => {
259
+ return serviceState.componentStates.get(name) || { status: 'idle' };
260
+ },
261
+ [componentName]
262
+ );
263
+
264
+ /**
265
+ * Check if a component needs re-scanning
266
+ */
267
+ const needsRescan = useCallback(
268
+ (name: string = componentName || ''): boolean => {
269
+ if (!name) return false;
270
+ return isComponentStale(name, config.scanCooldownMs);
271
+ },
272
+ [componentName, config.scanCooldownMs]
273
+ );
274
+
275
+ // Listen for HMR invalidation events
276
+ useEffect(() => {
277
+ const handleInvalidate = (event: CustomEvent<{ components: string[] }>) => {
278
+ const { components } = event.detail;
279
+
280
+ // If our component is in the list, trigger a debounced re-scan
281
+ if (componentName && components.includes(componentName)) {
282
+ setScanStatus('pending');
283
+ scanDebounced(configRef.current.hmrDebounceMs, componentName);
284
+ }
285
+ };
286
+
287
+ const handleScanStarted = (event: CustomEvent<{ componentName: string }>) => {
288
+ if (event.detail.componentName === componentName) {
289
+ setScanStatus('scanning');
290
+ }
291
+ };
292
+
293
+ const handleScanCompleted = (event: CustomEvent<{ componentName: string }>) => {
294
+ if (event.detail.componentName === componentName) {
295
+ setScanStatus('completed');
296
+ // Update last result from cache
297
+ const cached = getComponentA11yResult(componentName || '');
298
+ if (cached) {
299
+ setLastResult({
300
+ violations: cached.violations,
301
+ passes: cached.passes,
302
+ incomplete: cached.incomplete,
303
+ counts: cached.counts,
304
+ });
305
+ }
306
+ }
307
+ };
308
+
309
+ window.addEventListener('a11y-cache-invalidated', handleInvalidate as EventListener);
310
+ window.addEventListener('a11y-scan-started', handleScanStarted as EventListener);
311
+ window.addEventListener('a11y-scan-completed', handleScanCompleted as EventListener);
312
+
313
+ return () => {
314
+ window.removeEventListener('a11y-cache-invalidated', handleInvalidate as EventListener);
315
+ window.removeEventListener('a11y-scan-started', handleScanStarted as EventListener);
316
+ window.removeEventListener('a11y-scan-completed', handleScanCompleted as EventListener);
317
+ };
318
+ }, [componentName, scanDebounced]);
319
+
320
+ // Auto-scan when component name changes and cache is stale
321
+ useEffect(() => {
322
+ if (!autoScan || !componentName) return;
323
+
324
+ if (needsRescan(componentName)) {
325
+ scanDebounced(configRef.current.navigationDebounceMs, componentName);
326
+ } else {
327
+ // Load from cache
328
+ const cached = getComponentA11yResult(componentName);
329
+ if (cached) {
330
+ setLastResult({
331
+ violations: cached.violations,
332
+ passes: cached.passes,
333
+ incomplete: cached.incomplete,
334
+ counts: cached.counts,
335
+ });
336
+ setScanStatus('completed');
337
+ }
338
+ }
339
+ }, [autoScan, componentName, needsRescan, scanDebounced]);
340
+
341
+ return {
342
+ // Methods
343
+ scanComponent,
344
+ scanDebounced,
345
+ invalidate,
346
+ getComponentState,
347
+ needsRescan,
348
+ getSummary: getA11ySummary,
349
+
350
+ // State
351
+ scanStatus,
352
+ isScanning: scanStatus === 'scanning' || scanStatus === 'pending',
353
+ lastResult,
354
+ };
355
+ }
356
+
357
+ /**
358
+ * Dispatch a11y invalidation event (for use from vite-plugin HMR)
359
+ */
360
+ export function dispatchA11yInvalidate(components: string[], file: string): void {
361
+ window.dispatchEvent(new CustomEvent('a11y-invalidate-hmr', {
362
+ detail: { components, file, timestamp: Date.now() },
363
+ }));
364
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Actions logging hook - tracks callback invocations for debugging
3
+ *
4
+ * Similar to Storybook's Actions addon, this logs when callbacks like
5
+ * onClick, onChange, etc. are invoked, showing the arguments passed.
6
+ */
7
+
8
+ import { useState, useCallback, useRef } from "react";
9
+
10
+ export interface ActionLog {
11
+ id: string;
12
+ name: string;
13
+ args: unknown[];
14
+ timestamp: number;
15
+ count: number; // For repeated identical actions
16
+ }
17
+
18
+ export interface UseActionsReturn {
19
+ /** All logged actions */
20
+ logs: ActionLog[];
21
+ /** Add a new action log */
22
+ logAction: (name: string, args: unknown[]) => void;
23
+ /** Clear all logs */
24
+ clearLogs: () => void;
25
+ /** Wrap a callback to automatically log when called */
26
+ wrapCallback: <T extends (...args: unknown[]) => unknown>(
27
+ name: string,
28
+ callback?: T
29
+ ) => (...args: Parameters<T>) => ReturnType<T> | undefined;
30
+ /** Wrap multiple callbacks in an object */
31
+ wrapCallbacks: (
32
+ callbacks: Record<string, ((...args: unknown[]) => unknown) | undefined>
33
+ ) => Record<string, (...args: unknown[]) => unknown>;
34
+ }
35
+
36
+ const MAX_LOGS = 100;
37
+
38
+ export function useActions(): UseActionsReturn {
39
+ const [logs, setLogs] = useState<ActionLog[]>([]);
40
+ const logIdCounter = useRef(0);
41
+
42
+ const logAction = useCallback((name: string, args: unknown[]) => {
43
+ setLogs((prevLogs) => {
44
+ // Check if the last log is the same action (for counting repeated calls)
45
+ const lastLog = prevLogs[0];
46
+ if (
47
+ lastLog &&
48
+ lastLog.name === name &&
49
+ JSON.stringify(lastLog.args) === JSON.stringify(args)
50
+ ) {
51
+ // Increment count on existing log
52
+ return [
53
+ { ...lastLog, count: lastLog.count + 1, timestamp: Date.now() },
54
+ ...prevLogs.slice(1),
55
+ ];
56
+ }
57
+
58
+ // Add new log
59
+ const newLog: ActionLog = {
60
+ id: `action-${++logIdCounter.current}`,
61
+ name,
62
+ args,
63
+ timestamp: Date.now(),
64
+ count: 1,
65
+ };
66
+
67
+ // Keep only the last MAX_LOGS entries
68
+ return [newLog, ...prevLogs].slice(0, MAX_LOGS);
69
+ });
70
+ }, []);
71
+
72
+ const clearLogs = useCallback(() => {
73
+ setLogs([]);
74
+ }, []);
75
+
76
+ const wrapCallback = useCallback(
77
+ <T extends (...args: unknown[]) => unknown>(name: string, callback?: T) => {
78
+ return (...args: Parameters<T>): ReturnType<T> | undefined => {
79
+ logAction(name, args);
80
+ if (callback) {
81
+ return callback(...args) as ReturnType<T>;
82
+ }
83
+ return undefined;
84
+ };
85
+ },
86
+ [logAction]
87
+ );
88
+
89
+ const wrapCallbacks = useCallback(
90
+ (callbacks: Record<string, ((...args: unknown[]) => unknown) | undefined>) => {
91
+ const wrapped: Record<string, (...args: unknown[]) => unknown> = {};
92
+ for (const [name, callback] of Object.entries(callbacks)) {
93
+ wrapped[name] = wrapCallback(name, callback);
94
+ }
95
+ return wrapped;
96
+ },
97
+ [wrapCallback]
98
+ );
99
+
100
+ return {
101
+ logs,
102
+ logAction,
103
+ clearLogs,
104
+ wrapCallback,
105
+ wrapCallbacks,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Format a value for display in the actions panel
111
+ */
112
+ export function formatActionArg(value: unknown, maxLength = 100): string {
113
+ if (value === undefined) return "undefined";
114
+ if (value === null) return "null";
115
+ if (typeof value === "function") return "ƒ()";
116
+ if (typeof value === "symbol") return value.toString();
117
+
118
+ if (value instanceof Event) {
119
+ return `${value.constructor.name} { type: "${value.type}" }`;
120
+ }
121
+
122
+ if (value instanceof Element) {
123
+ const tag = value.tagName.toLowerCase();
124
+ const id = value.id ? `#${value.id}` : "";
125
+ const className = value.className ? `.${value.className.split(" ")[0]}` : "";
126
+ return `<${tag}${id}${className}>`;
127
+ }
128
+
129
+ try {
130
+ const str = JSON.stringify(value, null, 2);
131
+ if (str.length > maxLength) {
132
+ return str.slice(0, maxLength) + "...";
133
+ }
134
+ return str;
135
+ } catch {
136
+ return String(value);
137
+ }
138
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Centralized UI state management for the App component.
3
+ * Uses useReducer for predictable state updates and better performance.
4
+ */
5
+
6
+ import { useReducer, useCallback, useMemo } from 'react';
7
+
8
+ export type ActivePanel = 'styles' | 'accessibility' | 'interactions' | 'graph' | 'performance';
9
+
10
+ interface AppUIState {
11
+ activePanel: ActivePanel;
12
+ panelOpen: boolean;
13
+ showHealthDashboard: boolean;
14
+ showComparison: boolean;
15
+ showShortcutsHelp: boolean;
16
+ showMatrixView: boolean;
17
+ showCommandPalette: boolean;
18
+ showMultiViewport: boolean;
19
+ showAside: boolean;
20
+ linkCopied: boolean;
21
+ previewKey: number;
22
+ }
23
+
24
+ type AppUIAction =
25
+ | { type: 'SET_ACTIVE_PANEL'; payload: ActivePanel }
26
+ | { type: 'TOGGLE_PANEL' }
27
+ | { type: 'SET_PANEL_OPEN'; payload: boolean }
28
+ | { type: 'SET_HEALTH_DASHBOARD'; payload: boolean }
29
+ | { type: 'TOGGLE_COMPARISON' }
30
+ | { type: 'SET_COMPARISON'; payload: boolean }
31
+ | { type: 'TOGGLE_SHORTCUTS_HELP' }
32
+ | { type: 'SET_SHORTCUTS_HELP'; payload: boolean }
33
+ | { type: 'SET_MATRIX_VIEW'; payload: boolean }
34
+ | { type: 'SET_COMMAND_PALETTE'; payload: boolean }
35
+ | { type: 'SET_MULTI_VIEWPORT'; payload: boolean }
36
+ | { type: 'SET_LINK_COPIED'; payload: boolean }
37
+ | { type: 'INCREMENT_PREVIEW_KEY' }
38
+ | { type: 'TOGGLE_ASIDE' }
39
+ | { type: 'SET_ASIDE'; payload: boolean }
40
+ | { type: 'CLOSE_ALL_MODALS' };
41
+
42
+ function getInitialAsideState(): boolean {
43
+ try {
44
+ const stored = localStorage.getItem('fragments-aside-visible');
45
+ if (stored !== null) return stored === 'true';
46
+ } catch { /* noop */ }
47
+ return true;
48
+ }
49
+
50
+ const initialState: AppUIState = {
51
+ activePanel: 'accessibility',
52
+ panelOpen: false,
53
+ showHealthDashboard: false,
54
+ showComparison: false,
55
+ showShortcutsHelp: false,
56
+ showMatrixView: false,
57
+ showCommandPalette: false,
58
+ showMultiViewport: false,
59
+ showAside: getInitialAsideState(),
60
+ linkCopied: false,
61
+ previewKey: 0,
62
+ };
63
+
64
+ function appUIReducer(state: AppUIState, action: AppUIAction): AppUIState {
65
+ switch (action.type) {
66
+ case 'SET_ACTIVE_PANEL':
67
+ return { ...state, activePanel: action.payload };
68
+ case 'TOGGLE_PANEL':
69
+ return { ...state, panelOpen: !state.panelOpen };
70
+ case 'SET_PANEL_OPEN':
71
+ return { ...state, panelOpen: action.payload };
72
+ case 'SET_HEALTH_DASHBOARD':
73
+ return { ...state, showHealthDashboard: action.payload };
74
+ case 'TOGGLE_COMPARISON':
75
+ return { ...state, showComparison: !state.showComparison };
76
+ case 'SET_COMPARISON':
77
+ return { ...state, showComparison: action.payload };
78
+ case 'TOGGLE_SHORTCUTS_HELP':
79
+ return { ...state, showShortcutsHelp: !state.showShortcutsHelp };
80
+ case 'SET_SHORTCUTS_HELP':
81
+ return { ...state, showShortcutsHelp: action.payload };
82
+ case 'SET_MATRIX_VIEW':
83
+ // When enabling matrix view, disable multi-viewport
84
+ return {
85
+ ...state,
86
+ showMatrixView: action.payload,
87
+ showMultiViewport: action.payload ? false : state.showMultiViewport,
88
+ };
89
+ case 'SET_COMMAND_PALETTE':
90
+ return { ...state, showCommandPalette: action.payload };
91
+ case 'SET_MULTI_VIEWPORT':
92
+ // When enabling multi-viewport, disable matrix view
93
+ return {
94
+ ...state,
95
+ showMultiViewport: action.payload,
96
+ showMatrixView: action.payload ? false : state.showMatrixView,
97
+ };
98
+ case 'SET_LINK_COPIED':
99
+ return { ...state, linkCopied: action.payload };
100
+ case 'INCREMENT_PREVIEW_KEY':
101
+ return { ...state, previewKey: state.previewKey + 1 };
102
+ case 'TOGGLE_ASIDE': {
103
+ const next = !state.showAside;
104
+ try { localStorage.setItem('fragments-aside-visible', String(next)); } catch { /* noop */ }
105
+ return { ...state, showAside: next };
106
+ }
107
+ case 'SET_ASIDE': {
108
+ try { localStorage.setItem('fragments-aside-visible', String(action.payload)); } catch { /* noop */ }
109
+ return { ...state, showAside: action.payload };
110
+ }
111
+ case 'CLOSE_ALL_MODALS':
112
+ return {
113
+ ...state,
114
+ showShortcutsHelp: false,
115
+ showCommandPalette: false,
116
+ };
117
+ default:
118
+ return state;
119
+ }
120
+ }
121
+
122
+ export function useAppState() {
123
+ const [state, dispatch] = useReducer(appUIReducer, initialState);
124
+
125
+ const actions = useMemo(() => ({
126
+ setActivePanel: (panel: ActivePanel) => dispatch({ type: 'SET_ACTIVE_PANEL', payload: panel }),
127
+ togglePanel: () => dispatch({ type: 'TOGGLE_PANEL' }),
128
+ setPanelOpen: (open: boolean) => dispatch({ type: 'SET_PANEL_OPEN', payload: open }),
129
+ setHealthDashboard: (show: boolean) => dispatch({ type: 'SET_HEALTH_DASHBOARD', payload: show }),
130
+ toggleComparison: () => dispatch({ type: 'TOGGLE_COMPARISON' }),
131
+ setComparison: (show: boolean) => dispatch({ type: 'SET_COMPARISON', payload: show }),
132
+ toggleShortcutsHelp: () => dispatch({ type: 'TOGGLE_SHORTCUTS_HELP' }),
133
+ setShortcutsHelp: (show: boolean) => dispatch({ type: 'SET_SHORTCUTS_HELP', payload: show }),
134
+ setMatrixView: (show: boolean) => dispatch({ type: 'SET_MATRIX_VIEW', payload: show }),
135
+ setCommandPalette: (show: boolean) => dispatch({ type: 'SET_COMMAND_PALETTE', payload: show }),
136
+ setMultiViewport: (show: boolean) => dispatch({ type: 'SET_MULTI_VIEWPORT', payload: show }),
137
+ setLinkCopied: (copied: boolean) => dispatch({ type: 'SET_LINK_COPIED', payload: copied }),
138
+ incrementPreviewKey: () => dispatch({ type: 'INCREMENT_PREVIEW_KEY' }),
139
+ toggleAside: () => dispatch({ type: 'TOGGLE_ASIDE' }),
140
+ setAside: (show: boolean) => dispatch({ type: 'SET_ASIDE', payload: show }),
141
+ closeAllModals: () => dispatch({ type: 'CLOSE_ALL_MODALS' }),
142
+ }), []);
143
+
144
+ return { state, actions };
145
+ }
146
+
147
+ export type { AppUIState, AppUIAction };
@@ -0,0 +1,42 @@
1
+ import { useState, useEffect } from "react";
2
+ import type { CompiledFragmentsFile } from "@fragments-sdk/context/types";
3
+
4
+ interface UseCompiledFragmentsResult {
5
+ data: CompiledFragmentsFile | null;
6
+ loading: boolean;
7
+ error: string | null;
8
+ }
9
+
10
+ export function useCompiledFragments(): UseCompiledFragmentsResult {
11
+ const [data, setData] = useState<CompiledFragmentsFile | null>(null);
12
+ const [loading, setLoading] = useState(true);
13
+ const [error, setError] = useState<string | null>(null);
14
+
15
+ useEffect(() => {
16
+ let cancelled = false;
17
+
18
+ fetch("/fragments/compiled.json")
19
+ .then((res) => {
20
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
21
+ return res.json();
22
+ })
23
+ .then((json) => {
24
+ if (!cancelled) {
25
+ setData(json as CompiledFragmentsFile);
26
+ setLoading(false);
27
+ }
28
+ })
29
+ .catch((err) => {
30
+ if (!cancelled) {
31
+ setError(err instanceof Error ? err.message : String(err));
32
+ setLoading(false);
33
+ }
34
+ });
35
+
36
+ return () => {
37
+ cancelled = true;
38
+ };
39
+ }, []);
40
+
41
+ return { data, loading, error };
42
+ }