diff --git a/.changeset/modernize-action-menu.md b/.changeset/modernize-action-menu.md new file mode 100644 index 00000000000..c50e3b24459 --- /dev/null +++ b/.changeset/modernize-action-menu.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +ActionMenu: Refine menu spacing, typography, icons, interaction styles, and trigger-button typography to match GitHub App. 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/.changeset/modernize-keybinding-hint.md b/.changeset/modernize-keybinding-hint.md new file mode 100644 index 00000000000..e969b53f12f --- /dev/null +++ b/.changeset/modernize-keybinding-hint.md @@ -0,0 +1,5 @@ +--- +'@primer/react': minor +--- + +KeybindingHint: Refine individual keycap typography, sizing, and appearance. 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/modernize-text-input.md b/.changeset/modernize-text-input.md new file mode 100644 index 00000000000..f4ea3e34961 --- /dev/null +++ b/.changeset/modernize-text-input.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +TextInput: Refine typography, spacing, visuals, and interaction styles. diff --git a/.changeset/modernize-toggle-switch.md b/.changeset/modernize-toggle-switch.md new file mode 100644 index 00000000000..681e0c6173c --- /dev/null +++ b/.changeset/modernize-toggle-switch.md @@ -0,0 +1,5 @@ +--- +'@primer/react': minor +--- + +ToggleSwitch: Refine sizing, thumb alignment, and disabled appearance, and add a compact size. 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/.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 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/e2e/components/ActionMenu.test.ts b/e2e/components/ActionMenu.test.ts index 6b46c17139f..108dbb8bf80 100644 --- a/e2e/components/ActionMenu.test.ts +++ b/e2e/components/ActionMenu.test.ts @@ -71,6 +71,56 @@ const featureFlagVariants = [ ] as const test.describe('ActionMenu', () => { + test.describe('Modernized menu', () => { + for (const id of [ + 'components-actionmenu-features--modernized-menu', + 'components-actionmenu-features--modernized-menu-with-avatars', + ]) { + for (const theme of themes) { + test(`${id} ${theme} @aat`, async ({page}) => { + await visit(page, { + id, + globals: {colorScheme: theme}, + }) + await expect(page.getByRole('menu')).toBeVisible() + await expect(page).toHaveNoViolations() + }) + } + } + + test('aligns avatars, loading indicators and submenu descriptions', async ({page}) => { + await visit(page, {id: 'components-actionmenu-features--modernized-menu-with-states'}) + const menu = page.getByRole('menu') + await expect(menu.locator('[data-component="Avatar"]')).toHaveCount(3) + for (const avatar of await menu.locator('[data-component="Avatar"]').all()) { + await expect(avatar).toHaveCSS('width', '20px') + await expect(avatar).toHaveCSS('height', '20px') + } + + const loading = page.getByRole('menuitem', {name: /^Loading reviewers/}) + await expect(loading.locator('[data-component="Spinner"] svg')).toHaveCSS('width', '14px') + await expect(loading.locator('[data-component="Spinner"] svg')).toHaveCSS('height', '14px') + + const inactive = page.getByRole('menuitem', {name: 'Request review', exact: true}) + const inactiveIcon = await inactive.locator('svg').boundingBox() + const inactiveLabel = await inactive.locator('[data-component="ActionList.Item.Label"]').boundingBox() + expect(inactiveIcon!.y - inactiveLabel!.y).toBeCloseTo(3, 3) + + const submenu = page.getByRole('menuitem', {name: 'More reviewers', exact: true}) + await expect(submenu.locator('[data-description-variant]')).toHaveCSS('margin-right', '8px') + const chevron = await submenu.locator('[data-component="ActionList.TrailingVisual"] svg').boundingBox() + const label = await submenu.locator('[data-component="ActionList.Item.Label"]').boundingBox() + expect(chevron!.y - label!.y).toBeCloseTo(2, 3) + + await submenu.focus() + await page.keyboard.press('ArrowRight') + await expect(page.getByRole('menuitem', {name: 'Design', exact: true})).toBeVisible() + await page.keyboard.press('ArrowLeft') + await expect(submenu).toBeFocused() + await expect(page.getByRole('menu')).toHaveCount(1) + }) + }) + for (const story of stories) { test.describe(story.title, () => { for (const theme of themes) { diff --git a/e2e/components/TextInput.test.ts b/e2e/components/TextInput.test.ts index d640f166fae..c8113d6da24 100644 --- a/e2e/components/TextInput.test.ts +++ b/e2e/components/TextInput.test.ts @@ -3,6 +3,22 @@ import {visit} from '../test-helpers/storybook' import {themes} from '../test-helpers/themes' test.describe('TextInput', () => { + test.describe('Modernized accessibility', () => { + for (const theme of themes) { + test.describe(theme, () => { + for (const story of ['modernized-input', 'modernized-search', 'modernized-states']) { + test(`${story} @avt`, async ({page}) => { + await visit(page, { + id: `components-textinput-features--${story}`, + globals: {colorScheme: theme}, + }) + await expect(page).toHaveNoViolations() + }) + } + }) + } + }) + test.describe('Default', () => { for (const theme of themes) { test.describe(theme, () => { diff --git a/packages/react/src/ActionList/ActionList.modernize.module.css b/packages/react/src/ActionList/ActionList.modernize.module.css new file mode 100644 index 00000000000..02d2d51585c --- /dev/null +++ b/packages/react/src/ActionList/ActionList.modernize.module.css @@ -0,0 +1,224 @@ +.Overlay { + min-width: calc(var(--base-size-16) * 7); + background-color: var(--bgColor-default); + background-clip: padding-box; + /* stylelint-disable primer/box-shadow -- match GitHub App's floating border shadow */ + box-shadow: + 0 0 0 1px color-mix(in srgb, var(--borderColor-default) 50%, transparent), + 0 6px 12px -3px color-mix(in srgb, color-mix(in srgb, #000 90%, var(--bgColor-default)) 4%, transparent), + 0 6px 18px 0 color-mix(in srgb, color-mix(in srgb, #000 90%, var(--bgColor-default)) 12%, transparent); + /* stylelint-enable primer/box-shadow */ +} + +.ActionList { + --actionList-modernize-icon-size: calc(var(--base-size-16) - var(--base-size-2)); + + padding: var(--base-size-4); + /* stylelint-disable-next-line primer/typography -- GitHub App's menu typography has no matching Primer token */ + font-size: 13px; + /* stylelint-disable-next-line primer/typography -- match the 20px menu row line height */ + line-height: var(--base-size-20); + + & [data-component='ActionList.Item'] { + margin-inline: 0; + /* stylelint-disable-next-line primer/borders -- GitHub App's 8px radius has no matching Primer token */ + border-radius: 8px; + + & > [data-size] { + min-height: var(--base-size-28); + padding-inline: var(--base-size-8); + cursor: default; + border-radius: inherit; + } + + & > [data-size='medium'] { + padding-block: var(--base-size-4); + } + + &:where([data-has-description='true']) [data-component='ActionList.LeadingVisual'] { + min-height: var(--base-size-20); + height: var(--base-size-20); + align-self: start; + + & > [data-component='Avatar'] { + width: var(--base-size-20); + height: var(--base-size-20); + } + } + + &:where([data-inactive='true']:not([data-has-description='true'])) [data-component='ActionList.LeadingVisual'] { + margin-block-start: calc(var(--base-size-6) / 2); + align-self: start; + } + + &:where([aria-haspopup]) [data-component='ActionList.Item--DividerContainer'] > :not(:last-child) { + margin-inline-end: var(--base-size-8); + } + + &:where([aria-haspopup][data-has-description='true']) [data-component='ActionList.TrailingVisual'] { + min-height: 0; + height: var(--actionList-modernize-icon-size); + margin-block-start: var(--base-size-2); + } + } + + & [data-component='ActionList.Item.Label'], + & [data-component='ActionList.Description'], + & [data-component='ActionList.TrailingVisual'] { + font-size: inherit; + line-height: inherit; + } + + & [data-description-variant='block'] { + gap: 0; + } + + & [data-has-description='true'] [data-component='ActionList.Item.Label'] { + font-weight: var(--base-text-weight-medium); + } + + & [data-component='ActionList.Item--DividerContainer'] { + & > :not(:last-child) { + margin-inline-end: var(--base-size-24); + } + } + + & [data-component='KeybindingHint'] { + display: inline-flex; + } + + & [data-kbd-chord][data-size] { + min-width: 0; + padding: 0; + font-size: inherit; + line-height: inherit; + color: var(--fgColor-muted); + background: transparent; + border: 0; + gap: 0; + + & > [data-component='KeybindingHint.Key'] { + min-width: var(--actionList-modernize-icon-size); + width: auto; + padding: 0; + border: 0; + box-shadow: none; + background: transparent; + color: inherit; + font-size: inherit; + line-height: inherit; + text-align: center; + + &:where(:not([data-single-character])) { + padding-inline: var(--base-size-4); + } + } + } + + & [data-component='ActionList.LeadingVisual'] { + min-width: var(--actionList-modernize-icon-size); + min-height: 0; + height: var(--actionList-modernize-icon-size); + align-self: center; + + & > :where(svg, [data-component='Avatar']) { + width: var(--actionList-modernize-icon-size); + height: var(--actionList-modernize-icon-size); + } + } + + & [data-component='ActionList.Selection'] > svg, + & [data-component='ActionList.TrailingVisual'] > svg, + & [data-loading='true'] svg { + width: var(--actionList-modernize-icon-size); + height: var(--actionList-modernize-icon-size); + } + + & [data-is-disabled] { + & [data-component='ActionList.Item.Label'], + & [data-component='ActionList.Description'], + & [data-component='ActionList.LeadingVisual'], + & [data-component='ActionList.TrailingVisual'], + & [data-component='ActionList.Selection'] { + color: var(--fgColor-muted); + + & > svg { + color: inherit; + } + } + } + + & [data-component='ActionList.Divider'] { + margin: var(--base-size-4) var(--base-size-8); + /* stylelint-disable-next-line primer/colors -- match GitHub App's subtle separator */ + background: color-mix(in srgb, var(--borderColor-muted) 30%, transparent); + } + + &[data-dividers='true'] { + & [data-component='ActionList.Item--DividerContainer']::before, + & [data-description-variant='inline']::before { + top: calc(-1 * var(--base-size-4)); + } + } + + & [data-component='ActionList.Group']:not(:first-child) { + margin-block-start: 0; + } + + & [data-component='GroupHeadingWrap'] { + padding: var(--base-size-6) var(--base-size-8) var(--base-size-4); + font-weight: var(--base-text-weight-medium); + /* stylelint-disable-next-line primer/typography -- match GitHub App's 16px caption line height */ + line-height: var(--base-size-16); + + & > span { + font-weight: inherit; + } + } + + & [data-component='ActionList.Item']:not([data-is-disabled], [data-inactive='true'], [data-loading='true']) { + @media (hover: hover) { + &:hover { + cursor: default; + box-shadow: none; + } + } + + &:active { + box-shadow: none; + } + + &:focus-visible { + background: transparent; + box-shadow: none; + } + } + + & + [data-component='ActionList.Item']:where([data-variant='danger']):where( + :not([data-is-disabled], [data-inactive='true'], [data-loading='true']) + ) { + @media (hover: hover) { + &:hover { + background: var(--bgColor-danger-muted); + } + } + + &:active { + background: var(--bgColor-danger-muted); + } + + &:hover, + &:active { + & [data-component='ActionList.Item.Label'], + & [data-component='ActionList.LeadingVisual'], + & [data-component='ActionList.Selection'] { + color: var(--fgColor-danger); + } + + & [data-kbd-chord] { + background-color: transparent; + } + } + } +} diff --git a/packages/react/src/ActionList/ActionList.module.css b/packages/react/src/ActionList/ActionList.module.css index 7a4a9065c0a..965ccdf0044 100644 --- a/packages/react/src/ActionList/ActionList.module.css +++ b/packages/react/src/ActionList/ActionList.module.css @@ -190,7 +190,7 @@ color: var(--control-danger-fgColor-hover); } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background-color: var(--bgColor-default); transition: none; } @@ -206,7 +206,7 @@ color: var(--control-danger-fgColor-hover); } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background-color: var(--bgColor-default); transition: none; } diff --git a/packages/react/src/ActionList/List.tsx b/packages/react/src/ActionList/List.tsx index 11c00a37db7..79cd8a40215 100644 --- a/packages/react/src/ActionList/List.tsx +++ b/packages/react/src/ActionList/List.tsx @@ -9,6 +9,7 @@ import {useMergedRefs, useProvidedRefOrCreate} from '../hooks' import {FocusKeys, useFocusZone} from '../hooks/useFocusZone' import {clsx} from 'clsx' import classes from './ActionList.module.css' +import modernizeClasses from './ActionList.modernize.module.css' import useIsomorphicLayoutEffect from '../utils/useIsomorphicLayoutEffect' import {useFeatureFlag} from '../FeatureFlags' @@ -110,7 +111,7 @@ const UnwrappedList = ( {slots.heading} ( +
+ +
+ ), + ], + render: () => ( + + Actions + + + + + + + Copy + Copy to clipboard + + + + + + Edit + Edit this item + + + + + + + Download + Download the file to your computer + + + + + + Delete + This action cannot be undone + + + + + ), + play: async ({canvasElement}) => { + const canvas = within(canvasElement) + await userEvent.click(canvas.getByRole('button', {name: 'Actions'})) + const body = within(canvasElement.ownerDocument.body) + await waitFor(() => expect(body.getByRole('menu')).toBeVisible()) + await userEvent.keyboard('{ArrowDown}') + await expect(body.getByRole('menuitem', {name: 'Edit'})).toHaveFocus() + }, +} + +export const ModernizedMenuWithAvatars: StoryObj = { + decorators: ModernizedMenu.decorators, + render: () => ( + + Reviewers + + + + Request review + {[ + {name: 'maximedegreve', description: 'Frontend · Last active 2h ago'}, + {name: 'adrianmg', description: 'Backend · Last active 30m ago'}, + {name: 'daviddossett', description: 'Infrastructure · Last active 1d ago'}, + ].map(({name, description}) => ( + + + + + {name} + {description} + + ))} + + + + + ), + play: async ({canvasElement}) => { + const canvas = within(canvasElement) + await userEvent.click(canvas.getByRole('button', {name: 'Reviewers'})) + const body = within(canvasElement.ownerDocument.body) + await waitFor(() => expect(body.getByRole('menu')).toBeVisible()) + }, +} + +export const ModernizedMenuWithAvatarsOnly: StoryObj = { + decorators: ModernizedMenu.decorators, + render: () => ( + + Reviewers + + + + Request review + {['maximedegreve', 'adrianmg', 'daviddossett'].map(name => ( + + + + + {name} + + ))} + + + + + ), + play: ModernizedMenuWithAvatars.play, +} + +export const ModernizedMenuWithStates: StoryObj = { + render: () => ( + + Reviewers + + + + Request review + {['mona', 'octocat', 'hubot'].map(name => ( + + + + + {name} + Available for review + + ))} + + + + + + + + + More reviewers + Choose from another team + + + + + Design + Engineering + + + + + + + + Loading reviewers + + + + + + Request review + + + + + ), + play: async ({canvasElement}) => { + const canvas = within(canvasElement) + await userEvent.click(canvas.getByRole('button', {name: 'Reviewers'})) + const body = within(canvasElement.ownerDocument.body) + await waitFor(() => expect(body.getByRole('menu')).toBeVisible()) + await userEvent.keyboard('{ArrowDown}') + await expect(body.getByRole('menuitem', {name: 'octocat'})).toHaveFocus() + }, +} + export const LinksAndActions = () => ( Open menu diff --git a/packages/react/src/ActionMenu/ActionMenu.modernize.module.css b/packages/react/src/ActionMenu/ActionMenu.modernize.module.css new file mode 100644 index 00000000000..c4520c01ef0 --- /dev/null +++ b/packages/react/src/ActionMenu/ActionMenu.modernize.module.css @@ -0,0 +1,6 @@ +.Button:where([data-size='medium']) { + /* stylelint-disable-next-line primer/typography -- GitHub App's button typography has no matching Primer token */ + font-size: 13px; + /* 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/ActionMenu/ActionMenu.test.tsx b/packages/react/src/ActionMenu/ActionMenu.test.tsx index e0f641963bc..c5d95b02d0e 100644 --- a/packages/react/src/ActionMenu/ActionMenu.test.tsx +++ b/packages/react/src/ActionMenu/ActionMenu.test.tsx @@ -21,6 +21,7 @@ import type {JSX} from 'react' import {implementsClassName} from '../utils/testing' import {createRenderCounter} from '../utils/testing/profiler' import {FeatureFlags} from '../FeatureFlags' +import {KeybindingHint} from '../KeybindingHint' // Mock getAnchoredPosition for feature flag tests vi.mock('@primer/behaviors', async () => { @@ -209,6 +210,58 @@ function ExampleWithSubmenus(): JSX.Element { describe('ActionMenu', () => { implementsClassName(ActionMenu.Button) + it('uses compact menu rows without changing standalone ActionLists', async () => { + HTMLRender( + + + + 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 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 = () => diff --git a/packages/react/src/Button/ButtonBase.modern.module.css b/packages/react/src/Button/ButtonBase.modern.module.css new file mode 100644 index 00000000000..6260e86132e --- /dev/null +++ b/packages/react/src/Button/ButtonBase.modern.module.css @@ -0,0 +1,734 @@ +/* Base styles */ +.ButtonBase { + display: flex; + min-width: max-content; + height: var(--control-medium-size); + /* stylelint-disable-next-line primer/spacing */ + padding: 0 var(--control-medium-paddingInline-normal); + font-family: inherit; + font-size: var(--text-body-size-medium); + font-weight: var(--base-text-weight-medium); + color: var(--button-default-fgColor-rest); + text-align: center; + text-decoration: none; + cursor: pointer; + user-select: none; + background-color: transparent; + border: var(--borderWidth-thin) solid; + border-color: var(--button-default-borderColor-rest); + border-radius: var(--borderRadius-medium); + transition: 80ms cubic-bezier(0.65, 0, 0.35, 1); + transition-property: color, fill, background-color, border-color; + appearance: none; + align-items: center; + 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: calc(var(--base-size-12) - var(--base-size-2)) var(--base-size-8); + + &:where([data-size='small']) { + padding-inline: var(--base-size-8) var(--base-size-6); + } + + &:where([data-size='large']) { + padding-inline: var(--base-size-12) calc(var(--base-size-12) - var(--base-size-2)); + } + } + + &:focus-visible { + @mixin focusOutline; + } + + &:active { + transition: none; + } + + &:where([data-notification-indicator='button'], [data-notification-indicator='icon'].IconButton) { + position: relative; + } + + &:where([data-notification-indicator='leadingVisual']) .LeadingVisual { + position: relative; + } + + &:where([data-notification-indicator='button'])::before, + &:where([data-notification-indicator='icon'].IconButton)::before, + &:where([data-notification-indicator='leadingVisual']) .LeadingVisual::before { + position: absolute; + display: block; + width: var(--base-size-8); + height: var(--base-size-8); + content: ''; + /* stylelint-disable-next-line primer/colors */ + background-color: var(--fgColor-accent); + border-radius: var(--borderRadius-full); + /* stylelint-disable-next-line primer/box-shadow */ + box-shadow: 0 0 0 calc(var(--base-size-4) / 2) var(--bgColor-inset); + } + + &:where([data-notification-indicator='button'])::before { + top: calc(var(--base-size-4) / -2); + right: calc(var(--base-size-4) / -2); + } + + &:where([data-notification-indicator='icon'].IconButton)::before { + top: calc(50% - var(--base-size-12)); + right: calc(50% - var(--base-size-12)); + } + + &:where([data-notification-indicator='leadingVisual']) .LeadingVisual::before { + top: calc(var(--base-size-4) * -1); + right: calc(var(--base-size-4) * -1); + } + + &:disabled, + &[aria-disabled='true']:not([data-loading='true']), + &[aria-disabled='true'][data-loading-disabled-styles='true'] { + cursor: not-allowed; + box-shadow: none; + + & .Visual, + & .CounterLabel { + color: inherit; + } + } + + @media (forced-colors: active) { + &:focus { + outline: solid 1px transparent; + } + } + + /* Visuals */ + & :where(.Visual, .VisualWrap) { + display: flex; + pointer-events: none; + } + + & :where(.Visual) { + color: var(--fgColor-muted); + } + + /* IconButton */ + + &:where(.IconButton) { + display: inline-grid; + width: var(--control-medium-size); + min-width: unset; + /* stylelint-disable-next-line primer/spacing */ + padding: unset; + place-content: center; + flex-shrink: 0; + + &:where([data-size='small']) { + width: var(--control-small-size); + } + + &:where([data-size='large']) { + width: var(--control-large-size); + } + } + + /* LinkButton */ + + &:where([href]) { + display: inline-flex; + + &:hover { + text-decoration: none; + } + } + + /* Button layout */ + + & :where(.ButtonContent) { + flex: 1 0 auto; + display: grid; + grid-template-areas: 'leadingVisual text trailingVisual'; + grid-template-columns: min-content minmax(0, auto) min-content; + align-items: center; + align-content: center; + + & > :not(:last-child) { + margin-right: var(--base-size-6); + } + + /* Content alignment */ + + &:where([data-align='center']) { + justify-content: center; + } + + &:where([data-align='start']) { + justify-content: flex-start; + } + } + + & :where([data-component='leadingVisual']) { + grid-area: leadingVisual; + } + + & :where(.Label) { + /* 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; + } + + & :where([data-component='trailingVisual']) { + grid-area: trailingVisual; + } + + & :where([data-component='trailingAction']) { + margin-right: calc(var(--base-size-4) * -1); + } + + /* Size */ + + &:where([data-size='small']) { + height: var(--control-small-size); + /* stylelint-disable-next-line primer/spacing */ + padding: 0 var(--control-small-paddingInline-condensed); + gap: var(--base-size-6); + font-size: var(--text-body-size-small); + line-height: var(--base-text-lineHeight-normal); + + & .Label { + line-height: var(--base-text-lineHeight-normal); + } + } + + &:where([data-size='large']) { + height: var(--control-large-size); + /* stylelint-disable-next-line primer/spacing */ + padding: 0 var(--control-large-paddingInline-spacious); + gap: var(--base-size-6); + } + + /* Full width */ + + &:where([data-block='block']) { + width: 100%; + } + + /* Wrap label text */ + + &:where([data-label-wrap='true']) { + min-width: fit-content; + height: unset; + min-height: var(--control-medium-size); + + & .ButtonContent { + flex: 1 1 auto; + align-self: stretch; + /* stylelint-disable-next-line primer/spacing */ + padding-block: calc(var(--control-medium-paddingBlock) - var(--base-size-2)); + } + + & .Label { + /* stylelint-disable-next-line declaration-property-value-keyword-no-deprecated */ + word-break: break-word; + white-space: unset; + } + + &:where([data-size='small']) { + min-height: var(--control-small-size); + + & .ButtonContent { + /* stylelint-disable-next-line primer/spacing */ + padding-block: calc(var(--control-small-paddingBlock) - var(--base-size-2)); + } + } + + &:where([data-size='large']) { + min-height: var(--control-large-size); + /* stylelint-disable-next-line primer/spacing */ + padding-inline: var(--control-large-paddingInline-spacious); + + & .ButtonContent { + /* stylelint-disable-next-line primer/spacing */ + padding-block: calc(var(--control-large-paddingBlock) - var(--base-size-2)); + } + } + } + + /* Loading */ + + /* only hide label if there's no leading/trailing visuals + * move spinner to label spot if not leading/trailing visuals + */ + + &:where([data-loading='true']) { + & + .LoadingSpinner:not( + [data-component='leadingVisual'], + [data-component='trailingVisual'], + [data-component='trailingAction'] + ) { + grid-area: text; + margin-right: 0 !important; + place-self: center; + + & + .Label { + visibility: hidden; + } + } + } + + /* Styles for the spinner element displayed when the Button is in a loading state. + * Ensures the spinner is centered within its container. */ + .LoadingSpinner { + display: flex; + align-items: center; + justify-content: center; + } + + /* Default Variant */ + + &:where([data-variant='default']) { + background-color: var(--button-default-bgColor-rest); + box-shadow: var(--button-default-shadow-resting); + + &[aria-expanded='true'] { + background-color: var(--button-default-bgColor-active); + border-color: var(--button-default-borderColor-active); + } + + &:hover { + background-color: var(--button-default-bgColor-hover); + border-color: var(--button-default-borderColor-hover); + } + + &:active { + background-color: var(--button-default-bgColor-active); + border-color: var(--button-default-borderColor-active); + } + + &:disabled, + &[aria-disabled='true']:not([data-loading='true']), + &[aria-disabled='true'][data-loading-disabled-styles='true'] { + color: var(--control-fgColor-disabled); + background-color: var(--button-default-bgColor-disabled); + border-color: var(--button-default-borderColor-disabled); + box-shadow: none; + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-default-bgColor-disabled); + color: var(--buttonKeybindingHint-default-fgColor-disabled); + border-color: var(--buttonKeybindingHint-default-borderColor-disabled); + } + } + + & .CounterLabel { + background-color: var(--buttonCounter-default-bgColor-rest) !important; /* temporarily override our own sx prop */ + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-default-bgColor-rest); + color: var(--buttonKeybindingHint-default-fgColor-rest); + border-color: var(--buttonKeybindingHint-default-borderColor-rest); + } + + &:where(.IconButton) { + color: var(--fgColor-muted); + } + } + + /* Primary variant */ + + &:where([data-variant='primary']) { + color: var(--button-primary-fgColor-rest); + background-color: var(--button-primary-bgColor-rest); + border-color: var(--button-primary-borderColor-rest); + box-shadow: var(--shadow-resting-small); + + &[aria-expanded='true'] { + background-color: var(--button-primary-bgColor-active); + box-shadow: var(--button-primary-shadow-selected); + } + + &:hover { + background-color: var(--button-primary-bgColor-hover); + border-color: var(--button-primary-borderColor-hover); + } + + &:focus-visible { + @mixin focusOutlineOnEmphasis; + } + + &:active { + background-color: var(--button-primary-bgColor-active); + box-shadow: var(--button-primary-shadow-selected); + } + + &:disabled, + &[aria-disabled='true']:not([data-loading='true']), + &[aria-disabled='true'][data-loading-disabled-styles='true'] { + color: var(--button-primary-fgColor-disabled); + background-color: var(--button-primary-bgColor-disabled); + border-color: var(--button-primary-borderColor-disabled); + box-shadow: none; + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-primary-bgColor-disabled); + color: var(--buttonKeybindingHint-primary-fgColor-disabled); + border-color: var(--buttonKeybindingHint-primary-borderColor-disabled); + } + } + + & .CounterLabel { + color: var(--button-primary-fgColor-rest) !important; /* temporarily override our own sx prop */ + background-color: var(--buttonCounter-primary-bgColor-rest) !important; /* temporarily override our own sx prop */ + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-primary-bgColor-rest); + color: var(--buttonKeybindingHint-primary-fgColor-rest); + border-color: var(--buttonKeybindingHint-primary-borderColor-rest); + } + + /* temporarily using the fgColor to match legacy and reduce visual changes- will eventually be iconColor */ + & .Visual { + color: var(--button-primary-fgColor-rest); + } + } + + /* Danger variant */ + + &:where([data-variant='danger']) { + color: var(--button-danger-fgColor-rest); + background-color: var(--button-danger-bgColor-rest); + box-shadow: var(--button-default-shadow-resting); + + &[aria-expanded='true'] { + color: var(--button-danger-fgColor-active); + background-color: var(--button-danger-bgColor-active); + border-color: var(--button-danger-borderColor-active); + box-shadow: var(--button-danger-shadow-selected); + + & .Visual { + color: var(--button-danger-iconColor-hover); + } + } + + &:hover { + color: var(--button-danger-fgColor-hover); + background-color: var(--button-danger-bgColor-hover); + border-color: var(--button-danger-borderColor-hover); + box-shadow: var(--shadow-resting-small); + + & .CounterLabel { + color: var(--buttonCounter-danger-fgColor-hover) !important; /* temporarily override our own sx prop */ + background-color: var(--buttonCounter-danger-bgColor-hover) !important; + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-danger-bgColor-hover); + color: var(--buttonKeybindingHint-danger-fgColor-hover); + border-color: var(--buttonKeybindingHint-danger-borderColor-hover); + transition: 80ms ease-out; + } + + & .Visual { + color: var(--button-danger-iconColor-hover); + } + } + + &:active { + color: var(--button-danger-fgColor-active); + background-color: var(--button-danger-bgColor-active); + border-color: var(--button-danger-borderColor-active); + box-shadow: var(--button-danger-shadow-selected); + + & .CounterLabel { + color: var(--buttonCounter-danger-fgColor-hover) !important; /* temporarily override our own sx prop */ + background-color: var(--buttonCounter-danger-bgColor-hover) !important; + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-danger-bgColor-active); + color: var(--buttonKeybindingHint-danger-fgColor-active); + border-color: var(--buttonKeybindingHint-danger-borderColor-active); + transition: 80ms ease-out; + } + + & .Visual { + color: var(--button-danger-iconColor-hover); + } + } + + &:disabled, + &[aria-disabled='true']:not([data-loading='true']), + &[aria-disabled='true'][data-loading-disabled-styles='true'] { + color: var(--button-danger-fgColor-disabled); + background-color: var(--button-danger-bgColor-disabled); + border-color: var(--button-default-borderColor-disabled); + box-shadow: none; + + & .CounterLabel { + color: var(--buttonCounter-danger-fgColor-disabled) !important; /* temporarily override our own sx prop */ + background-color: var(--buttonCounter-danger-bgColor-disabled) !important; + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-danger-bgColor-disabled); + color: var(--buttonKeybindingHint-danger-fgColor-disabled); + border-color: var(--buttonKeybindingHint-danger-borderColor-disabled); + } + } + + & .CounterLabel { + color: var(--buttonCounter-danger-fgColor-rest) !important; /* temporarily override our own sx prop */ + background-color: var(--buttonCounter-danger-bgColor-rest) !important; + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-danger-bgColor-rest); + color: var(--buttonKeybindingHint-danger-fgColor-rest); + border-color: var(--buttonKeybindingHint-danger-borderColor-rest); + } + + & .Visual { + color: var(--button-danger-iconColor-rest); + } + } + + /* Invisible variant */ + + &:where([data-variant='invisible']) { + border-color: var(--button-invisible-borderColor-rest); + box-shadow: none; + + &[aria-expanded='true'] { + background-color: var(--button-invisible-bgColor-active); + } + + &:hover { + background-color: var(--button-invisible-bgColor-hover); + border-color: var(--button-invisible-borderColor-hover); + + & .Visual { + color: var(--button-invisible-iconColor-hover); + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-invisible-bgColor-hover); + transition: 80ms ease-out; + } + } + + &:active { + background-color: var(--button-invisible-bgColor-active); + + & .Visual { + color: var(--button-invisible-iconColor-hover); + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-invisible-bgColor-active); + transition: 80ms ease-out; + } + } + + &:disabled, + &[aria-disabled='true']:not([data-loading='true']), + &[aria-disabled='true'][data-loading-disabled-styles='true'] { + color: var(--button-invisible-fgColor-disabled); + background-color: var(--button-invisible-bgColor-disabled); + border-color: var(--button-invisible-borderColor-disabled); + box-shadow: none; + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-invisible-bgColor-disabled); + color: var(--buttonKeybindingHint-invisible-fgColor-disabled); + border-color: var(--buttonKeybindingHint-invisible-borderColor-disabled); + } + } + + & .Visual { + color: var(--button-invisible-iconColor-rest); + } + + & .CounterLabel { + background-color: var(--buttonCounter-invisible-bgColor-rest) !important; + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-invisible-bgColor-rest); + color: var(--buttonKeybindingHint-invisible-fgColor-rest); + border-color: var(--buttonKeybindingHint-invisible-borderColor-rest); + } + + &:where(.IconButton) { + color: var(--button-invisible-iconColor-rest); + } + } + + /* Link variant */ + + &:where([data-variant='link']) { + display: inline-flex; + min-width: fit-content; + height: unset; + padding: 0; + font-size: inherit; + color: var(--fgColor-link); + text-align: left; + border: unset; + border-radius: 0; + + &:where([data-no-visuals]:hover:not(:disabled, [aria-disabled='true'], [data-inactive])) { + text-decoration: underline; + } + + &:where(:not([data-no-visuals]):hover:not(:disabled, [aria-disabled='true'], [data-inactive])) .Label { + text-decoration: underline; + } + + &:focus-visible, + &:focus { + outline-offset: 2px; + } + + &:disabled, + &[aria-disabled='true']:not([data-loading='true']), + &[aria-disabled='true'][data-loading-disabled-styles='true'] { + color: var(--control-fgColor-disabled); + background-color: transparent; + border-color: transparent; + } + + & .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; + } + + &:where([data-inactive]) { + color: var(--button-inactive-fgColor); + background: transparent !important; + } + + & .Visual { + color: var(--fgColor-link); + } + } + + [data-a11y-link-underlines='true'] &:where([data-variant='link']) { + &[data-no-visuals] { + text-decoration: underline; + + &:where(:hover:not(:disabled, [aria-disabled='true'], [data-inactive])) { + text-decoration: none; + } + } + + &:not([data-no-visuals]) { + & .Label { + text-decoration: underline; + } + + &:where(:hover:not(:disabled, [aria-disabled='true'], [data-inactive])) .Label { + text-decoration: none; + } + } + } + + [data-a11y-link-underlines='false'] &:where([data-variant='link']) { + &[data-no-visuals] { + text-decoration: none; + background-image: none; + + &:where(:hover:not(:disabled, [aria-disabled='true'], [data-inactive])) { + text-decoration: underline; + } + } + + &:not([data-no-visuals]) { + background-image: none; + + & .Label { + text-decoration: none; + } + + &:where(:hover:not(:disabled, [aria-disabled='true'], [data-inactive])) .Label { + text-decoration: underline; + } + } + } + + /* Inactive */ + + &:where([data-inactive]), + &:where([data-inactive]):hover, + &:where([data-inactive]):active { + color: var(--button-inactive-fgColor); + cursor: auto; + background-color: var(--button-inactive-bgColor); + /* stylelint-disable-next-line primer/colors */ + border-color: var(--button-inactive-bgColor); + box-shadow: none; + + & .Visual, + & .CounterLabel { + color: inherit !important; + } + + & [data-component='KeybindingHint.Key'] { + background: var(--buttonKeybindingHint-inactive-bgColor); + color: var(--buttonKeybindingHint-inactive-fgColor); + border-color: var(--buttonKeybindingHint-inactive-borderColor); + } + } + + /* Icon-only + Counter */ + + &:where([data-icon-only-counter]) { + /* stylelint-disable-next-line primer/spacing */ + padding-inline: var(--control-medium-paddingInline-condensed); + + &:where([data-size='small']) { + /* stylelint-disable-next-line primer/spacing */ + padding-inline: var(--control-xsmall-paddingInline-condensed); + } + + &:where([data-size='large']) { + /* stylelint-disable-next-line primer/spacing */ + padding-inline: var(--control-large-paddingInline-normal); + } + } +} + +.ConditionalWrapper { + display: block; +} + +.ConditionalWrapperLink { + display: inline-flex; +} + +[data-kbd-chord] { + transition: 80ms ease-in; + transition-property: color, background-color, border-color; +} diff --git a/packages/react/src/Button/ButtonBase.modernize.module.css b/packages/react/src/Button/ButtonBase.modernize.module.css new file mode 100644 index 00000000000..ca445bfcb27 --- /dev/null +++ b/packages/react/src/Button/ButtonBase.modernize.module.css @@ -0,0 +1,56 @@ +.ButtonBase { + & [data-component='KeybindingHint.Key'] { + border: 0; + box-shadow: none; + } + + & [data-component='buttonContent'] > :not(:last-child) { + margin-right: var(--base-size-6); + } + + &: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; + } + + &: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); + } + + &:where([data-size='small'], [data-size='large']) { + gap: var(--base-size-6); + } + + &:where([data-size='small']), + &:where([data-size='small']:not([data-variant='link'])) [data-component='text'] { + line-height: var(--base-text-lineHeight-normal); + } + + &.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 this CSS Module and a single keyboard chord attribute */ + &:has([data-kbd-chord]) { + padding-inline: calc(var(--base-size-12) - var(--base-size-2)) var(--base-size-8); + + &:where([data-size='small']) { + padding-inline: var(--base-size-8) var(--base-size-6); + } + + &:where([data-size='large']) { + padding-inline: var(--base-size-12) calc(var(--base-size-12) - var(--base-size-2)); + } + } +} diff --git a/packages/react/src/Button/ButtonBase.module.css b/packages/react/src/Button/ButtonBase.module.css index 278b4979314..b4ccf7bbd9a 100644 --- a/packages/react/src/Button/ButtonBase.module.css +++ b/packages/react/src/Button/ButtonBase.module.css @@ -329,7 +329,7 @@ border-color: var(--button-default-borderColor-disabled); box-shadow: none; - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-default-bgColor-disabled); color: var(--buttonKeybindingHint-default-fgColor-disabled); border-color: var(--buttonKeybindingHint-default-borderColor-disabled); @@ -340,7 +340,7 @@ background-color: var(--buttonCounter-default-bgColor-rest) !important; /* temporarily override our own sx prop */ } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-default-bgColor-rest); color: var(--buttonKeybindingHint-default-fgColor-rest); border-color: var(--buttonKeybindingHint-default-borderColor-rest); @@ -386,7 +386,7 @@ border-color: var(--button-primary-borderColor-disabled); box-shadow: none; - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-primary-bgColor-disabled); color: var(--buttonKeybindingHint-primary-fgColor-disabled); border-color: var(--buttonKeybindingHint-primary-borderColor-disabled); @@ -398,7 +398,7 @@ background-color: var(--buttonCounter-primary-bgColor-rest) !important; /* temporarily override our own sx prop */ } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-primary-bgColor-rest); color: var(--buttonKeybindingHint-primary-fgColor-rest); border-color: var(--buttonKeybindingHint-primary-borderColor-rest); @@ -439,7 +439,7 @@ background-color: var(--buttonCounter-danger-bgColor-hover) !important; } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-danger-bgColor-hover); color: var(--buttonKeybindingHint-danger-fgColor-hover); border-color: var(--buttonKeybindingHint-danger-borderColor-hover); @@ -462,7 +462,7 @@ background-color: var(--buttonCounter-danger-bgColor-hover) !important; } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-danger-bgColor-active); color: var(--buttonKeybindingHint-danger-fgColor-active); border-color: var(--buttonKeybindingHint-danger-borderColor-active); @@ -487,7 +487,7 @@ background-color: var(--buttonCounter-danger-bgColor-disabled) !important; } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-danger-bgColor-disabled); color: var(--buttonKeybindingHint-danger-fgColor-disabled); border-color: var(--buttonKeybindingHint-danger-borderColor-disabled); @@ -499,7 +499,7 @@ background-color: var(--buttonCounter-danger-bgColor-rest) !important; } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-danger-bgColor-rest); color: var(--buttonKeybindingHint-danger-fgColor-rest); border-color: var(--buttonKeybindingHint-danger-borderColor-rest); @@ -529,7 +529,7 @@ color: var(--button-invisible-iconColor-hover); } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-invisible-bgColor-hover); transition: 80ms ease-out; } @@ -542,7 +542,7 @@ color: var(--button-invisible-iconColor-hover); } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-invisible-bgColor-active); transition: 80ms ease-out; } @@ -556,7 +556,7 @@ border-color: var(--button-invisible-borderColor-disabled); box-shadow: none; - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-invisible-bgColor-disabled); color: var(--buttonKeybindingHint-invisible-fgColor-disabled); border-color: var(--buttonKeybindingHint-invisible-borderColor-disabled); @@ -571,7 +571,7 @@ background-color: var(--buttonCounter-invisible-bgColor-rest) !important; } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-invisible-bgColor-rest); color: var(--buttonKeybindingHint-invisible-fgColor-rest); border-color: var(--buttonKeybindingHint-invisible-borderColor-rest); @@ -694,7 +694,7 @@ color: inherit !important; } - & [data-kbd-chord] { + & [data-component='KeybindingHint.Key'] { background: var(--buttonKeybindingHint-inactive-bgColor); color: var(--buttonKeybindingHint-inactive-fgColor); border-color: var(--buttonKeybindingHint-inactive-borderColor); diff --git a/packages/react/src/Button/ButtonBase.tsx b/packages/react/src/Button/ButtonBase.tsx index d4747b94d4d..8d3e0771e77 100644 --- a/packages/react/src/Button/ButtonBase.tsx +++ b/packages/react/src/Button/ButtonBase.tsx @@ -10,6 +10,7 @@ import {ConditionalWrapper} from '../internal/components/ConditionalWrapper' import {AriaStatus} from '../live-region' import {clsx} from 'clsx' import classes from './ButtonBase.module.css' +import modernizeClasses from './ButtonBase.modernize.module.css' import {isElement, isValidElementType} from 'react-is' import {useFeatureFlag} from '../FeatureFlags' @@ -111,7 +112,12 @@ 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, + modernizeClasses.ButtonBase, + LeadingVisual && modernizeClasses.HasLeadingVisual, + className, + )} data-block={block ? 'block' : null} data-inactive={inactive ? true : undefined} data-loading={Boolean(loading)} diff --git a/packages/react/src/Button/__tests__/__snapshots__/Button.test.tsx.snap b/packages/react/src/Button/__tests__/__snapshots__/Button.test.tsx.snap index 1051eac1018..a99745de095 100644 --- a/packages/react/src/Button/__tests__/__snapshots__/Button.test.tsx.snap +++ b/packages/react/src/Button/__tests__/__snapshots__/Button.test.tsx.snap @@ -2,7 +2,7 @@ exports[`Button > respects block prop 1`] = ` + {open && ( + setOpen(false)} + returnFocusRef={triggerRef} + footerButtons={[ + {content: tall ? 'Decline' : 'Cancel', onClick: () => setOpen(false)}, + {content: tall ? 'Accept' : 'Confirm', buttonType: '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..7fbc5406b24 --- /dev/null +++ b/packages/react/src/Dialog/Dialog.modernize.module.css @@ -0,0 +1,86 @@ +.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); + } +} + +.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' diff --git a/packages/react/src/KeybindingHint/KeybindingHint.features.stories.module.css b/packages/react/src/KeybindingHint/KeybindingHint.features.stories.module.css index 291d6fc3b87..a38784468d0 100644 --- a/packages/react/src/KeybindingHint/KeybindingHint.features.stories.module.css +++ b/packages/react/src/KeybindingHint/KeybindingHint.features.stories.module.css @@ -3,6 +3,32 @@ padding: var(--base-size-12); } +.Comparison, +.ComparisonRows { + padding: var(--base-size-16); + font-size: var(--text-body-size-small); +} + +.Comparison { + display: flex; +} + +.ComparisonRows { + display: flex; + flex-direction: column; + gap: var(--base-size-12); +} + +.ComparisonRow { + display: inline-flex; + align-items: center; + gap: var(--base-size-8); + + & > span { + color: var(--fgColor-muted); + } +} + .PrimaryBackground { background-color: var(--button-primary-bgColor-rest); padding: var(--base-size-12); diff --git a/packages/react/src/KeybindingHint/KeybindingHint.features.stories.tsx b/packages/react/src/KeybindingHint/KeybindingHint.features.stories.tsx index cc8ae462ead..b7c57dbde84 100644 --- a/packages/react/src/KeybindingHint/KeybindingHint.features.stories.tsx +++ b/packages/react/src/KeybindingHint/KeybindingHint.features.stories.tsx @@ -2,6 +2,7 @@ import type {Meta, StoryObj} from '@storybook/react-vite' import {KeybindingHint, type KeybindingHintProps} from '.' import {PlatformOverrideProvider, type Platform} from './platform' import classes from './KeybindingHint.features.stories.module.css' +import {Button} from '../Button' export default { title: 'Experimental/Components/KeybindingHint/Features', @@ -10,6 +11,58 @@ export default { const chord = 'Mod+Shift+K' +export const ModernizedKey = () => ( +
+ +
+) + +export const ModernizedSequences = () => ( +
+
+ + Open command palette +
+
+ + Submit without closing +
+
+) + +export const ModernizedChord = () => ( +
+
+ + Modifier keys are ordered consistently +
+
+) + +export const ModernizedLabels = () => ( +
+
+ + + Single-character keycaps are fixed width +
+
+ + + + Word keys auto-size to their label width +
+
+) + +export const ModernizedButton = () => ( +
+ +
+) + 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} + ) } 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..575976ff8cf --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.modernize.module.css @@ -0,0 +1,167 @@ +.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-component='ActionList.Selection'] > div { + width: calc(var(--base-size-16) - var(--base-size-2)); + height: calc(var(--base-size-16) - var(--base-size-2)); + border: 0; + background: transparent; + + &::before { + width: inherit; + height: inherit; + background-color: currentColor; + clip-path: none; + animation: none; + transition: none; + + @media (forced-colors: active) { + forced-color-adjust: none; + } + } + } + + & [data-component='ActionList.Selection'] > [data-component='Radio'] { + width: calc(var(--base-size-16) - var(--base-size-2)); + height: calc(var(--base-size-16) - var(--base-size-2)); + margin: 0; + color: inherit; + border: 0; + border-radius: 0; + background: transparent; + mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z'/%3E%3C/svg%3E") + center / contain no-repeat; + + &:where(:checked) { + background-color: currentColor; + + @media (forced-colors: active) { + forced-color-adjust: none; + } + } + } + + & [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-title-visually-hidden]) .TextInput { + border-start-start-radius: var(--borderRadius-large); + border-start-end-radius: var(--borderRadius-large); + } + + &: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..45550c204d4 100644 --- a/packages/react/src/SelectPanel/SelectPanel.test.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.test.tsx @@ -1,6 +1,6 @@ import {act, fireEvent, render, screen, waitFor} from '@testing-library/react' import {describe, expect, it, beforeEach, vi} from 'vitest' -import {page} from 'vitest/browser' +import {page, userEvent as browserUserEvent} from 'vitest/browser' import React from 'react' import {flushSync} from 'react-dom' import {SelectPanel, type SelectPanelProps, type ItemInput, type GroupedListProps} from '../SelectPanel' @@ -101,6 +101,89 @@ 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}, 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') + }) + + it.each(['anchored', 'modal'] as const)( + 'keeps the accessible name and search focus with a hidden title in the %s panel', + async variant => { + const variantProps = + variant === 'modal' ? {variant: 'modal' as const, onCancel: () => {}} : {variant: 'anchored' as const} + 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"]') + if (!control) throw new Error('Expected the search input to have a TextInput wrapper') + const style = getComputedStyle(control) + expect(style.outlineStyle).toBe('solid') + expect(style.outlineWidth).toBe('2px') + const radius = + variant === 'modal' + ? '6px' + : getComputedStyle(page.getByRole('dialog', {name: 'Choose an option', exact: true}).element()) + .borderTopLeftRadius + expect(style.borderTopLeftRadius).toBe(radius) + expect(style.borderTopRightRadius).toBe(radius) + expect(style.borderBottomLeftRadius).toBe(variant === 'modal' ? radius : '0px') + expect(style.borderBottomRightRadius).toBe(variant === 'modal' ? radius : '0px') + }, + ) + + 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'}, @@ -1494,17 +1577,40 @@ for (const usingRemoveActiveDescendant of [false, true]) { }) describe('As Modal', () => { - it('selections render as radios when variant modal and single select', async () => { - const user = userEvent.setup() + it('preserves single-select modal semantics with tick indicators', async () => { + const user = browserUserEvent renderWithProp( - {}} selected={undefined} />, + {}} + selected={undefined} + items={items.map((item, index) => ({...item, id: `item-${index}`}))} + />, usingRemoveActiveDescendant, ) await user.click(screen.getByText('Select items')) - expect(screen.getAllByRole('radio', {hidden: true}).length).toBe(items.length) + const radios = screen.getAllByRole('radio', {hidden: true}) + const getRadio = (index: number) => screen.getAllByRole('radio', {hidden: true})[index] + expect(radios).toHaveLength(items.length) + for (const radio of radios) { + expect(radio).not.toBeChecked() + expect(radio).toHaveStyle({width: '14px', height: '14px', borderWidth: '0px'}) + expect(getComputedStyle(radio).backgroundColor).toBe('rgba(0, 0, 0, 0)') + expect(getComputedStyle(radio).maskImage).not.toBe('none') + } + + await user.click(screen.getByRole('option', {name: 'item one'})) + await expect.poll(() => getRadio(0).getAttribute('aria-checked')).toBe('true') + await expect.poll(() => getComputedStyle(getRadio(0)).backgroundColor).toBe(getComputedStyle(getRadio(0)).color) + + await user.click(screen.getByRole('option', {name: 'item two'})) + await expect.poll(() => getRadio(0).getAttribute('aria-checked')).toBe('false') + await expect.poll(() => getComputedStyle(getRadio(0)).backgroundColor).toBe('rgba(0, 0, 0, 0)') + await expect.poll(() => getRadio(1).getAttribute('aria-checked')).toBe('true') + await expect.poll(() => getComputedStyle(getRadio(1)).backgroundColor).toBe(getComputedStyle(getRadio(1)).color) expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument() expect(screen.getByRole('button', {name: 'Cancel'})).toBeInTheDocument() diff --git a/packages/react/src/SelectPanel/SelectPanel.tsx b/packages/react/src/SelectPanel/SelectPanel.tsx index f3b655065d1..f47c99119bf 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 && !overlayProps?.maxHeight && !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 && ( input::-webkit-search-cancel-button, + & > input::-webkit-search-decoration { + display: none; + } +} diff --git a/packages/react/src/TextInput/TextInput.features.stories.tsx b/packages/react/src/TextInput/TextInput.features.stories.tsx index cd0db80c526..9952d2694f8 100644 --- a/packages/react/src/TextInput/TextInput.features.stories.tsx +++ b/packages/react/src/TextInput/TextInput.features.stories.tsx @@ -1,11 +1,12 @@ import type React from 'react' -import {useState} from 'react' +import {useRef, useState} from 'react' +import type {StoryObj} from '@storybook/react-vite' import FormControl from '../FormControl' import Heading from '../Heading' import {Stack} from '../Stack' import type {TextInputProps} from '../TextInput' import TextInput from '../TextInput' -import {CalendarIcon, CheckIcon, XCircleFillIcon} from '@primer/octicons-react' +import {CalendarIcon, CheckIcon, XCircleFillIcon, SearchIcon, LockIcon} from '@primer/octicons-react' import type {FormControlArgs} from '../utils/story-helpers' import {formControlArgTypes, textInputExcludedControlKeys} from '../utils/story-helpers' import classes from './TextInput.features.stories.module.css' @@ -14,6 +15,98 @@ export default { title: 'Components/TextInput/Features', } +export const ModernizedInput: StoryObj = { + decorators: [ + Story => ( +
+ +
+ ), + ], + render: () => , +} + +export const ModernizedSizes: StoryObj = { + decorators: ModernizedInput.decorators, + render: () => ( +
+ + + +
+ ), +} + +export const ModernizedSearch: StoryObj = { + decorators: ModernizedInput.decorators, + render: function SearchInput() { + const [value, setValue] = useState('Search query') + const inputRef = useRef(null) + return ( + setValue(event.target.value)} + trailingAction={ + { + setValue('') + inputRef.current?.focus() + }} + /> + } + /> + ) + }, +} + +export const ModernizedPassword: StoryObj = { + decorators: ModernizedInput.decorators, + render: () => ( + + ), +} + +export const ModernizedStates: StoryObj = { + decorators: ModernizedInput.decorators, + render: () => ( +
+ + + + + +
+ ), +} + +export const ModernizedVisualSizes: StoryObj = { + decorators: ModernizedInput.decorators, + render: () => ( +
+ {(['small', 'medium', 'large'] as const).map(size => ( + + ))} +
+ ), +} + export const Disabled = () => (
diff --git a/packages/react/src/TextInput/TextInput.modernize.module.css b/packages/react/src/TextInput/TextInput.modernize.module.css new file mode 100644 index 00000000000..08f4d5e7f20 --- /dev/null +++ b/packages/react/src/TextInput/TextInput.modernize.module.css @@ -0,0 +1,118 @@ +.TextInput[data-component='TextInput'] { + --textInput-modernize-padding: var(--base-size-12); + --textInput-modernize-visual-inset: var(--base-size-8); + --textInput-modernize-icon-size: var(--base-size-16); + --textInput-modernize-gap: var(--base-size-6); + --textInput-modernize-trailing-gap: var(--base-size-8); + --inner-action-size: var(--base-size-24); + + padding: 0; + /* stylelint-disable-next-line primer/typography -- GitHub App's 13px input text has no matching Primer token */ + font-size: 13px; + line-height: var(--base-text-lineHeight-normal); + -webkit-font-smoothing: antialiased; + /* stylelint-disable-next-line primer/borders -- GitHub App's 8px radius has no matching Primer token */ + border-radius: 8px; + box-shadow: none; + + &:where([data-size='small'], [data-variant='small']) { + --textInput-modernize-padding: var(--base-size-8); + --textInput-modernize-visual-inset: var(--base-size-6); + --textInput-modernize-icon-size: calc(var(--base-size-16) - var(--base-size-2)); + --textInput-modernize-gap: var(--base-size-4); + --textInput-modernize-trailing-gap: var(--base-size-4); + + font-size: var(--text-body-size-small); + } + + &:where([data-size='large'], [data-variant='large']) { + --textInput-modernize-padding: calc(var(--base-size-16) - var(--base-size-2)); + --textInput-modernize-visual-inset: calc(var(--base-size-12) - var(--base-size-2)); + --textInput-modernize-gap: var(--base-size-8); + --textInput-modernize-trailing-gap: var(--base-size-12); + + height: var(--base-size-40); + font-size: var(--text-body-size-medium); + } + + /* stylelint-disable primer/spacing -- local spacing variables reference Primer size tokens */ + & > :not(:last-child) { + margin-inline: 0 var(--textInput-modernize-gap); + } + + & > input { + min-width: 0; + padding: 0; + line-height: inherit; + + &::placeholder { + opacity: 1; + } + } + + &:where([data-no-leading-visual]) > input { + padding-inline-start: var(--textInput-modernize-padding); + } + + &:where([data-no-trailing-visual][data-no-trailing-action]) > input { + padding-inline-end: var(--textInput-modernize-padding); + } + + &:where([data-leading-visual]) { + padding-inline-start: var(--textInput-modernize-visual-inset); + } + + &:where([data-trailing-visual], [data-trailing-action]) { + padding-inline-end: var(--base-size-4); + + & > input:not(:last-child) { + margin-inline-end: var(--textInput-modernize-trailing-gap); + } + } + /* stylelint-enable primer/spacing */ + + & [data-component='TextInput.LeadingVisual'], + & [data-component='TextInput.TrailingVisual'] { + display: inline-flex; + align-items: center; + + & svg { + width: var(--textInput-modernize-icon-size); + height: var(--textInput-modernize-icon-size); + } + } + + & [data-component='TextInput.TrailingVisual'] { + min-width: var(--base-size-24); + justify-content: center; + } + + & [data-component='TextInput.Action'] { + margin-inline: 0; + } + + & [data-component='TextInput.Action'] svg { + width: calc(var(--base-size-16) - var(--base-size-2)); + height: calc(var(--base-size-16) - var(--base-size-2)); + } + + &:where([data-disabled]) { + color: var(--control-fgColor-disabled); + } + + &:where([data-disabled], [data-validation='error'], [data-trailing-action][data-focused]), + &:where([data-no-trailing-action]):focus-within { + border-color: var(--control-borderColor-rest); + } + + &:where([data-validation='error']) { + outline: var(--borderWidth-thin) solid var(--borderColor-danger-emphasis); + outline-offset: -1px; + + &:where([data-trailing-action])[data-focused], + &:where([data-no-trailing-action]):focus-within { + outline-color: var(--borderColor-danger-emphasis); + outline-width: var(--borderWidth-thick); + } + } +} diff --git a/packages/react/src/TextInput/TextInput.test.tsx b/packages/react/src/TextInput/TextInput.test.tsx index 0cbe72bfec3..951bb954b4b 100644 --- a/packages/react/src/TextInput/TextInput.test.tsx +++ b/packages/react/src/TextInput/TextInput.test.tsx @@ -2,6 +2,7 @@ import {SearchIcon} from '@primer/octicons-react' import userEvent from '@testing-library/user-event' import {render, fireEvent, screen, act} from '@testing-library/react' import {describe, it, expect, vi, afterEach} from 'vitest' +import {page, userEvent as browserUserEvent} from 'vitest/browser' import React, {createRef} from 'react' import TextInput from '../TextInput' import {FeatureFlags} from '../FeatureFlags' @@ -34,6 +35,58 @@ describe('TextInput', () => { expect(container.firstElementChild).toHaveAttribute('data-size', 'large') }) + describe.each(['ltr', 'rtl'] as const)('modernized spacing in %s', direction => { + it.each([ + {size: 'small', height: 28, fontSize: '12px', iconSize: 14, gap: 4}, + {size: 'medium', height: 32, fontSize: '13px', iconSize: 16, gap: 6}, + {size: 'large', height: 40, fontSize: '14px', iconSize: 16, gap: 8}, + ] as const)('aligns $size input text and visuals', async ({size, height, fontSize, iconSize, gap}) => { + render( +
+ +
, + ) + const input = page.getByRole('textbox', {name: 'Search', exact: true}).element() + const wrapper = input.parentElement + const icon = wrapper?.querySelector('[data-component="TextInput.LeadingVisual"] svg') + if (!wrapper || !icon) { + throw new Error('Expected the input wrapper and leading icon') + } + + await expect.poll(() => wrapper.getBoundingClientRect().height).toBe(height) + await expect.poll(() => getComputedStyle(input).fontSize).toBe(fontSize) + await expect.poll(() => icon.getBoundingClientRect().width).toBe(iconSize) + await expect + .poll(() => { + const inputBounds = input.getBoundingClientRect() + const iconBounds = icon.getBoundingClientRect() + return direction === 'rtl' ? iconBounds.left - inputBounds.right : inputBounds.left - iconBounds.right + }) + .toBe(gap) + }) + }) + + it.each([false, true])('emphasizes errors on focus with trailing action: %s', async withAction => { + render( + : undefined} + />, + ) + const input = page.getByRole('textbox', {name: 'Invalid input', exact: true}) + const wrapper = input.element().parentElement + if (!wrapper) { + throw new Error('Expected the input wrapper') + } + + await expect.poll(() => getComputedStyle(wrapper).outlineWidth).toBe('1px') + const errorColor = getComputedStyle(wrapper).outlineColor + await browserUserEvent.click(input) + await expect.poll(() => getComputedStyle(wrapper).outlineWidth).toBe('2px') + expect(getComputedStyle(wrapper).outlineColor).toBe(errorColor) + }) + it('renders block', () => { const {container} = render() expect(container.firstElementChild).toHaveAttribute('data-block') diff --git a/packages/react/src/TextInput/TextInput.tsx b/packages/react/src/TextInput/TextInput.tsx index de2c0e12af9..86d9bf51f7d 100644 --- a/packages/react/src/TextInput/TextInput.tsx +++ b/packages/react/src/TextInput/TextInput.tsx @@ -6,6 +6,7 @@ import {clsx} from 'clsx' import {AlertFillIcon} from '@primer/octicons-react' import classes from './TextInput.module.css' +import modernizeClasses from './TextInput.modernize.module.css' import TextInputInnerVisualSlot from '../internal/components/TextInputInnerVisualSlot' import type {Merge} from '../utils/types' import type {StyledWrapperProps} from '../internal/components/TextInputWrapper' @@ -138,7 +139,7 @@ const TextInput = React.forwardRef( const isOverLimit = counter?.isOverLimit ?? false // this class is necessary to style FilterSearch, plz no touchy! - const wrapperClasses = clsx(className, 'TextInput-wrapper') + const wrapperClasses = clsx(className, modernizeClasses.TextInput, 'TextInput-wrapper') const showLeadingLoadingIndicator = loading && (loaderPosition === 'leading' || Boolean(LeadingVisual && loaderPosition !== 'trailing')) const showTrailingLoadingIndicator = diff --git a/packages/react/src/TextInput/__snapshots__/TextInput.test.tsx.snap b/packages/react/src/TextInput/__snapshots__/TextInput.test.tsx.snap index 2f7134a0fd9..a1c1a5a68ff 100644 --- a/packages/react/src/TextInput/__snapshots__/TextInput.test.tsx.snap +++ b/packages/react/src/TextInput/__snapshots__/TextInput.test.tsx.snap @@ -4,7 +4,7 @@ exports[`TextInput > renders contrast 1`] = `
renders error 1`] = `
renders monospace 1`] = `
renders placeholder 1`] = `
should render a password input 1`] = `
& {label: string}) { + const id = useId() + return ( +
+ {label} + +
+ ) +} + +export const ModernizedSwitch: StoryObj = { + render: () => , + play: async ({canvas}) => { + const button = canvas.getByRole('button', {name: 'Enable notifications'}) + await expect(button).toHaveAttribute('aria-pressed', 'false') + }, +} + +export const ModernizedChecked = () => +export const ModernizedDisabled = () => +export const ModernizedCheckedDisabled = () => +export const ModernizedSizes = () => ( +
+ {(['compact', 'small', 'medium'] as const).map(size => ( + + ))} +
+) + export const Small = () => ( diff --git a/packages/react/src/ToggleSwitch/ToggleSwitch.modernize.module.css b/packages/react/src/ToggleSwitch/ToggleSwitch.modernize.module.css new file mode 100644 index 00000000000..80763996ec6 --- /dev/null +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.modernize.module.css @@ -0,0 +1,156 @@ +.StatusText[data-size] { + min-inline-size: var(--base-size-24); + margin-inline: 0 var(--base-size-8); + font-size: var(--text-body-size-small); + font-weight: var(--base-text-weight-medium); + line-height: var(--base-text-lineHeight-normal); + white-space: nowrap; +} + +.SwitchButton[data-size] { + width: var(--base-size-48); + height: var(--base-size-24); + border: 0; + 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); + height: var(--base-size-20); + } + + &:where([data-size='compact']) { + width: calc(var(--base-size-32) - var(--base-size-2)); + height: var(--base-size-16); + } + + &: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; + } +} + +.ToggleKnob[data-size] { + top: var(--base-size-2); + bottom: var(--base-size-2); + 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); + } + + &:where([data-size='compact']) { + width: var(--base-size-16); + } + + &:where([data-checked='true']) { + /* 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)); + } + + &:where([data-size='compact'][data-checked='true']) { + transform: translateX(calc(var(--base-size-12) - var(--base-size-2))); + } + + &:dir(rtl):where([data-checked='true']) { + 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.stories.tsx b/packages/react/src/ToggleSwitch/ToggleSwitch.stories.tsx index bcdf623b5d6..aea33002758 100644 --- a/packages/react/src/ToggleSwitch/ToggleSwitch.stories.tsx +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.stories.tsx @@ -50,7 +50,7 @@ Playground.argTypes = { control: { type: 'radio', }, - options: ['small', 'medium'], + options: ['compact', 'small', 'medium'], }, buttonLabelOn: { control: { diff --git a/packages/react/src/ToggleSwitch/ToggleSwitch.test.tsx b/packages/react/src/ToggleSwitch/ToggleSwitch.test.tsx index f665ff6d1dc..90ffa02ae60 100644 --- a/packages/react/src/ToggleSwitch/ToggleSwitch.test.tsx +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.test.tsx @@ -5,11 +5,109 @@ import ToggleSwitch from './' import userEvent from '@testing-library/user-event' import {implementsClassName} from '../utils/testing' import classes from './ToggleSwitch.module.css' +import {page, userEvent as browserUserEvent} from 'vitest/browser' const SWITCH_LABEL_TEXT = 'Switch label' describe('ToggleSwitch', () => { implementsClassName(ToggleSwitch, classes.ToggleSwitch) + it.each([ + ['compact', 30, 16], + ['small', 40, 20], + ['medium', 48, 24], + ] as const)('keeps the %s thumb inside the control in both directions', async (size, width, height) => { + const {rerender} = render( +
+ Size preview + +
, + ) + for (const direction of ['ltr', 'rtl']) { + rerender( +
+ Size preview + +
, + ) + const button = page.getByRole('button', {name: 'Size preview', exact: true}) + await expect.element(button).toHaveStyle({width: `${width}px`, height: `${height}px`}) + for (let toggle = 0; toggle < 2; toggle++) { + await browserUserEvent.click(button) + await expect + .poll(() => { + const track = button.element().getBoundingClientRect() + const thumb = button.element().lastElementChild?.getBoundingClientRect() + 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( + <> + Compact preference + + , + ) + const button = page.getByRole('button', {name: 'Compact preference', exact: true}) + await browserUserEvent.tab() + await expect.element(button).toHaveFocus() + await browserUserEvent.keyboard(' ') + await expect.element(button).toHaveAttribute('aria-pressed', 'true') + await expect.element(page.getByText('Enabled', {exact: true})).toBeVisible() + await browserUserEvent.keyboard('{Enter}') + await expect.element(button).toHaveAttribute('aria-pressed', 'false') + await expect.element(page.getByText('Disabled', {exact: true})).toBeVisible() + }) it('renders a switch that is turned off', () => { const {getByLabelText} = render( <> diff --git a/packages/react/src/ToggleSwitch/ToggleSwitch.tsx b/packages/react/src/ToggleSwitch/ToggleSwitch.tsx index 156586378c9..172cfef436f 100644 --- a/packages/react/src/ToggleSwitch/ToggleSwitch.tsx +++ b/packages/react/src/ToggleSwitch/ToggleSwitch.tsx @@ -8,6 +8,7 @@ import type {CellAlignment} from '../DataTable/column' import {AriaStatus} from '../live-region' import useSafeTimeout from '../hooks/useSafeTimeout' import classes from './ToggleSwitch.module.css' +import modernizeClasses from './ToggleSwitch.modernize.module.css' export interface ToggleSwitchProps extends Omit, 'onChange'> { /** The id of the DOM node that labels the switch */ @@ -25,7 +26,7 @@ export interface ToggleSwitchProps extends Omit> = ({size}) => (