@fragments-sdk/viewer 0.2.1 → 0.2.4

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 (60) hide show
  1. package/package.json +10 -3
  2. package/src/components/App.tsx +67 -4
  3. package/src/components/BottomPanel.tsx +31 -1
  4. package/src/components/ComponentGraph.tsx +1 -1
  5. package/src/components/EmptyVariantMessage.tsx +1 -1
  6. package/src/components/ErrorBoundary.tsx +2 -4
  7. package/src/components/FragmentRenderer.tsx +27 -4
  8. package/src/components/HeaderSearch.tsx +1 -1
  9. package/src/components/InteractionsPanel.tsx +5 -5
  10. package/src/components/LoadErrorMessage.tsx +26 -30
  11. package/src/components/NoVariantsMessage.tsx +1 -1
  12. package/src/components/PanelShell.tsx +1 -1
  13. package/src/components/PerformancePanel.tsx +4 -4
  14. package/src/components/PreviewArea.tsx +6 -0
  15. package/src/components/PropsEditor.tsx +33 -17
  16. package/src/components/SkeletonLoader.tsx +0 -1
  17. package/src/components/TokenStylePanel.tsx +3 -3
  18. package/src/components/TopToolbar.tsx +1 -1
  19. package/src/components/VariantMatrix.tsx +11 -1
  20. package/src/components/ViewerHeader.tsx +1 -1
  21. package/src/components/WebMCPDevTools.tsx +2 -2
  22. package/src/entry.tsx +4 -6
  23. package/src/hooks/useAppState.ts +1 -1
  24. package/src/preview-frame-entry.tsx +0 -2
  25. package/src/shared/DocsHeaderBar.module.scss +174 -0
  26. package/src/shared/DocsHeaderBar.tsx +149 -14
  27. package/src/shared/DocsSidebarNav.tsx +3 -3
  28. package/src/shared/index.ts +4 -1
  29. package/src/shared/types.ts +29 -3
  30. package/src/style-utils.ts +1 -1
  31. package/src/webmcp/runtime-tools.ts +1 -1
  32. package/tsconfig.json +2 -2
  33. package/src/assets/fragments-logo.ts +0 -4
  34. package/src/components/ActionsPanel.tsx +0 -332
  35. package/src/components/ComponentHeader.tsx +0 -88
  36. package/src/components/ContractPanel.tsx +0 -241
  37. package/src/components/FragmentEditor.tsx +0 -525
  38. package/src/components/HmrStatusIndicator.tsx +0 -61
  39. package/src/components/LandingPage.tsx +0 -420
  40. package/src/components/PropsTable.tsx +0 -111
  41. package/src/components/RelationsSection.tsx +0 -88
  42. package/src/components/ResizablePanel.tsx +0 -271
  43. package/src/components/RightSidebar.tsx +0 -102
  44. package/src/components/ScreenshotButton.tsx +0 -90
  45. package/src/components/Sidebar.tsx +0 -169
  46. package/src/components/UsageSection.tsx +0 -95
  47. package/src/components/VariantTabs.tsx +0 -40
  48. package/src/components/ViewportSelector.tsx +0 -172
  49. package/src/components/_future/CreatePage.tsx +0 -835
  50. package/src/composition-renderer.ts +0 -381
  51. package/src/constants/index.ts +0 -1
  52. package/src/hooks/index.ts +0 -2
  53. package/src/hooks/useHmrStatus.ts +0 -109
  54. package/src/hooks/useScrollSpy.ts +0 -78
  55. package/src/intelligence/healthReport.ts +0 -505
  56. package/src/intelligence/styleDrift.ts +0 -340
  57. package/src/intelligence/usageScanner.ts +0 -309
  58. package/src/utils/actionExport.ts +0 -372
  59. package/src/utils/colorSchemes.ts +0 -201
  60. package/src/webmcp/index.ts +0 -3
@@ -1,271 +0,0 @@
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;
@@ -1,102 +0,0 @@
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
- }
@@ -1,90 +0,0 @@
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
- });
@@ -1,169 +0,0 @@
1
- import React, { useState, useMemo } from 'react';
2
- import type { FragmentDefinition } from '@fragments-sdk/core';
3
-
4
- interface SidebarProps {
5
- fragments: Array<{ path: string; fragment: FragmentDefinition }>;
6
- activeFragment: string | null;
7
- onSelect: (path: string) => void;
8
- }
9
-
10
- export function Sidebar({ fragments, activeFragment, onSelect }: SidebarProps): React.ReactElement {
11
- const [search, setSearch] = useState('');
12
-
13
- // Group fragments by category
14
- const grouped = useMemo(() => {
15
- const groups: Record<string, typeof fragments> = {};
16
-
17
- for (const item of fragments) {
18
- const category = item.fragment.meta.category || 'uncategorized';
19
- if (!groups[category]) {
20
- groups[category] = [];
21
- }
22
- groups[category].push(item);
23
- }
24
-
25
- // Filter by search
26
- if (search) {
27
- const filtered: Record<string, typeof fragments> = {};
28
- for (const [category, items] of Object.entries(groups)) {
29
- const matchingItems = items.filter(
30
- (item) =>
31
- item.fragment.meta.name.toLowerCase().includes(search.toLowerCase()) ||
32
- item.fragment.meta.description.toLowerCase().includes(search.toLowerCase())
33
- );
34
- if (matchingItems.length > 0) {
35
- filtered[category] = matchingItems;
36
- }
37
- }
38
- return filtered;
39
- }
40
-
41
- return groups;
42
- }, [fragments, search]);
43
-
44
- return (
45
- <div
46
- style={{
47
- width: '280px',
48
- height: '100vh',
49
- background: '#f9fafb',
50
- borderRight: '1px solid #e5e7eb',
51
- display: 'flex',
52
- flexDirection: 'column',
53
- overflow: 'hidden',
54
- }}
55
- >
56
- {/* Header */}
57
- <div
58
- style={{
59
- padding: '16px',
60
- borderBottom: '1px solid #e5e7eb',
61
- }}
62
- >
63
- <h1
64
- style={{
65
- margin: 0,
66
- fontSize: '18px',
67
- fontWeight: 700,
68
- color: '#111827',
69
- }}
70
- >
71
- Fragments
72
- </h1>
73
- <p
74
- style={{
75
- margin: '4px 0 0',
76
- fontSize: '12px',
77
- color: '#6b7280',
78
- }}
79
- >
80
- {fragments.length} component{fragments.length !== 1 ? 's' : ''}
81
- </p>
82
- </div>
83
-
84
- {/* Search */}
85
- <div style={{ padding: '12px 16px' }}>
86
- <input
87
- type="text"
88
- placeholder="Search components..."
89
- value={search}
90
- onChange={(e) => setSearch(e.target.value)}
91
- style={{
92
- width: '100%',
93
- padding: '8px 12px',
94
- border: '1px solid #d1d5db',
95
- borderRadius: '6px',
96
- fontSize: '13px',
97
- outline: 'none',
98
- boxSizing: 'border-box',
99
- }}
100
- />
101
- </div>
102
-
103
- {/* Component list */}
104
- <div
105
- style={{
106
- flex: 1,
107
- overflow: 'auto',
108
- padding: '0 8px 16px',
109
- }}
110
- >
111
- {Object.entries(grouped).map(([category, items]) => (
112
- <div key={category} style={{ marginBottom: '16px' }}>
113
- <div
114
- style={{
115
- padding: '8px',
116
- fontSize: '11px',
117
- fontWeight: 600,
118
- color: '#6b7280',
119
- textTransform: 'uppercase',
120
- letterSpacing: '0.05em',
121
- }}
122
- >
123
- {category}
124
- </div>
125
- {items.map((item) => (
126
- <button
127
- key={item.path}
128
- onClick={() => onSelect(item.path)}
129
- style={{
130
- display: 'block',
131
- width: '100%',
132
- padding: '8px 12px',
133
- border: 'none',
134
- borderRadius: '6px',
135
- background: activeFragment === item.path ? '#e5e7eb' : 'transparent',
136
- textAlign: 'left',
137
- cursor: 'pointer',
138
- transition: 'background 0.15s',
139
- }}
140
- >
141
- <div
142
- style={{
143
- fontSize: '13px',
144
- fontWeight: 500,
145
- color: '#111827',
146
- }}
147
- >
148
- {item.fragment.meta.name}
149
- </div>
150
- <div
151
- style={{
152
- fontSize: '12px',
153
- color: '#6b7280',
154
- marginTop: '2px',
155
- overflow: 'hidden',
156
- textOverflow: 'ellipsis',
157
- whiteSpace: 'nowrap',
158
- }}
159
- >
160
- {item.fragment.meta.description}
161
- </div>
162
- </button>
163
- ))}
164
- </div>
165
- ))}
166
- </div>
167
- </div>
168
- );
169
- }