@fragments-sdk/cli 0.2.2

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 (259) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +106 -0
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +4783 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/chunk-4FDQSGKX.js +786 -0
  7. package/dist/chunk-4FDQSGKX.js.map +1 -0
  8. package/dist/chunk-7H2MMGYG.js +369 -0
  9. package/dist/chunk-7H2MMGYG.js.map +1 -0
  10. package/dist/chunk-BSCG3IP7.js +619 -0
  11. package/dist/chunk-BSCG3IP7.js.map +1 -0
  12. package/dist/chunk-LY2CFFPY.js +898 -0
  13. package/dist/chunk-LY2CFFPY.js.map +1 -0
  14. package/dist/chunk-MUZ6CM66.js +6636 -0
  15. package/dist/chunk-MUZ6CM66.js.map +1 -0
  16. package/dist/chunk-OAENNG3G.js +1489 -0
  17. package/dist/chunk-OAENNG3G.js.map +1 -0
  18. package/dist/chunk-XHNKNI6J.js +235 -0
  19. package/dist/chunk-XHNKNI6J.js.map +1 -0
  20. package/dist/core-DWKLGY4N.js +68 -0
  21. package/dist/core-DWKLGY4N.js.map +1 -0
  22. package/dist/generate-4LQNJ7SX.js +249 -0
  23. package/dist/generate-4LQNJ7SX.js.map +1 -0
  24. package/dist/index.d.ts +775 -0
  25. package/dist/index.js +41 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/init-EMVI47QG.js +416 -0
  28. package/dist/init-EMVI47QG.js.map +1 -0
  29. package/dist/mcp-bin.d.ts +1 -0
  30. package/dist/mcp-bin.js +1117 -0
  31. package/dist/mcp-bin.js.map +1 -0
  32. package/dist/scan-4YPRF7FV.js +12 -0
  33. package/dist/scan-4YPRF7FV.js.map +1 -0
  34. package/dist/service-QSZMZJBJ.js +208 -0
  35. package/dist/service-QSZMZJBJ.js.map +1 -0
  36. package/dist/static-viewer-MIPGZ4Z7.js +12 -0
  37. package/dist/static-viewer-MIPGZ4Z7.js.map +1 -0
  38. package/dist/test-SQ5ZHXWU.js +1067 -0
  39. package/dist/test-SQ5ZHXWU.js.map +1 -0
  40. package/dist/tokens-HSGMYK64.js +173 -0
  41. package/dist/tokens-HSGMYK64.js.map +1 -0
  42. package/dist/viewer-YRF4SQE4.js +11101 -0
  43. package/dist/viewer-YRF4SQE4.js.map +1 -0
  44. package/package.json +107 -0
  45. package/src/ai.ts +266 -0
  46. package/src/analyze.ts +265 -0
  47. package/src/bin.ts +916 -0
  48. package/src/build.ts +248 -0
  49. package/src/commands/a11y.ts +302 -0
  50. package/src/commands/add.ts +313 -0
  51. package/src/commands/audit.ts +195 -0
  52. package/src/commands/baseline.ts +221 -0
  53. package/src/commands/build.ts +144 -0
  54. package/src/commands/compare.ts +337 -0
  55. package/src/commands/context.ts +107 -0
  56. package/src/commands/dev.ts +107 -0
  57. package/src/commands/enhance.ts +858 -0
  58. package/src/commands/generate.ts +391 -0
  59. package/src/commands/init.ts +531 -0
  60. package/src/commands/link/figma.ts +645 -0
  61. package/src/commands/link/index.ts +10 -0
  62. package/src/commands/link/storybook.ts +267 -0
  63. package/src/commands/list.ts +49 -0
  64. package/src/commands/metrics.ts +114 -0
  65. package/src/commands/reset.ts +242 -0
  66. package/src/commands/scan.ts +537 -0
  67. package/src/commands/storygen.ts +207 -0
  68. package/src/commands/tokens.ts +251 -0
  69. package/src/commands/validate.ts +93 -0
  70. package/src/commands/verify.ts +215 -0
  71. package/src/core/composition.test.ts +262 -0
  72. package/src/core/composition.ts +255 -0
  73. package/src/core/config.ts +84 -0
  74. package/src/core/constants.ts +111 -0
  75. package/src/core/context.ts +380 -0
  76. package/src/core/defineSegment.ts +137 -0
  77. package/src/core/discovery.ts +337 -0
  78. package/src/core/figma.ts +263 -0
  79. package/src/core/fragment-types.ts +214 -0
  80. package/src/core/generators/context.ts +389 -0
  81. package/src/core/generators/index.ts +23 -0
  82. package/src/core/generators/registry.ts +364 -0
  83. package/src/core/generators/typescript-extractor.ts +374 -0
  84. package/src/core/importAnalyzer.ts +217 -0
  85. package/src/core/index.ts +149 -0
  86. package/src/core/loader.ts +155 -0
  87. package/src/core/node.ts +63 -0
  88. package/src/core/parser.ts +551 -0
  89. package/src/core/previewLoader.ts +172 -0
  90. package/src/core/schema/fragment.schema.json +189 -0
  91. package/src/core/schema/registry.schema.json +137 -0
  92. package/src/core/schema.ts +182 -0
  93. package/src/core/storyAdapter.test.ts +571 -0
  94. package/src/core/storyAdapter.ts +761 -0
  95. package/src/core/token-types.ts +287 -0
  96. package/src/core/types.ts +754 -0
  97. package/src/diff.ts +323 -0
  98. package/src/index.ts +43 -0
  99. package/src/mcp/__tests__/projectFields.test.ts +130 -0
  100. package/src/mcp/bin.ts +36 -0
  101. package/src/mcp/index.ts +8 -0
  102. package/src/mcp/server.ts +1310 -0
  103. package/src/mcp/utils.ts +54 -0
  104. package/src/mcp-bin.ts +36 -0
  105. package/src/migrate/__tests__/argTypes/argTypes.test.ts +189 -0
  106. package/src/migrate/__tests__/args/args.test.ts +452 -0
  107. package/src/migrate/__tests__/meta/meta.test.ts +198 -0
  108. package/src/migrate/__tests__/stories/stories.test.ts +278 -0
  109. package/src/migrate/__tests__/utils/utils.test.ts +371 -0
  110. package/src/migrate/__tests__/values/values.test.ts +303 -0
  111. package/src/migrate/bin.ts +108 -0
  112. package/src/migrate/converter.ts +658 -0
  113. package/src/migrate/detect.ts +196 -0
  114. package/src/migrate/index.ts +45 -0
  115. package/src/migrate/migrate.ts +163 -0
  116. package/src/migrate/parser.ts +1136 -0
  117. package/src/migrate/report.ts +624 -0
  118. package/src/migrate/types.ts +169 -0
  119. package/src/screenshot.ts +249 -0
  120. package/src/service/__tests__/ast-utils.test.ts +426 -0
  121. package/src/service/__tests__/enhance-scanner.test.ts +200 -0
  122. package/src/service/__tests__/figma/figma.test.ts +652 -0
  123. package/src/service/__tests__/metrics-store.test.ts +409 -0
  124. package/src/service/__tests__/patch-generator.test.ts +186 -0
  125. package/src/service/__tests__/props-extractor.test.ts +365 -0
  126. package/src/service/__tests__/token-registry.test.ts +267 -0
  127. package/src/service/analytics.ts +659 -0
  128. package/src/service/ast-utils.ts +444 -0
  129. package/src/service/browser-pool.ts +339 -0
  130. package/src/service/capture.ts +267 -0
  131. package/src/service/diff.ts +279 -0
  132. package/src/service/enhance/aggregator.ts +489 -0
  133. package/src/service/enhance/cache.ts +275 -0
  134. package/src/service/enhance/codebase-scanner.ts +357 -0
  135. package/src/service/enhance/context-generator.ts +529 -0
  136. package/src/service/enhance/doc-extractor.ts +523 -0
  137. package/src/service/enhance/index.ts +131 -0
  138. package/src/service/enhance/props-extractor.ts +665 -0
  139. package/src/service/enhance/scanner.ts +445 -0
  140. package/src/service/enhance/storybook-parser.ts +552 -0
  141. package/src/service/enhance/types.ts +346 -0
  142. package/src/service/enhance/variant-renderer.ts +479 -0
  143. package/src/service/figma.ts +1008 -0
  144. package/src/service/index.ts +249 -0
  145. package/src/service/metrics-store.ts +333 -0
  146. package/src/service/patch-generator.ts +349 -0
  147. package/src/service/report.ts +854 -0
  148. package/src/service/storage.ts +401 -0
  149. package/src/service/token-fixes.ts +281 -0
  150. package/src/service/token-parser.ts +504 -0
  151. package/src/service/token-registry.ts +721 -0
  152. package/src/service/utils.ts +172 -0
  153. package/src/setup.ts +241 -0
  154. package/src/shared/command-wrapper.ts +81 -0
  155. package/src/shared/dev-server-client.ts +199 -0
  156. package/src/shared/index.ts +8 -0
  157. package/src/shared/segment-loader.ts +59 -0
  158. package/src/shared/types.ts +147 -0
  159. package/src/static-viewer.ts +715 -0
  160. package/src/test/discovery.ts +172 -0
  161. package/src/test/index.ts +281 -0
  162. package/src/test/reporters/console.ts +194 -0
  163. package/src/test/reporters/json.ts +190 -0
  164. package/src/test/reporters/junit.ts +186 -0
  165. package/src/test/runner.ts +598 -0
  166. package/src/test/types.ts +245 -0
  167. package/src/test/watch.ts +200 -0
  168. package/src/validators.ts +152 -0
  169. package/src/viewer/__tests__/jsx-parser.test.ts +502 -0
  170. package/src/viewer/__tests__/render-utils.test.ts +232 -0
  171. package/src/viewer/__tests__/style-utils.test.ts +404 -0
  172. package/src/viewer/bin.ts +86 -0
  173. package/src/viewer/cli/health.ts +256 -0
  174. package/src/viewer/cli/index.ts +33 -0
  175. package/src/viewer/cli/scan.ts +124 -0
  176. package/src/viewer/cli/utils.ts +174 -0
  177. package/src/viewer/components/AccessibilityPanel.tsx +1404 -0
  178. package/src/viewer/components/ActionCapture.tsx +172 -0
  179. package/src/viewer/components/ActionsPanel.tsx +371 -0
  180. package/src/viewer/components/App.tsx +638 -0
  181. package/src/viewer/components/BottomPanel.tsx +224 -0
  182. package/src/viewer/components/CodePanel.tsx +589 -0
  183. package/src/viewer/components/CommandPalette.tsx +336 -0
  184. package/src/viewer/components/ComponentGraph.tsx +394 -0
  185. package/src/viewer/components/ComponentHeader.tsx +85 -0
  186. package/src/viewer/components/ContractPanel.tsx +234 -0
  187. package/src/viewer/components/ErrorBoundary.tsx +85 -0
  188. package/src/viewer/components/FigmaEmbed.tsx +231 -0
  189. package/src/viewer/components/FragmentEditor.tsx +485 -0
  190. package/src/viewer/components/HealthDashboard.tsx +452 -0
  191. package/src/viewer/components/HmrStatusIndicator.tsx +71 -0
  192. package/src/viewer/components/Icons.tsx +417 -0
  193. package/src/viewer/components/InteractionsPanel.tsx +720 -0
  194. package/src/viewer/components/IsolatedPreviewFrame.tsx +321 -0
  195. package/src/viewer/components/IsolatedRender.tsx +111 -0
  196. package/src/viewer/components/KeyboardShortcutsHelp.tsx +89 -0
  197. package/src/viewer/components/LandingPage.tsx +441 -0
  198. package/src/viewer/components/Layout.tsx +22 -0
  199. package/src/viewer/components/LeftSidebar.tsx +391 -0
  200. package/src/viewer/components/MultiViewportPreview.tsx +429 -0
  201. package/src/viewer/components/PreviewArea.tsx +404 -0
  202. package/src/viewer/components/PreviewFrameHost.tsx +310 -0
  203. package/src/viewer/components/PreviewPane.tsx +150 -0
  204. package/src/viewer/components/PreviewToolbar.tsx +176 -0
  205. package/src/viewer/components/PropsEditor.tsx +512 -0
  206. package/src/viewer/components/PropsTable.tsx +98 -0
  207. package/src/viewer/components/RelationsSection.tsx +57 -0
  208. package/src/viewer/components/ResizablePanel.tsx +328 -0
  209. package/src/viewer/components/RightSidebar.tsx +118 -0
  210. package/src/viewer/components/ScreenshotButton.tsx +90 -0
  211. package/src/viewer/components/Sidebar.tsx +169 -0
  212. package/src/viewer/components/SkeletonLoader.tsx +156 -0
  213. package/src/viewer/components/StoryRenderer.tsx +128 -0
  214. package/src/viewer/components/ThemeProvider.tsx +96 -0
  215. package/src/viewer/components/Toast.tsx +67 -0
  216. package/src/viewer/components/TokenStylePanel.tsx +708 -0
  217. package/src/viewer/components/UsageSection.tsx +95 -0
  218. package/src/viewer/components/VariantMatrix.tsx +350 -0
  219. package/src/viewer/components/VariantRenderer.tsx +131 -0
  220. package/src/viewer/components/VariantTabs.tsx +84 -0
  221. package/src/viewer/components/ViewportSelector.tsx +165 -0
  222. package/src/viewer/components/_future/CreatePage.tsx +836 -0
  223. package/src/viewer/composition-renderer.ts +381 -0
  224. package/src/viewer/constants/index.ts +1 -0
  225. package/src/viewer/constants/ui.ts +185 -0
  226. package/src/viewer/entry.tsx +299 -0
  227. package/src/viewer/hooks/index.ts +2 -0
  228. package/src/viewer/hooks/useA11yCache.ts +383 -0
  229. package/src/viewer/hooks/useA11yService.ts +498 -0
  230. package/src/viewer/hooks/useActions.ts +138 -0
  231. package/src/viewer/hooks/useAppState.ts +124 -0
  232. package/src/viewer/hooks/useFigmaIntegration.ts +132 -0
  233. package/src/viewer/hooks/useHmrStatus.ts +109 -0
  234. package/src/viewer/hooks/useKeyboardShortcuts.ts +222 -0
  235. package/src/viewer/hooks/usePreviewBridge.ts +347 -0
  236. package/src/viewer/hooks/useScrollSpy.ts +78 -0
  237. package/src/viewer/hooks/useUrlState.ts +330 -0
  238. package/src/viewer/hooks/useViewSettings.ts +125 -0
  239. package/src/viewer/index.html +28 -0
  240. package/src/viewer/index.ts +14 -0
  241. package/src/viewer/intelligence/healthReport.ts +505 -0
  242. package/src/viewer/intelligence/styleDrift.ts +340 -0
  243. package/src/viewer/intelligence/usageScanner.ts +309 -0
  244. package/src/viewer/jsx-parser.ts +485 -0
  245. package/src/viewer/postcss.config.js +6 -0
  246. package/src/viewer/preview-frame-entry.tsx +25 -0
  247. package/src/viewer/preview-frame.html +109 -0
  248. package/src/viewer/render-template.html +68 -0
  249. package/src/viewer/render-utils.ts +170 -0
  250. package/src/viewer/server.ts +276 -0
  251. package/src/viewer/style-utils.ts +414 -0
  252. package/src/viewer/styles/globals.css +355 -0
  253. package/src/viewer/tailwind.config.js +37 -0
  254. package/src/viewer/types/a11y.ts +197 -0
  255. package/src/viewer/utils/a11y-fixes.ts +471 -0
  256. package/src/viewer/utils/actionExport.ts +372 -0
  257. package/src/viewer/utils/colorSchemes.ts +201 -0
  258. package/src/viewer/utils/detectRelationships.ts +256 -0
  259. package/src/viewer/vite-plugin.ts +2143 -0
@@ -0,0 +1,708 @@
1
+ /**
2
+ * Token-Aware Style Comparison Panel
3
+ *
4
+ * Enhanced style comparison that shows:
5
+ * - Property, Figma value, Rendered value, Match status
6
+ * - Token names when values match design tokens
7
+ * - Hardcoded value warnings
8
+ * - Fix suggestions that can be copied
9
+ */
10
+
11
+ import { useState, useEffect, useCallback } from "react";
12
+ import clsx from "clsx";
13
+ import type { DesignToken, EnhancedStyleDiffItem, TokenUsageSummary } from "../../core/index.js";
14
+ import { CheckIcon, XIcon, LoadingIcon, FigmaIcon, WandIcon } from "./Icons.js";
15
+
16
+ // Alias for semantic clarity
17
+ const SyncingIcon = LoadingIcon;
18
+
19
+ /**
20
+ * Maps CSS properties to expected token categories
21
+ * This prevents false positives like "height: 49px" matching "--top-bar-height"
22
+ */
23
+ const PROPERTY_CATEGORY_MAP: Record<string, string[]> = {
24
+ // Color properties
25
+ color: ["color"],
26
+ backgroundColor: ["color"],
27
+ borderColor: ["color", "border"],
28
+ borderTopColor: ["color", "border"],
29
+ borderRightColor: ["color", "border"],
30
+ borderBottomColor: ["color", "border"],
31
+ borderLeftColor: ["color", "border"],
32
+ outlineColor: ["color"],
33
+ fill: ["color"],
34
+ stroke: ["color"],
35
+ caretColor: ["color"],
36
+ textDecorationColor: ["color"],
37
+ boxShadow: ["shadow", "color"],
38
+
39
+ // Spacing properties
40
+ margin: ["spacing"],
41
+ marginTop: ["spacing"],
42
+ marginRight: ["spacing"],
43
+ marginBottom: ["spacing"],
44
+ marginLeft: ["spacing"],
45
+ padding: ["spacing"],
46
+ paddingTop: ["spacing"],
47
+ paddingRight: ["spacing"],
48
+ paddingBottom: ["spacing"],
49
+ paddingLeft: ["spacing"],
50
+ gap: ["spacing"],
51
+ rowGap: ["spacing"],
52
+ columnGap: ["spacing"],
53
+
54
+ // Sizing properties (NOT spacing - heights shouldn't match spacing tokens)
55
+ width: ["sizing"],
56
+ height: ["sizing"],
57
+ minWidth: ["sizing"],
58
+ minHeight: ["sizing"],
59
+ maxWidth: ["sizing"],
60
+ maxHeight: ["sizing"],
61
+
62
+ // Border radius
63
+ borderRadius: ["radius"],
64
+ borderTopLeftRadius: ["radius"],
65
+ borderTopRightRadius: ["radius"],
66
+ borderBottomLeftRadius: ["radius"],
67
+ borderBottomRightRadius: ["radius"],
68
+
69
+ // Typography
70
+ fontSize: ["typography"],
71
+ fontWeight: ["typography"],
72
+ lineHeight: ["typography"],
73
+ letterSpacing: ["typography"],
74
+ fontFamily: ["typography"],
75
+
76
+ // Border
77
+ borderWidth: ["border"],
78
+ borderTopWidth: ["border"],
79
+ borderRightWidth: ["border"],
80
+ borderBottomWidth: ["border"],
81
+ borderLeftWidth: ["border"],
82
+
83
+ // Z-index
84
+ zIndex: ["z-index"],
85
+
86
+ // Animation
87
+ transitionDuration: ["animation"],
88
+ animationDuration: ["animation"],
89
+ transitionDelay: ["animation"],
90
+ animationDelay: ["animation"],
91
+ };
92
+
93
+ /**
94
+ * Get expected token categories for a CSS property
95
+ */
96
+ function getExpectedCategories(property: string): string[] | null {
97
+ return PROPERTY_CATEGORY_MAP[property] || null;
98
+ }
99
+
100
+ interface TokenStylePanelProps {
101
+ figmaUrl: string;
102
+ figmaStyles: Record<string, string> | null;
103
+ renderedStyles: Record<string, string> | null;
104
+ figmaLoading: boolean;
105
+ figmaError?: string;
106
+ onFetchFigma: () => void;
107
+ onRefreshRendered: () => void;
108
+ }
109
+
110
+ interface TokenData {
111
+ tokens: DesignToken[];
112
+ meta?: {
113
+ totalTokens: number;
114
+ parseTimeMs: number;
115
+ };
116
+ }
117
+
118
+ // Module-level cache for tokens to avoid refetching on tab switches
119
+ let cachedTokenData: TokenData | null = null;
120
+ let cachedTokenError: string | null = null;
121
+ let tokenFetchPromise: Promise<void> | null = null;
122
+
123
+ export function TokenStylePanel({
124
+ figmaUrl,
125
+ figmaStyles,
126
+ renderedStyles,
127
+ figmaLoading,
128
+ figmaError,
129
+ onFetchFigma,
130
+ onRefreshRendered,
131
+ }: TokenStylePanelProps) {
132
+ const [tokenData, setTokenData] = useState<TokenData | null>(null);
133
+ const [tokenError, setTokenError] = useState<string | null>(null);
134
+ const [tokenLoading, setTokenLoading] = useState(false);
135
+ const [copiedFix, setCopiedFix] = useState<string | null>(null);
136
+
137
+ // Fetch tokens on mount (with module-level caching)
138
+ useEffect(() => {
139
+ // Use cached data if available
140
+ if (cachedTokenData) {
141
+ setTokenData(cachedTokenData);
142
+ setTokenLoading(false);
143
+ return;
144
+ }
145
+ if (cachedTokenError) {
146
+ setTokenError(cachedTokenError);
147
+ setTokenLoading(false);
148
+ return;
149
+ }
150
+
151
+ // If a fetch is already in progress, wait for it
152
+ if (tokenFetchPromise) {
153
+ setTokenLoading(true);
154
+ tokenFetchPromise.then(() => {
155
+ setTokenData(cachedTokenData);
156
+ setTokenError(cachedTokenError);
157
+ setTokenLoading(false);
158
+ });
159
+ return;
160
+ }
161
+
162
+ const fetchTokens = async () => {
163
+ setTokenLoading(true);
164
+ setTokenError(null);
165
+
166
+ try {
167
+ const response = await fetch("/segments/tokens");
168
+
169
+ if (!response.ok) {
170
+ const data = await response.json();
171
+ if (data.error) {
172
+ cachedTokenError = data.suggestion || data.error;
173
+ setTokenError(cachedTokenError);
174
+ }
175
+ return;
176
+ }
177
+
178
+ const data = await response.json();
179
+ cachedTokenData = data;
180
+ setTokenData(data);
181
+ } catch (err) {
182
+ cachedTokenError = "Failed to fetch tokens";
183
+ setTokenError(cachedTokenError);
184
+ } finally {
185
+ setTokenLoading(false);
186
+ tokenFetchPromise = null;
187
+ }
188
+ };
189
+
190
+ tokenFetchPromise = fetchTokens();
191
+ }, []);
192
+
193
+ /**
194
+ * Find a token by value, filtered by property category to avoid false positives.
195
+ * Returns null if no appropriate token is found.
196
+ */
197
+ const tokenByValue = useCallback(
198
+ (value: string, property?: string): { token: DesignToken; confidence: "exact" | "value-only" } | null => {
199
+ if (!tokenData?.tokens) return null;
200
+
201
+ const normalized = normalizeValue(value);
202
+ const expectedCategories = property ? getExpectedCategories(property) : null;
203
+
204
+ // First pass: look for exact category match
205
+ for (const token of tokenData.tokens) {
206
+ const tokenNormalized = normalizeValue(token.resolvedValue);
207
+ if (tokenNormalized === normalized) {
208
+ // Check if this token's category matches what we expect for this property
209
+ if (expectedCategories && expectedCategories.includes(token.category)) {
210
+ return { token, confidence: "exact" };
211
+ }
212
+ }
213
+ }
214
+
215
+ // Second pass: if we have expectedCategories but found no match, don't return anything
216
+ // This prevents "height: 49px" from matching "--top-bar-height" (a sizing token when we want sizing)
217
+ if (expectedCategories) {
218
+ return null;
219
+ }
220
+
221
+ // Fallback: if we don't know the property type, return any matching token
222
+ // but mark it as "value-only" confidence
223
+ for (const token of tokenData.tokens) {
224
+ const tokenNormalized = normalizeValue(token.resolvedValue);
225
+ if (tokenNormalized === normalized) {
226
+ return { token, confidence: "value-only" };
227
+ }
228
+ }
229
+
230
+ return null;
231
+ },
232
+ [tokenData]
233
+ );
234
+
235
+ // Copy fix to clipboard
236
+ const copyFix = useCallback((property: string, tokenName: string) => {
237
+ const cssProperty = property.replace(/([A-Z])/g, "-$1").toLowerCase();
238
+ const code = `${cssProperty}: var(${tokenName});`;
239
+ navigator.clipboard.writeText(code);
240
+ setCopiedFix(property);
241
+ setTimeout(() => setCopiedFix(null), 2000);
242
+ }, []);
243
+
244
+ // Show loading state
245
+ if (figmaLoading) {
246
+ return (
247
+ <div className="flex items-center gap-2 text-tertiary p-4">
248
+ <SyncingIcon className="w-4 h-4 animate-spin" />
249
+ <span className="text-xs">Loading Figma styles...</span>
250
+ </div>
251
+ );
252
+ }
253
+
254
+ // Show error state
255
+ if (figmaError) {
256
+ return (
257
+ <div className="flex items-center gap-2 text-tertiary p-4">
258
+ <XIcon className="w-4 h-4 text-red-500" />
259
+ <span className="text-xs">{figmaError}</span>
260
+ <button
261
+ onClick={onFetchFigma}
262
+ className="text-xs text-[--color-accent] hover:underline ml-2"
263
+ >
264
+ Retry
265
+ </button>
266
+ </div>
267
+ );
268
+ }
269
+
270
+ // Show idle state
271
+ if (!figmaStyles) {
272
+ return (
273
+ <div className="flex items-center gap-2 text-tertiary p-4">
274
+ <FigmaIcon className="w-4 h-4" />
275
+ <span className="text-xs">Click to load style comparison</span>
276
+ <button
277
+ onClick={onFetchFigma}
278
+ className="text-xs text-[--color-accent] hover:underline ml-2"
279
+ >
280
+ Load
281
+ </button>
282
+ </div>
283
+ );
284
+ }
285
+
286
+ // Build comparison data
287
+ const figma = figmaStyles;
288
+ const rendered = renderedStyles || {};
289
+ const allProps = [...new Set([...Object.keys(figma), ...Object.keys(rendered)])];
290
+
291
+ const properties = allProps.map((prop) => {
292
+ const figmaValue = figma[prop] || "(not set)";
293
+ const renderedValue = rendered[prop] || "(not set)";
294
+ const match = compareValue(prop, figma[prop] || "", rendered[prop] || "");
295
+
296
+ // Find matching tokens (with category-aware filtering)
297
+ const figmaMatch = figma[prop] ? tokenByValue(figma[prop], prop) : null;
298
+ const renderedMatch = rendered[prop] ? tokenByValue(rendered[prop], prop) : null;
299
+
300
+ const figmaToken = figmaMatch?.token || null;
301
+ const renderedToken = renderedMatch?.token || null;
302
+ const figmaConfidence = figmaMatch?.confidence;
303
+ const renderedConfidence = renderedMatch?.confidence;
304
+
305
+ // Determine if hardcoded (Figma uses a token but rendered doesn't)
306
+ const isHardcoded = !!figmaToken && !renderedToken && figma[prop] !== rendered[prop];
307
+
308
+ return {
309
+ property: prop,
310
+ figma: figmaValue,
311
+ rendered: renderedValue,
312
+ match,
313
+ figmaToken,
314
+ renderedToken,
315
+ figmaConfidence,
316
+ renderedConfidence,
317
+ isHardcoded,
318
+ };
319
+ });
320
+
321
+ const differences = properties.filter((p) => !p.match).length;
322
+ const hardcodedCount = properties.filter((p) => p.isHardcoded).length;
323
+ const fixableCount = properties.filter((p) => p.isHardcoded && p.figmaToken).length;
324
+ const tokenUsageCount = properties.filter((p) => p.renderedToken).length;
325
+
326
+ // Calculate compliance
327
+ const compliancePercent =
328
+ properties.length > 0
329
+ ? Math.round(((tokenUsageCount + properties.filter((p) => p.match && !p.figmaToken).length) / properties.length) * 100)
330
+ : 100;
331
+
332
+ return (
333
+ <div className="overflow-x-auto p-4">
334
+ {/* Summary Header */}
335
+ <div className="flex items-center justify-between mb-3">
336
+ <div className="flex items-center gap-4">
337
+ <span className="text-xs font-medium text-primary">Style Comparison</span>
338
+
339
+ {/* Token info badge */}
340
+ {tokenData && (
341
+ <span className="text-xs text-tertiary">
342
+ {tokenData.meta?.totalTokens || tokenData.tokens.length} tokens loaded
343
+ </span>
344
+ )}
345
+ {tokenLoading && (
346
+ <span className="text-xs text-tertiary flex items-center gap-1">
347
+ <SyncingIcon className="w-3 h-3 animate-spin" />
348
+ Loading tokens...
349
+ </span>
350
+ )}
351
+ {tokenError && !tokenLoading && (
352
+ <span className="text-xs text-amber-600" title={tokenError}>
353
+ Tokens not configured
354
+ </span>
355
+ )}
356
+ </div>
357
+
358
+ <div className="flex items-center gap-3">
359
+ {/* Compliance badge */}
360
+ {tokenData && (
361
+ <span
362
+ className={clsx(
363
+ "text-xs font-medium px-2 py-0.5 rounded",
364
+ compliancePercent >= 80
365
+ ? "bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300"
366
+ : compliancePercent >= 50
367
+ ? "bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300"
368
+ : "bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300"
369
+ )}
370
+ >
371
+ {compliancePercent}% token compliance
372
+ </span>
373
+ )}
374
+
375
+ {/* Match summary */}
376
+ <span
377
+ className={clsx(
378
+ "text-xs font-medium",
379
+ differences === 0 ? "text-green-600" : "text-amber-600"
380
+ )}
381
+ >
382
+ {differences === 0 ? "All styles match" : `${differences} difference${differences !== 1 ? "s" : ""}`}
383
+ </span>
384
+
385
+ {/* Hardcoded warning */}
386
+ {hardcodedCount > 0 && (
387
+ <span className="text-xs font-medium text-red-600">
388
+ {hardcodedCount} hardcoded
389
+ </span>
390
+ )}
391
+ </div>
392
+ </div>
393
+
394
+ {/* Comparison Table */}
395
+ <table className="w-full text-xs">
396
+ <thead>
397
+ <tr className="border-b border-[--border-subtle]">
398
+ <th className="px-3 py-2 text-left text-tertiary font-medium">Property</th>
399
+ <th className="px-3 py-2 text-left text-tertiary font-medium">Figma</th>
400
+ {tokenData && (
401
+ <th className="px-3 py-2 text-left text-tertiary font-medium">Token</th>
402
+ )}
403
+ <th className="px-3 py-2 text-left text-tertiary font-medium">Rendered</th>
404
+ <th className="px-3 py-2 text-center text-tertiary font-medium w-12">Match</th>
405
+ {tokenData && fixableCount > 0 && (
406
+ <th className="px-3 py-2 text-center text-tertiary font-medium w-16">Fix</th>
407
+ )}
408
+ </tr>
409
+ </thead>
410
+ <tbody>
411
+ {properties.map((prop) => (
412
+ <tr
413
+ key={prop.property}
414
+ className={clsx(
415
+ "border-b border-[--border-subtle] last:border-b-0",
416
+ !prop.match && "bg-amber-50 dark:bg-amber-950/20",
417
+ prop.isHardcoded && "bg-red-50 dark:bg-red-950/20"
418
+ )}
419
+ >
420
+ <td className="px-3 py-2 font-mono text-primary">{prop.property}</td>
421
+ <td className="px-3 py-2">
422
+ <div className="flex items-center gap-2">
423
+ {/* Color swatch */}
424
+ {isColorProperty(prop.property) && prop.figma !== "(not set)" && (
425
+ <ColorSwatch color={prop.figma} />
426
+ )}
427
+ <span className="font-mono text-secondary truncate max-w-[120px]" title={prop.figma}>
428
+ {prop.figma}
429
+ </span>
430
+ </div>
431
+ </td>
432
+ {tokenData && (
433
+ <td className="px-3 py-2">
434
+ {prop.figmaToken ? (
435
+ <TokenBadge token={prop.figmaToken} confidence={prop.figmaConfidence} />
436
+ ) : prop.renderedToken ? (
437
+ <TokenBadge token={prop.renderedToken} confidence={prop.renderedConfidence} />
438
+ ) : (
439
+ <span className="text-tertiary">-</span>
440
+ )}
441
+ </td>
442
+ )}
443
+ <td className="px-3 py-2">
444
+ <div className="flex items-center gap-2">
445
+ {/* Color swatch */}
446
+ {isColorProperty(prop.property) && prop.rendered !== "(not set)" && (
447
+ <ColorSwatch color={prop.rendered} />
448
+ )}
449
+ <span className="font-mono text-secondary truncate max-w-[120px]" title={prop.rendered}>
450
+ {prop.rendered}
451
+ </span>
452
+ {/* Hardcoded badge */}
453
+ {prop.isHardcoded && (
454
+ <span className="text-[10px] px-1 py-0.5 bg-red-100 text-red-600 dark:bg-red-900 dark:text-red-300 rounded">
455
+ HC
456
+ </span>
457
+ )}
458
+ </div>
459
+ </td>
460
+ <td className="px-3 py-2 text-center">
461
+ {prop.match ? (
462
+ <CheckIcon className="w-4 h-4 text-green-600 mx-auto" />
463
+ ) : (
464
+ <XIcon className="w-4 h-4 text-amber-600 mx-auto" />
465
+ )}
466
+ </td>
467
+ {tokenData && fixableCount > 0 && (
468
+ <td className="px-3 py-2 text-center">
469
+ {prop.isHardcoded && prop.figmaToken && (
470
+ <button
471
+ onClick={() => copyFix(prop.property, prop.figmaToken!.name)}
472
+ className={clsx(
473
+ "p-1 rounded transition-colors",
474
+ copiedFix === prop.property
475
+ ? "bg-green-100 text-green-600"
476
+ : "hover:bg-[--bg-hover] text-tertiary hover:text-primary"
477
+ )}
478
+ title={`Copy: ${prop.property.replace(/([A-Z])/g, "-$1").toLowerCase()}: var(${prop.figmaToken.name});`}
479
+ >
480
+ {copiedFix === prop.property ? (
481
+ <CheckIcon className="w-3 h-3" />
482
+ ) : (
483
+ <WandIcon className="w-3 h-3" />
484
+ )}
485
+ </button>
486
+ )}
487
+ </td>
488
+ )}
489
+ </tr>
490
+ ))}
491
+ </tbody>
492
+ </table>
493
+
494
+ {/* Hardcoded fixes summary */}
495
+ {hardcodedCount > 0 && tokenData && (
496
+ <div className="mt-4 p-3 bg-amber-50 dark:bg-amber-950/30 rounded-lg border border-amber-200 dark:border-amber-800">
497
+ <div className="flex items-start gap-2">
498
+ <WandIcon className="w-4 h-4 text-amber-600 mt-0.5" />
499
+ <div>
500
+ <p className="text-xs font-medium text-amber-800 dark:text-amber-200">
501
+ {hardcodedCount} hardcoded value{hardcodedCount !== 1 ? "s" : ""} detected
502
+ </p>
503
+ <p className="text-xs text-amber-700 dark:text-amber-300 mt-1">
504
+ These values should use design tokens for consistency and theming support.
505
+ Click the fix button to copy the token-based CSS.
506
+ </p>
507
+ </div>
508
+ </div>
509
+ </div>
510
+ )}
511
+ </div>
512
+ );
513
+ }
514
+
515
+ // ----- Helper Components -----
516
+
517
+ /**
518
+ * Enhanced tooltip showing full token details on hover
519
+ */
520
+ function TokenBadge({
521
+ token,
522
+ confidence,
523
+ }: {
524
+ token: DesignToken;
525
+ confidence?: "exact" | "value-only";
526
+ }) {
527
+ const [showTooltip, setShowTooltip] = useState(false);
528
+
529
+ return (
530
+ <div className="relative inline-block">
531
+ <span
532
+ className={clsx(
533
+ "font-mono text-xs cursor-help px-1.5 py-0.5 rounded",
534
+ confidence === "value-only"
535
+ ? "text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-950/30"
536
+ : "text-purple-600 dark:text-purple-400 bg-purple-50 dark:bg-purple-950/30"
537
+ )}
538
+ onMouseEnter={() => setShowTooltip(true)}
539
+ onMouseLeave={() => setShowTooltip(false)}
540
+ >
541
+ {token.name}
542
+ </span>
543
+
544
+ {/* Enhanced tooltip */}
545
+ {showTooltip && (
546
+ <div
547
+ className="absolute z-50 left-0 top-full mt-1 p-3 bg-[--bg-primary] border border-[--border] rounded-lg shadow-lg min-w-[280px]"
548
+ style={{ maxWidth: "320px" }}
549
+ >
550
+ <div className="space-y-2 text-xs">
551
+ {/* Token name */}
552
+ <div>
553
+ <span className="text-tertiary">Token:</span>
554
+ <span className="ml-2 font-mono text-primary font-medium">{token.name}</span>
555
+ </div>
556
+
557
+ {/* Resolved value */}
558
+ <div className="flex items-center">
559
+ <span className="text-tertiary">Value:</span>
560
+ <span className="ml-2 font-mono text-secondary">{token.resolvedValue}</span>
561
+ {token.category === "color" && (
562
+ <ColorSwatch color={token.resolvedValue} />
563
+ )}
564
+ </div>
565
+
566
+ {/* Raw value (if different from resolved) */}
567
+ {token.rawValue !== token.resolvedValue && (
568
+ <div>
569
+ <span className="text-tertiary">Raw:</span>
570
+ <span className="ml-2 font-mono text-secondary">{token.rawValue}</span>
571
+ </div>
572
+ )}
573
+
574
+ {/* Category & Level */}
575
+ <div className="flex gap-4">
576
+ <div>
577
+ <span className="text-tertiary">Category:</span>
578
+ <span className="ml-2 text-secondary capitalize">{token.category}</span>
579
+ </div>
580
+ <div>
581
+ <span className="text-tertiary">Level:</span>
582
+ <span className="ml-2 text-secondary">
583
+ {token.level === 1 ? "Base" : token.level === 2 ? "Semantic" : "Component"}
584
+ </span>
585
+ </div>
586
+ </div>
587
+
588
+ {/* Theme */}
589
+ <div>
590
+ <span className="text-tertiary">Theme:</span>
591
+ <span className="ml-2 text-secondary">{token.theme}</span>
592
+ </div>
593
+
594
+ {/* Reference chain (if has references) */}
595
+ {token.referenceChain.length > 1 && (
596
+ <div>
597
+ <span className="text-tertiary">References:</span>
598
+ <div className="mt-1 font-mono text-secondary text-[10px] space-y-0.5">
599
+ {token.referenceChain.map((ref, i) => (
600
+ <div key={ref} className="flex items-center">
601
+ {i > 0 && <span className="mr-1 text-tertiary">→</span>}
602
+ <span>{ref}</span>
603
+ </div>
604
+ ))}
605
+ </div>
606
+ </div>
607
+ )}
608
+
609
+ {/* Source file */}
610
+ <div className="pt-1 border-t border-[--border-subtle]">
611
+ <span className="text-tertiary">Source:</span>
612
+ <span className="ml-2 font-mono text-[10px] text-tertiary truncate">
613
+ {token.sourceFile.split("/").slice(-2).join("/")}
614
+ {token.lineNumber && `:${token.lineNumber}`}
615
+ </span>
616
+ </div>
617
+
618
+ {/* Confidence indicator */}
619
+ {confidence === "value-only" && (
620
+ <div className="pt-1 text-amber-600 dark:text-amber-400">
621
+ ⚠️ Value match only - verify this is the correct token
622
+ </div>
623
+ )}
624
+ </div>
625
+ </div>
626
+ )}
627
+ </div>
628
+ );
629
+ }
630
+
631
+ function ColorSwatch({ color }: { color: string }) {
632
+ return (
633
+ <div
634
+ className="w-4 h-4 rounded border border-[--border] flex-shrink-0 ml-1"
635
+ style={{ backgroundColor: color }}
636
+ title={color}
637
+ />
638
+ );
639
+ }
640
+
641
+ // ----- Helper Functions -----
642
+
643
+ function isColorProperty(prop: string): boolean {
644
+ const colorProps = ["backgroundColor", "borderColor", "color", "fill", "stroke"];
645
+ return colorProps.includes(prop) || prop.toLowerCase().includes("color");
646
+ }
647
+
648
+ /**
649
+ * Normalize a CSS value for comparison.
650
+ * Handles colors (hex, rgb, rgba) and general values.
651
+ */
652
+ function normalizeValue(value: string): string {
653
+ if (!value) return "";
654
+
655
+ const trimmed = value.toLowerCase().trim();
656
+
657
+ // Already normalized hex
658
+ if (trimmed.match(/^#[0-9a-f]{6}$/i)) {
659
+ return trimmed;
660
+ }
661
+
662
+ // Short hex -> long hex
663
+ const shortHex = trimmed.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
664
+ if (shortHex) {
665
+ return `#${shortHex[1]}${shortHex[1]}${shortHex[2]}${shortHex[2]}${shortHex[3]}${shortHex[3]}`;
666
+ }
667
+
668
+ // Parse hex
669
+ const hexMatch = trimmed.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
670
+ if (hexMatch) {
671
+ return trimmed;
672
+ }
673
+
674
+ // Parse rgb/rgba
675
+ const rgbMatch = value.match(
676
+ /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+)?\s*\)/
677
+ );
678
+ if (rgbMatch) {
679
+ const r = parseInt(rgbMatch[1], 10).toString(16).padStart(2, "0");
680
+ const g = parseInt(rgbMatch[2], 10).toString(16).padStart(2, "0");
681
+ const b = parseInt(rgbMatch[3], 10).toString(16).padStart(2, "0");
682
+ return `#${r}${g}${b}`;
683
+ }
684
+
685
+ return trimmed;
686
+ }
687
+
688
+ function compareValue(prop: string, figma: string, rendered: string): boolean {
689
+ if (figma === rendered) return true;
690
+ if (!figma || !rendered) return false;
691
+
692
+ // Color comparison
693
+ if (isColorProperty(prop)) {
694
+ return normalizeValue(figma) === normalizeValue(rendered);
695
+ }
696
+
697
+ // Numeric comparison with near-zero tolerance for floating point rounding only
698
+ // Using < 0.1 ensures 1px vs 2px shows as mismatch, while 1.0001px vs 1px matches
699
+ const figmaNum = parseFloat(figma);
700
+ const renderedNum = parseFloat(rendered);
701
+ if (!isNaN(figmaNum) && !isNaN(renderedNum)) {
702
+ return Math.abs(figmaNum - renderedNum) < 0.1;
703
+ }
704
+
705
+ return false;
706
+ }
707
+
708
+ export default TokenStylePanel;