@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.
package/index.esm.js CHANGED
@@ -1900,13 +1900,19 @@ const cvaIconButton = cva({
1900
1900
  * @param {ButtonProps} props - The props for the Button component
1901
1901
  * @returns {ReactElement} Button component
1902
1902
  */
1903
- const Button = ({ onClick, children, loading = false, disabled = false, className, fullWidth = false, prefix, suffix, variant = "primary", type = "button", size = "medium", square = false, "data-testid": dataTestId, title, ariaLabel, ariaLabelledBy, ariaDescribedBy, ariaHidden = false, role, tabIndex, asChild = false, ref, ...rest }) => {
1903
+ const Button = ({ onClick, children, loading = false, disabled = false, className, fullWidth = false, prefix, suffix, variant = "primary", type = "button", size = "medium", square = false, "data-testid": dataTestId, title, ariaLabel, ariaLabelledBy, ariaDescribedBy, ariaHidden = false, role, tabIndex, asChild = false, keepFocus = false, onMouseDown, ref, ...rest }) => {
1904
1904
  const Comp = asChild ? Slot : "button";
1905
1905
  const sharedCompProps = {
1906
1906
  ref,
1907
1907
  title,
1908
1908
  role,
1909
1909
  onClick,
1910
+ onMouseDown: keepFocus
1911
+ ? (event) => {
1912
+ onMouseDown?.(event);
1913
+ event.preventDefault();
1914
+ }
1915
+ : onMouseDown,
1910
1916
  tabIndex,
1911
1917
  className: cvaButton({ disabled, size, square, variant, loading, fullWidth, className }),
1912
1918
  "aria-describedby": ariaDescribedBy,
@@ -2376,7 +2382,7 @@ const TAG_TEXT_MIN_WIDTH_PX = parseTailwindArbitraryValue(TAG_TEXT_MIN_WIDTH_CLA
2376
2382
  * @param {TagProps} props - The props for the Tag component.
2377
2383
  * @returns {ReactElement} The rendered Tag component.
2378
2384
  */
2379
- const Tag = ({ className, "data-testid": dataTestId, children, size = "medium", onClickClose, color = "info", disabled = false, ref, icon, onMouseEnter, style, removeTagLabel, removeButtonInTabOrder = true, }) => {
2385
+ const Tag = ({ className, "data-testid": dataTestId, children, size = "medium", onClickClose, color = "info", disabled = false, ref, icon, onMouseEnter, style, removeTagLabel, removeButtonInTabOrder = true, keepFocus = false, }) => {
2380
2386
  const textRef = useRef(null);
2381
2387
  const [shouldTruncate, setShouldTruncate] = useState(false);
2382
2388
  const textId = useId();
@@ -2407,7 +2413,7 @@ const Tag = ({ className, "data-testid": dataTestId, children, size = "medium",
2407
2413
  color,
2408
2414
  layout,
2409
2415
  border: color === "white" ? "default" : "none",
2410
- }), "data-testid": dataTestId, onMouseEnter: onMouseEnter, ref: ref, style: style, children: [icon !== null && icon !== undefined && size === "medium" ? (jsx("div", { className: cvaTagIconContainer(), "data-slot": "icon", children: icon })) : null, jsx("span", { className: cvaTagText({ truncate: shouldTruncate }), id: textId, ref: textRef, children: children }), Boolean(onClickClose) && size === "medium" && !disabled ? (jsx("div", { className: cvaTagIconContainer(), "data-slot": "dismiss", onClick: onClickClose, children: jsx(Tooltip, { disabled: disabled, label: removeTagLabel, placement: "bottom", children: jsx("button", { "aria-label": removeTagLabel, "aria-labelledby": `${removeButtonId} ${textId}`, className: cvaTagDismissButton(), id: removeButtonId, tabIndex: removeButtonInTabOrder ? undefined : -1, type: "button", children: jsx(Icon, { ariaHidden: true, className: cvaTagIcon(), "data-testid": `${dataTestId}Icon`, name: "XCircle", size: "small", style: { WebkitTransition: "-webkit-transform 0.150s" }, type: "solid" }) }) }) })) : null] }));
2416
+ }), "data-testid": dataTestId, onMouseEnter: onMouseEnter, ref: ref, style: style, children: [icon !== null && icon !== undefined && size === "medium" ? (jsx("div", { className: cvaTagIconContainer(), "data-slot": "icon", children: icon })) : null, jsx("span", { className: cvaTagText({ truncate: shouldTruncate }), id: textId, ref: textRef, children: children }), Boolean(onClickClose) && size === "medium" && !disabled ? (jsx("div", { className: cvaTagIconContainer(), "data-slot": "dismiss", onClick: onClickClose, children: jsx(Tooltip, { disabled: disabled, label: removeTagLabel, placement: "bottom", children: jsx("button", { "aria-label": removeTagLabel, "aria-labelledby": `${removeButtonId} ${textId}`, className: cvaTagDismissButton(), id: removeButtonId, onMouseDown: keepFocus ? event => event.preventDefault() : undefined, tabIndex: removeButtonInTabOrder ? undefined : -1, type: "button", children: jsx(Icon, { ariaHidden: true, className: cvaTagIcon(), "data-testid": `${dataTestId}Icon`, name: "XCircle", size: "small", style: { WebkitTransition: "-webkit-transform 0.150s" }, type: "solid" }) }) }) })) : null] }));
2411
2417
  };
2412
2418
 
2413
2419
  // Mirrors the slug logic in @trackunit/storybook-docs-components SectionName so anchors line up
@@ -4205,112 +4211,82 @@ const cvaClickable = cva({
4205
4211
  });
4206
4212
 
4207
4213
  /**
4208
- * Custom hook to measure the geometry of an element using a callback ref.
4209
- * Measures the size and position of the element relative to the viewport.
4210
- *
4211
- * @template TElement extends HTMLElement
4212
- * @returns {UseMeasureResult<HTMLElement>} An object containing `geometry`, `ref` callback, and `element`.
4213
- * @example
4214
- * ```tsx
4215
- * const { geometry, ref } = useMeasure();
4216
- * return <div ref={ref}>Width: {geometry.width}</div>;
4217
- * ```
4214
+ * The container doesn't clip its content: the header's focus ring is the browser's own, drawn outside the
4215
+ * header like a button's, and clipping would cut it off. The header and the content round their own corners
4216
+ * to the container's inner radius instead: `rounded-md` minus the 1px border, taken from the theme's
4217
+ * `--radius-md` so it follows the token.
4218
4218
  */
4219
- const useMeasure = ({ skip = false, onChange, } = {}) => {
4220
- const [element, setElement] = useState(null);
4221
- const [geometry, setGeometry] = useState(undefined);
4222
- const observerRef = useRef(null);
4223
- const onChangeRef = useRef(onChange);
4224
- const isInitialRender = useRef(true);
4225
- // Callback ref to track the element
4226
- const ref = useCallback((node) => {
4227
- setElement(node);
4228
- }, []);
4229
- const disconnectObserver = () => {
4230
- if (observerRef.current !== null) {
4231
- observerRef.current.disconnect();
4232
- observerRef.current = null;
4233
- }
4234
- };
4235
- useEffect(() => {
4236
- onChangeRef.current = onChange;
4237
- }, [onChange]);
4238
- useEffect(() => {
4239
- if (skip || element === null) {
4240
- return;
4241
- }
4242
- const updateGeometry = (rect) => {
4243
- const newGeometry = {
4244
- width: rect.width,
4245
- height: rect.height,
4246
- top: rect.top,
4247
- bottom: rect.bottom,
4248
- left: rect.left,
4249
- right: rect.right,
4250
- x: rect.x,
4251
- y: rect.y,
4252
- };
4253
- setGeometry(prevGeometry => {
4254
- if (isEqual(prevGeometry, newGeometry)) {
4255
- return prevGeometry;
4256
- }
4257
- if (isInitialRender.current === false) {
4258
- onChangeRef.current?.(newGeometry);
4259
- }
4260
- return newGeometry;
4261
- });
4262
- isInitialRender.current = false;
4263
- };
4264
- const handleResize = (entries) => {
4265
- for (const entry of entries) {
4266
- const rect = entry.target.getBoundingClientRect();
4267
- updateGeometry(rect);
4268
- }
4269
- };
4270
- disconnectObserver();
4271
- const observer = new ResizeObserver(handleResize);
4272
- observer.observe(element);
4273
- observerRef.current = observer;
4274
- const initialRect = element.getBoundingClientRect();
4275
- updateGeometry(initialRect);
4276
- return disconnectObserver;
4277
- }, [element, skip]);
4278
- return useMemo(() => ({ geometry, ref, element }), [geometry, ref, element]);
4279
- };
4280
-
4281
4219
  const cvaCollapse = cva({
4282
- base: ["flex", "flex-col", "overflow-hidden"],
4220
+ base: ["flex", "flex-col"],
4283
4221
  variants: {
4284
4222
  variant: {
4285
4223
  primary: ["border", "border-solid", "border-neutral-300", "rounded-md", "bg-white"],
4286
- secondary: "gap-3",
4224
+ secondary: [],
4287
4225
  },
4288
4226
  },
4289
4227
  });
4228
+ /**
4229
+ * The `::details-content` box is a one-row grid whose row animates from `0fr` to `1fr`, so the content
4230
+ * height is never measured in JavaScript. `content-visibility` is transitioned discretely so the content
4231
+ * stays visible until the closing animation ends. Browsers without `::details-content` support, users
4232
+ * who prefer reduced motion, and `animate={false}` get an instant open and close.
4233
+ */
4234
+ const cvaCollapseDetails = cva({
4235
+ variants: {
4236
+ animate: {
4237
+ true: [
4238
+ "details-content:grid",
4239
+ "details-content:grid-rows-[0fr]",
4240
+ "open:details-content:grid-rows-[1fr]",
4241
+ "motion-safe:details-content:transition-[grid-template-rows,content-visibility]",
4242
+ "motion-safe:details-content:transition-discrete",
4243
+ "motion-safe:details-content:duration-200",
4244
+ "motion-safe:details-content:ease-in-out",
4245
+ ],
4246
+ false: [],
4247
+ },
4248
+ },
4249
+ defaultVariants: {
4250
+ animate: true,
4251
+ },
4252
+ });
4253
+ /**
4254
+ * A closed primary header rounds its bottom corners. The `open` attribute is removed as soon as closing
4255
+ * starts, so when the closing is animated the rounding waits for the animation to end: until then the
4256
+ * content is still visible below a header that should stay square.
4257
+ */
4290
4258
  const cvaCollapseHeader = cva({
4291
- base: ["flex", "items-center", "cursor-pointer", "transition-all", "group/collapse"],
4259
+ base: [
4260
+ "flex",
4261
+ "items-center",
4262
+ "cursor-pointer",
4263
+ "transition-all",
4264
+ "group/collapse",
4265
+ "list-none",
4266
+ "[&::-webkit-details-marker]:hidden",
4267
+ ],
4292
4268
  variants: {
4293
- expanded: { true: [], false: [] },
4294
4269
  variant: {
4295
- primary: ["gap-4", "justify-between", "bg-white", "hover:bg-neutral-100"],
4270
+ primary: [
4271
+ "gap-4",
4272
+ "justify-between",
4273
+ "bg-white",
4274
+ "hover:bg-neutral-100",
4275
+ "rounded-t-[calc(var(--radius-md)-1px)]",
4276
+ "[details:not([open])>&]:rounded-b-[calc(var(--radius-md)-1px)]",
4277
+ ],
4296
4278
  secondary: ["w-fit"],
4297
4279
  },
4298
4280
  extraPadding: {
4299
4281
  true: [],
4300
4282
  false: [],
4301
4283
  },
4284
+ animate: {
4285
+ true: [],
4286
+ false: [],
4287
+ },
4302
4288
  },
4303
4289
  compoundVariants: [
4304
- {
4305
- variant: "primary",
4306
- expanded: true,
4307
- class: ["border-neutral-200", "border-b", "border-solid"],
4308
- },
4309
- {
4310
- variant: "primary",
4311
- expanded: false,
4312
- class: [],
4313
- },
4314
4290
  {
4315
4291
  variant: "primary",
4316
4292
  extraPadding: true,
@@ -4331,7 +4307,17 @@ const cvaCollapseHeader = cva({
4331
4307
  extraPadding: false,
4332
4308
  class: [],
4333
4309
  },
4310
+ {
4311
+ variant: "primary",
4312
+ animate: true,
4313
+ class: [
4314
+ "motion-safe:supports-[selector(::details-content)]:[details:not([open])>&]:[transition:background-color_150ms,border-radius_0s_200ms]",
4315
+ ],
4316
+ },
4334
4317
  ],
4318
+ defaultVariants: {
4319
+ animate: true,
4320
+ },
4335
4321
  });
4336
4322
  const cvaCollapseLabelContainer = cva({
4337
4323
  base: ["flex", "items-center"],
@@ -4351,13 +4337,45 @@ const cvaCollapseLabel = cva({
4351
4337
  },
4352
4338
  },
4353
4339
  });
4354
- const cvaCollapsible = cva({
4355
- base: ["block", "relative"],
4340
+ /**
4341
+ * The single grid item inside `::details-content`. It must not carry padding, because padding would
4342
+ * stay visible while the row is collapsed to `0fr`. `min-w-0` keeps wide content (a code block, a table)
4343
+ * from stretching the grid column past the Collapse: a grid item is otherwise at least as wide as its content.
4344
+ */
4345
+ const cvaCollapseContent = cva({
4346
+ base: ["min-h-0", "min-w-0", "overflow-clip"],
4356
4347
  variants: {
4357
4348
  variant: {
4358
- primary: [],
4349
+ primary: ["rounded-b-[calc(var(--radius-md)-1px)]"],
4359
4350
  secondary: [],
4360
4351
  },
4352
+ },
4353
+ });
4354
+ /**
4355
+ * Hidden while it has no children, so its padding doesn't show as an empty box. A `lazy` Collapse renders
4356
+ * its children a moment after the section opens, when the browser's `toggle` event arrives.
4357
+ *
4358
+ * The line between the header and the content is this element's top border, not the header's bottom border.
4359
+ * It is clipped away with the content, and it fades out over the closing animation so it doesn't end in a
4360
+ * hard cut when the content reaches zero height.
4361
+ */
4362
+ const cvaCollapsible = cva({
4363
+ base: ["block", "relative", "empty:hidden"],
4364
+ variants: {
4365
+ variant: {
4366
+ primary: [
4367
+ "border-t",
4368
+ "border-solid",
4369
+ "border-neutral-200",
4370
+ "transition-colors",
4371
+ "duration-200",
4372
+ "ease-in-out",
4373
+ "motion-reduce:transition-none",
4374
+ "[details:not([open])>*>&]:border-transparent",
4375
+ ],
4376
+ // Replaces the gap between header and content that the outer flex container used to provide.
4377
+ secondary: ["mt-3"],
4378
+ },
4361
4379
  extraPadding: {
4362
4380
  true: [],
4363
4381
  false: [],
@@ -4386,34 +4404,49 @@ const cvaCollapsible = cva({
4386
4404
  },
4387
4405
  ],
4388
4406
  });
4389
- const cvaCollapseAnimated = cva({
4390
- base: ["overflow-y-hidden", "transition-all"],
4391
- variants: {
4392
- expanded: {
4393
- true: "block",
4394
- false: "hidden",
4395
- },
4396
- },
4397
- defaultVariants: {
4398
- expanded: false,
4399
- },
4400
- });
4407
+ /**
4408
+ * Rotates when this Collapse's own `<details>` is open, with the same timing as the height animation.
4409
+ * The child combinator keeps a nested Collapse's chevron from rotating when only its parent is open.
4410
+ */
4401
4411
  const cvaChevronIcon = cva({
4402
- base: ["transition-transform"],
4403
- variants: {
4404
- expanded: {
4405
- true: "rotate-180",
4406
- false: "",
4407
- },
4408
- },
4409
- defaultVariants: {
4410
- expanded: false,
4411
- },
4412
+ base: [
4413
+ "transition-transform",
4414
+ "duration-200",
4415
+ "ease-in-out",
4416
+ "motion-reduce:transition-none",
4417
+ "[details[open]>summary_&]:rotate-180",
4418
+ ],
4412
4419
  });
4413
4420
 
4421
+ const INTERACTIVE_SELECTOR = "a,button,input,select,textarea,label,[role=button]";
4422
+ /**
4423
+ * The interactive element inside the summary that a click came from, such as a button in `headerAddon`.
4424
+ */
4425
+ const getInteractiveDescendant = (event) => {
4426
+ const { target, currentTarget } = event;
4427
+ if (!(target instanceof Element)) {
4428
+ return null;
4429
+ }
4430
+ const interactive = target.closest(INTERACTIVE_SELECTOR);
4431
+ return interactive !== null && interactive !== currentTarget && currentTarget.contains(interactive)
4432
+ ? interactive
4433
+ : null;
4434
+ };
4435
+
4436
+ const NATIVELY_ACTIVATABLE_SELECTOR = "a[href],button,input,label";
4437
+ /**
4438
+ * Whether an interactive element's own activation behaviour takes the click, so a `<summary>` around it doesn't
4439
+ * toggle natively. Calling preventDefault on such an element would cancel its action (e.g. a checkbox change).
4440
+ */
4441
+ const isNativelyActivatable = (element) => element.matches(NATIVELY_ACTIVATABLE_SELECTOR);
4442
+
4414
4443
  /**
4415
4444
  * The Collapse component is a container for additional information that adds context to various flows. It is used for displaying non-essential information that can be hidden away.
4416
4445
  *
4446
+ * It is built on the native `<details>` and `<summary>` elements, so keyboard support, screen reader state and
4447
+ * find-in-page come from the browser. Opening and closing animate in CSS; in Firefox closing doesn't animate, and
4448
+ * nothing animates when the user prefers reduced motion.
4449
+ *
4417
4450
  * ### When to use
4418
4451
  * - To keep content off the screen to shorten pages and reduce scrolling, while it's still only a tap away. Remember that the users might choose not to interact with the component and won't see the information within.
4419
4452
  * - To display additional details that are not essential or necessary in the main flow/page.
@@ -4454,23 +4487,85 @@ const cvaChevronIcon = cva({
4454
4487
  * </Collapse>
4455
4488
  * );
4456
4489
  * ```
4490
+ * @example Accordion group where opening one section closes the others
4491
+ * ```tsx
4492
+ * import { Collapse } from "@trackunit/react-components";
4493
+ *
4494
+ * const Faq = () => (
4495
+ * <>
4496
+ * <Collapse id="faq-billing" label="Billing" name="faq">Billing answers</Collapse>
4497
+ * <Collapse id="faq-access" label="Access" name="faq">Access answers</Collapse>
4498
+ * </>
4499
+ * );
4500
+ * ```
4501
+ * @example Controlled collapse
4502
+ * ```tsx
4503
+ * import { Collapse } from "@trackunit/react-components";
4504
+ * import { useState } from "react";
4505
+ *
4506
+ * const ControlledSection = () => {
4507
+ * const [expanded, setExpanded] = useState(false);
4508
+ * return (
4509
+ * <Collapse expanded={expanded} id="controlled" label="Details" onToggle={(_e, next) => setExpanded(next)}>
4510
+ * Details content
4511
+ * </Collapse>
4512
+ * );
4513
+ * };
4514
+ * ```
4457
4515
  * @param {CollapseProps} props - The props for the Collapse component
4458
4516
  * @returns {ReactElement} Collapse component
4459
4517
  */
4460
- const Collapse = ({ id, variant = "primary", initialExpanded = false, onToggle, label, children, className, headerClassName, headerAddon, "data-testid": dataTestId, animate = true, extraPadding = true, style, ref, }) => {
4461
- const LABEL_ID = uuidv4();
4462
- const [expanded, setExpanded] = useState(initialExpanded);
4463
- const handleClick = useCallback((e) => {
4464
- if (onToggle) {
4465
- onToggle(e, !expanded);
4518
+ const Collapse = ({ id, variant = "primary", initialExpanded = false, onToggle, label, children, className, headerClassName, headerAddon, "data-testid": dataTestId, animate = true, lazy = false, extraPadding = true, style, ref, name, expanded = undefined, }) => {
4519
+ const labelId = useId();
4520
+ const isControlled = expanded !== undefined;
4521
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(initialExpanded);
4522
+ const isOpen = isControlled ? expanded : uncontrolledOpen;
4523
+ const handleToggle = useCallback((event) => {
4524
+ // The native toggle event doesn't bubble, but React dispatches it to ancestor handlers as well.
4525
+ // Toggles from a nested Collapse or a popover in the content aren't this section's.
4526
+ if (event.target !== event.currentTarget) {
4527
+ return;
4466
4528
  }
4467
- setExpanded(!expanded);
4468
- }, [expanded, onToggle]);
4469
- return (jsxs("div", { className: cvaCollapse({ variant: variant, className }), "data-testid": dataTestId, ref: ref, style: style, children: [jsx("div", { "aria-controls": id, "aria-expanded": expanded, className: cvaCollapseHeader({ expanded, variant, extraPadding, className: headerClassName }), onClick: handleClick, role: "button", children: jsxs("div", { className: cvaCollapseLabelContainer({ variant }), children: [jsx(Text, { className: cvaCollapseLabel({ variant }), id: LABEL_ID, size: variant === "secondary" ? "small" : "medium", type: "span", weight: "bold", children: label }), jsxs("div", { className: "flex items-center gap-2", children: [headerAddon !== null && headerAddon !== undefined && variant !== "secondary" ? headerAddon : null, jsx(Icon, { ariaLabelledBy: LABEL_ID, className: cvaChevronIcon({ expanded }), name: "ChevronDown", size: variant === "secondary" ? "small" : "medium" })] })] }) }), jsx(Collapsible, { expanded: expanded, extraPadding: extraPadding, id: id, variant: variant, children: expanded || animate ? children : null })] }));
4470
- };
4471
- const Collapsible = ({ children, expanded, id, variant, extraPadding }) => {
4472
- const { geometry, ref } = useMeasure();
4473
- return (jsx("div", { className: cvaCollapseAnimated({ expanded }), id: id, style: { height: expanded ? (geometry?.height ?? "auto") : "0" }, children: jsx("div", { ref: ref, children: jsx("div", { className: cvaCollapsible({ variant, extraPadding }), children: children }) }) }));
4529
+ // Read the live attribute: jsdom fires a plain Event, and queued toggle events can be merged.
4530
+ const nextOpen = event.currentTarget.open;
4531
+ if (nextOpen === isOpen) {
4532
+ // The DOM matches what React rendered: the toggle came from mounting open or from a prop update, or
4533
+ // the section was toggled twice before the browser sent the event and is back where it started.
4534
+ return;
4535
+ }
4536
+ if (!isControlled) {
4537
+ setUncontrolledOpen(nextOpen);
4538
+ }
4539
+ onToggle?.(event, nextOpen);
4540
+ }, [isControlled, isOpen, onToggle]);
4541
+ // Runs in the capture phase, so an addon calling stopPropagation can't skip it.
4542
+ const handleSummaryClickCapture = useCallback((event) => {
4543
+ const interactive = getInteractiveDescendant(event);
4544
+ if (interactive !== null) {
4545
+ // Interactive descendants (e.g. a headerAddon button) keep their own click and don't toggle.
4546
+ // Elements without native activation behaviour would otherwise let the summary toggle.
4547
+ if (!isNativelyActivatable(interactive)) {
4548
+ event.preventDefault();
4549
+ }
4550
+ return;
4551
+ }
4552
+ if (!isControlled) {
4553
+ // The browser toggles and handleToggle reports it.
4554
+ return;
4555
+ }
4556
+ const parent = event.currentTarget.parentElement;
4557
+ const details = parent instanceof HTMLDetailsElement ? parent : null;
4558
+ event.preventDefault();
4559
+ // Toggle from what the user sees. The browser can have moved the section since `expanded` last changed
4560
+ // (find-in-page opening it, a `name` group closing it) without the parent following.
4561
+ const requestedOpen = details !== null ? !details.open : !isOpen;
4562
+ onToggle?.(event, requestedOpen);
4563
+ if (requestedOpen === isOpen && details !== null) {
4564
+ // The parent already holds the requested state, so no render will bring the section back in line.
4565
+ details.open = isOpen;
4566
+ }
4567
+ }, [isControlled, isOpen, onToggle]);
4568
+ return (jsx("div", { className: cvaCollapse({ variant, className }), "data-testid": dataTestId, ref: ref, style: style, children: jsxs("details", { className: cvaCollapseDetails({ animate }), "data-testid": dataTestId ? `${dataTestId}-details` : undefined, name: name, onToggle: handleToggle, open: isOpen, children: [jsx("summary", { className: cvaCollapseHeader({ variant, extraPadding, animate, className: headerClassName }), "data-testid": dataTestId ? `${dataTestId}-header` : undefined, onClickCapture: handleSummaryClickCapture, children: jsxs("div", { className: cvaCollapseLabelContainer({ variant }), children: [jsx(Text, { className: cvaCollapseLabel({ variant }), id: labelId, size: variant === "secondary" ? "small" : "medium", type: "span", weight: "bold", children: label }), jsxs("div", { className: "flex items-center gap-2", children: [headerAddon !== null && headerAddon !== undefined && variant !== "secondary" ? headerAddon : null, jsx(Icon, { ariaHidden: true, className: cvaChevronIcon(), name: "ChevronDown", size: variant === "secondary" ? "small" : "medium" })] })] }) }), jsx("div", { className: cvaCollapseContent({ variant }), "data-testid": dataTestId ? `${dataTestId}-content` : undefined, id: id, children: jsx("div", { className: cvaCollapsible({ variant, extraPadding }), children: !lazy || isOpen ? children : null }) })] }) }));
4474
4569
  };
4475
4570
 
4476
4571
  /**
@@ -9420,6 +9515,80 @@ const PopoverTitle = ({ children, action, divider = false, className, "data-test
9420
9515
  return (jsxs("div", { className: cvaPopoverTitleContainer({ divider, className }), "data-testid": dataTestId, ref: ref, style: style, children: [jsx(Text, { className: cvaPopoverTitleText(), size: "small", subtle: true, type: "div", uppercase: true, weight: "bold", children: children }), action] }));
9421
9516
  };
9422
9517
 
9518
+ /**
9519
+ * Custom hook to measure the geometry of an element using a callback ref.
9520
+ * Measures the size and position of the element relative to the viewport.
9521
+ *
9522
+ * @template TElement extends HTMLElement
9523
+ * @returns {UseMeasureResult<HTMLElement>} An object containing `geometry`, `ref` callback, and `element`.
9524
+ * @example
9525
+ * ```tsx
9526
+ * const { geometry, ref } = useMeasure();
9527
+ * return <div ref={ref}>Width: {geometry.width}</div>;
9528
+ * ```
9529
+ */
9530
+ const useMeasure = ({ skip = false, onChange, } = {}) => {
9531
+ const [element, setElement] = useState(null);
9532
+ const [geometry, setGeometry] = useState(undefined);
9533
+ const observerRef = useRef(null);
9534
+ const onChangeRef = useRef(onChange);
9535
+ const isInitialRender = useRef(true);
9536
+ // Callback ref to track the element
9537
+ const ref = useCallback((node) => {
9538
+ setElement(node);
9539
+ }, []);
9540
+ const disconnectObserver = () => {
9541
+ if (observerRef.current !== null) {
9542
+ observerRef.current.disconnect();
9543
+ observerRef.current = null;
9544
+ }
9545
+ };
9546
+ useEffect(() => {
9547
+ onChangeRef.current = onChange;
9548
+ }, [onChange]);
9549
+ useEffect(() => {
9550
+ if (skip || element === null) {
9551
+ return;
9552
+ }
9553
+ const updateGeometry = (rect) => {
9554
+ const newGeometry = {
9555
+ width: rect.width,
9556
+ height: rect.height,
9557
+ top: rect.top,
9558
+ bottom: rect.bottom,
9559
+ left: rect.left,
9560
+ right: rect.right,
9561
+ x: rect.x,
9562
+ y: rect.y,
9563
+ };
9564
+ setGeometry(prevGeometry => {
9565
+ if (isEqual(prevGeometry, newGeometry)) {
9566
+ return prevGeometry;
9567
+ }
9568
+ if (isInitialRender.current === false) {
9569
+ onChangeRef.current?.(newGeometry);
9570
+ }
9571
+ return newGeometry;
9572
+ });
9573
+ isInitialRender.current = false;
9574
+ };
9575
+ const handleResize = (entries) => {
9576
+ for (const entry of entries) {
9577
+ const rect = entry.target.getBoundingClientRect();
9578
+ updateGeometry(rect);
9579
+ }
9580
+ };
9581
+ disconnectObserver();
9582
+ const observer = new ResizeObserver(handleResize);
9583
+ observer.observe(element);
9584
+ observerRef.current = observer;
9585
+ const initialRect = element.getBoundingClientRect();
9586
+ updateGeometry(initialRect);
9587
+ return disconnectObserver;
9588
+ }, [element, skip]);
9589
+ return useMemo(() => ({ geometry, ref, element }), [geometry, ref, element]);
9590
+ };
9591
+
9423
9592
  const cvaPreferenceCard = cva({
9424
9593
  base: [
9425
9594
  "rounded-lg",
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@trackunit/react-router-components",
3
- "version": "2.0.9",
3
+ "version": "2.0.11",
4
4
  "repository": "https://github.com/Trackunit/manager",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "engines": {
7
7
  "node": ">=24.x"
8
8
  },
9
9
  "dependencies": {
10
- "@trackunit/css-class-variance-utilities": "^2.6.58",
11
- "@trackunit/i18n-library-translation": "^2.14.54",
12
- "@trackunit/react-components": "^7.0.9",
13
- "@trackunit/react-drawer": "^3.0.9",
14
- "@trackunit/shared-utils": "^1.22.58",
10
+ "@trackunit/css-class-variance-utilities": "^2.6.59",
11
+ "@trackunit/i18n-library-translation": "^2.14.55",
12
+ "@trackunit/react-components": "^8.0.0",
13
+ "@trackunit/react-drawer": "^3.0.11",
14
+ "@trackunit/shared-utils": "^1.22.59",
15
15
  "dequal": "^2.0.3",
16
16
  "zod": "^3.25.76"
17
17
  },
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.insertAttributeIntoOpeningTag = exports.logSummary = exports.parseTsx = exports.hasSpreadAttribute = exports.findJsxAttribute = exports.findJsxElements = exports.getLocalAliasFor = exports.getImportedAliases = exports.visitTsFiles = exports.visitTsxFiles = void 0;
36
+ exports.insertAttributeIntoOpeningTag = exports.logSummary = exports.parseTsx = exports.hasSpreadAttribute = exports.findJsxAttribute = exports.findJsxElements = exports.getLocalAliasFor = exports.getImportedAliases = exports.visitTsFiles = exports.visitTsxFiles = exports.isWorkspaceSourceFile = void 0;
37
37
  const devkit_1 = require("@nx/devkit");
38
38
  const ts = __importStar(require("typescript"));
39
39
  const TSX_EXTENSIONS = [".tsx", ".jsx"];
@@ -42,6 +42,12 @@ const isTsxFile = (filePath) => TSX_EXTENSIONS.some(ext => filePath.endsWith(ext
42
42
  const isTsFile = (filePath) => TS_EXTENSIONS.some(ext => filePath.endsWith(ext));
43
43
  const isUnderNodeModules = (filePath) => filePath.includes("/node_modules/") || filePath.startsWith("node_modules/");
44
44
  const isUnderDist = (filePath) => filePath.includes("/dist/") || filePath.startsWith("dist/") || filePath.includes("/.nx/");
45
+ /**
46
+ * Whether a path is a `.ts`/`.tsx`/`.jsx` file that migrations look at: not under `node_modules`, `dist` or `.nx`.
47
+ * Use it when a codemod walks the tree itself instead of going through {@link visitTsFiles}.
48
+ */
49
+ const isWorkspaceSourceFile = (filePath) => isTsFile(filePath) && !isUnderNodeModules(filePath) && !isUnderDist(filePath);
50
+ exports.isWorkspaceSourceFile = isWorkspaceSourceFile;
45
51
  /**
46
52
  * Visits every `.tsx`/`.jsx` file under the workspace root and invokes the
47
53
  * callback with the file path and its current contents. Files that don't
@@ -1 +1 @@
1
- {"version":3,"file":"jsx-utils.js","sourceRoot":"","sources":["../../../../../../libs/react/components/migrations/utils/jsx-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAqE;AACrE,+CAAiC;AAEjC,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,MAAM,CAAU,CAAC;AACjD,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAU,CAAC;AAEvD,MAAM,SAAS,GAAG,CAAC,QAAgB,EAAW,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;AACpG,MAAM,QAAQ,GAAG,CAAC,QAAgB,EAAW,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;AAElG,MAAM,kBAAkB,GAAG,CAAC,QAAgB,EAAW,EAAE,CACvD,QAAQ,CAAC,QAAQ,CAAC,gBAAgB,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC;AAE9E,MAAM,WAAW,GAAG,CAAC,QAAgB,EAAW,EAAE,CAChD,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAA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AACtF,CAAC,CAAC;AARW,QAAA,6BAA6B,iCAQxC","sourcesContent":["import { logger, type Tree, visitNotIgnoredFiles } from \"@nx/devkit\";\nimport * as ts from \"typescript\";\n\nconst TSX_EXTENSIONS = [\".tsx\", \".jsx\"] as const;\nconst TS_EXTENSIONS = [\".ts\", \".tsx\", \".jsx\"] as const;\n\nconst isTsxFile = (filePath: string): boolean => TSX_EXTENSIONS.some(ext => filePath.endsWith(ext));\nconst isTsFile = (filePath: string): boolean => TS_EXTENSIONS.some(ext => filePath.endsWith(ext));\n\nconst isUnderNodeModules = (filePath: string): boolean =>\n filePath.includes(\"/node_modules/\") || filePath.startsWith(\"node_modules/\");\n\nconst isUnderDist = (filePath: string): boolean =>\n filePath.includes(\"/dist/\") || filePath.startsWith(\"dist/\") || filePath.includes(\"/.nx/\");\n\n/**\n * Visits every `.tsx`/`.jsx` file under the workspace root and invokes the\n * callback with the file path and its current contents. Files that don't\n * include the marker substring are skipped, which makes large workspaces\n * cheap to scan.\n */\nexport const visitTsxFiles = (\n tree: Tree,\n marker: string,\n callback: (filePath: string, content: string) => string | null | undefined\n): number => {\n let touched = 0;\n visitNotIgnoredFiles(tree, \"/\", filePath => {\n if (!isTsxFile(filePath)) return;\n if (isUnderNodeModules(filePath) || isUnderDist(filePath)) return;\n const content = tree.read(filePath, \"utf-8\");\n if (content === null) return;\n if (!content.includes(marker)) return;\n const updated = callback(filePath, content);\n if (updated !== null && updated !== undefined && updated !== content) {\n tree.write(filePath, updated);\n touched += 1;\n }\n });\n return touched;\n};\n\n/**\n * Same as {@link visitTsxFiles} but also includes plain `.ts` files. Use this\n * when the codemod also rewrites non-JSX files such as helpers or hooks.\n */\nexport const visitTsFiles = (\n tree: Tree,\n marker: string,\n callback: (filePath: string, content: string) => string | null | undefined\n): number => {\n let touched = 0;\n visitNotIgnoredFiles(tree, \"/\", filePath => {\n if (!isTsFile(filePath)) return;\n if (isUnderNodeModules(filePath) || isUnderDist(filePath)) return;\n const content = tree.read(filePath, \"utf-8\");\n if (content === null) return;\n if (!content.includes(marker)) return;\n const updated = callback(filePath, content);\n if (updated !== null && updated !== undefined && updated !== content) {\n tree.write(filePath, updated);\n touched += 1;\n }\n });\n return touched;\n};\n\n/**\n * Mapping of imported component aliases to their original names for a given\n * package. For `import { IconButton as Btn } from \"@trackunit/react-components\"`\n * this returns `{ Btn: \"IconButton\" }`.\n *\n * Returns `null` when the file imports nothing from the package, which lets\n * callers short-circuit before parsing JSX.\n */\nexport const getImportedAliases = (sourceFile: ts.SourceFile, packageName: string): Record<string, string> | null => {\n const result: Record<string, string> = {};\n let found = false;\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const moduleSpecifier = stmt.moduleSpecifier;\n if (!ts.isStringLiteral(moduleSpecifier)) continue;\n if (moduleSpecifier.text !== packageName) continue;\n\n const namedBindings = stmt.importClause?.namedBindings;\n if (namedBindings === undefined || !ts.isNamedImports(namedBindings)) continue;\n\n for (const element of namedBindings.elements) {\n const localName = element.name.text;\n const importedName = element.propertyName?.text ?? localName;\n result[localName] = importedName;\n found = true;\n }\n }\n\n return found ? result : null;\n};\n\n/**\n * Returns the local alias used in this file for `originalName` when imported\n * from `packageName`, or `null` if the component is not imported.\n */\nexport const getLocalAliasFor = (\n sourceFile: ts.SourceFile,\n packageName: string,\n originalName: string\n): string | null => {\n const aliases = getImportedAliases(sourceFile, packageName);\n if (aliases === null) return null;\n for (const [local, original] of Object.entries(aliases)) {\n if (original === originalName) return local;\n }\n return null;\n};\n\nexport type JsxElementMatch = {\n /** The opening JSX element (the one carrying the attributes). */\n openingElement: ts.JsxOpeningElement | ts.JsxSelfClosingElement;\n /** The full element including children, or the self-closing element. */\n element: ts.JsxElement | ts.JsxSelfClosingElement;\n};\n\n/**\n * Finds every JSX element whose tag name resolves to one of `tagNames`\n * (typically the local aliases returned by {@link getImportedAliases}).\n *\n * The result intentionally includes both opening and full elements so callers\n * can manipulate attributes (via `openingElement`) or wrap/replace the whole\n * element (via `element`).\n */\nexport const findJsxElements = (\n sourceFile: ts.SourceFile,\n tagNames: ReadonlyArray<string>\n): ReadonlyArray<JsxElementMatch> => {\n const matches: Array<JsxElementMatch> = [];\n const tagSet = new Set(tagNames);\n\n const visit = (node: ts.Node): void => {\n if (ts.isJsxSelfClosingElement(node)) {\n if (ts.isIdentifier(node.tagName) && tagSet.has(node.tagName.text)) {\n matches.push({ openingElement: node, element: node });\n }\n } else if (ts.isJsxElement(node)) {\n const opening = node.openingElement;\n if (ts.isIdentifier(opening.tagName) && tagSet.has(opening.tagName.text)) {\n matches.push({ openingElement: opening, element: node });\n }\n }\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n return matches;\n};\n\n/**\n * Looks up a named JSX attribute on the opening element. Returns `null` when\n * the attribute is missing or part of a spread attribute (which we cannot\n * statically inspect).\n */\nexport const findJsxAttribute = (\n openingElement: ts.JsxOpeningElement | ts.JsxSelfClosingElement,\n attributeName: string\n): ts.JsxAttribute | null => {\n for (const attr of openingElement.attributes.properties) {\n if (!ts.isJsxAttribute(attr)) continue;\n if (!ts.isIdentifier(attr.name)) continue;\n if (attr.name.text === attributeName) return attr;\n }\n return null;\n};\n\n/**\n * `true` when the element forwards a spread expression such as `{...rest}`,\n * which means we can't be sure which attributes are actually set.\n */\nexport const hasSpreadAttribute = (openingElement: ts.JsxOpeningElement | ts.JsxSelfClosingElement): boolean => {\n return openingElement.attributes.properties.some(prop => ts.isJsxSpreadAttribute(prop));\n};\n\n/**\n * Parses the file as TSX so JSX is recognised. We do not need a full program\n * here; tsquery's `ast` helper produces a script-kind source file which loses\n * JSX context, so we go through `createSourceFile` directly.\n */\nexport const parseTsx = (content: string, fileName = \"file.tsx\"): ts.SourceFile =>\n ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);\n\n/**\n * Helper for codemods to log a one-line summary at the end of a run. Migration\n * runners aggregate logs per migration, so this keeps output focused.\n */\nexport const logSummary = (migrationName: string, touched: number, manualReviewNeeded?: number): void => {\n if (touched === 0) {\n logger.info(` ${migrationName}: no files changed`);\n return;\n }\n const reviewSuffix =\n manualReviewNeeded !== undefined && manualReviewNeeded > 0\n ? ` (${manualReviewNeeded} location(s) need manual review)`\n : \"\";\n logger.info(` ${migrationName}: updated ${touched} file(s)${reviewSuffix}`);\n};\n\n/**\n * Inserts an attribute string immediately after the tag name (so the new\n * attribute appears first). Returns the resulting source content.\n *\n * The added attribute is rendered verbatim, so callers are responsible for\n * including the leading space (e.g. ` title=\"Close\"`).\n */\nexport const insertAttributeIntoOpeningTag = (\n content: string,\n openingElement: ts.JsxOpeningElement | ts.JsxSelfClosingElement,\n attributeText: string\n): string => {\n const tagName = openingElement.tagName;\n const insertPos = tagName.getEnd();\n return `${content.slice(0, insertPos)} ${attributeText}${content.slice(insertPos)}`;\n};\n"]}
1
+ {"version":3,"file":"jsx-utils.js","sourceRoot":"","sources":["../../../../../../libs/react/components/migrations/utils/jsx-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAqE;AACrE,+CAAiC;AAEjC,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,MAAM,CAAU,CAAC;AACjD,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAU,CAAC;AAEvD,MAAM,SAAS,GAAG,CAAC,QAAgB,EAAW,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;AACpG,MAAM,QAAQ,GAAG,CAAC,QAAgB,EAAW,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;AAElG,MAAM,kBAAkB,GAAG,CAAC,QAAgB,EAAW,EAAE,CACvD,QAAQ,CAAC,QAAQ,CAAC,gBAAgB,CAAC,I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C,KAAK,aAAa,aAAa,OAAO,WAAW,YAAY,EAAE,CAAC,CAAC;AAC/E,CAAC,CAAC;AAVW,QAAA,UAAU,cAUrB;AAEF;;;;;;GAMG;AACI,MAAM,6BAA6B,GAAG,CAC3C,OAAe,EACf,cAA+D,EAC/D,aAAqB,EACb,EAAE;IACV,MAAM,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC;IACvC,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IACnC,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,IAAI,aAAa,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;AACtF,CAAC,CAAC;AARW,QAAA,6BAA6B,iCAQxC","sourcesContent":["import { logger, type Tree, visitNotIgnoredFiles } from \"@nx/devkit\";\nimport * as ts from \"typescript\";\n\nconst TSX_EXTENSIONS = [\".tsx\", \".jsx\"] as const;\nconst TS_EXTENSIONS = [\".ts\", \".tsx\", \".jsx\"] as const;\n\nconst isTsxFile = (filePath: string): boolean => TSX_EXTENSIONS.some(ext => filePath.endsWith(ext));\nconst isTsFile = (filePath: string): boolean => TS_EXTENSIONS.some(ext => filePath.endsWith(ext));\n\nconst isUnderNodeModules = (filePath: string): boolean =>\n filePath.includes(\"/node_modules/\") || filePath.startsWith(\"node_modules/\");\n\nconst isUnderDist = (filePath: string): boolean =>\n filePath.includes(\"/dist/\") || filePath.startsWith(\"dist/\") || filePath.includes(\"/.nx/\");\n\n/**\n * Whether a path is a `.ts`/`.tsx`/`.jsx` file that migrations look at: not under `node_modules`, `dist` or `.nx`.\n * Use it when a codemod walks the tree itself instead of going through {@link visitTsFiles}.\n */\nexport const isWorkspaceSourceFile = (filePath: string): boolean =>\n isTsFile(filePath) && !isUnderNodeModules(filePath) && !isUnderDist(filePath);\n\n/**\n * Visits every `.tsx`/`.jsx` file under the workspace root and invokes the\n * callback with the file path and its current contents. Files that don't\n * include the marker substring are skipped, which makes large workspaces\n * cheap to scan.\n */\nexport const visitTsxFiles = (\n tree: Tree,\n marker: string,\n callback: (filePath: string, content: string) => string | null | undefined\n): number => {\n let touched = 0;\n visitNotIgnoredFiles(tree, \"/\", filePath => {\n if (!isTsxFile(filePath)) return;\n if (isUnderNodeModules(filePath) || isUnderDist(filePath)) return;\n const content = tree.read(filePath, \"utf-8\");\n if (content === null) return;\n if (!content.includes(marker)) return;\n const updated = callback(filePath, content);\n if (updated !== null && updated !== undefined && updated !== content) {\n tree.write(filePath, updated);\n touched += 1;\n }\n });\n return touched;\n};\n\n/**\n * Same as {@link visitTsxFiles} but also includes plain `.ts` files. Use this\n * when the codemod also rewrites non-JSX files such as helpers or hooks.\n */\nexport const visitTsFiles = (\n tree: Tree,\n marker: string,\n callback: (filePath: string, content: string) => string | null | undefined\n): number => {\n let touched = 0;\n visitNotIgnoredFiles(tree, \"/\", filePath => {\n if (!isTsFile(filePath)) return;\n if (isUnderNodeModules(filePath) || isUnderDist(filePath)) return;\n const content = tree.read(filePath, \"utf-8\");\n if (content === null) return;\n if (!content.includes(marker)) return;\n const updated = callback(filePath, content);\n if (updated !== null && updated !== undefined && updated !== content) {\n tree.write(filePath, updated);\n touched += 1;\n }\n });\n return touched;\n};\n\n/**\n * Mapping of imported component aliases to their original names for a given\n * package. For `import { IconButton as Btn } from \"@trackunit/react-components\"`\n * this returns `{ Btn: \"IconButton\" }`.\n *\n * Returns `null` when the file imports nothing from the package, which lets\n * callers short-circuit before parsing JSX.\n */\nexport const getImportedAliases = (sourceFile: ts.SourceFile, packageName: string): Record<string, string> | null => {\n const result: Record<string, string> = {};\n let found = false;\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const moduleSpecifier = stmt.moduleSpecifier;\n if (!ts.isStringLiteral(moduleSpecifier)) continue;\n if (moduleSpecifier.text !== packageName) continue;\n\n const namedBindings = stmt.importClause?.namedBindings;\n if (namedBindings === undefined || !ts.isNamedImports(namedBindings)) continue;\n\n for (const element of namedBindings.elements) {\n const localName = element.name.text;\n const importedName = element.propertyName?.text ?? localName;\n result[localName] = importedName;\n found = true;\n }\n }\n\n return found ? result : null;\n};\n\n/**\n * Returns the local alias used in this file for `originalName` when imported\n * from `packageName`, or `null` if the component is not imported.\n */\nexport const getLocalAliasFor = (\n sourceFile: ts.SourceFile,\n packageName: string,\n originalName: string\n): string | null => {\n const aliases = getImportedAliases(sourceFile, packageName);\n if (aliases === null) return null;\n for (const [local, original] of Object.entries(aliases)) {\n if (original === originalName) return local;\n }\n return null;\n};\n\nexport type JsxElementMatch = {\n /** The opening JSX element (the one carrying the attributes). */\n openingElement: ts.JsxOpeningElement | ts.JsxSelfClosingElement;\n /** The full element including children, or the self-closing element. */\n element: ts.JsxElement | ts.JsxSelfClosingElement;\n};\n\n/**\n * Finds every JSX element whose tag name resolves to one of `tagNames`\n * (typically the local aliases returned by {@link getImportedAliases}).\n *\n * The result intentionally includes both opening and full elements so callers\n * can manipulate attributes (via `openingElement`) or wrap/replace the whole\n * element (via `element`).\n */\nexport const findJsxElements = (\n sourceFile: ts.SourceFile,\n tagNames: ReadonlyArray<string>\n): ReadonlyArray<JsxElementMatch> => {\n const matches: Array<JsxElementMatch> = [];\n const tagSet = new Set(tagNames);\n\n const visit = (node: ts.Node): void => {\n if (ts.isJsxSelfClosingElement(node)) {\n if (ts.isIdentifier(node.tagName) && tagSet.has(node.tagName.text)) {\n matches.push({ openingElement: node, element: node });\n }\n } else if (ts.isJsxElement(node)) {\n const opening = node.openingElement;\n if (ts.isIdentifier(opening.tagName) && tagSet.has(opening.tagName.text)) {\n matches.push({ openingElement: opening, element: node });\n }\n }\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n return matches;\n};\n\n/**\n * Looks up a named JSX attribute on the opening element. Returns `null` when\n * the attribute is missing or part of a spread attribute (which we cannot\n * statically inspect).\n */\nexport const findJsxAttribute = (\n openingElement: ts.JsxOpeningElement | ts.JsxSelfClosingElement,\n attributeName: string\n): ts.JsxAttribute | null => {\n for (const attr of openingElement.attributes.properties) {\n if (!ts.isJsxAttribute(attr)) continue;\n if (!ts.isIdentifier(attr.name)) continue;\n if (attr.name.text === attributeName) return attr;\n }\n return null;\n};\n\n/**\n * `true` when the element forwards a spread expression such as `{...rest}`,\n * which means we can't be sure which attributes are actually set.\n */\nexport const hasSpreadAttribute = (openingElement: ts.JsxOpeningElement | ts.JsxSelfClosingElement): boolean => {\n return openingElement.attributes.properties.some(prop => ts.isJsxSpreadAttribute(prop));\n};\n\n/**\n * Parses the file as TSX so JSX is recognised. We do not need a full program\n * here; tsquery's `ast` helper produces a script-kind source file which loses\n * JSX context, so we go through `createSourceFile` directly.\n */\nexport const parseTsx = (content: string, fileName = \"file.tsx\"): ts.SourceFile =>\n ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);\n\n/**\n * Helper for codemods to log a one-line summary at the end of a run. Migration\n * runners aggregate logs per migration, so this keeps output focused.\n */\nexport const logSummary = (migrationName: string, touched: number, manualReviewNeeded?: number): void => {\n if (touched === 0) {\n logger.info(` ${migrationName}: no files changed`);\n return;\n }\n const reviewSuffix =\n manualReviewNeeded !== undefined && manualReviewNeeded > 0\n ? ` (${manualReviewNeeded} location(s) need manual review)`\n : \"\";\n logger.info(` ${migrationName}: updated ${touched} file(s)${reviewSuffix}`);\n};\n\n/**\n * Inserts an attribute string immediately after the tag name (so the new\n * attribute appears first). Returns the resulting source content.\n *\n * The added attribute is rendered verbatim, so callers are responsible for\n * including the leading space (e.g. ` title=\"Close\"`).\n */\nexport const insertAttributeIntoOpeningTag = (\n content: string,\n openingElement: ts.JsxOpeningElement | ts.JsxSelfClosingElement,\n attributeText: string\n): string => {\n const tagName = openingElement.tagName;\n const insertPos = tagName.getEnd();\n return `${content.slice(0, insertPos)} ${attributeText}${content.slice(insertPos)}`;\n};\n"]}