From 11a735e02774f56848cadc0fb08f5c62b9644061 Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Mon, 9 Nov 2026 23:27:12 +0100 Subject: [PATCH 01/27] Fix medium shortcut button padding Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/button-shortcut-padding.md | 5 +++++ packages/react/src/Button/ButtonBase.module.css | 5 +++++ 2 files changed, 10 insertions(+) create mode 100644 .changeset/button-shortcut-padding.md diff --git a/.changeset/button-shortcut-padding.md b/.changeset/button-shortcut-padding.md new file mode 100644 index 00000000000..aa0cb53dffe --- /dev/null +++ b/.changeset/button-shortcut-padding.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +Button: Adjust horizontal padding for medium buttons with keyboard shortcuts. diff --git a/packages/react/src/Button/ButtonBase.module.css b/packages/react/src/Button/ButtonBase.module.css index 278b4979314..450375cf770 100644 --- a/packages/react/src/Button/ButtonBase.module.css +++ b/packages/react/src/Button/ButtonBase.module.css @@ -27,6 +27,11 @@ /* stylelint-disable-next-line selector-pseudo-class-disallowed-list -- scoped to CSS Module, audited (github/github-ui#17224) */ &:has([data-kbd-chord]) { padding-inline-end: var(--base-size-6); + + &:where([data-size='medium']) { + padding-inline-start: calc(var(--base-size-12) - var(--base-size-2)); + padding-inline-end: var(--base-size-8); + } } &:hover { From dc056b9ff577249ecedc774f992ec647f3f1045c Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Mon, 9 Nov 2026 23:44:25 +0100 Subject: [PATCH 02/27] Match Button spacing across sizes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/small-button-spacing.md | 5 + .../react/src/Button/ButtonBase.module.css | 47 ++++++---- packages/react/src/Button/ButtonBase.tsx | 2 +- .../src/Button/__tests__/Button.test.tsx | 91 +++++++++++++++++++ 4 files changed, 128 insertions(+), 17 deletions(-) create mode 100644 .changeset/small-button-spacing.md diff --git a/.changeset/small-button-spacing.md b/.changeset/small-button-spacing.md new file mode 100644 index 00000000000..d88f293563d --- /dev/null +++ b/.changeset/small-button-spacing.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +Button: Align visual spacing, keyboard shortcut padding, and label line height across button sizes. diff --git a/packages/react/src/Button/ButtonBase.module.css b/packages/react/src/Button/ButtonBase.module.css index 450375cf770..ab8df9c23ff 100644 --- a/packages/react/src/Button/ButtonBase.module.css +++ b/packages/react/src/Button/ButtonBase.module.css @@ -24,10 +24,27 @@ justify-content: space-between; gap: var(--base-size-8); + &.HasLeadingVisual:where(:not([data-icon-only-counter])) { + padding-inline: var(--base-size-8) var(--base-size-12); + + &:where([data-size='small']) { + padding-inline: var(--base-size-6) var(--base-size-8); + } + + &:where([data-size='large']) { + padding-inline: var(--base-size-12) var(--base-size-16); + } + } + /* stylelint-disable-next-line selector-pseudo-class-disallowed-list -- scoped to CSS Module, audited (github/github-ui#17224) */ &:has([data-kbd-chord]) { padding-inline-end: var(--base-size-6); + &:where([data-size='small']) { + /* stylelint-disable-next-line primer/spacing */ + padding-inline-start: var(--control-small-paddingInline-condensed); + } + &:where([data-size='medium']) { padding-inline-start: calc(var(--base-size-12) - var(--base-size-2)); padding-inline-end: var(--base-size-8); @@ -156,7 +173,7 @@ align-content: center; & > :not(:last-child) { - margin-right: var(--base-size-8); + margin-right: var(--base-size-6); } /* Content alignment */ @@ -175,7 +192,8 @@ } & :where(.Label) { - line-height: var(--text-body-lineHeight-medium); + /* stylelint-disable-next-line primer/typography -- match the 20px control label line height */ + line-height: var(--base-size-20); white-space: nowrap; grid-area: text; } @@ -194,16 +212,12 @@ height: var(--control-small-size); /* stylelint-disable-next-line primer/spacing */ padding: 0 var(--control-small-paddingInline-condensed); - gap: var(--control-small-gap); + gap: var(--base-size-6); font-size: var(--text-body-size-small); - - & .ButtonContent > :not(:last-child) { - /* stylelint-disable-next-line primer/spacing */ - margin-right: var(--control-small-gap); - } + line-height: var(--base-text-lineHeight-normal); & .Label { - line-height: var(--text-body-lineHeight-small); + line-height: var(--base-text-lineHeight-normal); } } @@ -211,16 +225,12 @@ height: var(--control-large-size); /* stylelint-disable-next-line primer/spacing */ padding: 0 var(--control-large-paddingInline-spacious); - gap: var(--control-large-gap); - - & .ButtonContent > :not(:last-child) { - /* stylelint-disable-next-line primer/spacing */ - margin-right: var(--control-large-gap); - } + gap: var(--base-size-6); /* stylelint-disable-next-line selector-pseudo-class-disallowed-list -- scoped to CSS Module, audited (github/github-ui#17224) */ &:has([data-kbd-chord]) { - padding-inline-end: var(--base-size-8); + padding-inline-start: var(--base-size-12); + padding-inline-end: calc(var(--base-size-12) - var(--base-size-2)); } } @@ -622,9 +632,14 @@ } & .Label { + line-height: var(--text-body-lineHeight-medium); white-space: unset; } + &:where([data-size='small']) .Label { + line-height: var(--text-body-lineHeight-small); + } + &:not([data-no-visuals]) .Label { text-underline-offset: 0.125rem; } diff --git a/packages/react/src/Button/ButtonBase.tsx b/packages/react/src/Button/ButtonBase.tsx index d4747b94d4d..23b48d09157 100644 --- a/packages/react/src/Button/ButtonBase.tsx +++ b/packages/react/src/Button/ButtonBase.tsx @@ -111,7 +111,7 @@ const ButtonBase = forwardRef(({children, as: Component = 'button', ...props}, f {...rest} // @ts-ignore temporary disable as we migrate to css modules, until we remove PolymorphicForwardRefComponent ref={mergedRef} - className={clsx(classes.ButtonBase, className)} + className={clsx(classes.ButtonBase, LeadingVisual && classes.HasLeadingVisual, className)} data-block={block ? 'block' : null} data-inactive={inactive ? true : undefined} data-loading={Boolean(loading)} diff --git a/packages/react/src/Button/__tests__/Button.test.tsx b/packages/react/src/Button/__tests__/Button.test.tsx index e95eb5d614d..61e6233e416 100644 --- a/packages/react/src/Button/__tests__/Button.test.tsx +++ b/packages/react/src/Button/__tests__/Button.test.tsx @@ -7,6 +7,7 @@ import {IconButton, Button, LinkButton} from '../../Button' import classes from '../ButtonBase.module.css' import {implementsClassName} from '../../utils/testing' import {FeatureFlags} from '../../FeatureFlags' +import {KeybindingHint} from '../../KeybindingHint' type StatefulLoadingButtonProps = { children?: React.ReactNode @@ -166,6 +167,96 @@ describe('Button', () => { expect(button.element()).toMatchSnapshot() }) + describe.each([ + {size: 'small', padding: '8px', leadingPadding: '6px', height: '28px', lineHeight: '18px'}, + {size: 'medium', padding: '12px', leadingPadding: '8px', height: '32px', lineHeight: '20px'}, + {size: 'large', padding: '16px', leadingPadding: '12px', height: '40px', lineHeight: '20px'}, + ] as const)('$size visual spacing', ({size, padding, leadingPadding, height, lineHeight}) => { + it.each([ + {leading: false, trailing: false}, + {leading: true, trailing: false}, + {leading: false, trailing: true}, + {leading: true, trailing: true}, + ])('spaces buttons with leading=$leading and trailing=$trailing', async ({leading, trailing}) => { + render( + , + ) + + const button = page.getByRole('button', {name: 'Search', exact: true}) + await expect + .poll(() => getComputedStyle(button.element()).paddingInlineStart) + .toBe(leading ? leadingPadding : padding) + expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(padding) + expect(getComputedStyle(button.element()).height).toBe(height) + expect(getComputedStyle(page.getByText('Search', {exact: true}).element()).lineHeight).toBe(lineHeight) + + const label = page.getByText('Search', {exact: true}).element().getBoundingClientRect() + const icons = button.element().querySelectorAll('svg') + if (leading) { + expect(label.left - icons[0].getBoundingClientRect().right).toBe(6) + } + if (trailing) { + expect(icons[icons.length - 1].getBoundingClientRect().left - label.right).toBe(6) + } + }) + + it('preserves inline Link height while applying leading visual padding', async () => { + render( +
+ +
, + ) + const button = page.getByRole('button', {name: 'Search', exact: true}) + await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(leadingPadding) + expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(padding) + expect(button.element().getBoundingClientRect().height).toBeLessThan(Number.parseFloat(height)) + const labelStyle = getComputedStyle(page.getByText('Search', {exact: true}).element()) + expect(labelStyle.fontSize).toBe('16px') + expect(labelStyle.lineHeight).toBe(size === 'small' ? '26px' : '24px') + }) + }) + + it.each([ + {size: 'small', padding: '4px'}, + {size: 'medium', padding: '8px'}, + {size: 'large', padding: '12px'}, + ] as const)('preserves $size icon-only counter padding', async ({size, padding}) => { + render(, + ) + const button = page.getByRole('button', {name: /^Save/}) + await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(start) + expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(end) + rerender( + , + ) + await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(start) + expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(end) + }) + it('styles primary button appropriately', () => { render( , - ) - - const button = page.getByRole('button', {name: 'Search', exact: true}) - await expect - .poll(() => getComputedStyle(button.element()).paddingInlineStart) - .toBe(leading ? leadingPadding : padding) - expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(padding) - expect(getComputedStyle(button.element()).height).toBe(height) - expect(getComputedStyle(page.getByText('Search', {exact: true}).element()).lineHeight).toBe(lineHeight) - - const label = page.getByText('Search', {exact: true}).element().getBoundingClientRect() - const icons = button.element().querySelectorAll('svg') - if (leading) { - expect(label.left - icons[0].getBoundingClientRect().right).toBe(6) - } - if (trailing) { - expect(icons[icons.length - 1].getBoundingClientRect().left - label.right).toBe(6) - } - }) - - it('preserves inline Link height while applying leading visual padding', async () => { - render( -
- -
, - ) - const button = page.getByRole('button', {name: 'Search', exact: true}) - await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(leadingPadding) - expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(padding) - expect(button.element().getBoundingClientRect().height).toBeLessThan(Number.parseFloat(height)) - const labelStyle = getComputedStyle(page.getByText('Search', {exact: true}).element()) - expect(labelStyle.fontSize).toBe('16px') - expect(labelStyle.lineHeight).toBe(size === 'small' ? '26px' : '24px') - }) - }) - - it.each([ - {size: 'small', padding: '4px'}, - {size: 'medium', padding: '8px'}, - {size: 'large', padding: '12px'}, - ] as const)('preserves $size icon-only counter padding', async ({size, padding}) => { - render(, - ) - const button = page.getByRole('button', {name: /^Save/}) - await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(start) - expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(end) - rerender( - , - ) - await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(start) - expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(end) - }) - it('styles primary button appropriately', () => { render( , + ) + + const button = page.getByRole('button', {name: 'Search', exact: true}) + await expect + .poll(() => getComputedStyle(button.element()).paddingInlineStart) + .toBe(leading ? leadingPadding : padding) + expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(padding) + expect(getComputedStyle(button.element()).height).toBe(height) + expect(getComputedStyle(page.getByText('Search', {exact: true}).element()).lineHeight).toBe(lineHeight) + + const label = page.getByText('Search', {exact: true}).element().getBoundingClientRect() + const icons = button.element().querySelectorAll('svg') + if (leading) { + expect(label.left - icons[0].getBoundingClientRect().right).toBe(6) + } + if (trailing) { + expect(icons[icons.length - 1].getBoundingClientRect().left - label.right).toBe(6) + } + }) + + it('preserves inline Link height while applying leading visual padding', async () => { + render( +
+ +
, + ) + const button = page.getByRole('button', {name: 'Search', exact: true}) + await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(leadingPadding) + expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(padding) + expect(button.element().getBoundingClientRect().height).toBeLessThan(Number.parseFloat(height)) + const labelStyle = getComputedStyle(page.getByText('Search', {exact: true}).element()) + expect(labelStyle.fontSize).toBe('16px') + expect(labelStyle.lineHeight).toBe(size === 'small' ? '26px' : '24px') + }) + }) + + it.each([ + {size: 'small', padding: '4px'}, + {size: 'medium', padding: '8px'}, + {size: 'large', padding: '12px'}, + ] as const)('preserves $size icon-only counter padding', async ({size, padding}) => { + render(, + ) + const button = page.getByRole('button', {name: /^Save/}) + await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(start) + expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(end) + rerender( + , + ) + await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(start) + expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(end) + }) + it('styles primary button appropriately', () => { render( export const Link = () => +export const AllSizes = () => ( +
+ + + +
+) + +const kitchenSinkVariants = ['default', 'primary', 'danger', 'invisible', 'link'] as const +const kitchenSinkSizes = ['small', 'medium', 'large'] as const + +export const AllVariants = () => ( + + {kitchenSinkVariants.map(variant => ( + + ))} + +) + +export const AllVariantsWithLeadingVisual = () => ( + + {kitchenSinkVariants.map(variant => ( + + ))} + +) + +export const KitchenSink = { + parameters: { + layout: 'fullscreen', + }, + render: () => ( +
+ + {kitchenSinkSizes.map(size => ( + + + {size} + + + + + Variants + + + {kitchenSinkVariants.map(variant => ( + + ))} + + + + + With leading visual + + + {kitchenSinkVariants.map(variant => ( + + ))} + + + + + With trailing visual + + + {kitchenSinkVariants.map(variant => ( + + ))} + + + + + With both visuals + + + {kitchenSinkVariants.map(variant => ( + + ))} + + + + + Disabled + + + {kitchenSinkVariants.map(variant => ( + + ))} + + + + + Inactive + + + {kitchenSinkVariants.map(variant => ( + + ))} + + + + + With key shortcut + + + {kitchenSinkVariants.map(variant => ( + + ))} + + + + + Block + + + + + + + + + ))} + +
+ ), +} + export const LeadingVisual = () => export const TrailingVisual = () => From 2ec907b584870e02c946f36c1110dcae4b71282a Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Tue, 10 Nov 2026 15:14:14 +0100 Subject: [PATCH 07/27] Button: match radius and font weight Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/button-modern-spacing.md | 2 +- .../Button/ButtonBase.modernize.module.css | 6 +++ .../src/Button/__tests__/Button.test.tsx | 37 +++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/.changeset/button-modern-spacing.md b/.changeset/button-modern-spacing.md index d88f293563d..3ab9e0fc1eb 100644 --- a/.changeset/button-modern-spacing.md +++ b/.changeset/button-modern-spacing.md @@ -2,4 +2,4 @@ '@primer/react': patch --- -Button: Align visual spacing, keyboard shortcut padding, and label line height across button sizes. +Button: Align visual spacing, keyboard shortcut padding, label line height, weight, and border radius across button sizes. diff --git a/packages/react/src/Button/ButtonBase.modernize.module.css b/packages/react/src/Button/ButtonBase.modernize.module.css index 28989a5a2bc..79979d7d5e9 100644 --- a/packages/react/src/Button/ButtonBase.modernize.module.css +++ b/packages/react/src/Button/ButtonBase.modernize.module.css @@ -3,6 +3,12 @@ margin-right: var(--base-size-6); } + &:where(:not([data-component='IconButton'])) { + font-weight: var(--base-text-weight-semibold); + /* stylelint-disable-next-line primer/borders -- GitHub App's 8px radius has no matching Primer token */ + border-radius: 8px; + } + &:where(:not([data-variant='link'])) [data-component='text'] { /* stylelint-disable-next-line primer/typography -- match the 20px control label line height */ line-height: var(--base-size-20); diff --git a/packages/react/src/Button/__tests__/Button.test.tsx b/packages/react/src/Button/__tests__/Button.test.tsx index 61e6233e416..6bb5fb5b9f3 100644 --- a/packages/react/src/Button/__tests__/Button.test.tsx +++ b/packages/react/src/Button/__tests__/Button.test.tsx @@ -172,6 +172,35 @@ describe('Button', () => { {size: 'medium', padding: '12px', leadingPadding: '8px', height: '32px', lineHeight: '20px'}, {size: 'large', padding: '16px', leadingPadding: '12px', height: '40px', lineHeight: '20px'}, ] as const)('$size visual spacing', ({size, padding, leadingPadding, height, lineHeight}) => { + it.each(['default', 'primary', 'danger', 'invisible', 'link'] as const)( + 'uses semibold text and an 8px radius for the %s variant', + async variant => { + render( + , + ) + const button = page.getByRole('button', {name: 'Label', exact: true}) + const label = page.getByText('Label', {exact: true}) + await expect.poll(() => getComputedStyle(button.element()).fontWeight).toBe('600') + await expect.poll(() => getComputedStyle(label.element()).fontWeight).toBe('600') + expect(getComputedStyle(button.element()).borderRadius).toBe('8px') + }, + ) + + it('does not apply the label weight to shortcut keycaps', async () => { + render( + , + ) + const button = page.getByRole('button', {name: /^Save/}) + await expect + .poll(() => getComputedStyle(button.element().querySelector('[data-component="text"]')!).fontWeight) + .toBe('600') + expect(getComputedStyle(button.element().querySelector('[data-kbd-chord]')!).fontWeight).toBe('400') + }) + it.each([ {leading: false, trailing: false}, {leading: true, trailing: false}, @@ -224,6 +253,14 @@ describe('Button', () => { }) }) + it.each(['small', 'medium', 'large'] as const)('does not change %s IconButton styles', async size => { + render() + + const button = page.getByRole('button', {name: 'Search', exact: true}) + await expect.poll(() => getComputedStyle(button.element()).fontWeight).toBe('500') + expect(getComputedStyle(button.element()).borderRadius).toBe('6px') + }) + it.each([ {size: 'small', padding: '4px'}, {size: 'medium', padding: '8px'}, From aa781565fc28fab9118432a66e8a6264176607a0 Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Tue, 10 Nov 2026 15:14:23 +0100 Subject: [PATCH 08/27] Ignore Playwright MCP artifacts Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 78cc2319772..b96272f69a7 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,7 @@ storybook-static coverage/ # Playwright +.playwright-mcp/ stats.html blob-report results.json From 4d7f9960ab39834442d2807b84a1ad08b1e7e8b4 Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Tue, 10 Nov 2026 15:26:53 +0100 Subject: [PATCH 09/27] Button: apply antialiased font smoothing Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .changeset/button-modern-spacing.md | 2 +- .../src/Button/ButtonBase.modernize.module.css | 1 + .../react/src/Button/__tests__/Button.test.tsx | 14 ++++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/.changeset/button-modern-spacing.md b/.changeset/button-modern-spacing.md index 3ab9e0fc1eb..ac3b109e0c5 100644 --- a/.changeset/button-modern-spacing.md +++ b/.changeset/button-modern-spacing.md @@ -2,4 +2,4 @@ '@primer/react': patch --- -Button: Align visual spacing, keyboard shortcut padding, label line height, weight, and border radius across button sizes. +Button: Align visual spacing, keyboard shortcut padding, label typography, and border radius across button sizes. diff --git a/packages/react/src/Button/ButtonBase.modernize.module.css b/packages/react/src/Button/ButtonBase.modernize.module.css index 79979d7d5e9..bbe95773817 100644 --- a/packages/react/src/Button/ButtonBase.modernize.module.css +++ b/packages/react/src/Button/ButtonBase.modernize.module.css @@ -5,6 +5,7 @@ &:where(:not([data-component='IconButton'])) { font-weight: var(--base-text-weight-semibold); + -webkit-font-smoothing: antialiased; /* stylelint-disable-next-line primer/borders -- GitHub App's 8px radius has no matching Primer token */ border-radius: 8px; } diff --git a/packages/react/src/Button/__tests__/Button.test.tsx b/packages/react/src/Button/__tests__/Button.test.tsx index 6bb5fb5b9f3..71ea908a6bb 100644 --- a/packages/react/src/Button/__tests__/Button.test.tsx +++ b/packages/react/src/Button/__tests__/Button.test.tsx @@ -195,10 +195,23 @@ describe('Button', () => { , ) const button = page.getByRole('button', {name: /^Save/}) + await expect + .poll(() => getComputedStyle(button.element()).getPropertyValue('-webkit-font-smoothing')) + .toBe('antialiased') await expect .poll(() => getComputedStyle(button.element().querySelector('[data-component="text"]')!).fontWeight) .toBe('600') + expect( + getComputedStyle(button.element().querySelector('[data-component="text"]')!).getPropertyValue( + '-webkit-font-smoothing', + ), + ).toBe('antialiased') expect(getComputedStyle(button.element().querySelector('[data-kbd-chord]')!).fontWeight).toBe('400') + expect( + getComputedStyle(button.element().querySelector('[data-kbd-chord]')!).getPropertyValue( + '-webkit-font-smoothing', + ), + ).toBe('antialiased') }) it.each([ @@ -259,6 +272,7 @@ describe('Button', () => { const button = page.getByRole('button', {name: 'Search', exact: true}) await expect.poll(() => getComputedStyle(button.element()).fontWeight).toBe('500') expect(getComputedStyle(button.element()).borderRadius).toBe('6px') + expect(getComputedStyle(button.element()).getPropertyValue('-webkit-font-smoothing')).not.toBe('antialiased') }) it.each([ From df9a086fc0834a9267d4962c14b96727db16e047 Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Tue, 10 Nov 2026 15:47:58 +0100 Subject: [PATCH 10/27] Delete .changeset/button-modern-spacing.md --- .changeset/button-modern-spacing.md | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 .changeset/button-modern-spacing.md diff --git a/.changeset/button-modern-spacing.md b/.changeset/button-modern-spacing.md deleted file mode 100644 index ac3b109e0c5..00000000000 --- a/.changeset/button-modern-spacing.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@primer/react': patch ---- - -Button: Align visual spacing, keyboard shortcut padding, label typography, and border radius across button sizes. From 46fe83eee883aa90515048baa6bace0109713bf8 Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Tue, 10 Nov 2026 15:49:07 +0100 Subject: [PATCH 11/27] Remove Button component test file Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/Button/__tests__/Button.test.tsx | 853 ------------------ 1 file changed, 853 deletions(-) delete mode 100644 packages/react/src/Button/__tests__/Button.test.tsx diff --git a/packages/react/src/Button/__tests__/Button.test.tsx b/packages/react/src/Button/__tests__/Button.test.tsx deleted file mode 100644 index 71ea908a6bb..00000000000 --- a/packages/react/src/Button/__tests__/Button.test.tsx +++ /dev/null @@ -1,853 +0,0 @@ -import {page, userEvent} from 'vitest/browser' -import {SearchIcon, HeartIcon} from '@primer/octicons-react' -import {render, fireEvent} from '@testing-library/react' -import {describe, it, expect, vi} from 'vitest' -import React from 'react' -import {IconButton, Button, LinkButton} from '../../Button' -import classes from '../ButtonBase.module.css' -import {implementsClassName} from '../../utils/testing' -import {FeatureFlags} from '../../FeatureFlags' -import {KeybindingHint} from '../../KeybindingHint' - -type StatefulLoadingButtonProps = { - children?: React.ReactNode - id?: string - ['aria-describedby']?: string - loadingAnnouncement?: string -} - -const StatefulLoadingButton = (props: StatefulLoadingButtonProps) => { - const [isLoading, setIsLoading] = React.useState(false) - const handleClick = () => { - setIsLoading(true) - } - - return ) - const button = page.getByRole('button') - expect(button.element().textContent).toEqual('Default') - }) - - it('preserves "onClick" prop', async () => { - const onClick = vi.fn() - render() - const button = page.getByRole('button') - await userEvent.click(button) - expect(onClick).toHaveBeenCalledTimes(1) - }) - - it('respects block prop', () => { - render( - , - ) - - const button = page.getByRole('button') - expect(button.element()).toMatchSnapshot() - }) - - it('displays a notification indicator on the button boundary', async () => { - render() - await expect.element(page.getByRole('button')).toHaveAttribute('data-notification-indicator', 'button') - }) - - it('displays a notification indicator on the leading visual', async () => { - render( - , - ) - - await expect.element(page.getByRole('button')).toHaveAttribute('data-notification-indicator', 'leadingVisual') - }) - - it('displays a notification indicator on an icon button icon', async () => { - render() - - await expect.element(page.getByRole('button')).toHaveAttribute('data-notification-indicator', 'icon') - }) - - it('warns when a leading visual notification indicator has no leading visual', () => { - const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - render() - - expect(consoleSpy).toHaveBeenCalledWith( - 'Button: `notificationIndicator="leadingVisual"` requires a `leadingVisual` prop.', - ) - consoleSpy.mockRestore() - }) - - it('respects the "disabled" prop', () => { - const onClick = vi.fn() - - render( - , - ) - - const button = page.getByRole('button') - expect(button.element().hasAttribute('disabled')).toEqual(true) - fireEvent.click(button.element()) - expect(onClick).toHaveBeenCalledTimes(0) - }) - - it('respects the small size prop', () => { - render( - , - ) - - const button = page.getByRole('button') - expect(button.element()).toMatchSnapshot() - }) - - it('respects the large size prop', () => { - render( - , - ) - - const button = page.getByRole('button') - expect(button.element()).toMatchSnapshot() - }) - - describe.each([ - {size: 'small', padding: '8px', leadingPadding: '6px', height: '28px', lineHeight: '18px'}, - {size: 'medium', padding: '12px', leadingPadding: '8px', height: '32px', lineHeight: '20px'}, - {size: 'large', padding: '16px', leadingPadding: '12px', height: '40px', lineHeight: '20px'}, - ] as const)('$size visual spacing', ({size, padding, leadingPadding, height, lineHeight}) => { - it.each(['default', 'primary', 'danger', 'invisible', 'link'] as const)( - 'uses semibold text and an 8px radius for the %s variant', - async variant => { - render( - , - ) - const button = page.getByRole('button', {name: 'Label', exact: true}) - const label = page.getByText('Label', {exact: true}) - await expect.poll(() => getComputedStyle(button.element()).fontWeight).toBe('600') - await expect.poll(() => getComputedStyle(label.element()).fontWeight).toBe('600') - expect(getComputedStyle(button.element()).borderRadius).toBe('8px') - }, - ) - - it('does not apply the label weight to shortcut keycaps', async () => { - render( - , - ) - const button = page.getByRole('button', {name: /^Save/}) - await expect - .poll(() => getComputedStyle(button.element()).getPropertyValue('-webkit-font-smoothing')) - .toBe('antialiased') - await expect - .poll(() => getComputedStyle(button.element().querySelector('[data-component="text"]')!).fontWeight) - .toBe('600') - expect( - getComputedStyle(button.element().querySelector('[data-component="text"]')!).getPropertyValue( - '-webkit-font-smoothing', - ), - ).toBe('antialiased') - expect(getComputedStyle(button.element().querySelector('[data-kbd-chord]')!).fontWeight).toBe('400') - expect( - getComputedStyle(button.element().querySelector('[data-kbd-chord]')!).getPropertyValue( - '-webkit-font-smoothing', - ), - ).toBe('antialiased') - }) - - it.each([ - {leading: false, trailing: false}, - {leading: true, trailing: false}, - {leading: false, trailing: true}, - {leading: true, trailing: true}, - ])('spaces buttons with leading=$leading and trailing=$trailing', async ({leading, trailing}) => { - render( - , - ) - - const button = page.getByRole('button', {name: 'Search', exact: true}) - await expect - .poll(() => getComputedStyle(button.element()).paddingInlineStart) - .toBe(leading ? leadingPadding : padding) - expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(padding) - expect(getComputedStyle(button.element()).height).toBe(height) - expect(getComputedStyle(page.getByText('Search', {exact: true}).element()).lineHeight).toBe(lineHeight) - - const label = page.getByText('Search', {exact: true}).element().getBoundingClientRect() - const icons = button.element().querySelectorAll('svg') - if (leading) { - expect(label.left - icons[0].getBoundingClientRect().right).toBe(6) - } - if (trailing) { - expect(icons[icons.length - 1].getBoundingClientRect().left - label.right).toBe(6) - } - }) - - it('preserves inline Link height while applying leading visual padding', async () => { - render( -
- -
, - ) - const button = page.getByRole('button', {name: 'Search', exact: true}) - await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(leadingPadding) - expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(padding) - expect(button.element().getBoundingClientRect().height).toBeLessThan(Number.parseFloat(height)) - const labelStyle = getComputedStyle(page.getByText('Search', {exact: true}).element()) - expect(labelStyle.fontSize).toBe('16px') - expect(labelStyle.lineHeight).toBe(size === 'small' ? '26px' : '24px') - }) - }) - - it.each(['small', 'medium', 'large'] as const)('does not change %s IconButton styles', async size => { - render() - - const button = page.getByRole('button', {name: 'Search', exact: true}) - await expect.poll(() => getComputedStyle(button.element()).fontWeight).toBe('500') - expect(getComputedStyle(button.element()).borderRadius).toBe('6px') - expect(getComputedStyle(button.element()).getPropertyValue('-webkit-font-smoothing')).not.toBe('antialiased') - }) - - it.each([ - {size: 'small', padding: '4px'}, - {size: 'medium', padding: '8px'}, - {size: 'large', padding: '12px'}, - ] as const)('preserves $size icon-only counter padding', async ({size, padding}) => { - render(, - ) - const button = page.getByRole('button', {name: /^Save/}) - await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(start) - expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(end) - rerender( - , - ) - await expect.poll(() => getComputedStyle(button.element()).paddingInlineStart).toBe(start) - expect(getComputedStyle(button.element()).paddingInlineEnd).toBe(end) - }) - - it('styles primary button appropriately', () => { - render( - , - ) - - const button = page.getByRole('button') - expect(button.element()).toMatchSnapshot() - }) - - it('styles invisible button appropriately', () => { - render( - , - ) - - const button = page.getByRole('button') - expect(button.element()).toMatchSnapshot() - }) - - it('styles danger button appropriately', () => { - render( - , - ) - - const button = page.getByRole('button') - expect(button.element()).toMatchSnapshot() - }) - - it('makes sure icon button has an aria-label', async () => { - render() - const IconOnlyButton = page.getByLabelText('Search button', { - exact: true, - }) - await expect.element(IconOnlyButton).toBeInTheDocument() - }) - - it('respects the alignContent prop', () => { - render( - , - ) - - const button = page.getByRole('button') - expect(button.element()).toMatchSnapshot() - }) - - it('should render the leadingVisual prop before the button content', async () => { - render( - , - ) - - await expect.element(page.getByTestId('leadingVisual')).toBeInTheDocument() - - const position = page - .getByText('content', { - exact: true, - }) - .element() - .compareDocumentPosition(page.getByTestId('leadingVisual').element()) - expect(position).toBe(Node.DOCUMENT_POSITION_PRECEDING) - }) - - it('should render the trailingVisual prop after the button content', async () => { - render( - , - ) - await expect.element(page.getByTestId('trailingVisual')).toBeInTheDocument() - - const position = page - .getByText('content', { - exact: true, - }) - .element() - .compareDocumentPosition(page.getByTestId('trailingVisual').element()) - expect(position).toBe(Node.DOCUMENT_POSITION_FOLLOWING) - }) - - it('should describe the button with a default loading announcement, and only when the button is in a loading state', async () => { - const buttonId = 'loading-button' - - render( - - content - , - ) - - const buttonNode = page.getByRole('button') - - await userEvent.click(buttonNode) - - await expect.element(buttonNode).toHaveAttribute('aria-describedby', `${buttonId}-loading-announcement`) - - fireEvent.click(buttonNode.element()) - - await expect.poll(() => document.getElementById(`${buttonId}-loading-announcement`)?.textContent).toBe('Loading') - }) - - it('should render a custom loading announcement, and only when the button is in a loading state', async () => { - const buttonId = 'loading-button' - - render( - - content - , - ) - - const buttonNode = page.getByRole('button') - - await userEvent.click(buttonNode) - - await expect.element(buttonNode).toHaveAttribute('aria-describedby', `${buttonId}-loading-announcement`) - - fireEvent.click(buttonNode.element()) - - await expect - .poll(() => document.getElementById(`${buttonId}-loading-announcement`)?.textContent) - .toBe('Action loading') - }) - - it('should be described by loading announcement AND whatever is passed to aria-describedby', async () => { - const buttonDescriptionId = 'button-description' - const buttonId = 'loading-button' - - render( - - content - , - ) - - const buttonNode = page.getByRole('button') - - await userEvent.click(buttonNode) - - const buttonDescribedBy = page.getByRole('button').element().getAttribute('aria-describedby') - const loadingAnnouncementId = `${buttonId}-loading-announcement` - - expect(buttonDescribedBy).toContain(loadingAnnouncementId) - - expect(buttonDescribedBy).toContain(buttonDescriptionId) - }) - - it('should only set aria-disabled to "true" when the button is in a loading state', async () => { - render( - - content - , - ) - - const buttonNode = page.getByRole('button') - - expect(buttonNode.element().getAttribute('aria-disabled')).not.toBe('true') - - await userEvent.click(buttonNode) - - await expect.element(buttonNode).toHaveAttribute('aria-disabled', 'true') - }) - - it('allows the consumer to override `aria-disabled`', async () => { - render() - - await expect.element(page.getByRole('button')).toHaveAttribute('aria-disabled', 'true') - }) - - describe('accessible loading disabled styles', () => { - const visualStyles = (element: Element) => { - const {backgroundColor, borderColor, color, cursor} = getComputedStyle(element) - return {backgroundColor, borderColor, color, cursor} - } - - const renderWithLoadingDisabledStyles = (children: React.ReactNode) => - render({children}) - - it('applies disabled styles to a loading primary button without using native disabled', async () => { - renderWithLoadingDisabledStyles( - <> - - - - , - ) - - const loadingButton = page.getByRole('button', { - name: 'Loading', - exact: true, - }) - const disabledButton = page.getByRole('button', { - name: 'Disabled', - exact: true, - }) - const enabledButton = page.getByRole('button', { - name: 'Enabled', - exact: true, - }) - - await expect.element(loadingButton).toHaveAttribute('aria-disabled', 'true') - await expect.element(loadingButton).toHaveAttribute('data-loading', 'true') - await expect.element(loadingButton).toHaveAttribute('data-loading-disabled-styles', 'true') - await expect.element(loadingButton).not.toBeDisabled() - expect(visualStyles(loadingButton.element())).toEqual(visualStyles(disabledButton.element())) - expect(visualStyles(loadingButton.element()).backgroundColor).not.toBe( - visualStyles(enabledButton.element()).backgroundColor, - ) - expect(visualStyles(loadingButton.element()).cursor).toBe('not-allowed') - }) - - it('applies disabled styles when loading is combined with aria-disabled', async () => { - renderWithLoadingDisabledStyles( - <> - - - , - ) - - const loadingButton = page.getByRole('button', { - name: 'Loading', - exact: true, - }) - const disabledButton = page.getByRole('button', { - name: 'Disabled', - exact: true, - }) - - await expect.element(loadingButton).toHaveAttribute('aria-disabled', 'true') - await expect.element(loadingButton).not.toBeDisabled() - expect(visualStyles(loadingButton.element())).toEqual(visualStyles(disabledButton.element())) - }) - - it('preserves existing loading styles when the feature flag is disabled', async () => { - render( - <> - - - , - ) - - const loadingButton = page.getByRole('button', { - name: 'Loading', - exact: true, - }) - const disabledButton = page.getByRole('button', { - name: 'Disabled', - exact: true, - }) - - await expect.element(loadingButton).not.toHaveAttribute('data-loading-disabled-styles') - expect(visualStyles(loadingButton.element())).not.toEqual(visualStyles(disabledButton.element())) - }) - - it('does not call onClick while loading', () => { - const onClick = vi.fn() - render( - , - ) - - fireEvent.click( - page - .getByRole('button', { - name: 'Submit', - exact: true, - }) - .element(), - ) - expect(onClick).not.toHaveBeenCalled() - }) - - it('remains focusable while loading', async () => { - render( - , - ) - - const button = page.getByRole('button', { - name: 'Submit', - exact: true, - }) - button.element().focus() - expect(button.element()).toHaveFocus() - }) - - it('still applies disabled styles for aria-disabled without loading', () => { - render( - <> - - - , - ) - - expect( - visualStyles( - page - .getByRole('button', { - name: 'Aria disabled', - exact: true, - }) - .element(), - ), - ).toEqual( - visualStyles( - page - .getByRole('button', { - name: 'Disabled', - exact: true, - }) - .element(), - ), - ) - }) - - it('does not let inactive override primary the same way disabled styles do', () => { - render( - <> - - - , - ) - - expect( - visualStyles( - page - .getByRole('button', { - name: 'Inactive', - exact: true, - }) - .element(), - ), - ).not.toEqual( - visualStyles( - page - .getByRole('button', { - name: 'Disabled', - exact: true, - }) - .element(), - ), - ) - }) - }) - - it('should preserve the accessible button name when the button is in a loading state', async () => { - render() - - await expect.element(page.getByRole('button')).toHaveAccessibleName('content') - }) - - it('should apply inline-flex display to loading wrapper when variant is link', async () => { - const {container} = render( - , - ) - - const wrapper = container.querySelector('[data-loading-wrapper]') - await expect.element(wrapper).toBeInTheDocument() - await expect.element(wrapper).toHaveClass(classes.ConditionalWrapperLink) - }) - - it('should render tooltip on an icon button when unsafeDisableTooltip prop is passed as false', async () => { - render() - const triggerEL = page.getByRole('button') - const tooltipEl = page.getByText('Heart', { - exact: true, - }) - await expect.element(triggerEL).toHaveAttribute('aria-labelledby', tooltipEl.element().id) - }) - it('should render description type tooltip on an icon button when unsafeDisableTooltip prop is passed as false', async () => { - render() - - const triggerEL = page.getByRole('button') - await expect.element(triggerEL).toHaveAttribute('aria-label', 'Heart') - const tooltipEl = page.getByText('Love is all around', { - exact: true, - }) - expect(triggerEL.element().getAttribute('aria-describedby')).toContain(tooltipEl.element().id) - }) - it('should render tooltip on an icon button by default', async () => { - render() - const triggerEl = page.getByRole('button') - const tooltipEl = page.getByText('Heart', { - exact: true, - }) - await expect.element(triggerEl).toHaveAttribute('aria-labelledby', tooltipEl.element().id) - await expect.element(triggerEl).not.toHaveAttribute('aria-label') - }) - it('should render aria-keyshorts on an icon button when keyshortcuts prop is passed', async () => { - render() - const triggerEl = page.getByRole('button') - await expect.element(triggerEl).toHaveAttribute('aria-keyshortcuts', 'Command+H') - }) - it('should append the keyshortcuts to the tooltip text that labels the icon button when keyshortcuts prop is passed', async () => { - render() - const triggerEl = page.getByRole('button', { - name: 'Heart (command h)', - exact: true, - }) - await expect.element(triggerEl).toBeInTheDocument() - }) - it('should render aria-keyshortcuts on an icon button when keyshortcuts prop is passed (Description Type)', async () => { - render() - - const triggerEl = page.getByRole('button') - await expect.element(triggerEl).toHaveAttribute('aria-keyshortcuts', 'Command+H') - }) - it('should append the keyshortcuts to the tooltip text that describes the icon button when keyshortcuts prop is passed (Description Type)', async () => { - render() - - const triggerEl = page.getByRole('button', { - name: 'Heart', - exact: true, - }) - await expect.element(triggerEl).toHaveAccessibleDescription('Love is all around (command h)') - }) -}) - -describe('data-component attributes', () => { - describe('Button', () => { - it('should have data-component="Button" on the button element', async () => { - const {container} = render() - await expect.element(container.querySelector('[data-component="Button"]')).toBeInTheDocument() - }) - - it('should have data-component="buttonContent" on the content wrapper', async () => { - const {container} = render() - await expect.element(container.querySelector('[data-component="buttonContent"]')).toBeInTheDocument() - }) - - it('should have data-component="text" on the text element', async () => { - const {container} = render() - await expect.element(container.querySelector('[data-component="text"]')).toBeInTheDocument() - }) - - it('should have data-component="leadingVisual" on leading visual', async () => { - const {container} = render() - await expect.element(container.querySelector('[data-component="leadingVisual"]')).toBeInTheDocument() - }) - - it('should have data-component="trailingVisual" on trailing visual', async () => { - const {container} = render() - await expect - .element(container.querySelector('[data-component="trailingVisual"]')) - .toBeInTheDocument() - }) - - it('should have data-component="ButtonCounter" on count element', async () => { - const {container} = render() - await expect.element(container.querySelector('[data-component="ButtonCounter"]')).toBeInTheDocument() - }) - - it('should have data-component="loadingSpinner" when loading without visuals', async () => { - const {container} = render() - await expect - .element(container.querySelector('[data-component="loadingSpinner"]')) - .toBeInTheDocument() - }) - }) - - describe('data-icon-only-counter', () => { - it('is set when count, leadingVisual, and no children are present', async () => { - const {container} = render(, - ) - await expect - .element(container.querySelector('[data-component="Button"]')) - .not.toHaveAttribute('data-icon-only-counter') - }) - - it('is not set when leadingVisual is missing', async () => { - const {container} = render() + const button = page.getByRole('button') + expect(button.element().textContent).toEqual('Default') + }) + + it('preserves "onClick" prop', async () => { + const onClick = vi.fn() + render() + const button = page.getByRole('button') + await userEvent.click(button) + expect(onClick).toHaveBeenCalledTimes(1) + }) + + it('respects block prop', () => { + render( + , + ) + + const button = page.getByRole('button') + expect(button.element()).toMatchSnapshot() + }) + + it('displays a notification indicator on the button boundary', async () => { + render() + await expect.element(page.getByRole('button')).toHaveAttribute('data-notification-indicator', 'button') + }) + + it('displays a notification indicator on the leading visual', async () => { + render( + , + ) + + await expect.element(page.getByRole('button')).toHaveAttribute('data-notification-indicator', 'leadingVisual') + }) + + it('displays a notification indicator on an icon button icon', async () => { + render() + + await expect.element(page.getByRole('button')).toHaveAttribute('data-notification-indicator', 'icon') + }) + + it('warns when a leading visual notification indicator has no leading visual', () => { + const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render() + + expect(consoleSpy).toHaveBeenCalledWith( + 'Button: `notificationIndicator="leadingVisual"` requires a `leadingVisual` prop.', + ) + consoleSpy.mockRestore() + }) + + it('respects the "disabled" prop', () => { + const onClick = vi.fn() + + render( + , + ) + + const button = page.getByRole('button') + expect(button.element().hasAttribute('disabled')).toEqual(true) + fireEvent.click(button.element()) + expect(onClick).toHaveBeenCalledTimes(0) + }) + + it('respects the small size prop', () => { + render( + , + ) + + const button = page.getByRole('button') + expect(button.element()).toMatchSnapshot() + }) + + it('respects the large size prop', () => { + render( + , + ) + + const button = page.getByRole('button') + expect(button.element()).toMatchSnapshot() + }) + + it('styles primary button appropriately', () => { + render( + , + ) + + const button = page.getByRole('button') + expect(button.element()).toMatchSnapshot() + }) + + it('styles invisible button appropriately', () => { + render( + , + ) + + const button = page.getByRole('button') + expect(button.element()).toMatchSnapshot() + }) + + it('styles danger button appropriately', () => { + render( + , + ) + + const button = page.getByRole('button') + expect(button.element()).toMatchSnapshot() + }) + + it('makes sure icon button has an aria-label', async () => { + render() + const IconOnlyButton = page.getByLabelText('Search button', { + exact: true, + }) + await expect.element(IconOnlyButton).toBeInTheDocument() + }) + + it('respects the alignContent prop', () => { + render( + , + ) + + const button = page.getByRole('button') + expect(button.element()).toMatchSnapshot() + }) + + it('should render the leadingVisual prop before the button content', async () => { + render( + , + ) + + await expect.element(page.getByTestId('leadingVisual')).toBeInTheDocument() + + const position = page + .getByText('content', { + exact: true, + }) + .element() + .compareDocumentPosition(page.getByTestId('leadingVisual').element()) + expect(position).toBe(Node.DOCUMENT_POSITION_PRECEDING) + }) + + it('should render the trailingVisual prop after the button content', async () => { + render( + , + ) + await expect.element(page.getByTestId('trailingVisual')).toBeInTheDocument() + + const position = page + .getByText('content', { + exact: true, + }) + .element() + .compareDocumentPosition(page.getByTestId('trailingVisual').element()) + expect(position).toBe(Node.DOCUMENT_POSITION_FOLLOWING) + }) + + it('should describe the button with a default loading announcement, and only when the button is in a loading state', async () => { + const buttonId = 'loading-button' + + render( + + content + , + ) + + const buttonNode = page.getByRole('button') + + await userEvent.click(buttonNode) + + await expect.element(buttonNode).toHaveAttribute('aria-describedby', `${buttonId}-loading-announcement`) + + fireEvent.click(buttonNode.element()) + + await expect.poll(() => document.getElementById(`${buttonId}-loading-announcement`)?.textContent).toBe('Loading') + }) + + it('should render a custom loading announcement, and only when the button is in a loading state', async () => { + const buttonId = 'loading-button' + + render( + + content + , + ) + + const buttonNode = page.getByRole('button') + + await userEvent.click(buttonNode) + + await expect.element(buttonNode).toHaveAttribute('aria-describedby', `${buttonId}-loading-announcement`) + + fireEvent.click(buttonNode.element()) + + await expect + .poll(() => document.getElementById(`${buttonId}-loading-announcement`)?.textContent) + .toBe('Action loading') + }) + + it('should be described by loading announcement AND whatever is passed to aria-describedby', async () => { + const buttonDescriptionId = 'button-description' + const buttonId = 'loading-button' + + render( + + content + , + ) + + const buttonNode = page.getByRole('button') + + await userEvent.click(buttonNode) + + const buttonDescribedBy = page.getByRole('button').element().getAttribute('aria-describedby') + const loadingAnnouncementId = `${buttonId}-loading-announcement` + + expect(buttonDescribedBy).toContain(loadingAnnouncementId) + + expect(buttonDescribedBy).toContain(buttonDescriptionId) + }) + + it('should only set aria-disabled to "true" when the button is in a loading state', async () => { + render( + + content + , + ) + + const buttonNode = page.getByRole('button') + + expect(buttonNode.element().getAttribute('aria-disabled')).not.toBe('true') + + await userEvent.click(buttonNode) + + await expect.element(buttonNode).toHaveAttribute('aria-disabled', 'true') + }) + + it('allows the consumer to override `aria-disabled`', async () => { + render() + + await expect.element(page.getByRole('button')).toHaveAttribute('aria-disabled', 'true') + }) + + describe('accessible loading disabled styles', () => { + const visualStyles = (element: Element) => { + const {backgroundColor, borderColor, color, cursor} = getComputedStyle(element) + return {backgroundColor, borderColor, color, cursor} + } + + const renderWithLoadingDisabledStyles = (children: React.ReactNode) => + render({children}) + + it('applies disabled styles to a loading primary button without using native disabled', async () => { + renderWithLoadingDisabledStyles( + <> + + + + , + ) + + const loadingButton = page.getByRole('button', { + name: 'Loading', + exact: true, + }) + const disabledButton = page.getByRole('button', { + name: 'Disabled', + exact: true, + }) + const enabledButton = page.getByRole('button', { + name: 'Enabled', + exact: true, + }) + + await expect.element(loadingButton).toHaveAttribute('aria-disabled', 'true') + await expect.element(loadingButton).toHaveAttribute('data-loading', 'true') + await expect.element(loadingButton).toHaveAttribute('data-loading-disabled-styles', 'true') + await expect.element(loadingButton).not.toBeDisabled() + expect(visualStyles(loadingButton.element())).toEqual(visualStyles(disabledButton.element())) + expect(visualStyles(loadingButton.element()).backgroundColor).not.toBe( + visualStyles(enabledButton.element()).backgroundColor, + ) + expect(visualStyles(loadingButton.element()).cursor).toBe('not-allowed') + }) + + it('applies disabled styles when loading is combined with aria-disabled', async () => { + renderWithLoadingDisabledStyles( + <> + + + , + ) + + const loadingButton = page.getByRole('button', { + name: 'Loading', + exact: true, + }) + const disabledButton = page.getByRole('button', { + name: 'Disabled', + exact: true, + }) + + await expect.element(loadingButton).toHaveAttribute('aria-disabled', 'true') + await expect.element(loadingButton).not.toBeDisabled() + expect(visualStyles(loadingButton.element())).toEqual(visualStyles(disabledButton.element())) + }) + + it('preserves existing loading styles when the feature flag is disabled', async () => { + render( + <> + + + , + ) + + const loadingButton = page.getByRole('button', { + name: 'Loading', + exact: true, + }) + const disabledButton = page.getByRole('button', { + name: 'Disabled', + exact: true, + }) + + await expect.element(loadingButton).not.toHaveAttribute('data-loading-disabled-styles') + expect(visualStyles(loadingButton.element())).not.toEqual(visualStyles(disabledButton.element())) + }) + + it('does not call onClick while loading', () => { + const onClick = vi.fn() + render( + , + ) + + fireEvent.click( + page + .getByRole('button', { + name: 'Submit', + exact: true, + }) + .element(), + ) + expect(onClick).not.toHaveBeenCalled() + }) + + it('remains focusable while loading', async () => { + render( + , + ) + + const button = page.getByRole('button', { + name: 'Submit', + exact: true, + }) + button.element().focus() + expect(button.element()).toHaveFocus() + }) + + it('still applies disabled styles for aria-disabled without loading', () => { + render( + <> + + + , + ) + + expect( + visualStyles( + page + .getByRole('button', { + name: 'Aria disabled', + exact: true, + }) + .element(), + ), + ).toEqual( + visualStyles( + page + .getByRole('button', { + name: 'Disabled', + exact: true, + }) + .element(), + ), + ) + }) + + it('does not let inactive override primary the same way disabled styles do', () => { + render( + <> + + + , + ) + + expect( + visualStyles( + page + .getByRole('button', { + name: 'Inactive', + exact: true, + }) + .element(), + ), + ).not.toEqual( + visualStyles( + page + .getByRole('button', { + name: 'Disabled', + exact: true, + }) + .element(), + ), + ) + }) + }) + + it('should preserve the accessible button name when the button is in a loading state', async () => { + render() + + await expect.element(page.getByRole('button')).toHaveAccessibleName('content') + }) + + it('should apply inline-flex display to loading wrapper when variant is link', async () => { + const {container} = render( + , + ) + + const wrapper = container.querySelector('[data-loading-wrapper]') + await expect.element(wrapper).toBeInTheDocument() + await expect.element(wrapper).toHaveClass(classes.ConditionalWrapperLink) + }) + + it('should render tooltip on an icon button when unsafeDisableTooltip prop is passed as false', async () => { + render() + const triggerEL = page.getByRole('button') + const tooltipEl = page.getByText('Heart', { + exact: true, + }) + await expect.element(triggerEL).toHaveAttribute('aria-labelledby', tooltipEl.element().id) + }) + it('should render description type tooltip on an icon button when unsafeDisableTooltip prop is passed as false', async () => { + render() + + const triggerEL = page.getByRole('button') + await expect.element(triggerEL).toHaveAttribute('aria-label', 'Heart') + const tooltipEl = page.getByText('Love is all around', { + exact: true, + }) + expect(triggerEL.element().getAttribute('aria-describedby')).toContain(tooltipEl.element().id) + }) + it('should render tooltip on an icon button by default', async () => { + render() + const triggerEl = page.getByRole('button') + const tooltipEl = page.getByText('Heart', { + exact: true, + }) + await expect.element(triggerEl).toHaveAttribute('aria-labelledby', tooltipEl.element().id) + await expect.element(triggerEl).not.toHaveAttribute('aria-label') + }) + it('should render aria-keyshorts on an icon button when keyshortcuts prop is passed', async () => { + render() + const triggerEl = page.getByRole('button') + await expect.element(triggerEl).toHaveAttribute('aria-keyshortcuts', 'Command+H') + }) + it('should append the keyshortcuts to the tooltip text that labels the icon button when keyshortcuts prop is passed', async () => { + render() + const triggerEl = page.getByRole('button', { + name: 'Heart (command h)', + exact: true, + }) + await expect.element(triggerEl).toBeInTheDocument() + }) + it('should render aria-keyshortcuts on an icon button when keyshortcuts prop is passed (Description Type)', async () => { + render() + + const triggerEl = page.getByRole('button') + await expect.element(triggerEl).toHaveAttribute('aria-keyshortcuts', 'Command+H') + }) + it('should append the keyshortcuts to the tooltip text that describes the icon button when keyshortcuts prop is passed (Description Type)', async () => { + render() + + const triggerEl = page.getByRole('button', { + name: 'Heart', + exact: true, + }) + await expect.element(triggerEl).toHaveAccessibleDescription('Love is all around (command h)') + }) +}) + +describe('data-component attributes', () => { + describe('Button', () => { + it('should have data-component="Button" on the button element', async () => { + const {container} = render() + await expect.element(container.querySelector('[data-component="Button"]')).toBeInTheDocument() + }) + + it('should have data-component="buttonContent" on the content wrapper', async () => { + const {container} = render() + await expect.element(container.querySelector('[data-component="buttonContent"]')).toBeInTheDocument() + }) + + it('should have data-component="text" on the text element', async () => { + const {container} = render() + await expect.element(container.querySelector('[data-component="text"]')).toBeInTheDocument() + }) + + it('should have data-component="leadingVisual" on leading visual', async () => { + const {container} = render() + await expect.element(container.querySelector('[data-component="leadingVisual"]')).toBeInTheDocument() + }) + + it('should have data-component="trailingVisual" on trailing visual', async () => { + const {container} = render() + await expect + .element(container.querySelector('[data-component="trailingVisual"]')) + .toBeInTheDocument() + }) + + it('should have data-component="ButtonCounter" on count element', async () => { + const {container} = render() + await expect.element(container.querySelector('[data-component="ButtonCounter"]')).toBeInTheDocument() + }) + + it('should have data-component="loadingSpinner" when loading without visuals', async () => { + const {container} = render() + await expect + .element(container.querySelector('[data-component="loadingSpinner"]')) + .toBeInTheDocument() + }) + }) + + describe('data-icon-only-counter', () => { + it('is set when count, leadingVisual, and no children are present', async () => { + const {container} = render(, + ) + await expect + .element(container.querySelector('[data-component="Button"]')) + .not.toHaveAttribute('data-icon-only-counter') + }) + + it('is not set when leadingVisual is missing', async () => { + const {container} = render( + + Standalone action + + + Actions + + + + Simple action + + + + + + + + + Search + Find a file + + + + + , + ) + + const trigger = page.getByRole('button', {name: 'Actions', exact: true}) + expect(getComputedStyle(trigger.element()).fontSize).toBe('13px') + const standaloneButton = page.getByRole('button', {name: 'Standalone button', exact: true}) + expect(getComputedStyle(standaloneButton.element()).fontSize).toBe('14px') + await userEvent.click(trigger) + + const simpleItem = page.getByRole('menuitem', {name: /^Simple action/}) + const descriptionItem = page.getByRole('menuitem', {name: 'Search', exact: true}) + await expect.element(descriptionItem).toBeVisible() + + expect(simpleItem.element().getBoundingClientRect().height).toBeCloseTo(28, 3) + expect(descriptionItem.element().getBoundingClientRect().height).toBeCloseTo(48, 3) + expect(descriptionItem.element().querySelector('svg')?.getBoundingClientRect().width).toBeCloseTo(14, 3) + const label = descriptionItem.element().querySelector('[data-component="ActionList.Item.Label"]')! + expect(getComputedStyle(label).fontSize).toBe('13px') + expect(getComputedStyle(label).fontWeight).toBe('500') + expect(getComputedStyle(label).lineHeight).toBe('20px') + + const standaloneItem = page.getByRole('button', {name: 'Standalone action', exact: true}) + expect(standaloneItem.element().getBoundingClientRect().height).toBeCloseTo(32, 3) + }) + it('renders data-component attributes for ActionMenu parts', async () => { const component = HTMLRender() diff --git a/packages/react/src/ActionMenu/ActionMenu.tsx b/packages/react/src/ActionMenu/ActionMenu.tsx index c33997690f5..6e7a6449031 100644 --- a/packages/react/src/ActionMenu/ActionMenu.tsx +++ b/packages/react/src/ActionMenu/ActionMenu.tsx @@ -15,6 +15,8 @@ import type {MandateProps} from '../utils/types' import type {ForwardRefComponent as PolymorphicForwardRefComponent} from '../utils/polymorphic' import {Tooltip} from '../TooltipV2/Tooltip' import styles from './ActionMenu.module.css' +import menuModernizeClasses from './ActionMenu.modernize.module.css' +import modernizeClasses from '../ActionList/ActionList.modernize.module.css' import {useResponsiveValue, type ResponsiveValue} from '../hooks/useResponsiveValue' import {isSlot} from '../utils/is-slot' import type {FCWithSlotMarker, WithSlotMarker} from '../utils/types/Slots' @@ -254,10 +256,16 @@ const Anchor: WithSlotMarker< /** this component is syntactical sugar 🍭 */ export type ActionMenuButtonProps = ButtonProps -const MenuButton = React.forwardRef(({...props}, anchorRef) => { +const MenuButton = React.forwardRef(({className, ...props}, anchorRef) => { return ( - + +) + export const Condensed = {args: {keys: chord}} export const Full = {args: {keys: chord, format: 'full'}} diff --git a/packages/react/src/KeybindingHint/KeybindingHint.modernize.module.css b/packages/react/src/KeybindingHint/KeybindingHint.modernize.module.css new file mode 100644 index 00000000000..5a3ff36f3b0 --- /dev/null +++ b/packages/react/src/KeybindingHint/KeybindingHint.modernize.module.css @@ -0,0 +1,65 @@ +.Chord[data-kbd-chord][data-size] { + min-width: 0; + padding: 0; + border: 0; + border-radius: 0; + box-shadow: none; + background: transparent; + color: inherit; + font-size: inherit; + line-height: inherit; + align-items: center; + gap: var(--base-size-4); + overflow: visible; +} + +.Key { + display: inline-block; + padding-block: var(--base-size-4); + padding-inline: var(--base-size-6); + border: var(--borderWidth-thin) solid var(--borderColor-muted); + /* stylelint-disable-next-line primer/borders -- match the reference's 4px keycap radius */ + border-radius: 4px; + background-color: var(--bgColor-muted); + color: var(--fgColor-default); + /* stylelint-disable primer/typography -- match the reference's 11px labels and 10px keycap line height */ + font-size: 11px; + line-height: 10px; + /* stylelint-enable primer/typography */ + font-family: inherit; + font-weight: var(--base-text-weight-normal); + text-align: center; + vertical-align: middle; + /* stylelint-disable-next-line primer/box-shadow -- the keycap's bottom edge uses its border token */ + box-shadow: inset 0 -1px 0 var(--borderColor-muted); + + &:where([data-single-character]) { + width: calc(var(--base-size-20) - var(--base-size-2)); + padding-inline: 0; + } +} + +.Key:where([data-size='small']) { + min-width: var(--base-size-16); + padding-block: var(--base-size-2); + /* stylelint-disable-next-line primer/typography -- retain the existing small keycap height */ + line-height: var(--base-size-8); + + &:where([data-single-character]) { + width: var(--base-size-16); + } +} + +.Key:where([data-variant='onEmphasis'], [data-variant='onPrimary']) { + border-color: transparent; + color: var(--fgColor-onEmphasis); + box-shadow: none; +} + +.Key:where([data-variant='onEmphasis']) { + background-color: var(--counter-bgColor-emphasis); +} + +.Key:where([data-variant='onPrimary']) { + background-color: var(--button-primary-bgColor-active); +} diff --git a/packages/react/src/KeybindingHint/KeybindingHint.test.tsx b/packages/react/src/KeybindingHint/KeybindingHint.test.tsx index 6144a7ab286..d721f5655d9 100644 --- a/packages/react/src/KeybindingHint/KeybindingHint.test.tsx +++ b/packages/react/src/KeybindingHint/KeybindingHint.test.tsx @@ -8,6 +8,32 @@ import {implementsClassName} from '../utils/testing' describe('KeybindingHint', () => { implementsClassName(props => ) + it('renders individually sized keycaps with space between them', async () => { + render() + const keys = ['⌃', '⇧', 'K'].map(name => page.getByText(name, {exact: true})) + for (const key of keys) { + await expect.element(key).toHaveStyle({width: '18px', height: '20px'}) + } + const boxes = keys.map(key => key.element().getBoundingClientRect()) + expect(boxes[1].left - boxes[0].right).toBe(4) + expect(boxes[2].left - boxes[1].right).toBe(4) + expect(keys[0].element().closest('[data-kbd-chord]')?.getBoundingClientRect().height).toBe(20) + }) + + it('lets word labels grow without widening single-character keycaps', async () => { + render( + <> + + + , + ) + const word = page.getByText('Esc', {exact: true}) + const letter = page.getByText('K', {exact: true}) + await expect.element(letter).toHaveStyle({width: '18px'}) + expect(word.element().getBoundingClientRect().width).toBeGreaterThan(18) + expect(word.element().getBoundingClientRect().height).toBe(letter.element().getBoundingClientRect().height) + }) + it('renders data-component="KeybindingHint" on the root element', async () => { render() await expect.element(page.getByTestId('keybinding-hint')).toHaveAttribute('data-component', 'KeybindingHint') diff --git a/packages/react/src/KeybindingHint/components/Chord.tsx b/packages/react/src/KeybindingHint/components/Chord.tsx index b07f8c9c68a..14f3642bef7 100644 --- a/packages/react/src/KeybindingHint/components/Chord.tsx +++ b/packages/react/src/KeybindingHint/components/Chord.tsx @@ -5,11 +5,14 @@ import {Key} from './Key' import {clsx} from 'clsx' import classes from './Chord.module.css' import {splitChord} from './utils' +import modernizeClasses from '../KeybindingHint.modernize.module.css' export const Chord = ({keys, format = 'condensed', variant = 'normal', size = 'normal'}: KeybindingHintProps) => ( + ))} diff --git a/packages/react/src/KeybindingHint/components/Key.tsx b/packages/react/src/KeybindingHint/components/Key.tsx index f17703c15bc..9d9d2e19e35 100644 --- a/packages/react/src/KeybindingHint/components/Key.tsx +++ b/packages/react/src/KeybindingHint/components/Key.tsx @@ -1,21 +1,34 @@ import VisuallyHidden from '../../_VisuallyHidden' import {accessibleKeyName, condensedKeyName, fullKeyName} from '../key-names' -import type {KeybindingHintFormat} from '../props' +import type {KeybindingHintFormat, KeybindingHintProps} from '../props' import {usePlatform} from '../platform' +import classes from '../KeybindingHint.modernize.module.css' interface KeyProps { name: string format: KeybindingHintFormat + variant: KeybindingHintProps['variant'] + size: KeybindingHintProps['size'] } /** Renders a single key with accessible alternative text. */ -export const Key = ({name, format}: KeyProps) => { +export const Key = ({name, format, variant, size}: KeyProps) => { const platform = usePlatform() + const label = format === 'condensed' ? condensedKeyName(name, platform) : fullKeyName(name, platform) return ( <> {accessibleKeyName(name, platform)} - {format === 'condensed' ? condensedKeyName(name, platform) : fullKeyName(name, platform)} + + {label} + ) } From 0662a2412edf8c048d68c731c38698975799ef7c Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Sun, 15 Nov 2026 00:47:16 +0100 Subject: [PATCH 19/27] Modernize Dialog density, layout, and comparison stories Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changeset/modernize-dialog.md | 5 + packages/react/src/Dialog/Dialog.docs.json | 6 ++ .../src/Dialog/Dialog.features.stories.tsx | 94 +++++++++++++++++++ .../src/Dialog/Dialog.modernize.module.css | 91 ++++++++++++++++++ .../src/Dialog/Dialog.stories.module.css | 16 ++++ packages/react/src/Dialog/Dialog.test.tsx | 33 +++++++ packages/react/src/Dialog/Dialog.tsx | 72 +++++++++++--- 7 files changed, 303 insertions(+), 14 deletions(-) create mode 100644 .changeset/modernize-dialog.md create mode 100644 packages/react/src/Dialog/Dialog.modernize.module.css diff --git a/.changeset/modernize-dialog.md b/.changeset/modernize-dialog.md new file mode 100644 index 00000000000..e085f3425fc --- /dev/null +++ b/.changeset/modernize-dialog.md @@ -0,0 +1,5 @@ +--- +'@primer/react': minor +--- + +Dialog: Refine header, body, and footer spacing and add a small visual density. diff --git a/packages/react/src/Dialog/Dialog.docs.json b/packages/react/src/Dialog/Dialog.docs.json index f2e5f204cf1..6e9cc8646e9 100644 --- a/packages/react/src/Dialog/Dialog.docs.json +++ b/packages/react/src/Dialog/Dialog.docs.json @@ -44,6 +44,12 @@ ], "importPath": "@primer/react", "props": [ + { + "name": "size", + "type": "'small' | 'medium'", + "defaultValue": "'medium'", + "description": "Visual density of the header, body, and footer. Small uses compact typography and spacing without changing the dialog's width or height." + }, { "name": "title", "type": "React.ReactNode", diff --git a/packages/react/src/Dialog/Dialog.features.stories.tsx b/packages/react/src/Dialog/Dialog.features.stories.tsx index aafb900258a..3428cbe2e6d 100644 --- a/packages/react/src/Dialog/Dialog.features.stories.tsx +++ b/packages/react/src/Dialog/Dialog.features.stories.tsx @@ -7,13 +7,107 @@ import {ActionList} from '../ActionList' import type {DialogProps, DialogWidth, DialogHeight} from './Dialog' import {Dialog} from './Dialog' import classes from './Dialog.stories.module.css' +import baseClasses from './Dialog.module.css' +import modernizeClasses from './Dialog.modernize.module.css' +import type {Meta, StoryObj} from '@storybook/react-vite' +import {expect, within} from 'storybook/test' /* Dialog Version 2 */ export default { title: 'Components/Dialog/Features', + component: Dialog, +} satisfies Meta + +function ComparisonDialog({small = false, tall = false}: {small?: boolean; tall?: boolean}) { + const [open, setOpen] = useState(false) + return ( +
+ + {open && ( + setOpen(false)} + footerButtons={[ + {content: tall ? 'Decline' : 'Cancel', onClick: () => setOpen(false)}, + {content: tall ? 'Accept' : 'Confirm', variant: 'primary', onClick: () => setOpen(false)}, + ]} + > + {tall + ? Array.from( + {length: 60}, + (_, i) => + `Paragraph ${i + 1}: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.`, + ).map(paragraph => ( +

+ {paragraph} +

+ )) + : small + ? 'This dialog uses the small UI font size.' + : 'This dialog is configured from Storybook controls.'} +
+ )} +
+ ) } +const openComparisonDialog: StoryObj['play'] = async ({canvas, canvasElement, userEvent}) => { + await userEvent.click(canvas.getByRole('button')) + await expect(within(canvasElement.ownerDocument.body).getByRole('dialog')).toBeVisible() +} + +export const ModernizedDialog: StoryObj = { + render: () => , + play: openComparisonDialog, +} +export const ModernizedSmall: StoryObj = { + render: () => , + play: openComparisonDialog, +} +export const ModernizedTall: StoryObj = { + render: () => , + play: openComparisonDialog, +} + +function ComparisonHeader({ + small = false, + subtitle, + closeButton = true, +}: { + small?: boolean + subtitle?: string + closeButton?: boolean +}) { + return ( +
+
+ +
+
+ Dialog title + {subtitle && {subtitle}} +
+ {closeButton && {}} />} +
+
+
+
+ ) +} + +export const ModernizedHeader = () => +export const ModernizedHeaderSmall = () => +export const ModernizedHeaderSubtitle = () => ( + +) +export const ModernizedHeaderTitleOnly = () => + const lipsum = ( <> diff --git a/packages/react/src/Dialog/Dialog.modernize.module.css b/packages/react/src/Dialog/Dialog.modernize.module.css new file mode 100644 index 00000000000..14bd697a1a0 --- /dev/null +++ b/packages/react/src/Dialog/Dialog.modernize.module.css @@ -0,0 +1,91 @@ +.Dialog[data-component] { + & .OverflowWrapper { + border-bottom: 0; + } + + &:where([data-size='small']) { + & .Body { + /* stylelint-disable primer/typography -- match compact UI typography */ + font-size: 13px; + line-height: var(--base-size-20); + /* stylelint-enable primer/typography */ + padding: var(--base-size-16); + } + + & .Footer { + padding: var(--base-size-12); + gap: var(--base-size-8); + } + } +} + +.Header { + min-height: var(--base-size-48); + padding-block: var(--base-size-8); + padding-inline: calc(var(--base-size-20) - var(--base-size-2)) var(--base-size-8); + box-shadow: none; + border-bottom: var(--borderWidth-thin) solid var(--borderColor-muted); +} + +.Header[data-size='small'], +:where(.Dialog[data-size='small']) .Header { + min-height: var(--base-size-40); + padding-block: var(--base-size-6); + padding-inline: var(--base-size-16) var(--base-size-6); + + & .Title { + /* stylelint-disable primer/typography -- match compact UI typography */ + font-size: 13px; + line-height: var(--base-size-20); + /* stylelint-enable primer/typography */ + } + + & [data-component='Dialog.CloseButton'] { + width: var(--base-size-28); + height: var(--base-size-28); + + & svg { + width: calc(var(--base-size-16) - var(--base-size-2)); + height: calc(var(--base-size-16) - var(--base-size-2)); + } + } +} + +.HeaderInner { + align-items: center; +} + +.Header[data-has-subtitle='true'] .HeaderInner { + align-items: flex-start; +} + +.HeaderContent { + min-width: 0; + padding: 0; +} + +.Title { + font-size: var(--text-body-size-medium); + font-weight: var(--base-text-weight-semibold); + line-height: var(--base-text-lineHeight-normal); +} + +.Subtitle { + margin-top: 0; +} + +.Body { + padding: var(--base-size-20); +} + +.Footer { + & [data-component='Button']:where([data-size='medium']) { + /* stylelint-disable-next-line primer/typography -- match footer control labels without changing standalone buttons */ + font-size: 13px; + } + + padding-block: var(--base-size-16); + padding-inline: var(--base-size-20); + gap: var(--base-size-12); + border-top: var(--borderWidth-thin) solid var(--borderColor-muted); +} diff --git a/packages/react/src/Dialog/Dialog.stories.module.css b/packages/react/src/Dialog/Dialog.stories.module.css index 5b8e489c39c..4f4fa637c9a 100644 --- a/packages/react/src/Dialog/Dialog.stories.module.css +++ b/packages/react/src/Dialog/Dialog.stories.module.css @@ -2,3 +2,19 @@ font-size: var(--text-body-size-medium, 0.75rem); margin-block-start: 0; } + +.Comparison { + padding: var(--base-size-16); +} + +.ComparisonParagraph { + margin: 0 0 var(--base-size-12); +} + +.ComparisonHeader { + max-width: 100%; + overflow: hidden; + border: var(--borderWidth-thin) solid var(--borderColor-muted); + border-radius: var(--borderRadius-large); + background: var(--bgColor-default); +} diff --git a/packages/react/src/Dialog/Dialog.test.tsx b/packages/react/src/Dialog/Dialog.test.tsx index 1e61eee0e77..763a3bb39db 100644 --- a/packages/react/src/Dialog/Dialog.test.tsx +++ b/packages/react/src/Dialog/Dialog.test.tsx @@ -10,6 +10,39 @@ import classes from './Dialog.module.css' describe('Dialog', () => { implementsClassName(Dialog, classes.Dialog) + it.each([ + ['small', '13px', '16px', 41], + ['medium', '14px', '20px', 49], + ] as const)( + 'applies %s visual density to the actual header and body', + async (size, fontSize, padding, headerHeight) => { + render( + {}} footerButtons={[{content: 'Confirm'}]}> + Density content + , + ) + const dialog = page.getByRole('dialog', {name: 'Density preview', exact: true}).element() + const title = page.getByRole('heading', {name: 'Density preview', exact: true}) + await expect.element(title).toHaveStyle({fontSize}) + const body = dialog.querySelector('[data-component="Dialog.Body"]') + expect(body).toHaveStyle({padding}) + expect(dialog.querySelector('[data-component="Dialog.Header"]')?.getBoundingClientRect().height).toBe( + headerHeight, + ) + await expect.element(page.getByRole('button', {name: 'Confirm', exact: true})).toHaveStyle({ + height: size === 'small' ? '28px' : '32px', + }) + }, + ) + + it('preserves an explicit footer button size in a small dialog', async () => { + render( + {}} footerButtons={[{content: 'Large action', size: 'large'}]}> + Content + , + ) + await expect.element(page.getByRole('button', {name: 'Large action', exact: true})).toHaveStyle({height: '40px'}) + }) it('renders with role "dialog" by default', async () => { render( {}}>Pay attention to me) diff --git a/packages/react/src/Dialog/Dialog.tsx b/packages/react/src/Dialog/Dialog.tsx index ef7b8d888d4..79f94ddd5dd 100644 --- a/packages/react/src/Dialog/Dialog.tsx +++ b/packages/react/src/Dialog/Dialog.tsx @@ -14,6 +14,7 @@ import type {ResponsiveValue} from '../hooks/useResponsiveValue' import type {ForwardRefComponent as PolymorphicForwardRefComponent} from '../utils/polymorphic' import classes from './Dialog.module.css' +import modernizeClasses from './Dialog.modernize.module.css' import {clsx} from 'clsx' import {useSlots} from '../hooks/useSlots' import {useResizeObserver} from '../hooks/useResizeObserver' @@ -61,6 +62,8 @@ export type DialogButtonProps = Omit & { */ export interface DialogProps { 'data-component'?: string + /** Visual density of the dialog header, body, and footer. */ + size?: 'small' | 'medium' /** * Title of the Dialog. Also serves as the aria-label for this Dialog. */ @@ -216,6 +219,7 @@ const DefaultHeader: React.FC> = ({ dialogLabelId, title, subtitle, + size, dialogDescriptionId, onClose, }) => { @@ -237,9 +241,9 @@ const DefaultHeader: React.FC> = ({ [onClose], ) return ( - -
-
+ +
+
{title ?? 'Dialog'} {subtitle && {subtitle}}
@@ -251,14 +255,16 @@ const DefaultHeader: React.FC> = ({ const DefaultBody: React.FC> = ({children}) => { return {children} } -const DefaultFooter: React.FC> = ({footerButtons}) => { +const DefaultFooter: React.FC> = ({footerButtons, size}) => { const {containerRef: footerRef} = useFocusZone({ bindKeys: FocusKeys.ArrowHorizontal | FocusKeys.Tab, focusInStrategy: 'closest', }) return footerButtons ? ( }> - + ({size: size === 'small' ? 'small' : 'medium', ...button}))} + /> ) : null } @@ -286,6 +292,7 @@ const _Dialog = React.forwardRef(false) const [footerButtonLayout, setFooterButtonLayout] = useState<'scroll' | 'wrap'>('wrap') - const defaultedProps = {...props, title, subtitle, role, dialogLabelId, dialogDescriptionId} + const defaultedProps = {...props, title, subtitle, size, role, dialogLabelId, dialogDescriptionId} const onBackdropClick = useCallback( (e: SyntheticEvent) => { if (e.target === e.currentTarget && lastMouseDownIsBackdrop) { @@ -424,7 +431,8 @@ const _Dialog = React.forwardRef {header} - + {body} {footer} @@ -447,15 +458,29 @@ _Dialog.displayName = 'Dialog' type StyledHeaderProps = React.ComponentProps<'div'> const Header = React.forwardRef(function Header({className, ...rest}, forwardRef) { - return
+ return ( +
+ ) }) as PolymorphicForwardRefComponent<'div', StyledHeaderProps> Header.displayName = 'Dialog.Header' type StyledTitleProps = React.ComponentProps<'h1'> const Title = React.forwardRef(function Title({className, ...rest}, forwardRef) { - // eslint-disable-next-line jsx-a11y/heading-has-content - return

+ return ( + // eslint-disable-next-line jsx-a11y/heading-has-content +

+ ) }) Title.displayName = 'Dialog.Title' @@ -467,7 +492,12 @@ const Subtitle = React.forwardRef(funct ) { return ( // eslint-disable-next-line jsx-a11y/heading-has-content -

+

) }) Subtitle.displayName = 'Dialog.Subtitle' @@ -475,7 +505,14 @@ Subtitle.displayName = 'Dialog.Subtitle' type StyledBodyProps = React.ComponentProps<'div'> const Body = React.forwardRef(function Body({className, ...rest}, forwardRef) { - return
+ return ( +
+ ) }) as PolymorphicForwardRefComponent<'div', StyledBodyProps> Body.displayName = 'Dialog.Body' @@ -483,7 +520,14 @@ Body.displayName = 'Dialog.Body' type StyledFooterProps = React.ComponentProps<'div'> const Footer = React.forwardRef(function Footer({className, ...rest}, forwardRef) { - return
+ return ( +
+ ) }) as PolymorphicForwardRefComponent<'div', StyledFooterProps> Footer.displayName = 'Dialog.Footer' From 38f60eb855104a87220da323b3e14e5875cfd4d3 Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Sun, 15 Nov 2026 00:47:16 +0100 Subject: [PATCH 20/27] Modernize SelectPanel and preserve custom overlay styles Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changeset/modernize-select-panel.md | 5 + .../preserve-select-panel-overlay-styles.md | 5 + .../src/SelectPanel/SelectPanel.docs.json | 6 + .../SelectPanel.features.stories.module.css | 8 + .../SelectPanel.features.stories.tsx | 144 ++++++++++++++++++ .../SelectPanel.modernize.module.css | 122 +++++++++++++++ .../src/SelectPanel/SelectPanel.test.tsx | 65 ++++++++ .../react/src/SelectPanel/SelectPanel.tsx | 59 +++++-- .../src/SelectPanel/SelectPanelMessage.tsx | 2 +- 9 files changed, 406 insertions(+), 10 deletions(-) create mode 100644 .changeset/modernize-select-panel.md create mode 100644 .changeset/preserve-select-panel-overlay-styles.md create mode 100644 packages/react/src/SelectPanel/SelectPanel.modernize.module.css diff --git a/.changeset/modernize-select-panel.md b/.changeset/modernize-select-panel.md new file mode 100644 index 00000000000..290e9d1dea3 --- /dev/null +++ b/.changeset/modernize-select-panel.md @@ -0,0 +1,5 @@ +--- +'@primer/react': minor +--- + +SelectPanel: Refine menu and filter styling and support visually hidden titles. diff --git a/.changeset/preserve-select-panel-overlay-styles.md b/.changeset/preserve-select-panel-overlay-styles.md new file mode 100644 index 00000000000..a37b76a094a --- /dev/null +++ b/.changeset/preserve-select-panel-overlay-styles.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +SelectPanel: Preserve custom overlay styles, including popup dimensions. diff --git a/packages/react/src/SelectPanel/SelectPanel.docs.json b/packages/react/src/SelectPanel/SelectPanel.docs.json index faa9ccbc97b..6f55100771f 100644 --- a/packages/react/src/SelectPanel/SelectPanel.docs.json +++ b/packages/react/src/SelectPanel/SelectPanel.docs.json @@ -35,6 +35,12 @@ ], "importPath": "@primer/react", "props": [ + { + "name": "titleVisuallyHidden", + "type": "boolean", + "defaultValue": "false", + "description": "Visually hides the title while retaining the panel's accessible name. Use only for intentionally headerless designs." + }, { "name": "items", "type": "ItemInput[]", diff --git a/packages/react/src/SelectPanel/SelectPanel.features.stories.module.css b/packages/react/src/SelectPanel/SelectPanel.features.stories.module.css index 034c1fe28ed..12204ee08c0 100644 --- a/packages/react/src/SelectPanel/SelectPanel.features.stories.module.css +++ b/packages/react/src/SelectPanel/SelectPanel.features.stories.module.css @@ -8,6 +8,14 @@ box-sizing: border-box; } +.Comparison { + padding: var(--base-size-16); +} + +.ComparisonField { + width: 240px; +} + .MutedText { color: var(--fgColor-muted); display: inline-block; diff --git a/packages/react/src/SelectPanel/SelectPanel.features.stories.tsx b/packages/react/src/SelectPanel/SelectPanel.features.stories.tsx index a63abe77687..0ebc36e5048 100644 --- a/packages/react/src/SelectPanel/SelectPanel.features.stories.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.features.stories.tsx @@ -38,6 +38,150 @@ const meta: Meta = { export default meta +type ComparisonPanelProps = { + countries?: boolean + multiple?: boolean + modal?: boolean + loading?: boolean + empty?: boolean + wide?: boolean + long?: boolean + grouped?: boolean + descriptions?: boolean + trailing?: boolean + defaultValue?: boolean + virtualized?: boolean +} + +const comparisonCountryNames = [ + 'United States', + 'Canada', + 'United Kingdom', + 'Germany', + 'France', + 'Japan', + 'Australia', + 'Brazil', +] +const comparisonGroupNames = ['Type', 'Priority', 'Area'] +const comparisonGroupLabels = [ + 'Bug', + 'Feature request', + 'Documentation', + 'High', + 'Medium', + 'Low', + 'Frontend', + 'Backend', + 'Infrastructure', +] +function ComparisonPanel(props: ComparisonPanelProps) { + const data = React.useMemo(() => { + const names = + props.empty || props.loading + ? [] + : props.countries + ? comparisonCountryNames + : props.grouped + ? comparisonGroupLabels + : Array.from({length: props.long ? 50 : 5}, (_, i) => `Option ${i + 1}`) + return names.map((text, i) => ({ + id: text, + text, + groupId: props.grouped ? comparisonGroupNames[Math.floor(i / 3)] : undefined, + description: props.descriptions ? `Description for ${text}` : undefined, + descriptionVariant: 'block' as const, + trailingText: props.trailing ? (i % 2 ? 'TypeScript' : 'JavaScript') : undefined, + })) + }, [props.empty, props.loading, props.countries, props.grouped, props.long, props.descriptions, props.trailing]) + const [single, setSingle] = useState(props.defaultValue ? data[0] : undefined) + const [multiple, setMultiple] = useState([]) + const [open, setOpen] = useState(false) + const [filter, setFilter] = useState('') + const title = props.countries ? 'Select a country' : props.grouped ? 'Select labels' : 'Options' + const placeholder = props.countries + ? 'Select a country' + : props.grouped + ? 'Select labels' + : props.multiple + ? 'Select items' + : 'Select an option' + const search = props.countries + ? 'Search countries...' + : props.grouped + ? 'Filter labels...' + : props.multiple + ? 'Search items...' + : 'Search options...' + const emptyText = props.countries ? 'No countries found' : 'No results found' + const filtered = data.filter(item => item.text.toLowerCase().includes(filter.toLowerCase())) + const selectionProps = props.multiple + ? {selected: multiple, onSelectedChange: setMultiple} + : {selected: single, onSelectedChange: setSingle} + const variantProps = props.modal + ? {variant: 'modal' as const, onCancel: () => setOpen(false)} + : {variant: 'anchored' as const} + return ( +
+ + {props.countries ? 'Country' : props.grouped ? 'Labels' : 'Option'} + ({groupId, header: {title: groupId}})) : undefined + } + textInputProps={props.modal ? undefined : {leadingVisual: undefined}} + message={!filtered.length && !props.loading ? {variant: 'empty', title: emptyText, body: ''} : undefined} + overlayProps={{ + style: {width: props.modal ? 480 : props.wide ? 384 : 280, height: props.modal ? 480 : undefined}, + }} + renderAnchor={({children, ...anchorProps}) => ( + + )} + /> + +
+ ) +} + +const openComparisonPanel: StoryObj['play'] = async ({canvas, canvasElement, userEvent}) => { + await userEvent.click(canvas.getByRole('button')) + await expect(within(canvasElement.ownerDocument.body).getByRole('listbox')).toBeVisible() +} +function comparisonPanelStory(props: ComparisonPanelProps = {}): StoryObj { + return {render: () => , play: openComparisonPanel} +} +export const ModernizedPanel = comparisonPanelStory() +export const ModernizedCountries = comparisonPanelStory({countries: true}) +export const ModernizedWide = comparisonPanelStory({countries: true, wide: true}) +export const ModernizedMultiple = comparisonPanelStory({multiple: true}) +export const ModernizedDefaultValue = comparisonPanelStory({defaultValue: true}) +export const ModernizedEmpty = comparisonPanelStory({empty: true}) +export const ModernizedLoading = comparisonPanelStory({loading: true}) +export const ModernizedGroups = comparisonPanelStory({grouped: true, multiple: true}) +export const ModernizedDescriptions = comparisonPanelStory({descriptions: true}) +export const ModernizedTrailingText = comparisonPanelStory({trailing: true}) +export const ModernizedLongList = comparisonPanelStory({long: true}) +export const ModernizedVirtualized = comparisonPanelStory({long: true, virtualized: true}) +export const ModernizedModal = comparisonPanelStory({countries: true, modal: true}) +export const ModernizedModalMultiple = comparisonPanelStory({grouped: true, multiple: true, modal: true}) +export const ModernizedModalLoading = comparisonPanelStory({countries: true, modal: true, loading: true}) + export const LegacyContrast: StoryObj = { render: () => ( diff --git a/packages/react/src/SelectPanel/SelectPanel.modernize.module.css b/packages/react/src/SelectPanel/SelectPanel.modernize.module.css new file mode 100644 index 00000000000..478381d446a --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.modernize.module.css @@ -0,0 +1,122 @@ +.Anchor:where([data-component='Button'][data-size='medium']) { + /* stylelint-disable-next-line primer/typography -- scope modern control labels to panel anchors */ + font-size: 13px; +} + +.Wrapper[data-component='SelectPanel'] { + & [data-description-variant='block'] { + padding-block: var(--base-size-2); + gap: var(--base-size-2); + } + + & [data-component='ActionList.Description'] { + font-size: var(--text-body-size-small); + } + + & [data-component='GroupHeadingWrap'] { + /* stylelint-disable-next-line primer/typography -- match caption line height */ + line-height: calc(var(--base-size-20) - var(--base-size-2)); + } + + & [data-component='ActionList.Group']:not(:first-child) { + margin-block-start: var(--base-size-4); + } + + & [data-component='SelectPanel.Message']:where([data-variant='empty']) { + min-height: calc(var(--base-size-96) + var(--base-size-48)); + + & [data-component='SelectPanel.MessageTitle'] { + font-size: var(--text-body-size-small); + font-weight: var(--base-text-weight-normal); + color: var(--fgColor-muted); + } + } + + & [data-component='FilteredActionList.Spinner'] { + min-height: var(--base-size-96); + + & [data-testid='filtered-action-list-spinner'] { + width: var(--base-size-16); + height: var(--base-size-16); + } + } + + & .Header { + padding-block: var(--base-size-8); + padding-inline: var(--base-size-16) var(--base-size-8); + align-items: center; + + & [data-component='SelectPanel.Title'] { + margin: 0; + font-size: var(--text-body-size-medium); + font-weight: var(--base-text-weight-semibold); + line-height: var(--base-text-lineHeight-normal); + } + + & [data-component='SelectPanel.Subtitle'] { + margin-inline: 0; + } + } + + &:where([data-title-visually-hidden]) .Header { + padding: 0; + min-height: 0; + } + + & .TextInput { + margin: 0; + width: 100%; + height: var(--base-size-36); + border: 0; + border-radius: 0; + box-shadow: none; + + &:focus-within { + outline: var(--borderWidth-thick) solid var(--focus-outlineColor); + outline-offset: calc(-1 * var(--borderWidth-thick)); + } + } + + &:where([data-variant='modal']) { + & .Header { + padding-block: var(--base-size-8) 0; + padding-inline-start: calc(var(--base-size-20) - var(--base-size-2)); + } + + & [data-component='FilteredActionList.Header'] { + padding: var(--base-size-8); + border-bottom: var(--borderWidth-thin) solid var(--borderColor-muted); + } + + & .TextInput { + height: var(--base-size-32); + border: var(--borderWidth-thin) solid var(--borderColor-default); + border-radius: var(--borderRadius-medium); + outline-offset: var(--base-size-2); + + & [data-component='input'] { + font-size: var(--text-body-size-medium); + } + } + + & [data-component='ActionList'] { + padding-block-start: calc(var(--base-size-12) - var(--base-size-2)); + } + } + + & .FooterButtons { + gap: var(--base-size-12); + } + + & [data-component='SelectPanel.Footer'] { + & [data-component='Button']:where([data-size='medium']) { + /* stylelint-disable-next-line primer/typography -- preserve standalone button typography */ + font-size: 13px; + } + + border-color: var(--borderColor-muted); + padding-block: var(--base-size-16); + padding-inline: var(--base-size-20); + gap: var(--base-size-12); + } +} diff --git a/packages/react/src/SelectPanel/SelectPanel.test.tsx b/packages/react/src/SelectPanel/SelectPanel.test.tsx index f5f70445d63..ff86e487895 100644 --- a/packages/react/src/SelectPanel/SelectPanel.test.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.test.tsx @@ -101,6 +101,71 @@ function BasicSelectPanel(passthroughProps: Record) { globalThis.Element.prototype.scrollTo = vi.fn() +describe('SelectPanel hidden title', () => { + it('preserves custom popup dimensions and consumer ActionList classes', async () => { + render( + {}} + onOpenChange={() => {}} + onFilterChange={() => {}} + overlayProps={{style: {width: 320}}} + actionListProps={{className: 'consumer-list'}} + />, + ) + const dialog = page.getByRole('dialog', {name: 'Custom panel', exact: true}) + await expect.element(dialog).toHaveStyle({width: '320px'}) + await expect.element(page.getByRole('listbox')).toHaveClass('consumer-list') + }) + + it('keeps the accessible name and search focus when the visible title is hidden', async () => { + render( + {}} + onOpenChange={() => {}} + onFilterChange={() => {}} + />, + ) + await expect.element(page.getByRole('dialog', {name: 'Choose an option', exact: true})).toBeVisible() + const title = page.getByRole('heading', {name: 'Choose an option', exact: true}).element() + expect(title.getBoundingClientRect().width).toBe(1) + expect(title.getBoundingClientRect().height).toBe(1) + await expect.element(page.getByRole('combobox', {name: 'Filter items', exact: true})).toHaveFocus() + const input = page.getByRole('combobox', {name: 'Filter items', exact: true}).element() + const control = input.closest('[data-component="TextInput"]') + expect(control).not.toBeNull() + expect(getComputedStyle(control!).outlineWidth).toBe('2px') + }) + + it('retains the subtitle as the description when the title is visually hidden', async () => { + render( + {}} + onOpenChange={() => {}} + onFilterChange={() => {}} + />, + ) + await expect + .element(page.getByRole('dialog', {name: 'Choose an option', exact: true})) + .toHaveAccessibleDescription('Choose one item from the list') + await expect.element(page.getByText('Choose one item from the list', {exact: true})).toBeVisible() + }) +}) + describe('SelectPanel state synchronization', () => { const synchronizedItems: ItemInput[] = [ {id: 'one', text: 'item one'}, diff --git a/packages/react/src/SelectPanel/SelectPanel.tsx b/packages/react/src/SelectPanel/SelectPanel.tsx index f3b655065d1..28a5a2c9c4f 100644 --- a/packages/react/src/SelectPanel/SelectPanel.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.tsx @@ -22,6 +22,9 @@ import {FilteredActionListLoadingTypes} from '../FilteredActionList/FilteredActi import {useFeatureFlag} from '../FeatureFlags' import {announce, announceFromElement} from '@primer/live-region-element' import classes from './SelectPanel.module.css' +import modernizeClasses from './SelectPanel.modernize.module.css' +import actionListModernizeClasses from '../ActionList/ActionList.modernize.module.css' +import visuallyHiddenClasses from '../VisuallyHidden/VisuallyHidden.module.css' import {clsx} from 'clsx' import {debounce} from '@github/mini-throttle' import {useResponsiveValue} from '../hooks/useResponsiveValue' @@ -75,6 +78,8 @@ export type SelectPanelSecondaryAction = | React.ReactElement interface SelectPanelBaseProps { + /** Visually hide the title while keeping the panel's accessible name. */ + titleVisuallyHidden?: boolean // TODO: Make `title` required in the next major version // eslint-disable-next-line @typescript-eslint/no-explicit-any title?: string | React.ReactElement @@ -192,6 +197,7 @@ function Panel({ selected, title = isMultiSelectVariant(selected) ? 'Select items' : 'Select an item', subtitle, + titleVisuallyHidden = false, onSelectedChange, filterValue: externalFilterValue, onFilterChange: externalOnFilterChange, @@ -635,6 +641,7 @@ function Panel({ return >(props: T) => { return renderAnchor({ ...props, + className: clsx(props.className, modernizeClasses.Anchor), ...(shouldAutoWireLabel ? { 'aria-labelledby': [labelId, selectedValueId].filter(Boolean).join(' '), @@ -787,7 +794,7 @@ function Panel({ const extendedTextInputProps: Partial = useMemo(() => { return { - className: classes.TextInput, + className: clsx(classes.TextInput, modernizeClasses.TextInput), contrast: legacyContrast, leadingVisual: SearchIcon, 'aria-label': inputLabel, @@ -917,21 +924,37 @@ function Panel({ } : {}), style: { - transform: variant === 'modal' ? 'translate(-50%, -50%)' : undefined, + ...(variant === 'anchored' && !height && !usingFullScreenOnNarrow + ? {maxHeight: 'min(384px, calc(100dvh - 32px))'} + : {}), + ...overlayProps?.style, + ...(variant === 'modal' ? {transform: 'translate(-50%, -50%)'} : {}), ...(isKeyboardVisible ? { maxHeight: availablePanelHeight !== undefined ? `${availablePanelHeight}px` : 'auto', } : {}), - } as React.CSSProperties, + }, onKeyDown: preventBubbling, }), - [titleId, subtitle, subtitleId, overlayProps, variant, isKeyboardVisible, availablePanelHeight, preventBubbling], + [ + titleId, + subtitle, + subtitleId, + overlayProps, + variant, + height, + usingFullScreenOnNarrow, + isKeyboardVisible, + availablePanelHeight, + preventBubbling, + ], ) return ( <> -
-
+
+
- + {title} {subtitle ? ( @@ -1028,6 +1065,10 @@ function Panel({ }} fullScreenOnNarrow={usingFullScreenOnNarrow} className={clsx(className, classes.FilteredActionList)} + actionListProps={{ + ...listProps.actionListProps, + className: clsx(listProps.actionListProps?.className, actionListModernizeClasses.ActionList), + }} focusPrependedElements={focusPrependedElements} virtualized={virtualized} /> @@ -1053,7 +1094,7 @@ function Panel({ {showPermanentCancelSaveButtons || showResponsiveCancelSaveButtons ? (
diff --git a/packages/react/src/SelectPanel/SelectPanelMessage.tsx b/packages/react/src/SelectPanel/SelectPanelMessage.tsx index 458c42883be..f0655693bd7 100644 --- a/packages/react/src/SelectPanel/SelectPanelMessage.tsx +++ b/packages/react/src/SelectPanel/SelectPanelMessage.tsx @@ -36,7 +36,7 @@ export const SelectPanelMessage: React.FC = ({ const IconComponent = CustomIcon || (variant !== 'empty' ? AlertIcon : undefined) return ( -
+
{IconComponent && ( Date: Sun, 15 Nov 2026 00:47:16 +0100 Subject: [PATCH 21/27] Document modernization review contract and align input size visuals Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- contributor-docs/component-modernization.md | 83 +++++++++++++++++++ .../TextInput/TextInput.features.stories.tsx | 6 +- 2 files changed, 86 insertions(+), 3 deletions(-) create mode 100644 contributor-docs/component-modernization.md diff --git a/contributor-docs/component-modernization.md b/contributor-docs/component-modernization.md new file mode 100644 index 00000000000..32f8518645e --- /dev/null +++ b/contributor-docs/component-modernization.md @@ -0,0 +1,83 @@ +# Component modernization experiment + +This document records the ongoing work to bring GitHub App's newer visual treatment into Primer React. It describes this experiment, not a blanket requirement to migrate every component. + +## Goal + +Match the reference's typography, spacing, sizing, alignment, and interaction styling while keeping Primer's public APIs and behavior. Port the visual treatment, not the component implementation or its entire stylesheet. + +Use the reference Storybook and app source as evidence. Do not claim that the running app was verified unless it was actually checked. + +## Implementation boundaries + +- Prefer the smallest complete change. Reuse existing Primer styles and override only the measured differences; do not duplicate styles that already work. +- Keep modernization styles component-scoped. Shared wrappers must not accidentally modernize unrelated consumers. For example, `TextInputWrapper` also serves Select, Textarea, and TextInputWithTokens. +- Put styles with the component that owns the surface: ActionMenu owns its trigger, while ActionList owns menu-row styling. Apply contextual changes only in the intended context. +- Preserve APIs, refs, keyboard behavior, controlled state, and accessibility. New behavior such as tokenization is a separate scope decision. +- Keep Primer's icons and theme tokens unless a change is explicitly agreed. Document intentional differences, including accessible opaque placeholders rather than faint reference placeholders and Primer's own high-contrast palettes. + +## Required comparison artifact + +Produce a standalone page using **live Storybook iframes**, not recreated controls or screenshots. + +1. Put **GitHub App on the left** and **Primer React on the right**, with equal iframe viewport widths. +2. **Stack every example pair vertically** so they can be reviewed together. Do not use an example picker. +3. Match example content: labels, placeholders, initial values, descriptions, item order, sizes, and visual roles. Match image fixtures where relevant; different icon artwork is an intentional exception. +4. Keep one **theme picker controlling all examples**, plus a reset action that restores every example's initial state. Both sides remain interactive. +5. Label intentional differences on the page. On narrow screens, preserve equal-width side-by-side previews with horizontal scrolling rather than shrinking one side differently. + +Keep comparison HTML separate from package runtime code and make it available as a review artifact. The page should link to its underlying stories. + +Do not invent reference counterparts for unsupported patterns. The current TextInput page compares default, sizes with leading visuals, search with a clear action, and password inputs. Tokenized input is outside the current modernization scope; Primer-only success/loading states are checked separately. + +## Working and verification loop + +1. Read the reference implementation and stories alongside Primer's existing styles and shared consumers. +2. Align the stories' content before judging the visual result. Keep the same starting coordinates and control widths so layout differences are meaningful. +3. Measure the result rather than relying only on appearance: font size/weight/line-height, dimensions, padding, gaps, icon bounds, borders, colors, and focus outlines. +4. Check supported sizes and themes, LTR/RTL, narrow layouts, validation, disabled/read-only states, and interaction behavior. For custom search clear actions, check that there is no duplicate native clear control, clearing restores focus, and empty-state visibility preserves layout. Normal-size placeholder text must meet the 4.5:1 contrast requirement. +5. Before committing, format changed files and run the smallest relevant build, type-check, lint, component, and accessibility checks. Build before tests because package builds clear outputs that other workspaces import. Explain unrelated baseline failures; do not silently treat them as passing. Use the repository's Linux snapshot workflow for canonical visual baselines. + +Keep the changeset accurate when runtime or public API changes are introduced or removed. See [testing](./testing.md), [CSS authoring](./authoring-css.md), and [versioning](./versioning.md) for the repository's standard guidance. + +## Existing implementation examples + +| Surface | Modernization styles | +| ---------------------------- | --------------------------------------------------------------------------------------------------------------- | +| Button | [ButtonBase.modernize.module.css](../packages/react/src/Button/ButtonBase.modernize.module.css) | +| ActionMenu trigger | [ActionMenu.modernize.module.css](../packages/react/src/ActionMenu/ActionMenu.modernize.module.css) | +| ActionMenu's ActionList rows | [ActionList.modernize.module.css](../packages/react/src/ActionList/ActionList.modernize.module.css) | +| Plain TextInput | [TextInput.modernize.module.css](../packages/react/src/TextInput/TextInput.modernize.module.css) | +| Dialog | [Dialog.modernize.module.css](../packages/react/src/Dialog/Dialog.modernize.module.css) | +| Main-export SelectPanel | [SelectPanel.modernize.module.css](../packages/react/src/SelectPanel/SelectPanel.modernize.module.css) | +| ToggleSwitch | [ToggleSwitch.modernize.module.css](../packages/react/src/ToggleSwitch/ToggleSwitch.modernize.module.css) | +| Experimental KeybindingHint | [KeybindingHint.modernize.module.css](../packages/react/src/KeybindingHint/KeybindingHint.modernize.module.css) | + +## Current batch boundaries + +Modernize the main-export SelectPanel, not deprecated SelectPanel2, and the current Dialog, not DialogV1. Use the existing experimental KeybindingHint for Kbd/KbdChord comparisons; do not introduce replacement keyboard exports. + +The approved visual additions are compact ToggleSwitch sizing, small Dialog density, and a visually hidden SelectPanel title that retains its accessible name. Keep existing defaults and state contracts. SelectPanel reuses ActionList's modernized surface and row styles; contextual keycap colors remain owned by Button and ActionList. + +Primer deliberately retains visible switch labels and indicators, its modal radio/Cancel/Save semantics, spinner-only loading presentation, and its existing modifier ordering. App switch fixtures enable its differentiate-without-color preference; App modal fixtures use its public footer to match Cancel/Save content and commit behavior. Grouped virtualization and the App's global keyboard-shortcut visibility feature have no current Primer counterpart and are not fabricated. + +## Local review setup + +These addresses describe the current review environment, not the repository's default Storybook port: + +| Resource | Address | +| ------------------------------ | ------------------------------------------------- | +| GitHub App reference Storybook | | +| Primer React Storybook | | +| TextInput stacked comparison | | +| ActionMenu overlay comparison | | +| Dialog stacked comparison | | +| SelectPanel stacked comparison | | +| Switch stacked comparison | | +| Keyboard stacked comparison | | + +Both Storybooks and the comparison-page server must be running. Port 6006 serves an unrelated Storybook in this setup; a missing entry in its MCP index does not mean a story is missing from Primer React. Verify the actual live story URLs. + +The stacked side-by-side page is the default review format. An overlay can supplement it when investigating fine alignment differences. + +The batch pages share a local comparison script and use lazy iframe loading to avoid mounting every story at once. SelectPanel previews retain desktop-width columns; narrower windows scroll horizontally rather than accidentally switching only one side into its responsive layout. Comparison fixtures in the reference worktree remain local and are not committed to that repository. diff --git a/packages/react/src/TextInput/TextInput.features.stories.tsx b/packages/react/src/TextInput/TextInput.features.stories.tsx index 9baf7cc5964..9952d2694f8 100644 --- a/packages/react/src/TextInput/TextInput.features.stories.tsx +++ b/packages/react/src/TextInput/TextInput.features.stories.tsx @@ -30,9 +30,9 @@ export const ModernizedSizes: StoryObj = { decorators: ModernizedInput.decorators, render: () => (
- - - + + +
), } From a103eb32c30be214141bd34836bf79e053a443d3 Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Sun, 15 Nov 2026 00:51:08 +0100 Subject: [PATCH 22/27] Preserve explicit SelectPanel maximum-height limits Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- packages/react/src/SelectPanel/SelectPanel.test.tsx | 3 ++- packages/react/src/SelectPanel/SelectPanel.tsx | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/react/src/SelectPanel/SelectPanel.test.tsx b/packages/react/src/SelectPanel/SelectPanel.test.tsx index ff86e487895..be1c21ab238 100644 --- a/packages/react/src/SelectPanel/SelectPanel.test.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.test.tsx @@ -112,12 +112,13 @@ describe('SelectPanel hidden title', () => { onSelectedChange={() => {}} onOpenChange={() => {}} onFilterChange={() => {}} - overlayProps={{style: {width: 320}}} + overlayProps={{style: {width: 320}, maxHeight: 'xsmall'}} actionListProps={{className: 'consumer-list'}} />, ) const dialog = page.getByRole('dialog', {name: 'Custom panel', exact: true}) await expect.element(dialog).toHaveStyle({width: '320px'}) + await expect.element(dialog).toHaveStyle({maxHeight: '192px'}) await expect.element(page.getByRole('listbox')).toHaveClass('consumer-list') }) diff --git a/packages/react/src/SelectPanel/SelectPanel.tsx b/packages/react/src/SelectPanel/SelectPanel.tsx index 28a5a2c9c4f..f47c99119bf 100644 --- a/packages/react/src/SelectPanel/SelectPanel.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.tsx @@ -924,7 +924,7 @@ function Panel({ } : {}), style: { - ...(variant === 'anchored' && !height && !usingFullScreenOnNarrow + ...(variant === 'anchored' && !height && !overlayProps?.maxHeight && !usingFullScreenOnNarrow ? {maxHeight: 'min(384px, calc(100dvh - 32px))'} : {}), ...overlayProps?.style, From 5a9f91c15e3967122d8c081d2afcefcd5ef143d2 Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Sun, 15 Nov 2026 00:56:30 +0100 Subject: [PATCH 23/27] Match compact Dialog icons and restore comparison trigger focus Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- packages/react/src/Dialog/Dialog.features.stories.tsx | 4 +++- packages/react/src/Dialog/Dialog.modernize.module.css | 5 ----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/packages/react/src/Dialog/Dialog.features.stories.tsx b/packages/react/src/Dialog/Dialog.features.stories.tsx index 3428cbe2e6d..8fc806cec4c 100644 --- a/packages/react/src/Dialog/Dialog.features.stories.tsx +++ b/packages/react/src/Dialog/Dialog.features.stories.tsx @@ -21,9 +21,10 @@ export default { function ComparisonDialog({small = false, tall = false}: {small?: boolean; tall?: boolean}) { const [open, setOpen] = useState(false) + const triggerRef = useRef(null) return (
- {open && ( @@ -33,6 +34,7 @@ function ComparisonDialog({small = false, tall = false}: {small?: boolean; tall? width={small ? 'small' : 'large'} height={tall ? 'small' : 'auto'} onClose={() => setOpen(false)} + returnFocusRef={triggerRef} footerButtons={[ {content: tall ? 'Decline' : 'Cancel', onClick: () => setOpen(false)}, {content: tall ? 'Accept' : 'Confirm', variant: 'primary', onClick: () => setOpen(false)}, diff --git a/packages/react/src/Dialog/Dialog.modernize.module.css b/packages/react/src/Dialog/Dialog.modernize.module.css index 14bd697a1a0..7fbc5406b24 100644 --- a/packages/react/src/Dialog/Dialog.modernize.module.css +++ b/packages/react/src/Dialog/Dialog.modernize.module.css @@ -43,11 +43,6 @@ & [data-component='Dialog.CloseButton'] { width: var(--base-size-28); height: var(--base-size-28); - - & svg { - width: calc(var(--base-size-16) - var(--base-size-2)); - height: calc(var(--base-size-16) - var(--base-size-2)); - } } } From f746efa1953345f744251bf55bb546456ae15a1c Mon Sep 17 00:00:00 2001 From: Siddharth Kshetrapal Date: Mon, 16 Nov 2026 12:53:47 +0100 Subject: [PATCH 24/27] Align switch indicators, state styling, and comparison fixtures Correct Dialog comparison primary actions and refine switch geometry, disabled colors, and size alignment. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changeset/modernize-toggle-switch.md | 2 +- .../src/Dialog/Dialog.features.stories.tsx | 2 +- .../ToggleSwitch.features.stories.module.css | 1 + .../ToggleSwitch.features.stories.tsx | 5 +- .../ToggleSwitch.modernize.module.css | 87 ++++++++++++++++++- .../src/ToggleSwitch/ToggleSwitch.test.tsx | 44 +++++++++- .../react/src/ToggleSwitch/ToggleSwitch.tsx | 17 ++-- 7 files changed, 141 insertions(+), 17 deletions(-) diff --git a/.changeset/modernize-toggle-switch.md b/.changeset/modernize-toggle-switch.md index 05ad98987d5..681e0c6173c 100644 --- a/.changeset/modernize-toggle-switch.md +++ b/.changeset/modernize-toggle-switch.md @@ -2,4 +2,4 @@ '@primer/react': minor --- -ToggleSwitch: Refine sizing, typography, and rounded controls, and add a compact size. +ToggleSwitch: Refine sizing, thumb alignment, and disabled appearance, and add a compact size. diff --git a/packages/react/src/Dialog/Dialog.features.stories.tsx b/packages/react/src/Dialog/Dialog.features.stories.tsx index 8fc806cec4c..a259416bd0e 100644 --- a/packages/react/src/Dialog/Dialog.features.stories.tsx +++ b/packages/react/src/Dialog/Dialog.features.stories.tsx @@ -37,7 +37,7 @@ function ComparisonDialog({small = false, tall = false}: {small?: boolean; tall? returnFocusRef={triggerRef} footerButtons={[ {content: tall ? 'Decline' : 'Cancel', onClick: () => setOpen(false)}, - {content: tall ? 'Accept' : 'Confirm', variant: 'primary', onClick: () => setOpen(false)}, + {content: tall ? 'Accept' : 'Confirm', buttonType: 'primary', onClick: () => setOpen(false)}, ]} > {tall diff --git a/packages/react/src/ToggleSwitch/ToggleSwitch.features.stories.module.css b/packages/react/src/ToggleSwitch/ToggleSwitch.features.stories.module.css index 6fe13199e0c..6d221c9b55a 100644 --- a/packages/react/src/ToggleSwitch/ToggleSwitch.features.stories.module.css +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.features.stories.module.css @@ -15,6 +15,7 @@ padding: var(--base-size-16); & .Comparison { + display: flex; padding: 0; } } diff --git a/packages/react/src/ToggleSwitch/ToggleSwitch.features.stories.tsx b/packages/react/src/ToggleSwitch/ToggleSwitch.features.stories.tsx index 1ff14319b94..3c8f92a6ef3 100644 --- a/packages/react/src/ToggleSwitch/ToggleSwitch.features.stories.tsx +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.features.stories.tsx @@ -31,11 +31,8 @@ function ComparisonSwitch({ export const ModernizedSwitch: StoryObj = { render: () => , - play: async ({canvas, userEvent}) => { + play: async ({canvas}) => { const button = canvas.getByRole('button', {name: 'Enable notifications'}) - await userEvent.click(button) - await expect(button).toHaveAttribute('aria-pressed', 'true') - await userEvent.click(button) await expect(button).toHaveAttribute('aria-pressed', 'false') }, } diff --git a/packages/react/src/ToggleSwitch/ToggleSwitch.modernize.module.css b/packages/react/src/ToggleSwitch/ToggleSwitch.modernize.module.css index 1c76e5771bb..80763996ec6 100644 --- a/packages/react/src/ToggleSwitch/ToggleSwitch.modernize.module.css +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.modernize.module.css @@ -14,6 +14,17 @@ border-radius: var(--borderRadius-full); outline: var(--borderWidth-thin) solid var(--controlTrack-borderColor-rest); outline-offset: -1px; + background-image: linear-gradient( + to right, + var(--control-checked-bgColor-rest) 35%, + var(--control-bgColor-active) 65% + ); + background-size: 160px 100%; + background-position: 100% 0; + background-repeat: no-repeat; + transition-property: background-position; + transition-duration: 125ms; + transition-timing-function: cubic-bezier(0.26, 0.75, 0.38, 0.45); &:where([data-size='small']) { width: var(--base-size-40); @@ -27,12 +38,28 @@ &:where([data-checked='true']) { outline-color: var(--control-checked-borderColor-rest); + background-position: 0 0; } &:where([data-disabled='true']) { opacity: 0.6; } + &:where([data-disabled='true'][data-checked='false']) { + &::after { + content: ''; + position: absolute; + inset: 0; + border: var(--borderWidth-thin) solid var(--borderColor-emphasis); + border-radius: inherit; + pointer-events: none; + } + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + } + &:focus-visible { outline: var(--focus-outline); outline-offset: 1px; @@ -42,11 +69,13 @@ .ToggleKnob[data-size] { top: var(--base-size-2); bottom: var(--base-size-2); - left: auto; - right: auto; inset-inline-start: var(--base-size-2); width: var(--base-size-32); border-radius: var(--borderRadius-full); + background-color: var(--controlKnob-bgColor-checked); + border-color: color-mix(in srgb, var(--controlKnob-borderColor-rest) 50%, transparent); + transition-duration: 150ms; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); &:where([data-size='small']) { width: var(--base-size-24); @@ -57,7 +86,8 @@ } &:where([data-checked='true']) { - border-color: transparent; + /* stylelint-disable-next-line primer/colors -- match the checked thumb border to its fill */ + border-color: var(--controlKnob-bgColor-checked); transform: translateX(var(--base-size-12)); } @@ -69,7 +99,58 @@ transform: translateX(calc(-1 * var(--base-size-12))); } + &:dir(rtl) { + left: auto; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + } + &:dir(rtl):where([data-size='compact'][data-checked='true']) { transform: translateX(calc(var(--base-size-2) - var(--base-size-12))); } } + +:where( + :global([data-color-mode='light'][data-light-theme='light_high_contrast']), + :global([data-color-mode='dark'][data-dark-theme='dark_high_contrast']) + ) + .SwitchButton[data-size] { + &:where([data-checked='false']) { + outline-color: var(--borderColor-emphasis); + } + + & .ToggleKnob:where([data-checked='false']) { + border-color: var(--controlKnob-borderColor-rest); + } +} + +.LineIconContainer[data-checked] { + position: absolute; + inset-inline-start: calc(var(--base-size-8) - var(--borderWidth-thin)); + width: var(--base-size-2); + flex-basis: auto; + color: var(--control-checked-fgColor-rest); + + &:where([data-size='compact']) { + inset-inline-start: var(--base-size-6); + } + + &:where([data-checked='false']) { + visibility: hidden; + } +} + +.CircleIconContainer[data-checked] { + position: absolute; + inset-inline-end: var(--base-size-4); + width: auto; + flex-basis: auto; + /* stylelint-disable-next-line primer/colors -- the filled glyph represents the off indicator's border */ + color: var(--control-borderColor-emphasis); + + &:where([data-checked='true']) { + visibility: hidden; + } +} diff --git a/packages/react/src/ToggleSwitch/ToggleSwitch.test.tsx b/packages/react/src/ToggleSwitch/ToggleSwitch.test.tsx index a75f2bcf1b7..90ffa02ae60 100644 --- a/packages/react/src/ToggleSwitch/ToggleSwitch.test.tsx +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.test.tsx @@ -37,13 +37,55 @@ describe('ToggleSwitch', () => { .poll(() => { const track = button.element().getBoundingClientRect() const thumb = button.element().lastElementChild?.getBoundingClientRect() - return thumb && thumb.left >= track.left && thumb.right <= track.right + if (!thumb) return false + const checked = button.element().getAttribute('aria-pressed') === 'true' + const inset = direction === 'ltr' ? thumb.left - track.left : track.right - thumb.right + const indicator = button.element().querySelectorAll('svg')[checked ? 0 : 1].getBoundingClientRect() + const indicatorInset = checked + ? direction === 'ltr' + ? indicator.left - track.left + : track.right - indicator.right + : direction === 'ltr' + ? track.right - indicator.right + : indicator.left - track.left + return ( + Math.abs(inset - (checked ? (size === 'compact' ? 12 : 14) : 2)) < 0.1 && + Math.abs(indicatorInset - (checked ? (size === 'compact' ? 6 : 7) : 4)) < 0.1 && + indicator.width === (checked ? 2 : size === 'compact' ? 6 : size === 'small' ? 8 : 10) + ) }) .toBe(true) } } }) + it.each([false, true])('keeps the %s state colors when the switch is disabled', async checked => { + const renderSwitch = (disabled: boolean) => ( + <> + Preference + + + ) + const {rerender} = render(renderSwitch(false)) + const button = page.getByRole('button', {name: 'Preference', exact: true}) + const trackStyles = getComputedStyle(button.element()) + const thumb = button.element().lastElementChild + if (!(thumb instanceof HTMLElement)) throw new Error('Missing switch thumb') + const enabled = { + backgroundImage: trackStyles.backgroundImage, + backgroundPosition: trackStyles.backgroundPosition, + thumbColor: getComputedStyle(thumb).backgroundColor, + } + rerender(renderSwitch(true)) + await expect.element(button).toHaveAttribute('aria-disabled', 'true') + await expect.element(button).toHaveStyle({ + opacity: '0.6', + backgroundImage: enabled.backgroundImage, + backgroundPosition: enabled.backgroundPosition, + }) + expect(getComputedStyle(thumb).backgroundColor).toBe(enabled.thumbColor) + }) + it('toggles a compact control with the keyboard and keeps custom state labels', async () => { render( <> diff --git a/packages/react/src/ToggleSwitch/ToggleSwitch.tsx b/packages/react/src/ToggleSwitch/ToggleSwitch.tsx index 4e085156a93..172cfef436f 100644 --- a/packages/react/src/ToggleSwitch/ToggleSwitch.tsx +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.tsx @@ -52,13 +52,14 @@ export interface ToggleSwitchProps extends Omit> = ({size}) => (