An open source design system that's fully customizable and agent ready
TypeScript
fix(ButtonGroup): round the trailing corner when the last member renders a layer (#2508) (#3844)
AK22e2da84c0ea
diff --git a/.changeset/buttongroup-trailing-radius.md b/.changeset/buttongroup-trailing-radius.mdnew file mode 100644index 0000000000..35482e54ea--- /dev/null+++ b/.changeset/buttongroup-trailing-radius.md@@ -0,0 +1,15 @@+---+'@astryxdesign/core': patch+---++[fix] Round the trailing corner of the last ButtonGroup member, even when it renders a layer (#2508)++ButtonGroup keyed its trailing border-radius off `:last-child`. But several members render an invisible layer element _after_ their button — a `Button` with a `tooltip` returns `button + tooltip layer`, and `DropdownMenu` returns `trigger + popover`, both rendered inline by `useLayer` rather than portaled. The layer took the `:last-child` slot, so the real trailing button silently kept square outer corners and the group ended in a flat-edged stub.++Layers always carry the native `popover` attribute, and a popover is never an in-flow member of the group. So the trailing radius now keys off `:not(:has(~ *:not([popover])))` — "no following element sibling that isn't a popover". Any sibling the group doesn't recognise still counts as a member, exactly as `:last-child` did. The leading edge still uses `:first-child`, which was never affected.++This also fixes the plain case of a tooltip'd icon button at the end of a toolbar group, and makes `<ButtonGroup><Button /><DropdownMenu /></ButtonGroup>` compose as a single connected control.++Browser note: the trailing radius now depends on `:has()`. This is not a new floor for the package — shipped CSS already relies on `:has()` (`InputGroup`, `Layout`'s edge compensation) — but it does change how ButtonGroup degrades: on browsers without `:has()` support (Firefox < 121), the trailing corner falls back to square for every member, where the no-layer case previously rounded. The degradation is cosmetic and graceful; nothing overflows or overlaps.++@AKnassadiff --git a/apps/storybook/stories/ButtonGroup.stories.tsx b/apps/storybook/stories/ButtonGroup.stories.tsxindex 307653d1df..dfc90f1280 100644--- a/apps/storybook/stories/ButtonGroup.stories.tsx+++ b/apps/storybook/stories/ButtonGroup.stories.tsx@@ -5,6 +5,7 @@ import {ButtonGroup} from '@astryxdesign/core/ButtonGroup';import {Button} from '@astryxdesign/core/Button';import {IconButton} from '@astryxdesign/core/IconButton';import {Icon} from '@astryxdesign/core/Icon';+import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';import {ClipboardDocumentIcon,ScissorsIcon,@@ -36,10 +37,7 @@ const iconSize = {width: 16, height: 16} as const;export const Horizontal: Story = {render: () => (<ButtonGroup label="Clipboard actions">- <Button- label="Copy"- icon={<ClipboardDocumentIcon style={iconSize} />}- />+ <Button label="Copy" icon={<ClipboardDocumentIcon style={iconSize} />} /><Button label="Cut" icon={<ScissorsIcon style={iconSize} />} /><Button label="Paste" icon={<ClipboardIcon style={iconSize} />} /></ButtonGroup>@@ -57,21 +55,21 @@ export const Vertical: Story = {),};-/** Icon-only button group for compact toolbars. */+/**+ * Icon-only button group for compact toolbars.+ *+ * The trailing button carries a tooltip, which renders an invisible layer after+ * it in the DOM — its outer corners must still round (#2508).+ */export const IconOnly: Story = {render: () => (<ButtonGroup label="Text formatting">- <IconButton- label="Bold"- icon={<Icon icon={BoldIcon} size="sm" />}- />- <IconButton- label="Italic"- icon={<Icon icon={ItalicIcon} size="sm" />}- />+ <IconButton label="Bold" icon={<Icon icon={BoldIcon} size="sm" />} />+ <IconButton label="Italic" icon={<Icon icon={ItalicIcon} size="sm" />} /><IconButtonlabel="Underline"icon={<Icon icon={UnderlineIcon} size="sm" />}+ tooltip="Underline"/></ButtonGroup>),@@ -159,3 +157,26 @@ export const Mixed: Story = {</ButtonGroup>),};++/**+ * A DropdownMenu composes as a group member — the split-button pattern, with no+ * dedicated primitive. Its popover is an invisible DOM sibling after the+ * trigger, so the trailing corner must still round (#2508).+ */+export const WithDropdownMenu: Story = {+ render: () => (+ <ButtonGroup label="Approve action">+ <Button label="Allow once" variant="primary" />+ <DropdownMenu+ hasChevron={false}+ button={{+ label: 'Allow options',+ variant: 'primary',+ isIconOnly: true,+ icon: <Icon icon="chevronDown" />,+ }}+ items={[{label: 'Allow for 30 minutes'}, {label: 'Always allow'}]}+ />+ </ButtonGroup>+ ),+};diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsxindex 09ec4ad8b9..43b46b448c 100644--- a/packages/core/src/Button/Button.tsx+++ b/packages/core/src/Button/Button.tsx@@ -434,6 +434,36 @@ const loadingStyles = stylex.create({},});+/**+ * "I am the last member of the group" — the trailing end cap.+ *+ * NOT `:last-child`: several members render an invisible layer element AFTER+ * their button (a tooltip'd Button returns button + layer; DropdownMenu returns+ * trigger + popover). `useLayer` renders those inline rather than portaling+ * them, so the layer — not the button — took the `:last-child` slot and the real+ * trailing button silently kept square corners (#2508).+ *+ * Layers always carry the native `popover` attribute (useLayer.tsx), and a+ * popover is never an in-flow member — it is `display: none` until shown, then+ * promoted to the top layer. So "last member" is: no following element sibling+ * that isn't a popover.+ *+ * Reading it the other way round — marking the *buttons* and testing for a+ * marked sibling — is the trap: it silently reclassifies anything it doesn't+ * recognise as "not a member", so a member wrapped in a `display: contents`+ * wrapper (Tooltip, HoverCard) or a raw child would make the button BEFORE it+ * round mid-group. Ignoring known layers keeps the predicate conservative: an+ * unrecognised sibling still counts, exactly as `:last-child` did, so the worst+ * case degrades to the old behaviour instead of a wrong corner.+ *+ * Kept as a same-file const: StyleX only statically evaluates a selector key+ * from a const in the same file.+ *+ * The leading edge still uses `:first-child` — a member's button always precedes+ * its own layer, so the first button is genuinely `:first-child`.+ */+const IS_LAST_ITEM = ':not(:has(~ *:not([popover])))';+const groupStyles = stylex.create({horizontal: {borderStartStartRadius: {@@ -446,11 +476,11 @@ const groupStyles = stylex.create({},borderStartEndRadius: {default: 0,- ':last-child': radiusVars['--radius-element'],+ [IS_LAST_ITEM]: radiusVars['--radius-element'],},borderEndEndRadius: {default: 0,- ':last-child': radiusVars['--radius-element'],+ [IS_LAST_ITEM]: radiusVars['--radius-element'],},borderInlineStartWidth: {default: borderVars['--border-width'],@@ -473,11 +503,11 @@ const groupStyles = stylex.create({},borderEndStartRadius: {default: 0,- ':last-child': radiusVars['--radius-element'],+ [IS_LAST_ITEM]: radiusVars['--radius-element'],},borderEndEndRadius: {default: 0,- ':last-child': radiusVars['--radius-element'],+ [IS_LAST_ITEM]: radiusVars['--radius-element'],},borderBlockStartWidth: {default: borderVars['--border-width'],diff --git a/packages/core/src/ButtonGroup/ButtonGroup.test.tsx b/packages/core/src/ButtonGroup/ButtonGroup.test.tsxindex 8e92631e90..6e16b564d0 100644--- a/packages/core/src/ButtonGroup/ButtonGroup.test.tsx+++ b/packages/core/src/ButtonGroup/ButtonGroup.test.tsx@@ -2,8 +2,10 @@/*** @file ButtonGroup.test.tsx- * @input Uses vitest, @testing-library/react, ButtonGroup and Button components- * @output Unit tests for ButtonGroup+ * @input Uses vitest, @testing-library/react, @babel/core + @stylexjs/babel-plugin,+ * ButtonGroup and Button components+ * @output Unit tests for ButtonGroup, incl. the compiled-CSS contract for the+ * trailing radius (#2508)* @position Testing; validates ButtonGroup component implementation** SYNC: When ButtonGroup component changes, update tests to match new behavior@@ -11,9 +13,16 @@import {describe, it, expect} from 'vitest';import {render, screen} from '@testing-library/react';+import {transformSync} from '@babel/core';+import stylexBabelPlugin from '@stylexjs/babel-plugin';+import {readFileSync} from 'node:fs';+import path from 'node:path';import {ButtonGroup} from './ButtonGroup';import {Button} from '../Button';import {IconButton} from '../IconButton';+import {DropdownMenu} from '../DropdownMenu';+import {Tooltip} from '../Tooltip';+import {HoverCard} from '../HoverCard';describe('ButtonGroup', () => {it('renders a group with aria-label', () => {@@ -188,4 +197,379 @@ describe('ButtonGroup', () => {screen.getByRole('button', {name: 'More options'}),).toBeInTheDocument();});++ // ===========================================================================+ // Trailing radius (issue #2508)+ //+ // The trailing end cap cannot be keyed off `:last-child`: members render an+ // invisible layer AFTER their button (tooltip'd Button, DropdownMenu), and+ // useLayer renders it inline rather than portaling it, so the layer steals the+ // slot. See IS_LAST_ITEM in Button.tsx.+ //+ // HOW THESE TESTS CATCH THE BUG+ // jsdom applies no StyleX CSS, so a DOM-only test cannot prove which rule+ // wins — and a test that hand-copies the selector is a tautology (revert+ // groupStyles to `:last-child` and it still passes). So the predicate is NOT+ // hand-copied here: `compileButtonRules()` runs the REAL StyleX babel plugin+ // over Button.tsx (same config as scripts/build-css.mjs) and reads the+ // trailing-radius rule's selector straight out of the emitted CSS, then+ // matches it against the real rendered DOM. Revert groupStyles to+ // `:last-child` and these go red.+ // ===========================================================================+ describe('trailing radius (#2508)', () => {+ /** The group members, in DOM order (excludes invisible layer siblings). */+ const items = (group: HTMLElement): Element[] =>+ Array.from(group.querySelectorAll(':scope > *:not([popover])'));++ // -- Compiled CSS, read from the source -----------------------------------++ /** One atomic StyleX rule, parsed out of the plugin's emitted CSS. */+ type CompiledRule = {+ /** Atomic class name, e.g. `xp0wexf`. */+ className: string;+ /** Selector text after the class, e.g. `:first-child`. '' if unconditional. */+ condition: string;+ /** CSS property, e.g. `border-start-end-radius`. */+ property: string;+ /** CSS value, e.g. `var(--radius-element)`. */+ value: string;+ /** The full compiled selector, e.g. `.xp0wexf:not(:has(~ [data-...]))`. */+ selector: string;+ };++ /**+ * Compiles Button.tsx with the real StyleX babel plugin and returns its+ * atomic rules. This is the CSS the browser actually gets — the whole point+ * is that the trailing-radius predicate comes from the SOURCE, never from a+ * string retyped in this file.+ */+ function compileButtonRules(): CompiledRule[] {+ const repoRoot = path.resolve(__dirname, '../../../..');+ const buttonSrc = path.resolve(__dirname, '../Button/Button.tsx');++ const result = transformSync(readFileSync(buttonSrc, 'utf8'), {+ babelrc: false,+ configFile: false,+ filename: buttonSrc,+ presets: [+ ['@babel/preset-typescript', {isTSX: true, allExtensions: true}],+ ['@babel/preset-react', {runtime: 'automatic'}],+ ],+ plugins: [+ [+ stylexBabelPlugin,+ {+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ unstable_moduleResolution: {type: 'commonJS', rootDir: repoRoot},+ },+ ],+ ],+ });++ const rules =+ (result?.metadata as {stylex?: [string, {ltr: string}, number][]})+ ?.stylex ?? [];++ return rules.flatMap(([, {ltr}]) => {+ // Plain atomic rules only: `.cls<condition>{prop:value}`. @media-wrapped+ // rules are irrelevant to the radius contract.+ const parsed = /^\.([\w-]+)([^{]*)\{([\w-]+):(.+)\}$/.exec(ltr);+ if (!parsed) {+ return [];+ }+ const [, className, condition, property, value] = parsed;+ return [+ {+ className,+ condition,+ property,+ value,+ selector: `.${className}${condition}`,+ },+ ];+ });+ }++ const COMPILED = compileButtonRules();++ /** A rounded (non-zero) corner is exactly this value in the compiled CSS. */+ const ROUNDED = 'var(--radius-element)';++ /** The two corners on the group's trailing edge — pure geometry. */+ const TRAILING_CORNERS = {+ horizontal: ['border-end-end-radius', 'border-start-end-radius'],+ vertical: ['border-end-end-radius', 'border-end-start-radius'],+ } as const;++ /** The two corners on the group's leading edge — pure geometry. */+ const LEADING_CORNERS = {+ horizontal: ['border-end-start-radius', 'border-start-start-radius'],+ vertical: ['border-start-end-radius', 'border-start-start-radius'],+ } as const;++ type Orientation = keyof typeof TRAILING_CORNERS;++ /**+ * The compiled rules that ROUND `corners` and are actually applied to `el`+ * (its class list carries them). StyleX emits the `default: 0` class and the+ * conditional class on every member, so this returns the same rules for any+ * member of the group — which rule *wins* is decided by the selector, and+ * that is what the tests below assert against the DOM.+ */+ const roundingRules = (+ el: Element,+ corners: ReadonlyArray<string>,+ ): CompiledRule[] =>+ COMPILED.filter(+ rule =>+ corners.includes(rule.property) &&+ rule.value === ROUNDED &&+ el.classList.contains(rule.className),+ );++ /** The compiled selectors that round `el`'s trailing corners. */+ const trailingRoundingSelectors = (+ el: Element,+ orientation: Orientation,+ ): string[] => {+ const rules = roundingRules(el, TRAILING_CORNERS[orientation]);+ // Guard against a vacuous pass: both trailing corners must be accounted+ // for, or the assertions below would be quantifying over an empty set.+ expect(rules.map(rule => rule.property).sort()).toEqual([+ ...TRAILING_CORNERS[orientation],+ ]);+ return rules.map(rule => rule.selector);+ };++ /** Does the compiled CSS actually round `el`'s trailing corners? */+ const hasRoundedTrailingCorners = (+ el: Element,+ orientation: Orientation = 'horizontal',+ ): boolean =>+ trailingRoundingSelectors(el, orientation).every(selector =>+ el.matches(selector),+ );++ // -- The compiled CSS contract --------------------------------------------++ it.each(['horizontal', 'vertical'] as const)(+ 'keys the trailing radius off layer-skipping, not :last-child (%s)',+ orientation => {+ render(+ <ButtonGroup label="Actions" orientation={orientation}>+ <Button label="Save" />+ </ButtonGroup>,+ );++ const save = screen.getByRole('button', {name: 'Save'});+ const selectors = trailingRoundingSelectors(save, orientation);++ for (const selector of selectors) {+ // `:last-child` is the bug: an inline layer element steals the slot.+ expect(selector).not.toContain(':last-child');+ // `[popover]` must survive compilation *verbatim*. StyleX only+ // statically evaluates a selector key from a same-file const; from a+ // .stylex.ts file it compiles to a mangled selector like `[x13pbwiz]`+ // that matches nothing in the DOM.+ expect(selector).toContain('[popover]');+ }+ },+ );++ it.each(['horizontal', 'vertical'] as const)(+ 'still rounds the leading corners off :first-child (%s)',+ orientation => {+ render(+ <ButtonGroup label="Actions" orientation={orientation}>+ <Button label="Save" />+ <Button label="More" tooltip="More options" />+ </ButtonGroup>,+ );++ const save = screen.getByRole('button', {name: 'Save'});+ const more = screen.getByRole('button', {name: 'More'});+ const rules = roundingRules(save, LEADING_CORNERS[orientation]);++ expect(rules.map(rule => rule.property).sort()).toEqual([+ ...LEADING_CORNERS[orientation],+ ]);+ for (const {condition, selector} of rules) {+ // The leading edge is genuinely safe on :first-child — a member's+ // button always precedes its own layer.+ expect(condition).toBe(':first-child');+ expect(save.matches(selector)).toBe(true);+ expect(more.matches(selector)).toBe(false);+ }+ },+ );++ // -- The compiled CSS, matched against the real DOM ------------------------++ it.each(['horizontal', 'vertical'] as const)(+ 'rounds a tooltip’d trailing Button, whose layer follows it in the DOM (%s)',+ orientation => {+ render(+ <ButtonGroup label="Actions" orientation={orientation}>+ <Button label="Save" />+ <Button label="More" tooltip="More options" />+ </ButtonGroup>,+ );++ const group = screen.getByRole('group');+ const save = screen.getByRole('button', {name: 'Save'});+ const more = screen.getByRole('button', {name: 'More'});++ // Precondition: the tooltip layer really is an inline DOM sibling that+ // follows the button — this is exactly what broke `:last-child`.+ expect(more).not.toBe(group.lastElementChild);+ expect(items(group).at(-1)).toBe(more);++ expect(hasRoundedTrailingCorners(more, orientation)).toBe(true);+ expect(hasRoundedTrailingCorners(save, orientation)).toBe(false);+ },+ );++ it.each(['horizontal', 'vertical'] as const)(+ 'rounds a trailing DropdownMenu trigger, whose popover follows it (%s)',+ orientation => {+ render(+ <ButtonGroup label="Approve action" orientation={orientation}>+ <Button label="Allow once" variant="primary" />+ <DropdownMenu+ button={{label: 'Allow options', variant: 'primary'}}+ items={[{label: 'Always allow'}]}+ />+ </ButtonGroup>,+ );++ const group = screen.getByRole('group');+ const allow = screen.getByRole('button', {name: 'Allow once'});+ const trigger = screen.getByRole('button', {name: 'Allow options'});++ // The popover surface is an inline sibling after the trigger.+ expect(trigger).not.toBe(group.lastElementChild);+ expect(items(group).at(-1)).toBe(trigger);++ expect(hasRoundedTrailingCorners(trigger, orientation)).toBe(true);+ expect(hasRoundedTrailingCorners(allow, orientation)).toBe(false);+ },+ );++ it('rounds a trailing link (<a>) member with a tooltip', () => {+ render(+ <ButtonGroup label="Actions">+ <Button label="Save" />+ <Button label="Docs" href="https://example.com" tooltip="Open docs" />+ </ButtonGroup>,+ );++ const group = screen.getByRole('group');+ const link = screen.getByRole('link', {name: 'Docs'});++ expect(link.tagName).toBe('A');+ expect(link).not.toBe(group.lastElementChild);+ expect(items(group).at(-1)).toBe(link);++ expect(hasRoundedTrailingCorners(link)).toBe(true);+ });++ it('rounds only the last member (first/middle/last)', () => {+ render(+ <ButtonGroup label="Actions">+ <Button label="First" />+ <Button label="Middle" tooltip="Middle tip" />+ <DropdownMenu+ button={{label: 'Last'}}+ items={[{label: 'An option'}]}+ />+ </ButtonGroup>,+ );++ const group = screen.getByRole('group');+ const [first, middle, last] = items(group);++ expect([first, middle, last].map(el => el.textContent)).toEqual([+ 'First',+ 'Middle',+ 'Last',+ ]);++ // Middle has a tooltip layer after it, but a *marked* sibling follows too,+ // so it must NOT take the trailing radius.+ expect(hasRoundedTrailingCorners(first)).toBe(false);+ expect(hasRoundedTrailingCorners(middle)).toBe(false);+ expect(hasRoundedTrailingCorners(last)).toBe(true);+ });++ it('rounds both edges of a lone tooltip’d member', () => {+ render(+ <ButtonGroup label="Actions">+ <Button label="Only" tooltip="The only one" />+ </ButtonGroup>,+ );++ const only = screen.getByRole('button', {name: 'Only'});++ // Leading edge is unaffected: a member's button always precedes its layer.+ expect(only.matches(':first-child')).toBe(true);+ expect(hasRoundedTrailingCorners(only)).toBe(true);+ });++ // -- Members the group does not recognise ---------------------------------+ //+ // The trailing predicate must stay CONSERVATIVE: a sibling the group does+ // not understand is still a member. Otherwise the button BEFORE it wrongly+ // takes the trailing radius and renders as a rounded notch mid-group —+ // worse than the bug being fixed, because it is silent and visual.++ it('does not round the preceding button when a Tooltip-wrapped member follows', () => {+ render(+ <ButtonGroup label="Actions">+ <Button label="Save" />+ <Tooltip content="Rich tip">+ <Button label="More" />+ </Tooltip>+ </ButtonGroup>,+ );++ const save = screen.getByRole('button', {name: 'Save'});++ // Tooltip wraps element children in a `display: contents` <div>, so the+ // inner Button is a DESCENDANT of the wrapper, not a DOM sibling of Save.+ expect(hasRoundedTrailingCorners(save)).toBe(false);+ });++ it('does not round the preceding button when a HoverCard-wrapped member follows', () => {+ render(+ <ButtonGroup label="Actions">+ <Button label="Save" />+ <HoverCard content="Preview">+ <Button label="More" />+ </HoverCard>+ </ButtonGroup>,+ );++ const save = screen.getByRole('button', {name: 'Save'});++ // Button has no `hoverCard` prop, so wrapping is the ONLY way to put a+ // HoverCard on a group button — this composition has no alternative.+ expect(hasRoundedTrailingCorners(save)).toBe(false);+ });++ it('does not round the preceding button when a raw <button> follows', () => {+ render(+ <ButtonGroup label="Actions">+ <Button label="Save" />+ <button type="button">Custom</button>+ </ButtonGroup>,+ );++ const save = screen.getByRole('button', {name: 'Save'});++ expect(hasRoundedTrailingCorners(save)).toBe(false);+ });+ });});diff --git a/packages/core/src/ButtonGroup/ButtonGroup.tsx b/packages/core/src/ButtonGroup/ButtonGroup.tsxindex 380bb27ed3..3280157268 100644--- a/packages/core/src/ButtonGroup/ButtonGroup.tsx+++ b/packages/core/src/ButtonGroup/ButtonGroup.tsx@@ -8,9 +8,10 @@* @output Exports ButtonGroup component, context, and types* @position Groups buttons with connected styling; consumed by index.ts*- * Children (Button, IconButton) consume the ButtonGroup context to- * apply position-aware styles using CSS :first-child / :last-child- * pseudo-classes — no cloneElement or wrapper divs needed.+ * Children (Button, IconButton) consume the ButtonGroup context to apply+ * position-aware styles in pure CSS — no cloneElement or wrapper divs needed.+ * The end-cap radius rules live in Button.tsx; see IS_LAST_ITEM there for why+ * the trailing edge cannot use :last-child (#2508).** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/ButtonGroup/ButtonGroup.doc.mjs (props table, features)@@ -97,7 +98,10 @@ const styles = stylex.create({* handling (only on outer edges), and horizontal or vertical orientation.** Children automatically detect the group via context and apply position-aware- * styles using CSS :first-child / :last-child pseudo-classes.+ * styles in pure CSS.+ *+ * Members that render their own layer — a Button with a `tooltip`, or a+ * DropdownMenu — compose correctly, including as the trailing member.** @example* ```@@ -107,6 +111,17 @@ const styles = stylex.create({* <Button label="Paste" />* </ButtonGroup>* ```+ *+ * @example+ * ```+ * <ButtonGroup label="Approve action">+ * <Button label="Allow once" variant="primary" />+ * <DropdownMenu+ * button={{label: 'Allow options', variant: 'primary', isIconOnly: true, icon: <Icon icon="chevronDown" />}}+ * items={[{label: 'Allow for 30 minutes'}, {label: 'Always allow'}]}+ * />+ * </ButtonGroup>+ * ```*/export function ButtonGroup({children,