Skip to content

Commit

Permalink
Move focus to UnitControl when switching to custom view
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronrobertshaw committed Jul 22, 2021
1 parent 6c36771 commit 3406995
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions packages/block-editor/src/components/width-control/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
ButtonGroup,
__experimentalUnitControl as UnitControl,
} from '@wordpress/components';
import { useState } from '@wordpress/element';
import { useEffect, useRef, useState } from '@wordpress/element';
import { edit } from '@wordpress/icons';
import { __ } from '@wordpress/i18n';

Expand Down Expand Up @@ -56,10 +56,18 @@ export default function WidthControl( props ) {
presetWidths = DEFAULT_WIDTHS,
} = props;

const ref = useRef();
const hasCustomValue = value && ! presetWidths.includes( value );
const [ customView, setCustomView ] = useState( hasCustomValue );
const currentUnit = parseUnit( value, units );

// When switching to the custom view, move focus to the UnitControl.
useEffect( () => {
if ( customView && ref.current ) {
ref.current.focus();
}
}, [ customView ] );

// Unless segmented control is desired return a normal UnitControl.
if ( ! isSegmentedControl ) {
return (
Expand All @@ -82,7 +90,12 @@ export default function WidthControl( props ) {
};

const renderCustomView = () => (
<UnitControl min={ min } unit={ currentUnit } { ...props } />
<UnitControl
ref={ ref }
min={ min }
unit={ currentUnit }
{ ...props }
/>
);

const renderPresetView = () => (
Expand Down

0 comments on commit 3406995

Please sign in to comment.