@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,472 @@
1
+ import { useState, useMemo, useRef, useEffect, useCallback } from 'react';
2
+ import type { FragmentDefinition } from '@fragments-sdk/core';
3
+ import { Sidebar, useSidebar, Text, Menu, Button, Box, Stack } from '@fragments-sdk/ui';
4
+
5
+ // Fuzzy matching utility
6
+ interface FuzzyMatch {
7
+ score: number;
8
+ indices: number[];
9
+ }
10
+
11
+ function fuzzyMatch(text: string, pattern: string): FuzzyMatch | null {
12
+ if (!pattern) return { score: 0, indices: [] };
13
+
14
+ const textLower = text.toLowerCase();
15
+ const patternLower = pattern.toLowerCase();
16
+
17
+ // Require substring match for short queries (<=3 chars) to avoid scattered single-char noise
18
+ if (patternLower.length <= 3 && !textLower.includes(patternLower)) {
19
+ return null;
20
+ }
21
+
22
+ const indices: number[] = [];
23
+ let patternIdx = 0;
24
+ let score = 0;
25
+ let consecutiveBonus = 0;
26
+ let maxGap = 0;
27
+
28
+ for (let i = 0; i < textLower.length && patternIdx < patternLower.length; i++) {
29
+ if (textLower[i] === patternLower[patternIdx]) {
30
+ indices.push(i);
31
+ if (indices.length > 1) {
32
+ const gap = i - indices[indices.length - 2];
33
+ if (gap === 1) {
34
+ consecutiveBonus += 5;
35
+ }
36
+ if (gap > maxGap) maxGap = gap;
37
+ }
38
+ if (i === 0 || text[i - 1] === ' ' || text[i - 1] === '-' || text[i - 1] === '_') {
39
+ score += 10;
40
+ }
41
+ patternIdx++;
42
+ }
43
+ }
44
+
45
+ if (patternIdx !== patternLower.length) {
46
+ return null;
47
+ }
48
+
49
+ // Penalize large gaps between matched characters
50
+ if (maxGap > 5) {
51
+ score -= maxGap * 2;
52
+ }
53
+
54
+ score += consecutiveBonus;
55
+ score += (patternLower.length / textLower.length) * 20;
56
+
57
+ // Reject very low scores (scattered single-char matches)
58
+ if (score <= 0 && patternLower.length > 1) {
59
+ return null;
60
+ }
61
+
62
+ return { score, indices };
63
+ }
64
+
65
+ interface SearchResult {
66
+ item: { path: string; fragment: FragmentDefinition };
67
+ score: number;
68
+ nameIndices: number[];
69
+ }
70
+
71
+ function searchFragment(
72
+ item: { path: string; fragment: FragmentDefinition },
73
+ query: string
74
+ ): SearchResult | null {
75
+ const { fragment } = item;
76
+ // Skip invalid fragments
77
+ if (!fragment?.meta) return null;
78
+ const { name, category, tags } = fragment.meta;
79
+
80
+ const nameMatch = fuzzyMatch(name, query);
81
+ if (nameMatch) {
82
+ return { item, score: nameMatch.score + 100, nameIndices: nameMatch.indices };
83
+ }
84
+
85
+ const categoryMatch = fuzzyMatch(category, query);
86
+ if (categoryMatch) {
87
+ return { item, score: categoryMatch.score + 50, nameIndices: [] };
88
+ }
89
+
90
+ if (tags) {
91
+ for (const tag of tags) {
92
+ const tagMatch = fuzzyMatch(tag, query);
93
+ if (tagMatch) {
94
+ return { item, score: tagMatch.score + 25, nameIndices: [] };
95
+ }
96
+ }
97
+ }
98
+
99
+ return null;
100
+ }
101
+
102
+ function useDebounce<T>(value: T, delay: number): T {
103
+ const [debouncedValue, setDebouncedValue] = useState(value);
104
+
105
+ useEffect(() => {
106
+ const timer = setTimeout(() => setDebouncedValue(value), delay);
107
+ return () => clearTimeout(timer);
108
+ }, [value, delay]);
109
+
110
+ return debouncedValue;
111
+ }
112
+
113
+ function HighlightedText({ text, indices }: { text: string; indices: number[] }) {
114
+ if (indices.length === 0) return <>{text}</>;
115
+
116
+ const result: React.ReactNode[] = [];
117
+ let lastIndex = 0;
118
+
119
+ for (let i = 0; i < indices.length; i++) {
120
+ const matchIndex = indices[i];
121
+ if (matchIndex > lastIndex) {
122
+ result.push(text.slice(lastIndex, matchIndex));
123
+ }
124
+ result.push(
125
+ <span key={matchIndex} style={{ color: 'var(--text-primary)', fontWeight: 500 }}>
126
+ {text[matchIndex]}
127
+ </span>
128
+ );
129
+ lastIndex = matchIndex + 1;
130
+ }
131
+
132
+ if (lastIndex < text.length) {
133
+ result.push(text.slice(lastIndex));
134
+ }
135
+
136
+ return <>{result}</>;
137
+ }
138
+
139
+ interface LeftSidebarProps {
140
+ fragments: Array<{ path: string; fragment: FragmentDefinition }>;
141
+ activeFragment: string | null;
142
+ searchQuery: string;
143
+ onSelect: (path: string) => void;
144
+ showHealth?: boolean;
145
+ onHealthClick?: () => void;
146
+ }
147
+
148
+ const FilterIcon = ({ active }: { active?: boolean }) => (
149
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
150
+ <path
151
+ d="M2 3h12l-4.5 5.5V13l-3-1.5V8.5L2 3z"
152
+ stroke={active ? 'var(--color-brand, #3b82f6)' : 'currentColor'}
153
+ strokeWidth="1.5"
154
+ strokeLinejoin="round"
155
+ fill={active ? 'var(--color-brand, #3b82f6)' : 'none'}
156
+ fillOpacity={active ? 0.15 : 0}
157
+ />
158
+ </svg>
159
+ );
160
+
161
+ const isInstalled = (path: string) => path.startsWith('@');
162
+
163
+ /** Normalize category names to Title Case: "form" → "Form", "Data Display" stays */
164
+ function titleCase(str: string): string {
165
+ return str.replace(/\b\w/g, (c) => c.toUpperCase());
166
+ }
167
+
168
+ /** Normalize category to a canonical key so "Form" and "Forms" merge into one group.
169
+ * Returns the singular form as grouping key. */
170
+ function categoryKey(raw: string): string {
171
+ const tc = titleCase(raw.trim());
172
+ // Strip trailing "s" plurals (Forms→Form, Buttons→Button) but not short words like "Tabs"
173
+ if (tc.length > 4 && tc.endsWith('s') && !tc.endsWith('ss')) {
174
+ return tc.slice(0, -1);
175
+ }
176
+ return tc;
177
+ }
178
+
179
+ /** Pluralize a category name for display: "Form" → "Forms", "General" stays */
180
+ function pluralizeCategory(key: string): string {
181
+ // Already plural or naturally non-plural categories
182
+ const nonPlural = new Set(['General', 'Feedback', 'Layout', 'Navigation', 'Typography', 'Deprecated', 'Data Display']);
183
+ if (nonPlural.has(key)) return key;
184
+ // Already ends in s (edge case)
185
+ if (key.endsWith('s')) return key;
186
+ return key + 's';
187
+ }
188
+
189
+ export function LeftSidebar({ fragments, activeFragment, searchQuery, onSelect, showHealth, onHealthClick }: LeftSidebarProps) {
190
+ const [focusedIndex, setFocusedIndex] = useState(-1);
191
+ const [showCustom, setShowCustom] = useState(true);
192
+ const [showLibrary, setShowLibrary] = useState(true);
193
+ const { isMobile, setOpen } = useSidebar();
194
+ const navRef = useRef<HTMLDivElement>(null);
195
+
196
+ // Determine if both sources exist (only show filter when useful)
197
+ const hasBothSources = useMemo(() => {
198
+ let hasCustom = false;
199
+ let hasLibrary = false;
200
+ for (const item of fragments) {
201
+ if (isInstalled(item.path)) hasLibrary = true;
202
+ else hasCustom = true;
203
+ if (hasCustom && hasLibrary) return true;
204
+ }
205
+ return false;
206
+ }, [fragments]);
207
+
208
+ const debouncedSearch = useDebounce(searchQuery, 150);
209
+
210
+ const searchResults = useMemo(() => {
211
+ if (!debouncedSearch) return null;
212
+
213
+ const results: SearchResult[] = [];
214
+ for (const item of fragments) {
215
+ const result = searchFragment(item, debouncedSearch);
216
+ if (result) results.push(result);
217
+ }
218
+
219
+ results.sort((a, b) => b.score - a.score);
220
+ return results;
221
+ }, [fragments, debouncedSearch]);
222
+
223
+ const highlightMap = useMemo(() => {
224
+ const map = new Map<string, number[]>();
225
+ if (searchResults) {
226
+ for (const result of searchResults) {
227
+ map.set(result.item.path, result.nameIndices);
228
+ }
229
+ }
230
+ return map;
231
+ }, [searchResults]);
232
+
233
+ const isFilterActive = showCustom !== showLibrary;
234
+
235
+ // Apply source filter
236
+ const sourceFiltered = useMemo(() => {
237
+ if (!isFilterActive) return fragments;
238
+ return fragments.filter(item =>
239
+ showLibrary ? isInstalled(item.path) : !isInstalled(item.path)
240
+ );
241
+ }, [fragments, isFilterActive, showLibrary]);
242
+
243
+ // Flat alphabetical list (search results sorted by relevance, otherwise alphabetical)
244
+ const flatItems = useMemo(() => {
245
+ if (searchResults) {
246
+ return searchResults
247
+ .map(r => r.item)
248
+ .filter(item => item.fragment?.meta?.name)
249
+ .filter(item => !isFilterActive || (showLibrary ? isInstalled(item.path) : !isInstalled(item.path)));
250
+ }
251
+ return [...sourceFiltered]
252
+ .filter(item => item.fragment?.meta?.name)
253
+ .sort((a, b) =>
254
+ a.fragment.meta.name.toLowerCase().localeCompare(b.fragment.meta.name.toLowerCase())
255
+ );
256
+ }, [sourceFiltered, searchResults, isFilterActive, showLibrary]);
257
+
258
+ // Group items by category when not searching (for large lists)
259
+ const categoryGroups = useMemo(() => {
260
+ if (searchResults || flatItems.length < 30) return null; // Flat list for small sets or search
261
+ const groups = new Map<string, typeof flatItems>();
262
+ for (const item of flatItems) {
263
+ const raw = item.fragment.meta.category || 'Uncategorized';
264
+ const key = categoryKey(raw);
265
+ if (!groups.has(key)) groups.set(key, []);
266
+ groups.get(key)!.push(item);
267
+ }
268
+ // Sort categories alphabetically, map key → display label
269
+ return [...groups.entries()]
270
+ .sort((a, b) => a[0].toLowerCase().localeCompare(b[0].toLowerCase()))
271
+ .map(([key, items]) => [pluralizeCategory(key), items] as const);
272
+ }, [flatItems, searchResults]);
273
+
274
+ const keyboardItems = useMemo(() => {
275
+ const componentItems = flatItems.map((item) => ({ type: 'component' as const, path: item.path }));
276
+ if (!onHealthClick) return componentItems;
277
+ return [{ type: 'dashboard' as const }, ...componentItems];
278
+ }, [flatItems, onHealthClick]);
279
+
280
+ useEffect(() => {
281
+ if (focusedIndex >= 0 && focusedIndex < keyboardItems.length && navRef.current) {
282
+ // Query all nav item buttons rendered by Sidebar.Item inside the nav
283
+ const buttons = navRef.current.querySelectorAll<HTMLButtonElement>('li > button[type="button"]');
284
+ if (buttons[focusedIndex]) {
285
+ buttons[focusedIndex].focus();
286
+ }
287
+ }
288
+ }, [focusedIndex, keyboardItems.length]);
289
+
290
+ // Scroll the active sidebar item into view on mount and when activeFragment changes
291
+ useEffect(() => {
292
+ if (!activeFragment || !navRef.current) return;
293
+ // Small delay to let the DOM render after category grouping
294
+ const timer = setTimeout(() => {
295
+ const activeButton = navRef.current?.querySelector<HTMLButtonElement>('[aria-current="page"]');
296
+ if (activeButton) {
297
+ activeButton.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
298
+ }
299
+ }, 100);
300
+ return () => clearTimeout(timer);
301
+ }, [activeFragment]);
302
+
303
+ useEffect(() => {
304
+ setFocusedIndex(-1);
305
+ }, [searchQuery]);
306
+
307
+ const handleSelect = (path: string) => {
308
+ onSelect(path);
309
+ if (isMobile) {
310
+ setOpen(false);
311
+ }
312
+ };
313
+
314
+ const handleHealthClick = () => {
315
+ onHealthClick?.();
316
+ if (isMobile) {
317
+ setOpen(false);
318
+ }
319
+ };
320
+
321
+ const handleKeyDown = useCallback((e: KeyboardEvent) => {
322
+ const target = e.target as HTMLElement;
323
+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
324
+ return;
325
+ }
326
+
327
+ if (e.key === 'Escape') {
328
+ setFocusedIndex(-1);
329
+ return;
330
+ }
331
+
332
+ if (e.key === 'ArrowDown') {
333
+ e.preventDefault();
334
+ setFocusedIndex(prev => (prev + 1) >= keyboardItems.length ? 0 : prev + 1);
335
+ } else if (e.key === 'ArrowUp') {
336
+ e.preventDefault();
337
+ setFocusedIndex(prev => (prev - 1) < 0 ? keyboardItems.length - 1 : prev - 1);
338
+ } else if (e.key === 'Enter' && focusedIndex >= 0 && focusedIndex < keyboardItems.length) {
339
+ e.preventDefault();
340
+ const currentItem = keyboardItems[focusedIndex];
341
+ if (currentItem.type === 'dashboard') {
342
+ handleHealthClick();
343
+ } else {
344
+ handleSelect(currentItem.path);
345
+ }
346
+ }
347
+ }, [keyboardItems, focusedIndex, handleHealthClick, handleSelect]);
348
+
349
+ useEffect(() => {
350
+ document.addEventListener('keydown', handleKeyDown);
351
+ return () => document.removeEventListener('keydown', handleKeyDown);
352
+ }, [handleKeyDown]);
353
+
354
+ return (
355
+ <>
356
+ {/* Component list */}
357
+ <Sidebar.Nav aria-label="Components">
358
+ <div ref={navRef}>
359
+ {onHealthClick && (
360
+ <Sidebar.Section label="Overview">
361
+ <Sidebar.Item
362
+ active={!!showHealth}
363
+ onClick={handleHealthClick}
364
+ >
365
+ Dashboard
366
+ </Sidebar.Item>
367
+ </Sidebar.Section>
368
+ )}
369
+
370
+ {categoryGroups ? (
371
+ // Grouped by category for large component lists
372
+ <>
373
+ {categoryGroups.map(([category, items]) => (
374
+ <Sidebar.Section key={category} label={`${category} (${items.length})`}>
375
+ {items.map((item) => {
376
+ const hasError = !!(item.fragment as any)?._loadError;
377
+ return (
378
+ <Sidebar.Item
379
+ key={item.path}
380
+ active={activeFragment === item.path}
381
+ onClick={() => handleSelect(item.path)}
382
+ >
383
+ <span style={{ display: 'flex', alignItems: 'center', gap: '6px', width: '100%' }}>
384
+ <HighlightedText
385
+ text={item.fragment.meta.name}
386
+ indices={highlightMap.get(item.path) || []}
387
+ />
388
+ {hasError && (
389
+ <span
390
+ title="Missing dependencies"
391
+ style={{ color: 'var(--color-warning, #f59e0b)', fontSize: '14px', lineHeight: 1, flexShrink: 0 }}
392
+ >
393
+ &#9888;
394
+ </span>
395
+ )}
396
+ </span>
397
+ </Sidebar.Item>
398
+ );
399
+ })}
400
+ </Sidebar.Section>
401
+ ))}
402
+ </>
403
+ ) : (
404
+ // Flat list for search results or small component sets
405
+ <Sidebar.Section
406
+ label="Components"
407
+ action={hasBothSources ? (
408
+ <Menu modal={false}>
409
+ <Menu.Trigger asChild>
410
+ <Button variant="ghost" size="sm" icon aria-label="Filter components by source">
411
+ <FilterIcon active={isFilterActive} />
412
+ </Button>
413
+ </Menu.Trigger>
414
+ <Menu.Content>
415
+ <Menu.CheckboxItem checked={showCustom} onCheckedChange={setShowCustom}>
416
+ Custom
417
+ </Menu.CheckboxItem>
418
+ <Menu.CheckboxItem checked={showLibrary} onCheckedChange={setShowLibrary}>
419
+ Fragments UI
420
+ </Menu.CheckboxItem>
421
+ </Menu.Content>
422
+ </Menu>
423
+ ) : undefined}
424
+ >
425
+ {flatItems.map((item) => {
426
+ const hasError = !!(item.fragment as any)?._loadError;
427
+ return (
428
+ <Sidebar.Item
429
+ key={item.path}
430
+ active={activeFragment === item.path}
431
+ onClick={() => handleSelect(item.path)}
432
+ >
433
+ <span style={{ display: 'flex', alignItems: 'center', gap: '6px', width: '100%' }}>
434
+ <HighlightedText
435
+ text={item.fragment.meta.name}
436
+ indices={highlightMap.get(item.path) || []}
437
+ />
438
+ {hasError && (
439
+ <span
440
+ title="Missing dependencies"
441
+ style={{ color: 'var(--color-warning, #f59e0b)', fontSize: '14px', lineHeight: 1, flexShrink: 0 }}
442
+ >
443
+ &#9888;
444
+ </span>
445
+ )}
446
+ </span>
447
+ </Sidebar.Item>
448
+ );
449
+ })}
450
+ </Sidebar.Section>
451
+ )}
452
+
453
+ {flatItems.length === 0 && (
454
+ <Box paddingX="lg" paddingY="sm" style={{ textAlign: 'center' }}>
455
+ <Text size="sm" color="tertiary">No results</Text>
456
+ </Box>
457
+ )}
458
+ </div>
459
+ </Sidebar.Nav>
460
+
461
+ {/* Footer */}
462
+ <Sidebar.Footer>
463
+ <Stack direction="row" align="center" justify="between" style={{ width: '100%' }}>
464
+ <Text size="xs" color="tertiary">
465
+ {isFilterActive || searchResults ? `${flatItems.length} of ${fragments.length}` : fragments.length} components
466
+ </Text>
467
+ <Sidebar.CollapseToggle />
468
+ </Stack>
469
+ </Sidebar.Footer>
470
+ </>
471
+ );
472
+ }
@@ -0,0 +1,102 @@
1
+ import { Stack, Text, Alert, Box } from "@fragments-sdk/ui";
2
+
3
+ interface LoadErrorMessageProps {
4
+ error: { message: string; dependencies: string[] };
5
+ componentName?: string;
6
+ }
7
+
8
+ export function LoadErrorMessage({ error, componentName }: LoadErrorMessageProps) {
9
+ const deps = error.dependencies || [];
10
+ const errorMessage = error.message || "Unknown error";
11
+
12
+ // Determine if the error is a missing module/dependency issue
13
+ const isModuleError =
14
+ /Failed to resolve import|Cannot find module|Module not found|does not provide an export/.test(
15
+ errorMessage
16
+ );
17
+
18
+ // Only suggest packages if the error is actually about missing modules
19
+ let suggestedPackages: string[] = [];
20
+ if (isModuleError) {
21
+ if (deps.length > 0) {
22
+ suggestedPackages = [...deps];
23
+ } else {
24
+ const match = errorMessage.match(/Failed to resolve import ["']([^"']+)["']/);
25
+ if (match) {
26
+ suggestedPackages = [match[1]];
27
+ }
28
+ }
29
+ }
30
+
31
+ const hasMissingDeps = suggestedPackages.length > 0;
32
+ const installCmd = `pnpm add ${suggestedPackages.join(" ")}`;
33
+
34
+ return (
35
+ <Stack align="center" justify="center" style={{ height: "100%", padding: "24px" }}>
36
+ <Alert variant="warning">
37
+ <Alert.Body>
38
+ <Alert.Title>{hasMissingDeps ? "Missing Dependencies" : "Failed to Load"}</Alert.Title>
39
+ <Alert.Content>
40
+ <Stack direction="column" gap="sm">
41
+ {hasMissingDeps ? (
42
+ <>
43
+ <Text size="xs" color="secondary">
44
+ {componentName ? `${componentName} requires` : "This component requires"}{" "}
45
+ packages that are not installed in your project.
46
+ </Text>
47
+ <Text size="xs" weight="semibold" color="secondary">
48
+ Install with:
49
+ </Text>
50
+ <Box
51
+ as="code"
52
+ padding="sm"
53
+ background="tertiary"
54
+ rounded="sm"
55
+ style={{
56
+ display: "block",
57
+ fontFamily: "monospace",
58
+ fontSize: "12px",
59
+ userSelect: "all",
60
+ }}
61
+ >
62
+ {installCmd}
63
+ </Box>
64
+ <Text size="xs" color="tertiary">
65
+ After installing, restart the dev server.
66
+ </Text>
67
+ </>
68
+ ) : (
69
+ <>
70
+ <Text size="xs" color="secondary">
71
+ {componentName ? `${componentName} couldn't` : "This component couldn't"} be
72
+ loaded. This may be due to a schema validation error or missing imports.
73
+ </Text>
74
+ <Text size="xs" weight="semibold" color="secondary">
75
+ Error:
76
+ </Text>
77
+ <Box
78
+ as="pre"
79
+ padding="sm"
80
+ background="tertiary"
81
+ rounded="sm"
82
+ style={{
83
+ fontFamily: "monospace",
84
+ fontSize: "11px",
85
+ whiteSpace: "pre-wrap",
86
+ wordBreak: "break-word",
87
+ margin: 0,
88
+ maxHeight: "200px",
89
+ overflow: "auto",
90
+ }}
91
+ >
92
+ {errorMessage}
93
+ </Box>
94
+ </>
95
+ )}
96
+ </Stack>
97
+ </Alert.Content>
98
+ </Alert.Body>
99
+ </Alert>
100
+ </Stack>
101
+ );
102
+ }