Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/thirty-worms-wave.md
Original file line number Diff line number Diff line change
@@ -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.
14 changes: 14 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -551,6 +562,9 @@
"ButtonGroup": [
"./dist/ButtonGroup.d.ts"
],
"SegmentedControl": [
"./dist/SegmentedControl.d.ts"
],
"LinkButton": [
"./dist/LinkButton.d.ts"
],
Expand Down
26 changes: 26 additions & 0 deletions src/SegmentedControl.ts
Original file line number Diff line number Diff line change
@@ -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';
149 changes: 149 additions & 0 deletions src/components/SegmentedControl/SegmentedControl.mdx
Original file line number Diff line number Diff line change
@@ -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';

<Meta of={SegmentedControlStories} />

# 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.

<MetaTable
designSystemTeamVerified={false}
figmaLink="https://www.figma.com/design/gmHnKr3tOzvnYp1FZeIl4t/Stand--Editorial-tool-Design-System?node-id=2740-4774&m=dev"
reactAriaLink="https://react-aria.adobe.com/ToggleButtonGroup"
/>

## 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

<SandboxReact componentName={componentName} componentTsx={componentTsx} />

```tsx
import {
SegmentedControl,
SegmentedControlItem,
} from '@guardian/stand/SegmentedControl';

<SegmentedControl
aria-label="Preview width"
defaultSelectedKey={425}
onSelectionChange={(key) => console.log(key)}
>
<SegmentedControlItem id={320}>320</SegmentedControlItem>
<SegmentedControlItem id={375}>375</SegmentedControlItem>
<SegmentedControlItem id={425}>425</SegmentedControlItem>
<SegmentedControlItem id={650}>650</SegmentedControlItem>
</SegmentedControl>;
```

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

<Canvas layout="padded" of={Default} />

### Controlled

<Canvas layout="padded" of={Controlled} />

### Selected positions

<Canvas layout="padded" of={SelectedPositions} />

## Customisation

### Custom theme

Group token overrides are inherited by all items. Item-level overrides take precedence.

<Canvas layout="padded" of={CustomTheme} />

```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.

<Canvas layout="padded" of={CssOverrides} />

## 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`.
82 changes: 82 additions & 0 deletions src/components/SegmentedControl/SegmentedControl.stories.tsx
Original file line number Diff line number Diff line change
@@ -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) => (
<SegmentedControlItem key={width} id={width}>
{width}
</SegmentedControlItem>
)),
},
} satisfies Meta<typeof SegmentedControl>;

type Story = StoryObj<typeof SegmentedControl>;

export const Default = {} satisfies Story;

export const Controlled = {
render: function ControlledSegmentedControl(args) {
const [selectedKey, setSelectedKey] = useState<Key>(425);
return (
<>
<SegmentedControl
{...args}
selectedKey={selectedKey}
onSelectionChange={setSelectedKey}
/>
<p>Preview width: {selectedKey}px</p>
</>
);
},
} satisfies Story;

export const SelectedPositions = {
render: (args) => (
<div css={css({ display: 'grid', gap: '1rem', justifyItems: 'start' })}>
{widths.map((selected) => (
<SegmentedControl
{...args}
key={selected}
aria-label={`Preview width, ${selected}px selected`}
defaultSelectedKey={selected}
/>
))}
</div>
),
} 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;
66 changes: 66 additions & 0 deletions src/components/SegmentedControl/SegmentedControl.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<ThemeContext.Provider value={mergedTheme}>
<RACToggleButtonGroup
{...props}
selectionMode="single"
orientation="horizontal"
disallowEmptySelection
selectedKeys={selectedKey !== undefined ? [selectedKey] : undefined}
defaultSelectedKeys={
defaultSelectedKey !== undefined ? [defaultSelectedKey] : undefined
}
onSelectionChange={(keys) => {
const [key] = keys;
if (key !== undefined) {
onSelectionChange?.(key);
}
}}
css={[segmentedControlStyles(mergedTheme), cssOverrides]}
/>
</ThemeContext.Provider>
);
}

export function SegmentedControlItem({
theme = {},
cssOverrides,
...props
}: SegmentedControlItemProps) {
const mergedTheme = mergeDeep(useContext(ThemeContext), theme);

return (
<RACToggleButton
{...props}
css={[segmentedControlItemStyles(mergedTheme), cssOverrides]}
/>
);
}
24 changes: 24 additions & 0 deletions src/components/SegmentedControl/sandbox.ts
Original file line number Diff line number Diff line change
@@ -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 (
<>
<SegmentedControl
aria-label="Preview width"
selectedKey={selectedKey}
onSelectionChange={setSelectedKey}
>
{[320, 375, 425, 650].map((width) => (
<SegmentedControlItem key={width} id={width}>{width}</SegmentedControlItem>
))}
</SegmentedControl>
<p>Preview width: {selectedKey}px</p>
</>
);
};
`;
Loading
Loading