@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,498 @@
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 { Result } from 'axe-core';
12
+ import type {
13
+ A11yServiceConfig,
14
+ SerializedViolation,
15
+ ComponentScanState,
16
+ ScanStatus,
17
+ } from '../types/a11y.js';
18
+ import {
19
+ updateComponentA11yResult,
20
+ getComponentA11yResult,
21
+ invalidateComponents,
22
+ isComponentStale,
23
+ getA11ySummary,
24
+ } from './useA11yCache.js';
25
+
26
+ // Default configuration
27
+ const DEFAULT_CONFIG: A11yServiceConfig = {
28
+ hmrDebounceMs: 500,
29
+ navigationDebounceMs: 200,
30
+ scanCooldownMs: 1000,
31
+ maxConcurrentScans: 2,
32
+ };
33
+
34
+ // Global state for the service (singleton pattern)
35
+ interface A11yServiceState {
36
+ activeScanCount: number;
37
+ scanQueue: Array<{
38
+ componentName: string;
39
+ targetSelector: string;
40
+ variant?: string;
41
+ resolve: (result: ScanResult | null) => void;
42
+ reject: (error: Error) => void;
43
+ }>;
44
+ debounceTimers: Map<string, NodeJS.Timeout>;
45
+ lastScanTimes: Map<string, number>;
46
+ componentStates: Map<string, ComponentScanState>;
47
+ }
48
+
49
+ const serviceState: A11yServiceState = {
50
+ activeScanCount: 0,
51
+ scanQueue: [],
52
+ debounceTimers: new Map(),
53
+ lastScanTimes: new Map(),
54
+ componentStates: new Map(),
55
+ };
56
+
57
+ // Cache the axe-core module
58
+ let axeModule: typeof import('axe-core') | null = null;
59
+
60
+ export interface ScanResult {
61
+ violations: SerializedViolation[];
62
+ passes: number;
63
+ incomplete: number;
64
+ counts: {
65
+ critical: number;
66
+ serious: number;
67
+ moderate: number;
68
+ minor: number;
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Convert axe-core Result to SerializedViolation
74
+ */
75
+ function serializeViolation(result: Result): SerializedViolation {
76
+ return {
77
+ id: result.id,
78
+ impact: result.impact || null,
79
+ description: result.description,
80
+ help: result.help,
81
+ helpUrl: result.helpUrl,
82
+ tags: result.tags,
83
+ nodes: result.nodes.map(node => ({
84
+ html: node.html,
85
+ target: node.target as string[],
86
+ failureSummary: node.failureSummary,
87
+ any: node.any?.map(check => ({
88
+ id: check.id,
89
+ data: check.data,
90
+ relatedNodes: check.relatedNodes?.map(rn => ({
91
+ html: rn.html,
92
+ target: rn.target as string[],
93
+ })),
94
+ impact: check.impact,
95
+ message: check.message,
96
+ })),
97
+ all: node.all?.map(check => ({
98
+ id: check.id,
99
+ data: check.data,
100
+ relatedNodes: check.relatedNodes?.map(rn => ({
101
+ html: rn.html,
102
+ target: rn.target as string[],
103
+ })),
104
+ impact: check.impact,
105
+ message: check.message,
106
+ })),
107
+ none: node.none?.map(check => ({
108
+ id: check.id,
109
+ data: check.data,
110
+ relatedNodes: check.relatedNodes?.map(rn => ({
111
+ html: rn.html,
112
+ target: rn.target as string[],
113
+ })),
114
+ impact: check.impact,
115
+ message: check.message,
116
+ })),
117
+ })),
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Run axe-core scan on a target element
123
+ */
124
+ async function runAxeScan(targetSelector: string): Promise<ScanResult | null> {
125
+ // Load axe-core if not cached
126
+ if (!axeModule) {
127
+ axeModule = await import('axe-core');
128
+ }
129
+ // Handle both ESM default export and CommonJS module
130
+ const axe = (axeModule as { default?: typeof import('axe-core') }).default || axeModule;
131
+
132
+ const target = document.querySelector(targetSelector);
133
+ if (!target) {
134
+ console.warn(`[A11y] Target element not found: ${targetSelector}`);
135
+ return null;
136
+ }
137
+
138
+ // Configure axe-core
139
+ axe.configure({
140
+ rules: [
141
+ { id: 'color-contrast', enabled: true },
142
+ { id: 'image-alt', enabled: true },
143
+ { id: 'button-name', enabled: true },
144
+ { id: 'link-name', enabled: true },
145
+ { id: 'label', enabled: true },
146
+ { id: 'aria-valid-attr', enabled: true },
147
+ { id: 'aria-valid-attr-value', enabled: true },
148
+ ],
149
+ });
150
+
151
+ // Run the scan
152
+ const results = await axe.run(target as HTMLElement, {
153
+ resultTypes: ['violations', 'passes', 'incomplete', 'inapplicable'],
154
+ });
155
+
156
+ // Count violations by severity
157
+ const counts = {
158
+ critical: 0,
159
+ serious: 0,
160
+ moderate: 0,
161
+ minor: 0,
162
+ };
163
+
164
+ for (const violation of results.violations) {
165
+ switch (violation.impact) {
166
+ case 'critical':
167
+ counts.critical++;
168
+ break;
169
+ case 'serious':
170
+ counts.serious++;
171
+ break;
172
+ case 'moderate':
173
+ counts.moderate++;
174
+ break;
175
+ case 'minor':
176
+ default:
177
+ counts.minor++;
178
+ break;
179
+ }
180
+ }
181
+
182
+ return {
183
+ violations: results.violations.map(serializeViolation),
184
+ passes: results.passes.length,
185
+ incomplete: results.incomplete.length,
186
+ counts,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Process the scan queue
192
+ */
193
+ async function processQueue(config: A11yServiceConfig): Promise<void> {
194
+ while (
195
+ serviceState.scanQueue.length > 0 &&
196
+ serviceState.activeScanCount < config.maxConcurrentScans
197
+ ) {
198
+ const item = serviceState.scanQueue.shift();
199
+ if (!item) break;
200
+
201
+ serviceState.activeScanCount++;
202
+
203
+ // Update component state
204
+ serviceState.componentStates.set(item.componentName, {
205
+ status: 'scanning',
206
+ lastScanAt: Date.now(),
207
+ });
208
+
209
+ // Dispatch scanning event
210
+ window.dispatchEvent(new CustomEvent('a11y-scan-started', {
211
+ detail: { componentName: item.componentName },
212
+ }));
213
+
214
+ try {
215
+ const result = await runAxeScan(item.targetSelector);
216
+
217
+ if (result) {
218
+ // Update cache with full results
219
+ updateComponentA11yResult(item.componentName, {
220
+ violations: result.violations,
221
+ passes: result.passes,
222
+ incomplete: result.incomplete,
223
+ counts: result.counts,
224
+ variant: item.variant,
225
+ });
226
+
227
+ serviceState.componentStates.set(item.componentName, {
228
+ status: 'completed',
229
+ lastScanAt: Date.now(),
230
+ });
231
+ } else {
232
+ serviceState.componentStates.set(item.componentName, {
233
+ status: 'error',
234
+ error: 'Target element not found',
235
+ });
236
+ }
237
+
238
+ serviceState.lastScanTimes.set(item.componentName, Date.now());
239
+ item.resolve(result);
240
+ } catch (error) {
241
+ serviceState.componentStates.set(item.componentName, {
242
+ status: 'error',
243
+ error: error instanceof Error ? error.message : 'Scan failed',
244
+ });
245
+ item.reject(error instanceof Error ? error : new Error('Scan failed'));
246
+ } finally {
247
+ serviceState.activeScanCount--;
248
+
249
+ // Dispatch scan complete event
250
+ window.dispatchEvent(new CustomEvent('a11y-scan-completed', {
251
+ detail: { componentName: item.componentName },
252
+ }));
253
+
254
+ // Process next item in queue
255
+ processQueue(config);
256
+ }
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Options for the useA11yService hook
262
+ */
263
+ export interface UseA11yServiceOptions {
264
+ /** Override default configuration */
265
+ config?: Partial<A11yServiceConfig>;
266
+ /** Component name being scanned */
267
+ componentName?: string;
268
+ /** Target selector for scanning */
269
+ targetSelector?: string;
270
+ /** Current variant name */
271
+ variant?: string;
272
+ /** Auto-scan when component changes */
273
+ autoScan?: boolean;
274
+ }
275
+
276
+ /**
277
+ * A11y Service Hook
278
+ *
279
+ * Provides methods for triggering and managing accessibility scans.
280
+ */
281
+ export function useA11yService(options: UseA11yServiceOptions = {}) {
282
+ const {
283
+ config: configOverrides = {},
284
+ componentName,
285
+ targetSelector = '[data-preview-container="true"]',
286
+ variant,
287
+ autoScan = true,
288
+ } = options;
289
+
290
+ const config: A11yServiceConfig = { ...DEFAULT_CONFIG, ...configOverrides };
291
+ const configRef = useRef(config);
292
+ configRef.current = config;
293
+
294
+ const [scanStatus, setScanStatus] = useState<ScanStatus>('idle');
295
+ const [lastResult, setLastResult] = useState<ScanResult | null>(null);
296
+
297
+ /**
298
+ * Queue a scan for a component
299
+ */
300
+ const scanComponent = useCallback(
301
+ (
302
+ targetComponentName: string = componentName || '',
303
+ targetSel: string = targetSelector,
304
+ targetVariant?: string
305
+ ): Promise<ScanResult | null> => {
306
+ if (!targetComponentName) {
307
+ return Promise.resolve(null);
308
+ }
309
+
310
+ // Check cooldown
311
+ const lastScan = serviceState.lastScanTimes.get(targetComponentName);
312
+ if (lastScan && Date.now() - lastScan < configRef.current.scanCooldownMs) {
313
+ // Return cached result if available
314
+ const cached = getComponentA11yResult(targetComponentName);
315
+ if (cached) {
316
+ return Promise.resolve({
317
+ violations: cached.violations,
318
+ passes: cached.passes,
319
+ incomplete: cached.incomplete,
320
+ counts: cached.counts,
321
+ });
322
+ }
323
+ }
324
+
325
+ return new Promise((resolve, reject) => {
326
+ serviceState.scanQueue.push({
327
+ componentName: targetComponentName,
328
+ targetSelector: targetSel,
329
+ variant: targetVariant || variant,
330
+ resolve,
331
+ reject,
332
+ });
333
+
334
+ serviceState.componentStates.set(targetComponentName, { status: 'pending' });
335
+ setScanStatus('pending');
336
+
337
+ // Start processing
338
+ processQueue(configRef.current);
339
+ });
340
+ },
341
+ [componentName, targetSelector, variant]
342
+ );
343
+
344
+ /**
345
+ * Scan with debouncing (for HMR or rapid changes)
346
+ */
347
+ const scanDebounced = useCallback(
348
+ (
349
+ debounceMs: number = configRef.current.hmrDebounceMs,
350
+ targetComponentName: string = componentName || ''
351
+ ) => {
352
+ if (!targetComponentName) return;
353
+
354
+ // Clear existing timer
355
+ const existingTimer = serviceState.debounceTimers.get(targetComponentName);
356
+ if (existingTimer) {
357
+ clearTimeout(existingTimer);
358
+ }
359
+
360
+ // Set new timer
361
+ const timer = setTimeout(() => {
362
+ serviceState.debounceTimers.delete(targetComponentName);
363
+ scanComponent(targetComponentName);
364
+ }, debounceMs);
365
+
366
+ serviceState.debounceTimers.set(targetComponentName, timer);
367
+ },
368
+ [componentName, scanComponent]
369
+ );
370
+
371
+ /**
372
+ * Invalidate cache for components and optionally trigger re-scan
373
+ */
374
+ const invalidate = useCallback(
375
+ (componentNames: string[], rescan: boolean = true) => {
376
+ invalidateComponents(componentNames);
377
+
378
+ if (rescan) {
379
+ // Debounce each component's re-scan
380
+ for (const name of componentNames) {
381
+ scanDebounced(configRef.current.hmrDebounceMs, name);
382
+ }
383
+ }
384
+ },
385
+ [scanDebounced]
386
+ );
387
+
388
+ /**
389
+ * Get current scan state for a component
390
+ */
391
+ const getComponentState = useCallback(
392
+ (name: string = componentName || ''): ComponentScanState => {
393
+ return serviceState.componentStates.get(name) || { status: 'idle' };
394
+ },
395
+ [componentName]
396
+ );
397
+
398
+ /**
399
+ * Check if a component needs re-scanning
400
+ */
401
+ const needsRescan = useCallback(
402
+ (name: string = componentName || ''): boolean => {
403
+ if (!name) return false;
404
+ return isComponentStale(name, config.scanCooldownMs);
405
+ },
406
+ [componentName, config.scanCooldownMs]
407
+ );
408
+
409
+ // Listen for HMR invalidation events
410
+ useEffect(() => {
411
+ const handleInvalidate = (event: CustomEvent<{ components: string[] }>) => {
412
+ const { components } = event.detail;
413
+
414
+ // If our component is in the list, trigger a debounced re-scan
415
+ if (componentName && components.includes(componentName)) {
416
+ setScanStatus('pending');
417
+ scanDebounced(configRef.current.hmrDebounceMs, componentName);
418
+ }
419
+ };
420
+
421
+ const handleScanStarted = (event: CustomEvent<{ componentName: string }>) => {
422
+ if (event.detail.componentName === componentName) {
423
+ setScanStatus('scanning');
424
+ }
425
+ };
426
+
427
+ const handleScanCompleted = (event: CustomEvent<{ componentName: string }>) => {
428
+ if (event.detail.componentName === componentName) {
429
+ setScanStatus('completed');
430
+ // Update last result from cache
431
+ const cached = getComponentA11yResult(componentName || '');
432
+ if (cached) {
433
+ setLastResult({
434
+ violations: cached.violations,
435
+ passes: cached.passes,
436
+ incomplete: cached.incomplete,
437
+ counts: cached.counts,
438
+ });
439
+ }
440
+ }
441
+ };
442
+
443
+ window.addEventListener('a11y-cache-invalidated', handleInvalidate as EventListener);
444
+ window.addEventListener('a11y-scan-started', handleScanStarted as EventListener);
445
+ window.addEventListener('a11y-scan-completed', handleScanCompleted as EventListener);
446
+
447
+ return () => {
448
+ window.removeEventListener('a11y-cache-invalidated', handleInvalidate as EventListener);
449
+ window.removeEventListener('a11y-scan-started', handleScanStarted as EventListener);
450
+ window.removeEventListener('a11y-scan-completed', handleScanCompleted as EventListener);
451
+ };
452
+ }, [componentName, scanDebounced]);
453
+
454
+ // Auto-scan when component name changes and cache is stale
455
+ useEffect(() => {
456
+ if (!autoScan || !componentName) return;
457
+
458
+ if (needsRescan(componentName)) {
459
+ scanDebounced(configRef.current.navigationDebounceMs, componentName);
460
+ } else {
461
+ // Load from cache
462
+ const cached = getComponentA11yResult(componentName);
463
+ if (cached) {
464
+ setLastResult({
465
+ violations: cached.violations,
466
+ passes: cached.passes,
467
+ incomplete: cached.incomplete,
468
+ counts: cached.counts,
469
+ });
470
+ setScanStatus('completed');
471
+ }
472
+ }
473
+ }, [autoScan, componentName, needsRescan, scanDebounced]);
474
+
475
+ return {
476
+ // Methods
477
+ scanComponent,
478
+ scanDebounced,
479
+ invalidate,
480
+ getComponentState,
481
+ needsRescan,
482
+ getSummary: getA11ySummary,
483
+
484
+ // State
485
+ scanStatus,
486
+ isScanning: scanStatus === 'scanning' || scanStatus === 'pending',
487
+ lastResult,
488
+ };
489
+ }
490
+
491
+ /**
492
+ * Dispatch a11y invalidation event (for use from vite-plugin HMR)
493
+ */
494
+ export function dispatchA11yInvalidate(components: string[], file: string): void {
495
+ window.dispatchEvent(new CustomEvent('a11y-invalidate-hmr', {
496
+ detail: { components, file, timestamp: Date.now() },
497
+ }));
498
+ }
@@ -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
+ }