Skip to content

Commit

Permalink
Fix UnitControl resets unit when value is cleared (WordPress#39531)
Browse files Browse the repository at this point in the history
* Avoid setting unit from effect hook if parsed to `undefined`

* Add unit test

* Add changelog entry

* Remove duplicated `Bug Fix` section in the CHANGELOG

Co-authored-by: Marco Ciampini <[email protected]>
  • Loading branch information
2 people authored and jostnes committed Mar 23, 2022
1 parent 08d22fd commit 8b1c4e4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
### Bug Fix

- `NumberControl`: commit (and constrain) value on `blur` event ([#39186](https://github.com/WordPress/gutenberg/pull/39186)).
- Fix `UnitControl`'s reset of unit when the quantity value is cleared. ([#39531](https://github.com/WordPress/gutenberg/pull/39531/)).

### Deprecation

Expand Down
4 changes: 3 additions & 1 deletion packages/components/src/unit-control/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ function UnforwardedUnitControl(
);

useEffect( () => {
setUnit( parsedUnit );
if ( parsedUnit !== undefined ) {
setUnit( parsedUnit );
}
}, [ parsedUnit ] );

// Stores parsed value for hand-off in state reducer.
Expand Down
19 changes: 19 additions & 0 deletions packages/components/src/unit-control/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,25 @@ describe( 'UnitControl', () => {
await waitFor( () => expect( selectA ).toHaveValue( 'vw' ) );
expect( selectB ).toHaveValue( 'vw' );
} );

it( 'should maintain the chosen non-default unit when value is cleared', async () => {
const units = [
{ value: 'pt', label: 'pt' },
{ value: 'vmax', label: 'vmax' },
];

const { user } = render(
<UnitControl units={ units } value="5" />
);

const select = getSelect();
await user.selectOptions( select, [ 'vmax' ] );

const input = getInput();
await user.clear( input );

expect( select ).toHaveValue( 'vmax' );
} );
} );

describe( 'Unit Parser', () => {
Expand Down

0 comments on commit 8b1c4e4

Please sign in to comment.