Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix: catch unstable merged refs (#5429)

nynexman44647a9ff42ba907
diff --git a/.changeset/stabilize-hoisted-merged-refs.md b/.changeset/stabilize-hoisted-merged-refs.md
new file mode 100644
index 0000000000..6941e6ea65
--- /dev/null
+++ b/.changeset/stabilize-hoisted-merged-refs.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Keep merged refs stable across Avatar, Button, SideNav, TabList, and TopNav.
+
+@nynexman4464
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index c853b691aa..091c922f81 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -249,11 +249,12 @@ Style objects imported from another module are read from that module, so
rewrite that moves the styles onto the child. Removing a node can shift layout,
so it is never applied by `--fix`.
-### `@astryx/no-inline-merge-refs`
+### `@astryx/no-unstable-merged-refs`
Flags two unstable ref-composition patterns:
-1. `mergeRefs(...)` inside a JSX `ref` prop. Calling the utility during render
+1. `mergeRefs(...)` used by a JSX `ref` prop, whether the call appears inline
+ or is first assigned to a local variable. Calling the utility during render
creates a new callback ref every time, so React detaches and reattaches the
element on unrelated rerenders.
2. An inline callback passed to `useMergedRefs(...)`. The changing input makes
@@ -264,6 +265,8 @@ Use `useMergedRefs(...)` with stable ref inputs instead.
```tsx
// Bad
<div ref={mergeRefs(forwardedRef, internalRef)} />;
+const mergedRef = mergeRefs(forwardedRef, internalRef);
+<div ref={mergedRef} />;
useMergedRefs(forwardedRef, node => setNode(node));
// Good — the hook itself may be called inline when Hooks ordering is valid
@@ -274,8 +277,8 @@ const ref = useMergedRefs(forwardedRef, internalRef);
<div ref={ref} />;
```
-The rule is an error in both tiers because core contains no inline
-`mergeRefs(...)` JSX callsites.
+The rule is an error in both tiers because core contains no render-time
+`mergeRefs(...)` JSX ref callsites.
### `@astryx/require-letter-spacing`
@@ -552,7 +555,9 @@ Breadcrumbs shipped the second shape. Both halves read as correct in review, and
```tsx
<button
- {...mergeProps(themeProps('breadcrumb-item-menu-trigger'), {...popover.triggerProps})}
+ {...mergeProps(themeProps('breadcrumb-item-menu-trigger'), {
+ ...popover.triggerProps,
+ })}
{...stylex.props(itemStyles.link, itemStyles.buttonReset)}
/>
```
diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.js
index 5e64105c9b..4f19bb3f21 100644
--- a/internal/eslint-plugin-astryx/index.js
+++ b/internal/eslint-plugin-astryx/index.js
@@ -17,7 +17,7 @@
* - no-hover-on-disabled: Flags a :hover condition that can still match a disabled element (browsers suppress a disabled control's events, not its hover styling)
* - require-table-section: Requires TableRow/tr to sit inside TableHeader/TableBody/TableFooter (a row directly inside a table emits <table><tr>, which browsers repair on parse and React does not)
* - disabled-cursor: Flags a cursor that promises an interaction without giving way to not-allowed on a disabled element
- * - no-inline-merge-refs: Flags mergeRefs calls inside JSX ref props (use useMergedRefs for stable identity)
+ * - no-unstable-merged-refs: Flags render-time mergeRefs callbacks and unstable callback inputs to useMergedRefs
*
* Philosophy: Strict for agents (CI), lenient for humans (local dev)
* - "strict" config: All rules as errors - use in CI/agent environments
@@ -44,7 +44,7 @@ import focusOutlineSharedRule from './focus-outline-shared.js';
import noHoverOnDisabledRule from './no-hover-on-disabled.js';
import disabledCursorRule from './disabled-cursor.js';
import noReactNamespaceHooksRule from './no-react-namespace-hooks.js';
-import noInlineMergeRefsRule from './no-inline-merge-refs.js';
+import noUnstableMergedRefsRule from './no-unstable-merged-refs.js';
import copyrightHeaderRule from './copyright-header.js';
import noRawConsoleCliRule from './no-raw-console-cli.js';
import requireBasePropsRule from './require-base-props.js';
@@ -64,7 +64,10 @@ const STYLE_PROPERTIES = {
pattern: /^['"]?\d+(\.\d+)?(px|rem|em)['"]?$/,
tokenVar: 'textSizeVars',
message: 'Use textSizeVars token instead of hardcoded fontSize',
- examples: ["textSizeVars['--font-size-xs']", "textSizeVars['--font-size-base']"],
+ examples: [
+ "textSizeVars['--font-size-xs']",
+ "textSizeVars['--font-size-base']",
+ ],
},
fontWeight: {
pattern: /^\d{3}$/,
@@ -85,20 +88,76 @@ const STYLE_PROPERTIES = {
message: 'Use spacingVars token instead of hardcoded padding',
examples: ["spacingVars['--spacing-2']"],
},
- paddingTop: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- paddingRight: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- paddingBottom: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- paddingLeft: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- paddingBlock: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- paddingInline: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- margin: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- marginTop: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- marginRight: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- marginBottom: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- marginLeft: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- marginBlock: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- marginInline: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
- gap: { pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/, tokenVar: 'spacingVars', message: 'Use spacingVars token' },
+ paddingTop: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ paddingRight: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ paddingBottom: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ paddingLeft: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ paddingBlock: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ paddingInline: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ margin: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ marginTop: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ marginRight: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ marginBottom: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ marginLeft: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ marginBlock: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ marginInline: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
+ gap: {
+ pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
+ tokenVar: 'spacingVars',
+ message: 'Use spacingVars token',
+ },
// Border radius
borderRadius: {
pattern: /^['"]?\d+(\.\d+)?(px|rem)['"]?$/,
@@ -128,8 +187,18 @@ const STYLE_PROPERTIES = {
// Properties to skip (these are typically fine as hardcoded values)
const SKIP_VALUES = [
- '0', '0px', 'inherit', 'initial', 'unset', 'auto', 'none',
- '100%', '50%', '0%', 'transparent', 'currentColor',
+ '0',
+ '0px',
+ 'inherit',
+ 'initial',
+ 'unset',
+ 'auto',
+ 'none',
+ '100%',
+ '50%',
+ '0%',
+ 'transparent',
+ 'currentColor',
];
/**
@@ -168,7 +237,8 @@ const noHardcodedStylesRule = {
meta: {
type: 'suggestion',
docs: {
- description: 'Enforce usage of Astryx design tokens instead of hardcoded values in StyleX',
+ description:
+ 'Enforce usage of Astryx design tokens instead of hardcoded values in StyleX',
category: 'Best Practices',
recommended: true,
},
@@ -183,7 +253,7 @@ const noHardcodedStylesRule = {
// Allow specific properties to be ignored
ignore: {
type: 'array',
- items: { type: 'string' },
+ items: {type: 'string'},
},
},
additionalProperties: false,
@@ -272,7 +342,7 @@ const plugin = {
'no-hover-on-disabled': noHoverOnDisabledRule,
'disabled-cursor': disabledCursorRule,
'no-react-namespace-hooks': noReactNamespaceHooksRule,
- 'no-inline-merge-refs': noInlineMergeRefsRule,
+ 'no-unstable-merged-refs': noUnstableMergedRefsRule,
'require-base-props': requireBasePropsRule,
'require-ref-prop': requireRefPropRule,
'copyright-header': copyrightHeaderRule,
@@ -341,7 +411,7 @@ plugin.configs.strict = {
// honour. Error in both tiers, and autofixable.
'@astryx/disabled-cursor': 'error',
'@astryx/no-react-namespace-hooks': 'error',
- '@astryx/no-inline-merge-refs': 'error',
+ '@astryx/no-unstable-merged-refs': 'error',
'@astryx/require-base-props': 'error',
'@astryx/require-ref-prop': 'error',
'@astryx/copyright-header': 'error',
@@ -399,7 +469,7 @@ plugin.configs.recommended = {
// honour. Error in both tiers, and autofixable.
'@astryx/disabled-cursor': 'error',
'@astryx/no-react-namespace-hooks': 'error',
- '@astryx/no-inline-merge-refs': 'error',
+ '@astryx/no-unstable-merged-refs': 'error',
'@astryx/require-base-props': 'warn',
'@astryx/require-ref-prop': 'warn',
'@astryx/copyright-header': 'error',
diff --git a/internal/eslint-plugin-astryx/no-inline-merge-refs.js b/internal/eslint-plugin-astryx/no-inline-merge-refs.js
deleted file mode 100644
index c870e59be9..0000000000
--- a/internal/eslint-plugin-astryx/no-inline-merge-refs.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file no-inline-merge-refs.js
- * @description Prevents unstable ref composition during render.
- */
-
-const noInlineMergeRefsRule = {
- meta: {
- type: 'problem',
- docs: {
- description:
- 'Prevent render-inline mergeRefs calls and unstable callback arguments to useMergedRefs',
- category: 'Astryx Conventions',
- recommended: true,
- },
- messages: {
- useHook:
- 'Do not call mergeRefs inside a JSX ref prop. Use useMergedRefs so the callback ref remains stable across rerenders.',
- stableInput:
- 'Do not pass an inline callback to useMergedRefs. Pass a stable ref directly or memoize the callback first.',
- },
- schema: [],
- },
- create(context) {
- const importedMergeRefs = new Set();
- const importedUseMergedRefs = new Set();
-
- function isInsideRefAttribute(node) {
- let current = node.parent;
- while (current) {
- if (current.type === 'JSXExpressionContainer') {
- const attribute = current.parent;
- return (
- attribute?.type === 'JSXAttribute' &&
- attribute.name?.type === 'JSXIdentifier' &&
- attribute.name.name === 'ref'
- );
- }
- current = current.parent;
- }
- return false;
- }
-
- return {
- ImportDeclaration(node) {
- for (const specifier of node.specifiers) {
- if (
- specifier.type !== 'ImportSpecifier' ||
- specifier.imported.type !== 'Identifier'
- ) {
- continue;
- }
- if (specifier.imported.name === 'mergeRefs') {
- importedMergeRefs.add(specifier.local.name);
- } else if (specifier.imported.name === 'useMergedRefs') {
- importedUseMergedRefs.add(specifier.local.name);
- }
- }
- },
- CallExpression(node) {
- if (node.callee.type !== 'Identifier') {
- return;
- }
- if (
- importedMergeRefs.has(node.callee.name) &&
- isInsideRefAttribute(node)
- ) {
- context.report({node, messageId: 'useHook'});
- return;
- }
- if (importedUseMergedRefs.has(node.callee.name)) {
- for (const argument of node.arguments) {
- if (
- argument.type === 'ArrowFunctionExpression' ||
- argument.type === 'FunctionExpression'
- ) {
- context.report({node: argument, messageId: 'stableInput'});
- }
- }
- }
- },
- };
- },
-};
-
-export default noInlineMergeRefsRule;
diff --git a/internal/eslint-plugin-astryx/no-unstable-merged-refs.js b/internal/eslint-plugin-astryx/no-unstable-merged-refs.js
new file mode 100644
index 0000000000..6416b55702
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-unstable-merged-refs.js
@@ -0,0 +1,165 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-unstable-merged-refs.js
+ * @description Prevents unstable ref composition during render.
+ */
+
+const noUnstableMergedRefsRule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Prevent render-time mergeRefs calls used as JSX refs and unstable callback arguments to useMergedRefs',
+ category: 'Astryx Conventions',
+ recommended: true,
+ },
+ messages: {
+ useHook:
+ 'Do not create a JSX ref with mergeRefs during render. Use useMergedRefs so the callback ref remains stable across rerenders.',
+ stableInput:
+ 'Do not pass an inline callback to useMergedRefs. Pass a stable ref directly or memoize the callback first.',
+ },
+ schema: [],
+ },
+ create(context) {
+ const sourceCode = context.sourceCode ?? context.getSourceCode();
+ const mergeRefsVariables = new Map();
+ const reportedMergeRefsVariables = new WeakSet();
+
+ function findRefAttribute(node) {
+ let current = node.parent;
+ while (current) {
+ if (current.type === 'JSXExpressionContainer') {
+ const attribute = current.parent;
+ return attribute?.type === 'JSXAttribute' &&
+ attribute.name?.type === 'JSXIdentifier' &&
+ attribute.name.name === 'ref'
+ ? attribute
+ : null;
+ }
+ current = current.parent;
+ }
+ return null;
+ }
+
+ function findReferencedVariable(identifier) {
+ let scope = sourceCode.getScope(identifier);
+ while (scope) {
+ const variable = scope.set?.get(identifier.name);
+ if (variable) {
+ return variable.references.some(
+ reference => reference.identifier === identifier,
+ )
+ ? variable
+ : null;
+ }
+ scope = scope.upper;
+ }
+ return null;
+ }
+
+ function isNamedImport(identifier, importedName) {
+ const variable = findReferencedVariable(identifier);
+ return variable?.defs.some(
+ definition =>
+ definition.type === 'ImportBinding' &&
+ definition.node.type === 'ImportSpecifier' &&
+ definition.node.imported.type === 'Identifier' &&
+ definition.node.imported.name === importedName,
+ );
+ }
+
+ function unwrap(node) {
+ let current = node;
+ while (
+ current &&
+ (current.type === 'TSAsExpression' ||
+ current.type === 'TSSatisfiesExpression' ||
+ current.type === 'TSNonNullExpression')
+ ) {
+ current = current.expression;
+ }
+ return current;
+ }
+
+ function enclosingFunction(node) {
+ let current = node.parent;
+ while (current) {
+ if (
+ current.type === 'ArrowFunctionExpression' ||
+ current.type === 'FunctionDeclaration' ||
+ current.type === 'FunctionExpression'
+ ) {
+ return current;
+ }
+ current = current.parent;
+ }
+ return null;
+ }
+
+ return {
+ VariableDeclarator(node) {
+ const initializer = unwrap(node.init);
+ const declarationFunction = enclosingFunction(node);
+ if (
+ node.id.type !== 'Identifier' ||
+ initializer?.type !== 'CallExpression' ||
+ initializer.callee.type !== 'Identifier' ||
+ !isNamedImport(initializer.callee, 'mergeRefs') ||
+ declarationFunction == null
+ ) {
+ return;
+ }
+ const [variable] = sourceCode.getDeclaredVariables(node);
+ if (variable) {
+ mergeRefsVariables.set(variable, {
+ call: initializer,
+ functionNode: declarationFunction,
+ });
+ }
+ },
+ Identifier(node) {
+ if (findRefAttribute(node) == null) {
+ return;
+ }
+ const variable = findReferencedVariable(node);
+ const declaration = variable
+ ? mergeRefsVariables.get(variable)
+ : undefined;
+ if (
+ variable &&
+ declaration?.functionNode === enclosingFunction(node) &&
+ !reportedMergeRefsVariables.has(variable)
+ ) {
+ reportedMergeRefsVariables.add(variable);
+ context.report({node: declaration.call, messageId: 'useHook'});
+ }
+ },
+ CallExpression(node) {
+ if (node.callee.type !== 'Identifier') {
+ return;
+ }
+ if (
+ isNamedImport(node.callee, 'mergeRefs') &&
+ findRefAttribute(node) != null
+ ) {
+ context.report({node, messageId: 'useHook'});
+ return;
+ }
+ if (isNamedImport(node.callee, 'useMergedRefs')) {
+ for (const argument of node.arguments) {
+ if (
+ argument.type === 'ArrowFunctionExpression' ||
+ argument.type === 'FunctionExpression'
+ ) {
+ context.report({node: argument, messageId: 'stableInput'});
+ }
+ }
+ }
+ },
+ };
+ },
+};
+
+export default noUnstableMergedRefsRule;
diff --git a/internal/eslint-plugin-astryx/no-inline-merge-refs.test.mjs b/internal/eslint-plugin-astryx/no-unstable-merged-refs.test.mjs
similarity index 52%
rename from internal/eslint-plugin-astryx/no-inline-merge-refs.test.mjs
rename to internal/eslint-plugin-astryx/no-unstable-merged-refs.test.mjs
index f320198eec..2e27fa975d 100644
--- a/internal/eslint-plugin-astryx/no-inline-merge-refs.test.mjs
+++ b/internal/eslint-plugin-astryx/no-unstable-merged-refs.test.mjs
@@ -1,21 +1,23 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file no-inline-merge-refs.test.mjs
+ * @file no-unstable-merged-refs.test.mjs
*/
import {RuleTester} from 'eslint';
-import rule from './no-inline-merge-refs.js';
+import tsParser from '@typescript-eslint/parser';
+import rule from './no-unstable-merged-refs.js';
const ruleTester = new RuleTester({
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
+ parser: tsParser,
parserOptions: {ecmaFeatures: {jsx: true}},
},
});
-ruleTester.run('no-inline-merge-refs', rule, {
+ruleTester.run('no-unstable-merged-refs', rule, {
valid: [
{
code: `
@@ -39,6 +41,33 @@ ruleTester.run('no-inline-merge-refs', rule, {
}
`,
},
+ {
+ code: `
+ import {mergeRefs} from '../utils';
+ const mergedRef = mergeRefs(forwardedRef, internalRef);
+ function Component({mergedRef}) {
+ return <div ref={mergedRef} />;
+ }
+ `,
+ },
+ {
+ code: `
+ import {mergeRefs} from '../utils';
+ const mergedRef = mergeRefs(forwardedRef, internalRef);
+ function Component() {
+ return <div ref={mergedRef} />;
+ }
+ `,
+ },
+ {
+ code: `
+ import {mergeRefs} from '../utils';
+ function Component(mergeRefs) {
+ const mergedRef = mergeRefs(forwardedRef, internalRef);
+ return <div ref={mergedRef} />;
+ }
+ `,
+ },
{
code: `
function mergeRefs() {}
@@ -57,6 +86,39 @@ ruleTester.run('no-inline-merge-refs', rule, {
`,
errors: [{messageId: 'useHook'}],
},
+ {
+ code: `
+ import {mergeRefs} from '../utils';
+ function Component() {
+ const mergedRef = mergeRefs(forwardedRef, internalRef);
+ return <div ref={mergedRef} />;
+ }
+ `,
+ errors: [{messageId: 'useHook'}],
+ },
+ {
+ code: `
+ import {mergeRefs as combineRefs} from '@astryxdesign/core/utils';
+ function Component() {
+ const mergedRef = combineRefs(forwardedRef, internalRef);
+ return <div ref={enabled ? mergedRef : forwardedRef} />;
+ }
+ `,
+ errors: [{messageId: 'useHook'}],
+ },
+ {
+ code: `
+ import {mergeRefs} from '../utils';
+ function Component() {
+ const mergedRef = mergeRefs(
+ forwardedRef,
+ internalRef,
+ ) as React.Ref<HTMLDivElement>;
+ return <div ref={mergedRef!} />;
+ }
+ `,
+ errors: [{messageId: 'useHook'}],
+ },
{
code: `
import {mergeRefs as combineRefs} from '@astryxdesign/core/utils';
diff --git a/packages/core/src/Avatar/Avatar.test.tsx b/packages/core/src/Avatar/Avatar.test.tsx
index 3be98ee700..c382581934 100644
--- a/packages/core/src/Avatar/Avatar.test.tsx
+++ b/packages/core/src/Avatar/Avatar.test.tsx
@@ -569,6 +569,23 @@ describe('Avatar', () => {
render(<Avatar name="Ada Lovelace" ref={ref} data-testid="a" />);
expect(ref.current).toBe(screen.getByTestId('a'));
});
+
+ it('keeps its merged ref attached across unrelated rerenders', () => {
+ const ref = vi.fn();
+ const {rerender} = render(
+ <Avatar name="Ada Lovelace" size="sm" tooltip={false} ref={ref} />,
+ );
+ const avatar = screen.getByRole('img', {name: 'Ada Lovelace'});
+ expect(ref).toHaveBeenLastCalledWith(avatar);
+ ref.mockClear();
+
+ rerender(
+ <Avatar name="Ada Lovelace" size="lg" tooltip={false} ref={ref} />,
+ );
+
+ expect(ref).not.toHaveBeenCalled();
+ expect(screen.getByRole('img', {name: 'Ada Lovelace'})).toBe(avatar);
+ });
});
});
diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsx
index e282f9c941..3e68db711a 100644
--- a/packages/core/src/Avatar/Avatar.tsx
+++ b/packages/core/src/Avatar/Avatar.tsx
@@ -19,7 +19,14 @@
* Last synced props: alt, fallbackSrc, name, size, src, status, href, as, target, rel, onClick
*/
-import {isValidElement, useMemo, useRef, useState, type ReactNode} from 'react';
+import {
+ isValidElement,
+ useCallback,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
import type {BaseProps} from '../BaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -34,7 +41,8 @@ import {
type AvatarStatusLabelTarget,
} from './AvatarStatusLabelContext';
import {useAvatarGroup} from '../AvatarGroup/AvatarGroupContext';
-import {mergeProps, mergeRefs} from '../utils';
+import {mergeProps} from '../utils';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import {themeProps} from '../utils/themeProps';
import {firstCharacter} from '../utils/characters';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
@@ -608,47 +616,62 @@ export function Avatar({
label: undefined,
update: null,
});
- // A fresh callback ref every render, so React reattaches it on every commit
- // and the name is recomposed after React has written this render's props.
+ const {
+ 'aria-hidden': consumerAriaHidden,
+ 'aria-label': consumerAriaLabel,
+ role: consumerRole,
+ } = props;
+ // Recompose the name after React has written any relevant prop changes.
// `update` covers the other direction: a label that changes while the avatar
// itself does not re-render.
- const nameRef = (element: HTMLElement | null) => {
- if (element == null) {
- return;
- }
- const target = statusLabelRef.current;
- target.update = () => {
- const composed = composeAccessibleName(
- t,
- nameLabel,
- meaningful(target.label) ?? getStatusLabel(status),
- );
- // A consumer's own ARIA wins here exactly as it does in render, where
- // the derived props spread before `{...props}`.
- if (props['aria-label'] == null) {
- setAttributeOrRemove(element, 'aria-label', composed);
+ const nameRef = useCallback(
+ (element: HTMLElement | null) => {
+ if (element == null) {
+ return;
}
- // An `<a>`/`<button>` root carries its own role and must not be hidden,
- // so only the name transfers there.
- if (!isInteractive) {
- if (props.role == null) {
- element.setAttribute('role', composed ? 'img' : 'presentation');
+ const target = statusLabelRef.current;
+ target.update = () => {
+ const composed = composeAccessibleName(
+ t,
+ nameLabel,
+ meaningful(target.label) ?? getStatusLabel(status),
+ );
+ // A consumer's own ARIA wins here exactly as it does in render, where
+ // the derived props spread before `{...props}`.
+ if (consumerAriaLabel == null) {
+ setAttributeOrRemove(element, 'aria-label', composed);
}
- if (props['aria-hidden'] == null) {
- setAttributeOrRemove(
- element,
- 'aria-hidden',
- composed ? undefined : 'true',
- );
+ // An `<a>`/`<button>` root carries its own role and must not be hidden,
+ // so only the name transfers there.
+ if (!isInteractive) {
+ if (consumerRole == null) {
+ element.setAttribute('role', composed ? 'img' : 'presentation');
+ }
+ if (consumerAriaHidden == null) {
+ setAttributeOrRemove(
+ element,
+ 'aria-hidden',
+ composed ? undefined : 'true',
+ );
+ }
}
- }
- };
- target.update();
- return () => {
- target.update = null;
- };
- };
- const rootRef = mergeRefs(
+ };
+ target.update();
+ return () => {
+ target.update = null;
+ };
+ },
+ [
+ consumerAriaHidden,
+ consumerAriaLabel,
+ consumerRole,
+ isInteractive,
+ nameLabel,
+ status,
+ t,
+ ],
+ );
+ const rootRef = useMergedRefs(
ref,
showTooltip ? tooltipHook.ref : undefined,
nameRef,
diff --git a/packages/core/src/Button/Button.test.tsx b/packages/core/src/Button/Button.test.tsx
index c4a1a1ea78..4ffac1fe3e 100644
--- a/packages/core/src/Button/Button.test.tsx
+++ b/packages/core/src/Button/Button.test.tsx
@@ -151,6 +151,19 @@ describe('Button', () => {
expect(ref).toHaveBeenCalledWith(expect.any(HTMLButtonElement));
});
+ it('keeps its merged ref attached across unrelated rerenders', () => {
+ const ref = vi.fn();
+ const {rerender} = render(<Button label="Test" ref={ref} />);
+ const button = screen.getByRole('button');
+ expect(ref).toHaveBeenLastCalledWith(button);
+ ref.mockClear();
+
+ rerender(<Button label="Test" variant="primary" ref={ref} />);
+
+ expect(ref).not.toHaveBeenCalled();
+ expect(screen.getByRole('button')).toBe(button);
+ });
+
// endContent tests
it('renders endContent after label', () => {
render(
diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx
index f1010407e9..8a70a00dcf 100644
--- a/packages/core/src/Button/Button.tsx
+++ b/packages/core/src/Button/Button.tsx
@@ -42,7 +42,8 @@ import {VisuallyHidden} from '../VisuallyHidden';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {useSize} from '../SizeContext/SizeContext';
import {useButtonGroup} from '../ButtonGroup/ButtonGroupContext';
-import {mergeProps, mergeRefs} from '../utils';
+import {mergeProps} from '../utils';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
import {themeProps} from '../utils/themeProps';
@@ -757,9 +758,9 @@ export function Button({
: null;
// Merge the consumer ref with the tooltip hook's trigger ref so both point at
- // the same element. mergeRefs tolerates undefined, so this is a no-op for the
- // tooltip side when no tooltip is set.
- const mergedButtonRef = mergeRefs(
+ // the same element. useMergedRefs tolerates undefined, so this is a no-op for
+ // the tooltip side when no tooltip is set.
+ const mergedButtonRef = useMergedRefs(
ref,
tooltip != null ? tooltipHook.ref : undefined,
);
diff --git a/packages/core/src/SideNav/SideNavHeading.tsx b/packages/core/src/SideNav/SideNavHeading.tsx
index d0b625c95d..fe90aa8ae8 100644
--- a/packages/core/src/SideNav/SideNavHeading.tsx
+++ b/packages/core/src/SideNav/SideNavHeading.tsx
@@ -40,7 +40,8 @@ import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useSideNavCollapse} from './SideNavCollapseContext';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
-import {mergeProps, mergeRefs} from '../utils';
+import {mergeProps} from '../utils';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import type {BaseProps} from '../BaseProps';
import {useMenuHover} from '../hooks/useMenuHover';
import {NavHeadingCloseContext} from '../NavMenu/NavMenuContext';
@@ -399,11 +400,18 @@ export function SideNavHeading({
// setTriggerEl belongs on the chevron button, not this root: it is the
// focus-restore target and a <div> cannot take focus. triggerRef stays here
// because the panel anchors to the whole heading.
- const setRef = mergeRefs<HTMLDivElement>(
+ const setRef = useMergedRefs<HTMLDivElement>(
rootRef,
ref,
menu ? popover.triggerRef : undefined,
);
+ const collapsedSetRef = useMergedRefs<HTMLElement>(
+ collapsedItemRef,
+ ref,
+ // Collapsed, this button is the trigger, so it takes both roles.
+ menu ? popover.triggerRef : undefined,
+ menu ? setTriggerEl : undefined,
+ );
// In collapsed mode: hide if no icon, show icon-only if has icon
if (isCollapsed && !icon) {
@@ -412,14 +420,6 @@ export function SideNavHeading({
if (isCollapsed && icon) {
const collapsedIcon = <span {...stylex.props(styles.icon)}>{icon}</span>;
- const collapsedSetRef = mergeRefs<HTMLElement>(
- collapsedItemRef,
- ref,
- // Collapsed, this button is the trigger, so it takes both roles.
- menu ? popover.triggerRef : undefined,
- menu ? setTriggerEl : undefined,
- );
-
let collapsedElement: ReactNode;
if (headingHref) {
diff --git a/packages/core/src/TabList/TabMenu.tsx b/packages/core/src/TabList/TabMenu.tsx
index 261509781d..e2cb390a85 100644
--- a/packages/core/src/TabList/TabMenu.tsx
+++ b/packages/core/src/TabList/TabMenu.tsx
@@ -37,7 +37,8 @@ import {useListFocus} from '../hooks/useListFocus';
import {useTabListContext} from './TabListContext';
import type {TabListSize} from './TabListContext';
import {tabScope} from './tab.markers.stylex';
-import {mergeProps, mergeRefs} from '../utils';
+import {mergeProps} from '../utils';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
@@ -336,7 +337,7 @@ export function TabMenu({
[tabListCtx, popover],
);
- const setButtonRef = mergeRefs<HTMLButtonElement>(
+ const setButtonRef = useMergedRefs<HTMLButtonElement>(
popover.triggerRef,
buttonRef,
ref,
diff --git a/packages/core/src/TopNav/TopNavHeading.tsx b/packages/core/src/TopNav/TopNavHeading.tsx
index 77519b62f1..cdb5b2f434 100644
--- a/packages/core/src/TopNav/TopNavHeading.tsx
+++ b/packages/core/src/TopNav/TopNavHeading.tsx
@@ -34,7 +34,8 @@ import {Link} from '../Link';
import {Icon} from '../Icon';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
-import {mergeProps, mergeRefs} from '../utils';
+import {mergeProps} from '../utils';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import type {BaseProps} from '../BaseProps';
import {useMenuHover} from '../hooks/useMenuHover';
import {NavHeadingCloseContext} from '../NavMenu/NavMenuContext';
@@ -363,7 +364,7 @@ export function TopNavHeading({
// setTriggerEl belongs on the chevron button, not this root: it is the
// focus-restore target and a <div> cannot take focus. triggerRef stays here
// because the panel anchors to the whole heading.
- const setRef = mergeRefs<HTMLElement>(
+ const setRef = useMergedRefs<HTMLElement>(
rootRef,
ref,
menu ? popover.triggerRef : undefined,
diff --git a/packages/core/src/TopNav/TopNavMenu.tsx b/packages/core/src/TopNav/TopNavMenu.tsx
index bd2d4890ab..8e4b64cf90 100644
--- a/packages/core/src/TopNav/TopNavMenu.tsx
+++ b/packages/core/src/TopNav/TopNavMenu.tsx
@@ -29,7 +29,8 @@ import {useMenuHover} from '../hooks/useMenuHover';
import {useListFocus} from '../hooks/useListFocus';
import {useTypeahead} from '../hooks/useTypeahead';
import {Icon} from '../Icon';
-import {mergeProps, mergeRefs} from '../utils';
+import {mergeProps} from '../utils';
+import {useMergedRefs} from '../hooks/useMergedRefs';
import type {BaseProps} from '../BaseProps';
import {navItemStyles} from '../NavItem/navItemStyles.stylex';
import {useTopNavSlot} from './TopNavContext';
@@ -361,7 +362,7 @@ export function TopNavMenu({
popoverId: popover.id,
});
- const setTriggerRef = mergeRefs<HTMLButtonElement>(
+ const setTriggerRef = useMergedRefs<HTMLButtonElement>(
triggerButtonRef,
popover.triggerRef,
setTriggerEl,
@@ -426,7 +427,7 @@ export function TopNavMenu({
// Menu container carries both the hover hook's ref (for its open/close
// focus management) and the list-focus ref (for roving tabindex/typeahead).
- const setMenuRef = mergeRefs<HTMLDivElement>(menuRef, listRef);
+ const setMenuRef = useMergedRefs<HTMLDivElement>(menuRef, listRef);
// Mobile bar: hide menus entirely
if (renderMode === 'mobile-bar') {