diff --git a/.changeset/thirty-worms-wave.md b/.changeset/thirty-worms-wave.md new file mode 100644 index 00000000..8dedc0b3 --- /dev/null +++ b/.changeset/thirty-worms-wave.md @@ -0,0 +1,5 @@ +--- +'@guardian/stand': minor +--- + +Add SegmentedControl and SegmentedControlItem (`@guardian/stand/SegmentedControl`), a connected single-selection control built on React Aria. Selection uses a single item key via `selectedKey`, `defaultSelectedKey` and `onSelectionChange`. Only the Small / Condensed text variant is currently supported. diff --git a/package.json b/package.json index 97f920e8..a0488c20 100644 --- a/package.json +++ b/package.json @@ -78,6 +78,16 @@ "default": "./dist/Button.cjs" } }, + "./SegmentedControl": { + "import": { + "types": "./dist/SegmentedControl.d.ts", + "default": "./dist/SegmentedControl.js" + }, + "require": { + "types": "./dist/SegmentedControl.d.cts", + "default": "./dist/SegmentedControl.cjs" + } + }, "./ButtonGroup": { "import": { "types": "./dist/ButtonGroup.d.ts", @@ -495,6 +505,7 @@ "./component/pagination.css": "./dist/styleD/build/css/component/pagination.css", "./component/button.css": "./dist/styleD/build/css/component/button.css", "./component/buttonGroup.css": "./dist/styleD/build/css/component/buttonGroup.css", + "./component/segmentedControl.css": "./dist/styleD/build/css/component/segmentedControl.css", "./component/typography.css": "./dist/styleD/build/css/component/typography.css", "./component/icon.css": "./dist/styleD/build/css/component/icon.css", "./component/favicon.css": "./dist/styleD/build/css/component/favicon.css", @@ -551,6 +562,9 @@ "ButtonGroup": [ "./dist/ButtonGroup.d.ts" ], + "SegmentedControl": [ + "./dist/SegmentedControl.d.ts" + ], "LinkButton": [ "./dist/LinkButton.d.ts" ], diff --git a/src/SegmentedControl.ts b/src/SegmentedControl.ts new file mode 100644 index 00000000..8c677242 --- /dev/null +++ b/src/SegmentedControl.ts @@ -0,0 +1,26 @@ +/** + * SegmentedControl component entry point + * + * Peer dependencies required to use these components: + * - `@emotion/react` + * - `react` + * - `react-dom` + * - `react-aria-components` + * - `typescript` + * + * See the `peerDependencies` section of package.json for compatible versions. + * + * If you only need the built CSS (./component/segmentedControl.css), + * you don't need to install these. + */ +export { + SegmentedControl, + SegmentedControlItem, +} from './components/SegmentedControl/SegmentedControl'; +export type { + SegmentedControlProps, + SegmentedControlItemProps, +} from './components/SegmentedControl/types'; +export type { PartialSegmentedControlTheme as SegmentedControlTheme } from './components/SegmentedControl/styles'; +export { componentSegmentedControl } from './styleD/build/typescript/component/segmentedControl'; +export type { ComponentSegmentedControl } from './styleD/build/typescript/component/segmentedControl'; diff --git a/src/components/SegmentedControl/SegmentedControl.mdx b/src/components/SegmentedControl/SegmentedControl.mdx new file mode 100644 index 00000000..f688490c --- /dev/null +++ b/src/components/SegmentedControl/SegmentedControl.mdx @@ -0,0 +1,149 @@ +import { Meta, Canvas } from '@storybook/addon-docs/blocks'; +import { MetaTable } from '../../util/storybook/MetaTable'; +import SegmentedControlStories, { + Default, + Controlled, + SelectedPositions, + CustomTheme, + CssOverrides, +} from './SegmentedControl.stories'; +import { SandboxReact } from '../../util/storybook/sandbox/Sandbox'; +import { componentName, componentTsx } from './sandbox'; + + + +# SegmentedControl + +A connected, horizontal set of options where exactly one is selected, built on [React Aria ToggleButtonGroup and ToggleButton](https://react-aria.adobe.com/ToggleButtonGroup). +The API follows [React Spectrum's SegmentedControl](https://react-spectrum.adobe.com/SegmentedControl): selection is a single item `id`, and once an item is selected it cannot be cleared. + +Currently only Figma's Small / Condensed text variant is implemented: 32px-high segments with 12px Open Sans Compact labels. +XSmall, default font width and icon variants are not yet supported. + + + +## When to use + +- To switch between a small number of related options, such as preview widths or time periods. +- Use Tabs instead when each choice opens an associated content panel, or RadioGroup for a radio-style form field. + +## Peer dependencies + +- `@emotion/react` +- `react` +- `react-dom` +- `react-aria-components` +- `typescript` + +See the `peerDependencies` section of `package.json` for compatible versions. +CSS-only consumers do not need these peers. + +Load Open Sans using the [Getting Started font guidance](?path=/docs/getting-started--docs). + +## Example usage + + + +```tsx +import { + SegmentedControl, + SegmentedControlItem, +} from '@guardian/stand/SegmentedControl'; + + console.log(key)} +> + 320 + 375 + 425 + 650 +; +``` + +Supply an accessible group name using `aria-label`, or `aria-labelledby` pointing to a visible label. +Each `SegmentedControlItem` needs a unique string or number `id`. + +## Props + +| Name | Type | Required | Default | Description | +| -------------------------------- | ------------------------------------------ | ----------- | ------- | ----------------------------------------------------------- | +| `aria-label` / `aria-labelledby` | `string` | Conditional | N/A | Provide one to name the group. | +| `children` | `ReactNode` | Yes | N/A | `SegmentedControlItem` items, optionally inside a fragment. | +| `selectedKey` | `Key` | No | N/A | The `id` of the selected item (controlled). | +| `defaultSelectedKey` | `Key` | No | N/A | The `id` of the initially selected item (uncontrolled). | +| `onSelectionChange` | `(key: Key) => void` | No | N/A | Called with the `id` of the newly selected item. | +| `theme` | `SegmentedControlTheme` | No | N/A | Token overrides inherited by items. | +| `cssOverrides` | `SerializedStyles` or `SerializedStyles[]` | No | N/A | Styles applied to the group. | +| `className` | `string` or render function | No | N/A | Class name applied to the group. | + +Other props follow the [React Aria ToggleButtonGroup API](https://react-aria.adobe.com/ToggleButtonGroup#api). +The group uses React Aria's single-selection semantics: a `radiogroup` of `radio` buttons. +Arrow keys move focus between items; Space or Enter selects the focused item. + +### SegmentedControlItem props + +| Name | Type | Required | Default | Description | +| -------------- | ------------------------------------------ | -------- | ------- | ----------------------------------------------- | +| `id` | `string` or `number` | Yes | N/A | Selection identifier within the group. | +| `children` | `ReactNode` | Yes | N/A | Visible label. | +| `theme` | `SegmentedControlTheme` | No | N/A | Overrides inherited group tokens for this item. | +| `cssOverrides` | `SerializedStyles` or `SerializedStyles[]` | No | N/A | Styles applied to this item. | +| `className` | `string` or render function | No | N/A | Class name applied to this item. | + +Other props follow the [React Aria ToggleButton API](https://react-aria.adobe.com/ToggleButton#api). + +## Stories + +### Default + + + +### Controlled + + + +### Selected positions + + + +## Customisation + +### Custom theme + +Group token overrides are inherited by all items. Item-level overrides take precedence. + + + +```tsx +import { semanticColors } from '@guardian/stand'; +import type { SegmentedControlTheme } from '@guardian/stand/SegmentedControl'; + +const theme: SegmentedControlTheme = { + item: { + selected: { + backgroundColor: semanticColors.fill.greenWeak, + borderColor: semanticColors.border.success, + color: semanticColors.text.green, + }, + }, +}; +``` + +### CSS overrides + +This example fills the available width and gives each segment equal space. + + + +## Custom Component Build + +Due to its interactive behaviour (single selection, keyboard navigation and accessibility semantics), SegmentedControl is only available as a React component with Emotion for styling. + +If you need a segmented control outside React, you would need to build your own and replicate React Aria's behaviour. +The design tokens are available as CSS variables from `@guardian/stand/component/segmentedControl.css`, and as `componentSegmentedControl` from `@guardian/stand/SegmentedControl` or `@guardian/stand`. diff --git a/src/components/SegmentedControl/SegmentedControl.stories.tsx b/src/components/SegmentedControl/SegmentedControl.stories.tsx new file mode 100644 index 00000000..61e7534b --- /dev/null +++ b/src/components/SegmentedControl/SegmentedControl.stories.tsx @@ -0,0 +1,82 @@ +import { css } from '@emotion/react'; +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { useState } from 'react'; +import type { Key } from 'react-aria-components'; +import { semanticColors } from '../../styleD/build/typescript/semantic/colors'; +import { SegmentedControl, SegmentedControlItem } from './SegmentedControl'; + +const widths = [320, 375, 425, 650]; + +const meta = { + title: 'Stand/Tools Design System/Components/SegmentedControl', + component: SegmentedControl, + args: { + 'aria-label': 'Preview width', + defaultSelectedKey: 425, + children: widths.map((width) => ( + + {width} + + )), + }, +} satisfies Meta; + +type Story = StoryObj; + +export const Default = {} satisfies Story; + +export const Controlled = { + render: function ControlledSegmentedControl(args) { + const [selectedKey, setSelectedKey] = useState(425); + return ( + <> + +

Preview width: {selectedKey}px

+ + ); + }, +} satisfies Story; + +export const SelectedPositions = { + render: (args) => ( +
+ {widths.map((selected) => ( + + ))} +
+ ), +} satisfies Story; + +export const CustomTheme = { + args: { + theme: { + item: { + selected: { + backgroundColor: semanticColors.fill.greenWeak, + borderColor: semanticColors.border.success, + color: semanticColors.text.green, + }, + }, + }, + }, +} satisfies Story; + +export const CssOverrides = { + args: { + cssOverrides: css({ + width: '100%', + '> button': { flex: 1 }, + }), + }, +} satisfies Story; + +export default meta; diff --git a/src/components/SegmentedControl/SegmentedControl.tsx b/src/components/SegmentedControl/SegmentedControl.tsx new file mode 100644 index 00000000..7680fb53 --- /dev/null +++ b/src/components/SegmentedControl/SegmentedControl.tsx @@ -0,0 +1,66 @@ +import { createContext, useContext } from 'react'; +import { + ToggleButton as RACToggleButton, + ToggleButtonGroup as RACToggleButtonGroup, +} from 'react-aria-components'; +import { mergeDeep } from '../../util/mergeDeep'; +import { + defaultSegmentedControlTheme, + segmentedControlItemStyles, + segmentedControlStyles, +} from './styles'; +import type { SegmentedControlTheme } from './styles'; +import type { SegmentedControlItemProps, SegmentedControlProps } from './types'; + +const ThemeContext = createContext(defaultSegmentedControlTheme); + +export function SegmentedControl({ + theme = {}, + cssOverrides, + selectedKey, + defaultSelectedKey, + onSelectionChange, + ...props +}: SegmentedControlProps) { + const mergedTheme: SegmentedControlTheme = mergeDeep( + defaultSegmentedControlTheme, + theme, + ); + + return ( + + { + const [key] = keys; + if (key !== undefined) { + onSelectionChange?.(key); + } + }} + css={[segmentedControlStyles(mergedTheme), cssOverrides]} + /> + + ); +} + +export function SegmentedControlItem({ + theme = {}, + cssOverrides, + ...props +}: SegmentedControlItemProps) { + const mergedTheme = mergeDeep(useContext(ThemeContext), theme); + + return ( + + ); +} diff --git a/src/components/SegmentedControl/sandbox.ts b/src/components/SegmentedControl/sandbox.ts new file mode 100644 index 00000000..d0fb2b0e --- /dev/null +++ b/src/components/SegmentedControl/sandbox.ts @@ -0,0 +1,24 @@ +export const componentName = 'SegmentedControl'; + +export const componentTsx = /* javascript */ `import { useState } from 'react'; +import { SegmentedControl, SegmentedControlItem } from '@guardian/stand/SegmentedControl'; + +export const Component = () => { + const [selectedKey, setSelectedKey] = useState(425); + + return ( + <> + + {[320, 375, 425, 650].map((width) => ( + {width} + ))} + +

Preview width: {selectedKey}px

+ + ); +}; +`; diff --git a/src/components/SegmentedControl/styles.ts b/src/components/SegmentedControl/styles.ts new file mode 100644 index 00000000..71f3d271 --- /dev/null +++ b/src/components/SegmentedControl/styles.ts @@ -0,0 +1,114 @@ +import type { SerializedStyles } from '@emotion/react'; +import { css } from '@emotion/react'; +import { + componentSegmentedControl, + type ComponentSegmentedControl, +} from '../../styleD/build/typescript/component/segmentedControl'; +import { convertTypographyToEmotionStringStyle } from '../../styleD/utils/semantic/typography'; +import type { DeepPartial, Prettify } from '../../util/types'; + +export type SegmentedControlTheme = Prettify; +export type PartialSegmentedControlTheme = Prettify< + DeepPartial +>; +export const defaultSegmentedControlTheme: SegmentedControlTheme = + componentSegmentedControl; + +export const segmentedControlStyles = ( + theme: SegmentedControlTheme, +): SerializedStyles => css` + display: inline-flex; + align-items: stretch; + border-radius: ${theme.group.borderRadius}; + background-color: ${theme.group.backgroundColor}; +`; + +export const segmentedControlItemStyles = ( + theme: SegmentedControlTheme, +): SerializedStyles => css` + appearance: none; + box-sizing: border-box; + display: inline-flex; + align-items: center; + justify-content: center; + position: relative; + margin: 0; + height: ${theme.item.height}; + padding: 0 calc(${theme.item.paddingInline} - ${theme.item.borderWidth}); + border: ${theme.item.borderWidth} solid ${theme.item.borderColor}; + border-inline-color: transparent; + border-radius: 0; + background-color: ${theme.group.backgroundColor}; + color: ${theme.item.color}; + ${convertTypographyToEmotionStringStyle(theme.item.typography)} + line-height: ${theme.item.lineHeight}; + white-space: nowrap; + cursor: pointer; + + &:first-child { + border-inline-start-color: ${theme.item.borderColor}; + border-start-start-radius: ${theme.group.borderRadius}; + border-end-start-radius: ${theme.group.borderRadius}; + } + + &:last-child { + border-inline-end-color: ${theme.item.borderColor}; + border-start-end-radius: ${theme.group.borderRadius}; + border-end-end-radius: ${theme.group.borderRadius}; + } + + &:not(:last-child)::after { + content: ''; + position: absolute; + inset-block: calc(${theme.item.separatorInset} - ${theme.item.borderWidth}); + inset-inline-end: 0; + border-inline-end: ${theme.item.borderWidth} solid ${theme.item.borderColor}; + pointer-events: none; + } + + &[data-selected]::after, + &:has(+ [data-selected])::after { + display: none; + } + + &[data-hovered] { + background-color: ${theme.item.hover.backgroundColor}; + } + + &[data-pressed] { + background-color: ${theme.item.pressed.backgroundColor}; + } + + &[data-selected] { + z-index: 1; + background-color: ${theme.item.selected.backgroundColor}; + border-color: ${theme.item.selected.borderColor}; + color: ${theme.item.selected.color}; + } + + &[data-selected][data-hovered] { + background-color: ${theme.item.selected.hover.backgroundColor}; + } + + &[data-selected][data-pressed] { + background-color: ${theme.item.selected.pressed.backgroundColor}; + } + + &[data-focus-visible] { + z-index: 2; + outline: ${theme.item.focusVisible.outlineWidth} solid + ${theme.item.focusVisible.outlineColor}; + outline-offset: ${theme.item.focusVisible.outlineOffset}; + } + + @media (forced-colors: active) { + &[data-selected] { + border-color: Highlight; + color: Highlight; + } + + &[data-focus-visible] { + outline-color: Highlight; + } + } +`; diff --git a/src/components/SegmentedControl/types.ts b/src/components/SegmentedControl/types.ts new file mode 100644 index 00000000..1d543211 --- /dev/null +++ b/src/components/SegmentedControl/types.ts @@ -0,0 +1,39 @@ +import type { + Key, + ToggleButtonGroupProps as RACToggleButtonGroupProps, + ToggleButtonProps as RACToggleButtonProps, +} from 'react-aria-components'; +import type { DefaultProps } from '../../util/types'; +import type { SegmentedControlTheme } from './styles'; + +export interface SegmentedControlProps + extends + DefaultProps, + Omit< + RACToggleButtonGroupProps, + | 'selectionMode' + | 'orientation' + | 'selectedKeys' + | 'defaultSelectedKeys' + | 'onSelectionChange' + | 'disallowEmptySelection' + | 'isDisabled' + > { + /** The id of the selected item (controlled). */ + selectedKey?: Key; + /** The id of the initially selected item (uncontrolled). */ + defaultSelectedKey?: Key; + /** Called with the id of the newly selected item. */ + onSelectionChange?: (key: Key) => void; +} + +export interface SegmentedControlItemProps + extends + DefaultProps, + Omit< + RACToggleButtonProps, + 'id' | 'isSelected' | 'defaultSelected' | 'onChange' | 'isDisabled' + > { + /** Identifier matched by the group's selectedKey or defaultSelectedKey. */ + id: Key; +} diff --git a/src/index.ts b/src/index.ts index 4a4a806e..d43ab105 100644 --- a/src/index.ts +++ b/src/index.ts @@ -34,6 +34,8 @@ export { componentButton } from './styleD/build/typescript/component/button'; export type { ComponentButton } from './styleD/build/typescript/component/button'; export { componentButtonGroup } from './styleD/build/typescript/component/buttonGroup'; export type { ComponentButtonGroup } from './styleD/build/typescript/component/buttonGroup'; +export { componentSegmentedControl } from './styleD/build/typescript/component/segmentedControl'; +export type { ComponentSegmentedControl } from './styleD/build/typescript/component/segmentedControl'; export { componentCheckbox } from './styleD/build/typescript/component/checkbox'; export type { ComponentCheckbox } from './styleD/build/typescript/component/checkbox'; export { componentToggleSwitch } from './styleD/build/typescript/component/toggleSwitch'; diff --git a/src/styleD/build/css/component/segmentedControl.css b/src/styleD/build/css/component/segmentedControl.css new file mode 100644 index 00000000..2bc59bea --- /dev/null +++ b/src/styleD/build/css/component/segmentedControl.css @@ -0,0 +1,29 @@ +/** + * Do not edit directly, this file was auto-generated. + */ + +:root { + --component-segmented-control-group-background-color: #ededed; + --component-segmented-control-group-border-radius: 0.25rem; + --component-segmented-control-item-height: 2rem; + --component-segmented-control-item-padding-inline: 0.75rem; + --component-segmented-control-item-separator-inset: 0.25rem; + --component-segmented-control-item-border-width: 0.0625rem; + --component-segmented-control-item-border-color: #cccccc; + --component-segmented-control-item-color: #545454; + --component-segmented-control-item-line-height: 1; + --component-segmented-control-item-typography-font: normal 460 0.75rem/1.3 + 'Open Sans'; + --component-segmented-control-item-typography-font-width: 88; + --component-segmented-control-item-typography-letter-spacing: 0rem; + --component-segmented-control-item-hover-background-color: #c5dfec; + --component-segmented-control-item-pressed-background-color: #8abed7; + --component-segmented-control-item-selected-background-color: #c5dfec; + --component-segmented-control-item-selected-border-color: #0072a9; + --component-segmented-control-item-selected-color: #000000; + --component-segmented-control-item-selected-hover-background-color: #8abed7; + --component-segmented-control-item-selected-pressed-background-color: #5ca5c8; + --component-segmented-control-item-focus-visible-outline-width: 0.125rem; + --component-segmented-control-item-focus-visible-outline-color: #0072a9; + --component-segmented-control-item-focus-visible-outline-offset: 0.125rem; +} diff --git a/src/styleD/build/typescript/component/segmentedControl.ts b/src/styleD/build/typescript/component/segmentedControl.ts new file mode 100644 index 00000000..759af824 --- /dev/null +++ b/src/styleD/build/typescript/component/segmentedControl.ts @@ -0,0 +1,47 @@ +/** + * Do not edit directly, this file was auto-generated. + */ + +export const componentSegmentedControl = { + group: { + backgroundColor: '#ededed', + borderRadius: '0.25rem', + }, + item: { + height: '2rem', + paddingInline: '0.75rem', + separatorInset: '0.25rem', + borderWidth: '0.0625rem', + borderColor: '#cccccc', + color: '#545454', + lineHeight: 1, + typography: { + font: 'normal 460 0.75rem/1.3 Open Sans', + fontWidth: 88, + letterSpacing: '0rem', + }, + hover: { + backgroundColor: '#c5dfec', + }, + pressed: { + backgroundColor: '#8abed7', + }, + selected: { + backgroundColor: '#c5dfec', + borderColor: '#0072a9', + color: '#000000', + hover: { + backgroundColor: '#8abed7', + }, + pressed: { + backgroundColor: '#5ca5c8', + }, + }, + focusVisible: { + outlineWidth: '0.125rem', + outlineColor: '#0072a9', + outlineOffset: '0.125rem', + }, + }, +}; +export type ComponentSegmentedControl = typeof componentSegmentedControl; diff --git a/src/styleD/tokens/component/segmentedControl.json b/src/styleD/tokens/component/segmentedControl.json new file mode 100644 index 00000000..d77c405a --- /dev/null +++ b/src/styleD/tokens/component/segmentedControl.json @@ -0,0 +1,112 @@ +{ + "component": { + "segmentedControl": { + "group": { + "backgroundColor": { + "$type": "color", + "$value": "{semantic.colors.fill.neutralWeak}" + }, + "borderRadius": { + "$type": "dimension", + "$value": "{semantic.radius.cornerSm}" + } + }, + "item": { + "height": { + "$type": "dimension", + "$value": "{semantic.sizing.height.sm}" + }, + "paddingInline": { + "$type": "dimension", + "$value": "{semantic.spacing.stackSm}" + }, + "separatorInset": { + "$type": "dimension", + "$value": "{semantic.spacing.stackXxs}" + }, + "borderWidth": { + "$type": "dimension", + "$value": "{semantic.sizing.border.default}" + }, + "borderColor": { + "$type": "color", + "$value": "{semantic.colors.border.weak}" + }, + "color": { + "$type": "color", + "$value": "{semantic.colors.text.weak}" + }, + "lineHeight": { + "$type": "number", + "$value": 1 + }, + "typography": { + "font": { + "$type": "typography", + "$value": "{semantic.typography.bodyCompactXs.font}" + }, + "fontWidth": { + "$type": "number", + "$value": "{semantic.typography.bodyCompactXs.fontWidth}" + }, + "letterSpacing": { + "$type": "dimension", + "$value": "{semantic.typography.bodyCompactXs.letterSpacing}" + } + }, + "hover": { + "backgroundColor": { + "$type": "color", + "$value": "{semantic.colors.fill.unselectedHoverWeak}" + } + }, + "pressed": { + "backgroundColor": { + "$type": "color", + "$value": "{semantic.colors.fill.unselectedPressedWeak}" + } + }, + "selected": { + "backgroundColor": { + "$type": "color", + "$value": "{semantic.colors.fill.selectedWeak}" + }, + "borderColor": { + "$type": "color", + "$value": "{semantic.colors.border.selected}" + }, + "color": { + "$type": "color", + "$value": "{semantic.colors.text.strong}" + }, + "hover": { + "backgroundColor": { + "$type": "color", + "$value": "{semantic.colors.fill.selectedHoverWeak}" + } + }, + "pressed": { + "backgroundColor": { + "$type": "color", + "$value": "{semantic.colors.fill.selectedPressedWeak}" + } + } + }, + "focusVisible": { + "outlineWidth": { + "$type": "dimension", + "$value": "{semantic.sizing.border.md}" + }, + "outlineColor": { + "$type": "color", + "$value": "{semantic.colors.border.focused}" + }, + "outlineOffset": { + "$type": "dimension", + "$value": "{semantic.sizing.border.md}" + } + } + } + } + } +}