Skip to content
Merged
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
1 change: 1 addition & 0 deletions packages/ui/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

### New Features

- Add `SwitchControl` component. ([#83146](https://github.com/WordPress/gutenberg/pull/83146))
- Add `Switch` form primitive ([#83039](https://github.com/WordPress/gutenberg/pull/83039)).
- Add `RadioGroup` form primitive ([#83038](https://github.com/WordPress/gutenberg/pull/83038)).
- Add `CheckboxGroup` form primitive ([#82556](https://github.com/WordPress/gutenberg/pull/82556)).
Expand Down
1 change: 1 addition & 0 deletions packages/ui/src/form/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ export * from './checkbox-control';
export * from './input-control';
export * from './select-control';
export { SearchableChipSelectControl } from './searchable-chip-select-control';
export * from './switch-control';
export * from './textarea-control';
export * from './with-validation';
2 changes: 2 additions & 0 deletions packages/ui/src/form/primitives/switch/switch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import type { SwitchProps } from './types';
* A low-level switch primitive.
*
* Use `Field` to associate an accessible label.
*
* Prefer `SwitchControl` for labeled items.
*/
export const Switch = forwardRef< HTMLSpanElement, SwitchProps >(
function Switch( { className, ...props }, ref ) {
Expand Down
1 change: 1 addition & 0 deletions packages/ui/src/form/switch-control/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { SwitchControl } from './switch-control';
77 changes: 77 additions & 0 deletions packages/ui/src/form/switch-control/stories/index.story.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { SwitchControl } from '../';
import {
WITH_DETAILS_DESCRIPTION,
DETAILS_EXAMPLE,
} from '../../stories/shared';

const meta: Meta< typeof SwitchControl > = {
title: 'Design System/Components/Form/SwitchControl',
component: SwitchControl,
argTypes: {
checked: { control: false },
onCheckedChange: { action: 'onCheckedChange' },
},
parameters: {
componentStatus: {
status: 'use-with-caution',
whereUsed: 'global',
notes: 'Not yet recommended for use alongside components from `@wordpress/components`, pending review of style consistency with `@wordpress/components` and component set completeness. See [WordPress/gutenberg#76135](https://github.com/WordPress/gutenberg/issues/76135).',
},
},
};
export default meta;

type Story = StoryObj< typeof SwitchControl >;

export const Default: Story = {
args: {
label: 'Label',
},
};

export const WithDescription: Story = {
args: {
...Default.args,
description: 'This is the description.',
},
};

export const WithLongLabel: Story = {
args: {
...Default.args,
label: 'This is a long label that should wrap to the next line. This is a long label that should wrap to the next line. This is a long label that should wrap to the next line.',
},
};

export const VisuallyHiddenLabel: Story = {
args: {
...Default.args,
hideLabelFromVision: true,
},
};

export const WithDetails: Story = {
parameters: {
docs: { description: { story: WITH_DETAILS_DESCRIPTION } },
},
args: {
...Default.args,
details: DETAILS_EXAMPLE,
},
};

export const Disabled: Story = {
args: {
...Default.args,
disabled: true,
},
};

export const DisabledChecked: Story = {
args: {
...Default.args,
disabled: true,
defaultChecked: true,
},
};
27 changes: 27 additions & 0 deletions packages/ui/src/form/switch-control/style.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@layer wp-ui {
@layer utilities, components, compositions, overrides;

@layer components {
.root {
--_wp-ui-switch-control-switch-height: var(--wpds-dimension-size-2xs);
--_wp-ui-switch-control-label-line-height: max(var(--_wp-ui-switch-control-switch-height), var(--wpds-typography-line-height-xs));
}

.switch-wrapper {
display: flex;
align-items: center;
/* Size the wrapper to one label line so the switch centers on the first line. */
height: 1lh;
line-height: var(--_wp-ui-switch-control-label-line-height);
overflow: visible;
}

.label {
--wp-ui-field-label-line-height: var(--_wp-ui-switch-control-label-line-height);
}

.root:not(:has(.switch[data-disabled])) .label {
cursor: var(--wpds-cursor-control);
}
}
}
69 changes: 69 additions & 0 deletions packages/ui/src/form/switch-control/switch-control.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import clsx from 'clsx';
import { forwardRef, Fragment } from '@wordpress/element';
import { Field, Switch } from '../primitives';
import { Stack } from '../../stack';
import type { SwitchControlProps } from './types';
import styles from './style.module.css';

const ROOT_RENDER = <Stack gap="sm" align="start" />;

const TextContainer = ( {
isStack,
...restProps
}: {
isStack?: boolean;
} & React.PropsWithChildren ) =>
isStack ? (
<Stack direction="column" gap="xs" { ...restProps } />
) : (
<Fragment { ...restProps } />
);

/**
* A complete switch field with integrated label and description.
*/
export const SwitchControl = forwardRef< HTMLSpanElement, SwitchControlProps >(
function SwitchControl(
{
label,
description,
details,
hideLabelFromVision,
className,
name,
...switchProps
},
ref
) {
const hasSupportingText = !! description || !! details;

return (
<Field.Root
name={ name }
className={ clsx( styles.root, className ) }
render={ ROOT_RENDER }
>
<div className={ styles[ 'switch-wrapper' ] }>
<Switch
ref={ ref }
className={ styles.switch }
{ ...switchProps }
/>
</div>
<TextContainer isStack={ hasSupportingText }>
<Field.Label
variant="plain"
hideFromVision={ hideLabelFromVision }
className={ styles.label }
>
{ label }
</Field.Label>
{ description && (
<Field.Description>{ description }</Field.Description>
) }
{ details && <Field.Details>{ details }</Field.Details> }
</TextContainer>
</Field.Root>
);
}
);
174 changes: 174 additions & 0 deletions packages/ui/src/form/switch-control/test/index.jsdom.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createRef } from '@wordpress/element';
import { describe, expect, it, vi } from 'vitest';
import { SwitchControl } from '../index';

globalThis.wpVitest.mockPointerEvent();

describe( 'SwitchControl', () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just noticed no tests for the disabled state here, but I checked other form components don't have them either.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, I'm trying not to overtest things where there should be sufficient test coverage upstream in Base UI, and where we have no integration risks.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup, seems fine

it( 'forwards ref', () => {
const ref = createRef< HTMLSpanElement >();

render( <SwitchControl ref={ ref } label="Enable updates" /> );

expect( ref.current ).toBeInstanceOf( HTMLSpanElement );
} );

it( 'renders with a visible label', () => {
render( <SwitchControl label="Enable updates" /> );

expect(
screen.getByRole( 'switch', { name: 'Enable updates' } )
).toBeVisible();
expect( screen.getByText( 'Enable updates' ) ).toBeVisible();
} );

it( 'renders with a visually hidden label', () => {
render( <SwitchControl label="Enable updates" hideLabelFromVision /> );

expect(
screen.getByRole( 'switch', { name: 'Enable updates' } )
).toBeVisible();
} );

it( 'renders accessible label and description', () => {
render(
<SwitchControl
label="Enable updates"
description="Receive email updates"
/>
);

expect(
screen.getByRole( 'switch', {
name: 'Enable updates',
description: 'Receive email updates',
} )
).toBeVisible();
} );

it( 'renders with details', () => {
render(
<SwitchControl
label="Terms"
details={
<span>
Read the <a href="#terms">terms</a>
</span>
}
/>
);

expect( screen.getByText( /Read the/ ) ).toBeVisible();
} );

it( 'toggles when the label is clicked', async () => {
const user = userEvent.setup();

render( <SwitchControl label="Enable updates" /> );

const control = screen.getByRole( 'switch', {
name: 'Enable updates',
} );
expect( control ).not.toBeChecked();

await user.click( screen.getByText( 'Enable updates' ) );

expect( control ).toBeChecked();
} );

describe( 'Form data behavior', () => {
it( 'submits correct form data when checked with custom name and value', async () => {
const user = userEvent.setup();
const handleSubmit = vi.fn( ( event ) => {
event.preventDefault();
return new FormData( event.currentTarget );
} );

render(
<form onSubmit={ handleSubmit }>
<SwitchControl
label="Enable notifications"
name="notifications"
value="yes"
/>
<button type="submit">Submit</button>
</form>
);

const control = screen.getByRole( 'switch', {
name: 'Enable notifications',
} );
const submitButton = screen.getByRole( 'button', {
name: 'Submit',
} );

await user.click( control );
expect( control ).toBeChecked();

await user.click( submitButton );

const formData = handleSubmit.mock.results[ 0 ].value;
expect( formData.get( 'notifications' ) ).toBe( 'yes' );
} );

it( 'does not include an unchecked switch in form data', async () => {
const user = userEvent.setup();
const handleSubmit = vi.fn( ( event ) => {
event.preventDefault();
return new FormData( event.currentTarget );
} );

render(
<form onSubmit={ handleSubmit }>
<SwitchControl
label="Enable notifications"
name="notifications"
value="yes"
/>
<button type="submit">Submit</button>
</form>
);

const submitButton = screen.getByRole( 'button', {
name: 'Submit',
} );

await user.click( submitButton );

const formData = handleSubmit.mock.results[ 0 ].value;
expect( formData.get( 'notifications' ) ).toBeNull();
} );

it( 'uses "on" as default value when no value prop is provided', async () => {
const user = userEvent.setup();
const handleSubmit = vi.fn( ( event ) => {
event.preventDefault();
return new FormData( event.currentTarget );
} );

render(
<form onSubmit={ handleSubmit }>
<SwitchControl label="Enable feature" name="feature" />
<button type="submit">Submit</button>
</form>
);

const control = screen.getByRole( 'switch', {
name: 'Enable feature',
} );
const submitButton = screen.getByRole( 'button', {
name: 'Submit',
} );

await user.click( control );
expect( control ).toBeChecked();

await user.click( submitButton );

const formData = handleSubmit.mock.results[ 0 ].value;
expect( formData.get( 'feature' ) ).toBe( 'on' );
} );
} );
} );
5 changes: 5 additions & 0 deletions packages/ui/src/form/switch-control/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { Switch } from '../primitives';
import type { ControlProps } from '../types';

export type SwitchControlProps = React.ComponentProps< typeof Switch > &
ControlProps;
Loading