Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Components]: Add SegmentedControl #31937

Merged
merged 30 commits into from
Jul 14, 2021
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
dcacf9f
temp commit
ntsekouras May 18, 2021
5fceebe
follow up
ntsekouras Jun 10, 2021
cac3d00
add/fix types
ntsekouras Jun 17, 2021
26d056a
remove duplicate ref in tsconfig
ntsekouras Jun 17, 2021
5669930
Add the test snapshots
ntsekouras Jun 17, 2021
6db5fa6
fix story
ntsekouras Jun 17, 2021
e227c1f
tweak styles - need fixes
ntsekouras Jun 17, 2021
22622d9
demo usage in PostFeaturedImage for styling fixes
ntsekouras Jun 17, 2021
bd04f01
remove `size` prop
ntsekouras Jun 17, 2021
76f04aa
Polish.
jasmussen Jun 17, 2021
1ed460a
tweak some types and README
ntsekouras Jun 17, 2021
375e2cd
update tests
ntsekouras Jun 17, 2021
865f405
Fix sliding.
jasmussen Jun 18, 2021
f29de11
refactor to not use `important`
ntsekouras Jun 18, 2021
bfd4125
rebase and small changes from feedback
ntsekouras Jul 7, 2021
d99905d
update snapshots as `CONTROL_HEIGHT` has changed to 36px
ntsekouras Jul 7, 2021
7d6a327
remove control for demo purposes
ntsekouras Jul 8, 2021
2abdf75
Update packages/components/src/segmented-control/README.md
ntsekouras Jul 8, 2021
c6e80fb
Fix storybook active icon color
ntsekouras Jul 8, 2021
bcfd9cd
add + update tests
ntsekouras Jul 8, 2021
050a08a
try new approach
ntsekouras Jul 8, 2021
80a4063
update tests
ntsekouras Jul 13, 2021
904153e
update storybook and readme
ntsekouras Jul 13, 2021
660e9b5
remove demo code
ntsekouras Jul 13, 2021
5f68a23
add focus style to control
ntsekouras Jul 13, 2021
db60768
address feedback part 1
ntsekouras Jul 13, 2021
c635735
address feedback part 2
ntsekouras Jul 13, 2021
5a6e6e3
export SegmentedControlOption
ntsekouras Jul 14, 2021
1c157f6
add id to button props
ntsekouras Jul 14, 2021
6046e1a
create string id
ntsekouras Jul 14, 2021
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
6 changes: 6 additions & 0 deletions docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -1151,6 +1151,12 @@
"markdown_source": "../packages/components/src/search-control/README.md",
"parent": "components"
},
{
"title": "SegmentedControl",
"slug": "segmented-control",
"markdown_source": "../packages/components/src/segmented-control/README.md",
"parent": "components"
},
{
"title": "SelectControl",
"slug": "select-control",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ exports[`base field should render correctly 1`] = `
.emotion-0:focus,
.emotion-0[data-focused='true'] {
border-color: var( --wp-admin-theme-color, #00669b);
box-shadow: 0 0 0,0.5px,[object Object];
box-shadow: 0 0 0,0.5px,var( --wp-admin-theme-color, #00669b);
}

<div
Expand Down
1 change: 1 addition & 0 deletions packages/components/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export { default as ResizableBox } from './resizable-box';
export { default as ResponsiveWrapper } from './responsive-wrapper';
export { default as SandBox } from './sandbox';
export { default as SearchControl } from './search-control';
export { SegmentedControl as __experimentalSegmentedControl } from './segmented-control';
export { default as SelectControl } from './select-control';
export { default as Snackbar } from './snackbar';
export { default as SnackbarList } from './snackbar/list';
Expand Down
71 changes: 71 additions & 0 deletions packages/components/src/segmented-control/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# SegementedControl

<div class="callout callout-alert">
This feature is still experimental. “Experimental” means this is an early implementation subject to drastic and breaking changes.
</div>

`SegementedControl` is a form component that lets users choose options represented in horizontal segments. To render options for this control use `SegmentedControl.Option` component.

## Usage

```js
import { __experimentalSegmentedControl as SegmentedControl } from '@wordpress/components';

function Example() {
return (
<SegmentedControl
label="my label"
value="vertical"
isBlock
>
<SegmentedControl.Option value="horizontal" label="horizontal" />
<SegmentedControl.Option value="vertical" label="vertical" />
</SegmentedControl>
);
}
```

## Props

### `label`

- Type: `string`

Label for the form element.

### `baseId`

- Type: `string`
- Required: No

ID that will serve as a base for all the items IDs.

### `isAdaptiveWidth`

- Type: `boolean`
- Required: No
- Default: `false`

Determines if segments should be rendered with equal widths.

### `isBlock`

- Type: `boolean`
- Required: No
- Default: `false`

Renders `SegmentedControl` as a (CSS) block element.

### `onChange`

- Type: `boolean`
- Required: No
- Default: `false`

Callback when a segment is selected.

### `value`

- Type: `string | number`

The value of the `SegmentedControl`.
112 changes: 112 additions & 0 deletions packages/components/src/segmented-control/component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
import { cx } from '@emotion/css';
// eslint-disable-next-line no-restricted-imports
import { RadioGroup, useRadioState } from 'reakit';
import useResizeAware from 'react-resize-aware';

/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useRef, useMemo } from '@wordpress/element';
import { useMergeRefs } from '@wordpress/compose';

/**
* Internal dependencies
*/
import {
contextConnect,
useContextSystem,
PolymorphicComponentProps,
} from '../ui/context';
import { View } from '../view';
import * as styles from './styles';
import { useUpdateEffect } from '../utils/hooks';
import Backdrop from './segmented-control-backdrop';
import Option from './segmented-control-option';
import type { SegmentedControlProps } from './types';
import RadioContext from './radio-context';

const noop = () => {};

function SegmentedControl(
props: PolymorphicComponentProps< SegmentedControlProps, 'input' >,
forwardedRef: import('react').Ref< any >
) {
const {
className,
baseId,
isAdaptiveWidth = false,
isBlock = false,
id,
label,
onChange = noop,
value,
children,
...otherProps
} = useContextSystem( props, 'SegmentedControl' );

const containerRef = useRef();
const [ resizeListener, sizes ] = useResizeAware();

const radio = useRadioState( {
baseId: baseId || id,
state: value,
} );

// Propagate radio.state change
useUpdateEffect( () => {
onChange( radio.state );
}, [ radio.state ] );

// Sync incoming value with radio.state
useUpdateEffect( () => {
if ( value !== radio.state ) {
radio.setState( value );
}
}, [ value ] );

const classes = useMemo(
() =>
cx(
styles.SegmentedControl,
isBlock && styles.block,
'medium',
className
),
[ className ]
);
return (
<RadioContext.Provider
value={ { ...radio, isBlock: ! isAdaptiveWidth } }
>
<RadioGroup
{ ...radio }
aria-label={ label }
as={ View }
className={ classes }
{ ...otherProps }
ref={ useMergeRefs( [ containerRef, forwardedRef ] ) }
>
{ resizeListener }
<Backdrop
{ ...radio }
containerRef={ containerRef }
containerWidth={ sizes.width }
/>
{ children }
</RadioGroup>
</RadioContext.Provider>
);
}

const ConnectedSegmentedControl: any = contextConnect(
SegmentedControl,
'SegmentedControl'
);
ConnectedSegmentedControl.Option = Option;

export default ConnectedSegmentedControl;
1 change: 1 addition & 0 deletions packages/components/src/segmented-control/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as SegmentedControl } from './component';
13 changes: 13 additions & 0 deletions packages/components/src/segmented-control/radio-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* WordPress dependencies
*/
import { createContext } from '@wordpress/element';

/**
* Internal dependencies
*/
import type { SegmentedControlRadioState } from './types';

const RadioContext = createContext( {} as SegmentedControlRadioState );

export default RadioContext;
ntsekouras marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* WordPress dependencies
*/
import { useState, useEffect, memo } from '@wordpress/element';

/**
* Internal dependencies
*/
import type { SegmentedControlBackdropProps } from './types';
import { BackdropView } from './styles';

function SegmentedControlBackdrop( {
containerRef,
containerWidth,
state,
}: SegmentedControlBackdropProps ) {
const [ left, setLeft ] = useState( 0 );
const [ width, setWidth ] = useState( 0 );
const [ canAnimate, setCanAnimate ] = useState( false );

useEffect( () => {
const containerNode = containerRef?.current;
if ( ! containerNode ) return;

/**
* Workaround for Reakit
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe we should add some details here for future reference? @diegohaz do you know any additional information about this workaround?

Copy link
Member

Choose a reason for hiding this comment

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

It's not clear to me what this workaround is solving either. 🤔

*/
const targetNode = containerNode.querySelector(
`[data-value="${ state }"]`
);
if ( ! targetNode ) return;

const { x: parentX } = containerNode.getBoundingClientRect();
const { width: offsetWidth, x } = targetNode.getBoundingClientRect();
const borderWidth = 1;
const offsetLeft = x - parentX - borderWidth;

setLeft( offsetLeft );
setWidth( offsetWidth );

if ( ! canAnimate ) {
window.requestAnimationFrame( () => {
setCanAnimate( true );
} );
}
}, [ canAnimate, containerRef, containerWidth, state ] );

return (
<BackdropView
role="presentation"
style={ {
transform: `translateX(${ left }px)`,
transition: canAnimate ? undefined : 'none',
width,
} }
/>
);
}

export default memo( SegmentedControlBackdrop );
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
import { cx } from '@emotion/css';
ntsekouras marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line no-restricted-imports
import { Radio } from 'reakit';

/**
* WordPress dependencies
*/
import { memo } from '@wordpress/element';

/**
* Internal dependencies
*/
import * as styles from './styles';
import type { SegmentedControlButtonProps } from './types';

const {
ButtonContentView,
LabelPlaceholderView,
LabelView,
SeparatorView,
} = styles;

function SegmentedControlButton( {
className,
forwardedRef,
isBlock = false,
label,
showSeparator,
value,
...props
}: SegmentedControlButtonProps ) {
const isActive = props.state === value;
const labelViewClasses = cx( isBlock && styles.labelBlock );
const classes = cx(
styles.buttonView,
className,
isActive && styles.buttonActive
);
return (
<LabelView className={ labelViewClasses } data-active={ isActive }>
<Radio
{ ...props }
as="button"
aria-label={ label }
className={ classes }
data-value={ value }
ref={ forwardedRef }
value={ value }
>
<ButtonContentView>{ label }</ButtonContentView>
<LabelPlaceholderView aria-hidden>
{ label }
</LabelPlaceholderView>
</Radio>
<SegmentedControlSeparator isActive={ ! showSeparator } />
</LabelView>
);
}

const SegmentedControlSeparator = memo(
( { isActive }: { isActive: boolean } ) => {
const classes = cx( isActive && styles.separatorActive );
return <SeparatorView aria-hidden className={ classes } />;
}
);

export default memo( SegmentedControlButton );
Loading