@trackunit/react-components 7.0.9 → 8.0.0

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.
@@ -0,0 +1,593 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.collapseNativeDetails = void 0;
37
+ const devkit_1 = require("@nx/devkit");
38
+ const path = __importStar(require("path"));
39
+ const ts = __importStar(require("typescript"));
40
+ const jsx_utils_1 = require("../utils/jsx-utils");
41
+ const MIGRATION_NAME = "collapse-native-details";
42
+ const PACKAGE_NAME = "@trackunit/react-components";
43
+ const COMPONENT_NAME = "Collapse";
44
+ const NEW_EVENT_TYPE = "SyntheticEvent<HTMLElement>";
45
+ const LAZY_PROP = "lazy";
46
+ /** Extensions tried when resolving a relative import to a file. */
47
+ const MODULE_EXTENSIONS = [".ts", ".tsx", ".jsx"];
48
+ const TEST_FILE_PATTERN = /\.(spec|test)\.[jt]sx?$/;
49
+ /** Attributes the old header had. Other components have them too, so they only count next to a header query. */
50
+ const OLD_HEADER_ATTRIBUTE_PATTERN = /aria-expanded|aria-controls/;
51
+ /** A variable assigned on a line, as in `const header = screen.getByRole(…)`: group 1 is its name. */
52
+ const HEADER_VARIABLE_PATTERN = /(?:const|let|var)\s+([A-Za-z_][\w]*)\s*=/;
53
+ /** Any button query by role, used to count the specs whose header queries can't be identified statically. */
54
+ const BUTTON_ROLE_QUERY_PATTERN = /ByRole\(\s*["'`]button["'`]/;
55
+ /** A button query with a string or regex `name`, which may span lines: group 1 is the name literal. */
56
+ const NAMED_BUTTON_QUERY_PATTERN = /ByRole\(\s*["'`]button["'`]\s*,\s*\{\s*name:\s*(\/(?:\\.|[^/\\\n])+\/[a-z]*|"[^"\n]*"|'[^'\n]*'|`[^`$\n]*`)/g;
57
+ /** A nameless button query scoped to a test id, e.g. `within(screen.getByTestId("x")).getByRole("button")`: group 1 is the id. */
58
+ const SCOPED_BUTTON_QUERY_PATTERN = /within\(\s*(?:screen\.)?(?:get|query|find)ByTestId\(\s*["'`]([^"'`]+)["'`]\s*\)\s*\)\.(?:get|query|find)(?:All)?ByRole\(\s*["'`]button["'`]\s*\)/g;
59
+ /** Elements that are interactive themselves, so nesting them in the `<summary>` header is `nested-interactive`. */
60
+ const INTERACTIVE_ELEMENTS = new Set([
61
+ "a",
62
+ "button",
63
+ "input",
64
+ "select",
65
+ "textarea",
66
+ "Button",
67
+ "IconButton",
68
+ "ToggleGroup",
69
+ "Link",
70
+ "ExternalLink",
71
+ "Checkbox",
72
+ "Toggle",
73
+ "RadioGroup",
74
+ "Select",
75
+ "TextField",
76
+ "MoreMenu",
77
+ ]);
78
+ const RELATIVE_IMPORT_PATTERN = /(?:from\s+|import\s*\(\s*|require\s*\(\s*)["'](\.{1,2}\/[^"']+)["']/g;
79
+ const location = (file, node) => `${file.filePath}:${file.sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1}`;
80
+ const addEdit = (file, edit) => {
81
+ // The same handler can be reached through several Collapses; record each edit once.
82
+ if (!file.edits.some(existing => existing.start === edit.start && existing.end === edit.end)) {
83
+ file.edits.push(edit);
84
+ }
85
+ };
86
+ const applyEdits = (content, edits) => [...edits]
87
+ .sort((a, b) => b.start - a.start)
88
+ .reduce((updated, { start, end, text }) => `${updated.slice(0, start)}${text}${updated.slice(end)}`, content);
89
+ const getReactImports = (sourceFile) => {
90
+ const named = new Map();
91
+ const namespaces = new Set();
92
+ for (const stmt of sourceFile.statements) {
93
+ if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier))
94
+ continue;
95
+ if (stmt.moduleSpecifier.text !== "react")
96
+ continue;
97
+ const clause = stmt.importClause;
98
+ if (clause === undefined)
99
+ continue;
100
+ if (clause.name !== undefined)
101
+ namespaces.add(clause.name.text);
102
+ const bindings = clause.namedBindings;
103
+ if (bindings === undefined)
104
+ continue;
105
+ if (ts.isNamespaceImport(bindings)) {
106
+ namespaces.add(bindings.name.text);
107
+ }
108
+ else {
109
+ for (const element of bindings.elements) {
110
+ named.set(element.name.text, element.propertyName?.text ?? element.name.text);
111
+ }
112
+ }
113
+ }
114
+ return { named, namespaces };
115
+ };
116
+ const bindsName = (name, identifier) => ts.isIdentifier(name)
117
+ ? name.text === identifier
118
+ : name.elements.some(element => !ts.isOmittedExpression(element) && bindsName(element.name, identifier));
119
+ /** The statements a scope node holds directly, or none when the node isn't a scope with statements. */
120
+ const statementsOf = (node) => ts.isBlock(node) ||
121
+ ts.isSourceFile(node) ||
122
+ ts.isModuleBlock(node) ||
123
+ ts.isCaseClause(node) ||
124
+ ts.isDefaultClause(node)
125
+ ? node.statements
126
+ : [];
127
+ /**
128
+ * Finds the declaration an identifier refers to, walking out through the scopes that enclose `from`, so two
129
+ * components in one file that each declare `handleToggle` resolve to their own.
130
+ *
131
+ * Returns `null` when the name is a parameter, a destructured binding or an import, or isn't declared in this file.
132
+ */
133
+ const resolveLocalDeclaration = (from, identifier) => {
134
+ // `from` is inside a source file, and the source file is the outermost scope.
135
+ for (let scope = from.parent;; scope = scope.parent) {
136
+ if (ts.isFunctionLike(scope) && scope.parameters.some(parameter => bindsName(parameter.name, identifier))) {
137
+ return null;
138
+ }
139
+ for (const statement of statementsOf(scope)) {
140
+ if (ts.isFunctionDeclaration(statement) && statement.name?.text === identifier)
141
+ return statement;
142
+ if (!ts.isVariableStatement(statement))
143
+ continue;
144
+ for (const declaration of statement.declarationList.declarations) {
145
+ if (!bindsName(declaration.name, identifier))
146
+ continue;
147
+ return ts.isIdentifier(declaration.name) ? declaration : null;
148
+ }
149
+ }
150
+ if (ts.isSourceFile(scope))
151
+ return null;
152
+ }
153
+ };
154
+ /** Unwraps parentheses and `useCallback(fn, deps)` to reach the function itself. */
155
+ const unwrapFunction = (expression) => {
156
+ if (ts.isParenthesizedExpression(expression))
157
+ return unwrapFunction(expression.expression);
158
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression))
159
+ return expression;
160
+ if (ts.isCallExpression(expression)) {
161
+ const callee = expression.expression;
162
+ const calleeName = ts.isIdentifier(callee)
163
+ ? callee.text
164
+ : ts.isPropertyAccessExpression(callee)
165
+ ? callee.name.text
166
+ : null;
167
+ const firstArgument = expression.arguments[0];
168
+ if (calleeName === "useCallback" && firstArgument !== undefined)
169
+ return unwrapFunction(firstArgument);
170
+ }
171
+ return null;
172
+ };
173
+ const jsxExpressionOf = (attribute) => {
174
+ const initializer = attribute.initializer;
175
+ if (initializer === undefined || !ts.isJsxExpression(initializer))
176
+ return null;
177
+ return initializer.expression ?? null;
178
+ };
179
+ /** Resolves a relative import specifier to a file that exists in the tree. */
180
+ const resolveRelativeModule = (tree, fromFile, specifier) => {
181
+ const base = path.posix.normalize(path.posix.join(path.posix.dirname(fromFile), specifier));
182
+ const candidates = [
183
+ base,
184
+ ...MODULE_EXTENSIONS.map(ext => `${base}${ext}`),
185
+ ...MODULE_EXTENSIONS.map(ext => `${base}/index${ext}`),
186
+ ];
187
+ return candidates.find(candidate => tree.exists(candidate) && tree.isFile(candidate)) ?? null;
188
+ };
189
+ /* -------------------------------------------------------------------------- */
190
+ /* onToggle: MouseEvent<HTMLDivElement> -> SyntheticEvent<HTMLElement> */
191
+ /* -------------------------------------------------------------------------- */
192
+ /** Returns the replacement text when `type` is React's MouseEvent, or `null` when it isn't. */
193
+ const syntheticEventReplacement = (type, reactImports) => {
194
+ if (!ts.isTypeReferenceNode(type))
195
+ return null;
196
+ const typeName = type.typeName;
197
+ if (ts.isIdentifier(typeName)) {
198
+ return reactImports.named.get(typeName.text) === "MouseEvent" ? NEW_EVENT_TYPE : null;
199
+ }
200
+ if (ts.isIdentifier(typeName.left) && reactImports.namespaces.has(typeName.left.text)) {
201
+ return typeName.right.text === "MouseEvent" ? `${typeName.left.text}.${NEW_EVENT_TYPE}` : null;
202
+ }
203
+ return null;
204
+ };
205
+ const retypeOnToggle = (file, attribute, reactImports) => {
206
+ const expression = jsxExpressionOf(attribute);
207
+ if (expression === null)
208
+ return;
209
+ const flagForReview = () => {
210
+ file.manualReview.push(`${location(file, attribute)}: check the onToggle handler's event parameter; its type is now SyntheticEvent<HTMLElement> (was MouseEvent<HTMLDivElement>).`);
211
+ };
212
+ const declaration = ts.isIdentifier(expression) ? resolveLocalDeclaration(attribute, expression.text) : null;
213
+ const handler = !ts.isIdentifier(expression)
214
+ ? unwrapFunction(expression)
215
+ : declaration === null
216
+ ? null
217
+ : ts.isFunctionDeclaration(declaration)
218
+ ? declaration
219
+ : declaration.initializer !== undefined
220
+ ? unwrapFunction(declaration.initializer)
221
+ : null;
222
+ if (handler === null) {
223
+ flagForReview();
224
+ return;
225
+ }
226
+ // The event type is on the handler's first parameter, or on the variable's own function type:
227
+ // `const onToggle: (event: MouseEvent<HTMLDivElement>, expanded: boolean) => void = (event, expanded) => …`.
228
+ const annotation = declaration !== null && ts.isVariableDeclaration(declaration) ? declaration.type : undefined;
229
+ const eventType = handler.parameters[0]?.type ??
230
+ (annotation !== undefined && ts.isFunctionTypeNode(annotation) ? annotation.parameters[0]?.type : undefined);
231
+ if (eventType === undefined) {
232
+ // Typed some other way, such as a type alias. Untyped handlers need nothing.
233
+ if (annotation?.getText().includes("MouseEvent") === true)
234
+ flagForReview();
235
+ return;
236
+ }
237
+ const replacement = syntheticEventReplacement(eventType, reactImports);
238
+ if (replacement === null) {
239
+ // A MouseEvent this migration can't tie to React, such as one behind an alias.
240
+ if (eventType.getText().includes("MouseEvent"))
241
+ flagForReview();
242
+ return;
243
+ }
244
+ addEdit(file, { start: eventType.getStart(), end: eventType.getEnd(), text: replacement });
245
+ if (!replacement.includes("."))
246
+ file.needsSyntheticEventImport = true;
247
+ };
248
+ /** Adds `SyntheticEvent` to the react import and drops `MouseEvent` when nothing else uses it. */
249
+ const updateReactImport = (content, filePath) => {
250
+ const sourceFile = (0, jsx_utils_1.parseTsx)(content, filePath);
251
+ const reactImports = getReactImports(sourceFile);
252
+ const mouseEventLocal = [...reactImports.named.entries()].find(([, imported]) => imported === "MouseEvent")?.[0];
253
+ let mouseEventStillUsed = false;
254
+ if (mouseEventLocal !== undefined) {
255
+ const visit = (node) => {
256
+ if (mouseEventStillUsed || ts.isImportDeclaration(node))
257
+ return;
258
+ if (ts.isIdentifier(node) && node.text === mouseEventLocal) {
259
+ mouseEventStillUsed = true;
260
+ return;
261
+ }
262
+ ts.forEachChild(node, visit);
263
+ };
264
+ visit(sourceFile);
265
+ }
266
+ const hasSyntheticEvent = [...reactImports.named.values()].includes("SyntheticEvent");
267
+ for (const stmt of sourceFile.statements) {
268
+ if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier))
269
+ continue;
270
+ if (stmt.moduleSpecifier.text !== "react")
271
+ continue;
272
+ const bindings = stmt.importClause?.namedBindings;
273
+ if (bindings === undefined || !ts.isNamedImports(bindings))
274
+ continue;
275
+ const kept = bindings.elements
276
+ .filter(element => mouseEventStillUsed || (element.propertyName?.text ?? element.name.text) !== "MouseEvent")
277
+ .map(element => element.getText());
278
+ const isSorted = kept.every((name, index) => index === 0 || (kept[index - 1] ?? "").localeCompare(name) <= 0);
279
+ const withSyntheticEvent = hasSyntheticEvent ? kept : [...kept, "SyntheticEvent"];
280
+ const merged = isSorted ? [...withSyntheticEvent].sort((a, b) => a.localeCompare(b)) : withSyntheticEvent;
281
+ return `${content.slice(0, bindings.getStart())}{ ${merged.join(", ")} }${content.slice(bindings.getEnd())}`;
282
+ }
283
+ return hasSyntheticEvent ? content : `import { SyntheticEvent } from "react";\n${content}`;
284
+ };
285
+ const containsJsx = (node) => ts.isJsxElement(node) ||
286
+ ts.isJsxSelfClosingElement(node) ||
287
+ ts.isJsxFragment(node) ||
288
+ ts.forEachChild(node, containsJsx) === true;
289
+ /** `null`, `undefined`, booleans, strings and numbers render nothing interactive. */
290
+ const isEmptyOrTextLiteral = (expression) => ts.isParenthesizedExpression(expression)
291
+ ? isEmptyOrTextLiteral(expression.expression)
292
+ : expression.kind === ts.SyntaxKind.NullKeyword ||
293
+ expression.kind === ts.SyntaxKind.TrueKeyword ||
294
+ expression.kind === ts.SyntaxKind.FalseKeyword ||
295
+ (ts.isIdentifier(expression) && expression.text === "undefined") ||
296
+ ts.isStringLiteralLike(expression) ||
297
+ ts.isNumericLiteral(expression);
298
+ /**
299
+ * Interactive controls in the addon are `nested-interactive` inside a native `<summary>`.
300
+ * They are logged, not moved: the controls belong in the content, and where they go there is a layout decision.
301
+ */
302
+ const flagInteractiveAddon = (file, attribute) => {
303
+ const expression = jsxExpressionOf(attribute);
304
+ if (expression === null)
305
+ return;
306
+ const flagOpaque = () => {
307
+ const source = expression.getText();
308
+ file.manualReview.push(`${location(file, attribute)}: headerAddon is \`${source.length > 60 ? `${source.slice(0, 57)}...` : source}\`, which this migration can't look into (it comes from a prop, an import or a call). If it can render interactive controls such as a Button or ToggleGroup, move those into the content (e.g. a toolbar row at the top): the header is now a native <summary>, and controls nested in it are reported by axe as nested-interactive.`);
309
+ };
310
+ if (isEmptyOrTextLiteral(expression))
311
+ return;
312
+ const declaration = ts.isIdentifier(expression) ? resolveLocalDeclaration(attribute, expression.text) : null;
313
+ const addonRoot = !ts.isIdentifier(expression)
314
+ ? expression
315
+ : declaration !== null && ts.isVariableDeclaration(declaration)
316
+ ? (declaration.initializer ?? null)
317
+ : null;
318
+ if (addonRoot === null) {
319
+ flagOpaque();
320
+ return;
321
+ }
322
+ const found = new Set();
323
+ const visit = (node) => {
324
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
325
+ const tagName = node.tagName.getText();
326
+ if (INTERACTIVE_ELEMENTS.has(tagName))
327
+ found.add(tagName);
328
+ }
329
+ ts.forEachChild(node, visit);
330
+ };
331
+ visit(addonRoot);
332
+ if (found.size === 0) {
333
+ if (!containsJsx(addonRoot) && !isEmptyOrTextLiteral(addonRoot))
334
+ flagOpaque();
335
+ return;
336
+ }
337
+ file.manualReview.push(`${location(file, attribute)}: headerAddon contains interactive controls (${[...found].join(", ")}). The header is now a native <summary>, which is interactive itself, so axe reports nested-interactive and screen readers may not announce these controls. Clicks on them still don't toggle the section, but move them into the content (e.g. a toolbar row at the top), and keep only non-interactive items such as status icons or badges in headerAddon.`);
338
+ };
339
+ /* -------------------------------------------------------------------------- */
340
+ /* animate={false} -> animate={false} lazy */
341
+ /* -------------------------------------------------------------------------- */
342
+ /** The `lazy` attribute that keeps the old rendering of this `animate` value, or `null` when it is always true. */
343
+ const lazyAttributeFor = (animate) => {
344
+ // The `animate` shorthand means `animate={true}`.
345
+ if (animate.initializer === undefined)
346
+ return null;
347
+ const expression = jsxExpressionOf(animate);
348
+ if (expression === null || expression.kind === ts.SyntaxKind.TrueKeyword)
349
+ return null;
350
+ if (expression.kind === ts.SyntaxKind.FalseKeyword)
351
+ return LAZY_PROP;
352
+ const text = expression.getText();
353
+ const isSimple = ts.isIdentifier(expression) || ts.isPropertyAccessExpression(expression);
354
+ return `${LAZY_PROP}={!${isSimple ? text : `(${text})`}}`;
355
+ };
356
+ /**
357
+ * `animate={false}` used to also mean "render children only while open". That is now the separate `lazy` prop,
358
+ * so it is added wherever `animate` is, or can be, false. It goes in alphabetical position when the attributes
359
+ * are sorted, and right after `animate` otherwise.
360
+ */
361
+ const keepLazyRendering = (file, openingElement, animate) => {
362
+ const lazyAttribute = lazyAttributeFor(animate);
363
+ if (lazyAttribute === null)
364
+ return;
365
+ const named = [];
366
+ for (const attribute of openingElement.attributes.properties) {
367
+ if (ts.isJsxAttribute(attribute) && ts.isIdentifier(attribute.name)) {
368
+ named.push({ attribute, name: attribute.name.text.toLowerCase() });
369
+ }
370
+ }
371
+ const isSorted = named.length === openingElement.attributes.properties.length &&
372
+ named.every(({ name }, index) => index === 0 || (named[index - 1]?.name ?? "") <= name);
373
+ const anchor = isSorted ? (named.filter(({ name }) => name < LAZY_PROP).at(-1)?.attribute ?? animate) : animate;
374
+ const leadingTrivia = file.sourceFile.text.slice(anchor.getFullStart(), anchor.getStart());
375
+ const separator = /^\s+$/.test(leadingTrivia) ? leadingTrivia : " ";
376
+ addEdit(file, { start: anchor.getEnd(), end: anchor.getEnd(), text: `${separator}${lazyAttribute}` });
377
+ };
378
+ const reachedCollapses = (state, dependenciesOf, testFile) => {
379
+ const reached = { files: 0, labels: new Set(), testIds: new Set() };
380
+ const visited = new Set([testFile]);
381
+ const queue = [testFile];
382
+ for (let next = queue.shift(); next !== undefined; next = queue.shift()) {
383
+ const facts = state.collapses.get(next);
384
+ if (facts !== undefined) {
385
+ reached.files++;
386
+ for (const label of facts.labels)
387
+ reached.labels.add(label);
388
+ for (const testId of facts.testIds)
389
+ reached.testIds.add(testId);
390
+ }
391
+ for (const dependency of dependenciesOf(next)) {
392
+ if (visited.has(dependency))
393
+ continue;
394
+ visited.add(dependency);
395
+ queue.push(dependency);
396
+ }
397
+ }
398
+ return reached;
399
+ };
400
+ const flagOldHeaderQueries = (state) => {
401
+ // Nothing renders a Collapse, so no test can target its header.
402
+ if (state.collapses.size === 0)
403
+ return;
404
+ const testFiles = [];
405
+ (0, devkit_1.visitNotIgnoredFiles)(state.tree, "/", filePath => {
406
+ if ((0, jsx_utils_1.isWorkspaceSourceFile)(filePath) && TEST_FILE_PATTERN.test(filePath))
407
+ testFiles.push(filePath);
408
+ });
409
+ // The import graph is followed outward from the test files, so only files a test can reach are read.
410
+ const dependencies = new Map();
411
+ const dependenciesOf = (filePath) => {
412
+ const known = dependencies.get(filePath);
413
+ if (known !== undefined)
414
+ return known;
415
+ const resolved = new Set();
416
+ for (const match of (state.tree.read(filePath, "utf-8") ?? "").matchAll(RELATIVE_IMPORT_PATTERN)) {
417
+ const specifier = match[1];
418
+ const target = specifier === undefined ? null : resolveRelativeModule(state.tree, filePath, specifier);
419
+ if (target !== null)
420
+ resolved.add(target);
421
+ }
422
+ const result = [...resolved];
423
+ dependencies.set(filePath, result);
424
+ return result;
425
+ };
426
+ let unidentifiedFiles = 0;
427
+ for (const testFile of testFiles) {
428
+ const reached = reachedCollapses(state, dependenciesOf, testFile);
429
+ if (reached.files === 0)
430
+ continue;
431
+ const content = state.tree.read(testFile, "utf-8") ?? "";
432
+ const lines = headerQueryLines(reached, content);
433
+ if (lines.length === 0) {
434
+ if (BUTTON_ROLE_QUERY_PATTERN.test(content) || OLD_HEADER_ATTRIBUTE_PATTERN.test(content))
435
+ unidentifiedFiles++;
436
+ continue;
437
+ }
438
+ state.manualReview.push(`${testFile} (${lines.length === 1 ? "line" : "lines"} ${lines.join(", ")}): these queries target the header of a Collapse, which is now a native <summary> without role="button", aria-expanded or aria-controls (other button queries in the file may too, if their Collapse label isn't static). Query it with getByTestId("<data-testid>-header"), or to keep checking the label, with within(getByTestId("<data-testid>-header")).getByText(label): a bare getByText(label) also matches the same text elsewhere and no longer proves it is the header. Read the state from the open attribute of the "<data-testid>-details" element. Content is in the DOM while the section is closed (unless the Collapse is lazy), so finding it doesn't prove the section expanded: assert the open attribute instead.`);
439
+ }
440
+ if (unidentifiedFiles > 0) {
441
+ state.manualReview.push(`${unidentifiedFiles} other test ${unidentifiedFiles === 1 ? "file renders" : "files render"} a Collapse and ${unidentifiedFiles === 1 ? "queries" : "query"} buttons by role or ${unidentifiedFiles === 1 ? "asserts" : "assert"} aria-expanded or aria-controls. Those usually target other elements. Any that targeted a Collapse header, for example by a label rendered from a variable, now fail with 'Unable to find an accessible element with the role "button"': fix them as described for the files above.`);
442
+ }
443
+ };
444
+ /**
445
+ * 1-based line numbers in a test file of queries and assertions that target the old Collapse header.
446
+ *
447
+ * `aria-expanded` and `aria-controls` are also on selects, popovers and menus, so an assertion on them counts only
448
+ * when its line holds a header query or a variable assigned from one.
449
+ */
450
+ const headerQueryLines = (reached, content) => {
451
+ const lineOf = (index) => content.slice(0, index).split("\n").length;
452
+ const lines = new Set();
453
+ for (const match of content.matchAll(SCOPED_BUTTON_QUERY_PATTERN)) {
454
+ const testId = match[1];
455
+ if (testId !== undefined && reached.testIds.has(testId))
456
+ lines.add(lineOf(match.index));
457
+ }
458
+ for (const match of content.matchAll(NAMED_BUTTON_QUERY_PATTERN)) {
459
+ const name = match[1];
460
+ if (name !== undefined && matchesCollapseLabel(reached.labels, name))
461
+ lines.add(lineOf(match.index));
462
+ }
463
+ const sourceLines = content.split("\n");
464
+ const headerVariables = [...lines]
465
+ .map(line => HEADER_VARIABLE_PATTERN.exec(sourceLines[line - 1] ?? "")?.[1])
466
+ .filter(name => name !== undefined);
467
+ sourceLines.forEach((line, index) => {
468
+ if (!OLD_HEADER_ATTRIBUTE_PATTERN.test(line))
469
+ return;
470
+ const usesHeaderVariable = headerVariables.some(name => new RegExp(`(?<![\\w$])${name}(?![\\w$])`).test(line));
471
+ if (lines.has(index + 1) || usesHeaderVariable)
472
+ lines.add(index + 1);
473
+ });
474
+ return [...lines].sort((a, b) => a - b);
475
+ };
476
+ /** Whether a query's `name` literal (a string or a regex) matches one of the static Collapse labels. */
477
+ const matchesCollapseLabel = (labels, nameLiteral) => {
478
+ if (!nameLiteral.startsWith("/")) {
479
+ const name = nameLiteral.slice(1, -1).trim();
480
+ return labels.has(name);
481
+ }
482
+ const lastSlash = nameLiteral.lastIndexOf("/");
483
+ let pattern;
484
+ try {
485
+ pattern = new RegExp(nameLiteral.slice(1, lastSlash), nameLiteral.slice(lastSlash + 1).replace(/[gy]/g, ""));
486
+ }
487
+ catch {
488
+ return false;
489
+ }
490
+ return [...labels].some(label => pattern.test(label));
491
+ };
492
+ /** The text of a string literal attribute, `{"text"}`, or the key of a translation call such as `{t("key")}`. */
493
+ const staticAttributeText = (attribute) => {
494
+ if (attribute === null || attribute.initializer === undefined)
495
+ return null;
496
+ if (ts.isStringLiteral(attribute.initializer))
497
+ return attribute.initializer.text;
498
+ const expression = jsxExpressionOf(attribute);
499
+ if (expression === null)
500
+ return null;
501
+ if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression))
502
+ return expression.text;
503
+ if (ts.isCallExpression(expression)) {
504
+ const [firstArgument] = expression.arguments;
505
+ if (firstArgument !== undefined && ts.isStringLiteral(firstArgument))
506
+ return firstArgument.text;
507
+ }
508
+ return null;
509
+ };
510
+ /* -------------------------------------------------------------------------- */
511
+ /** Migrates the Collapses in one file and returns its new content, or `null` when nothing in it changes. */
512
+ const migrateCollapseUsages = (state, filePath, content) => {
513
+ const sourceFile = (0, jsx_utils_1.parseTsx)(content, filePath);
514
+ const aliases = (0, jsx_utils_1.getImportedAliases)(sourceFile, PACKAGE_NAME);
515
+ if (aliases === null)
516
+ return null;
517
+ const collapseAliases = Object.entries(aliases)
518
+ .filter(([, imported]) => imported === COMPONENT_NAME)
519
+ .map(([local]) => local);
520
+ if (collapseAliases.length === 0)
521
+ return null;
522
+ const matches = (0, jsx_utils_1.findJsxElements)(sourceFile, collapseAliases);
523
+ if (matches.length === 0)
524
+ return null;
525
+ const file = {
526
+ filePath,
527
+ sourceFile,
528
+ edits: [],
529
+ needsSyntheticEventImport: false,
530
+ manualReview: state.manualReview,
531
+ };
532
+ const facts = { labels: new Set(), testIds: new Set() };
533
+ state.collapses.set(filePath, facts);
534
+ const reactImports = getReactImports(sourceFile);
535
+ for (const { openingElement } of matches) {
536
+ const onToggle = (0, jsx_utils_1.findJsxAttribute)(openingElement, "onToggle");
537
+ if (onToggle !== null)
538
+ retypeOnToggle(file, onToggle, reactImports);
539
+ const headerAddon = (0, jsx_utils_1.findJsxAttribute)(openingElement, "headerAddon");
540
+ if (headerAddon !== null)
541
+ flagInteractiveAddon(file, headerAddon);
542
+ if ((0, jsx_utils_1.findJsxAttribute)(openingElement, LAZY_PROP) === null) {
543
+ const animate = (0, jsx_utils_1.findJsxAttribute)(openingElement, "animate");
544
+ if (animate !== null) {
545
+ keepLazyRendering(file, openingElement, animate);
546
+ }
547
+ else if ((0, jsx_utils_1.hasSpreadAttribute)(openingElement)) {
548
+ file.manualReview.push(`${location(file, openingElement)}: this Collapse gets props from a spread. If they can include animate={false}, also pass lazy: animate={false} now only turns the animation off, and lazy renders children only while the section is open, as animate={false} used to.`);
549
+ }
550
+ }
551
+ const label = staticAttributeText((0, jsx_utils_1.findJsxAttribute)(openingElement, "label"));
552
+ if (label !== null)
553
+ facts.labels.add(label);
554
+ const testId = staticAttributeText((0, jsx_utils_1.findJsxAttribute)(openingElement, "data-testid"));
555
+ if (testId !== null)
556
+ facts.testIds.add(testId);
557
+ }
558
+ if (file.edits.length === 0)
559
+ return null;
560
+ const edited = applyEdits(content, file.edits);
561
+ return file.needsSyntheticEventImport ? updateReactImport(edited, filePath) : edited;
562
+ };
563
+ /**
564
+ * Migrates consumers to the 7.0.0 `Collapse`, rebuilt on native `<details>`/`<summary>`:
565
+ *
566
+ * - Retypes `onToggle` handlers declared as `(event: MouseEvent<HTMLDivElement>, …)`, inline or in the same file,
567
+ * to `SyntheticEvent<HTMLElement>` and updates the `react` import.
568
+ * - Adds `lazy` next to `animate={false}` (and `lazy={!value}` next to a dynamic `animate={value}`): `animate` now
569
+ * only controls the animation, and `lazy` renders children only while the section is open.
570
+ * - Logs, without changing them:
571
+ * - Collapses that get their props from a spread, which may carry `animate={false}`.
572
+ * - `headerAddon`s that contain interactive controls (e.g. a `Button` or `ToggleGroup`), which would be
573
+ * `nested-interactive` inside the native `<summary>`, and ones it can't look into (a prop, an import or a call).
574
+ * - `onToggle` handlers it can't resolve or whose `MouseEvent` type it can't rewrite.
575
+ * - Test lines that target the old header, which was a `role="button"` with `aria-expanded` and `aria-controls`:
576
+ * nameless button queries scoped to a Collapse's `data-testid`, button queries whose `name` matches a Collapse's
577
+ * static label (a string or a `t("key")` key), and assertions on those two attributes next to such a query.
578
+ * Other button queries and attribute assertions in tests that render a Collapse are counted in a single note,
579
+ * since they usually target other elements.
580
+ *
581
+ * Handlers and addons passed by name are resolved in the scope of the Collapse that uses them.
582
+ */
583
+ const collapseNativeDetails = (tree) => {
584
+ const state = { tree, collapses: new Map(), manualReview: [] };
585
+ const touched = (0, jsx_utils_1.visitTsxFiles)(tree, PACKAGE_NAME, (filePath, content) => migrateCollapseUsages(state, filePath, content));
586
+ flagOldHeaderQueries(state);
587
+ for (const message of state.manualReview)
588
+ devkit_1.logger.warn(` ${MIGRATION_NAME}: ${message}`);
589
+ (0, jsx_utils_1.logSummary)(MIGRATION_NAME, touched, state.manualReview.length);
590
+ };
591
+ exports.collapseNativeDetails = collapseNativeDetails;
592
+ exports.default = exports.collapseNativeDetails;
593
+ //# sourceMappingURL=collapse-native-details.js.map