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

UnitControl: Set correct unit when units has one option #33634

Merged
merged 1 commit into from
Jul 23, 2021
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
32 changes: 32 additions & 0 deletions packages/components/src/unit-control/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ const getInput = () =>
document.body.querySelector( '.components-unit-control input' );
const getSelect = () =>
document.body.querySelector( '.components-unit-control select' );
const getUnitLabel = () =>
document.body.querySelector( '.components-unit-control__unit-label' );

const fireKeyDown = ( data ) =>
fireEvent.keyDown( document.activeElement || document.body, data );
Expand Down Expand Up @@ -50,6 +52,16 @@ describe( 'UnitControl', () => {
expect( input ).toBeTruthy();
expect( select ).toBeFalsy();
} );

it( 'should render label if single units', () => {
render( <UnitControl units={ [ { value: '%', label: '%' } ] } /> );

const select = getSelect();
const label = getUnitLabel();

expect( select ).toBeFalsy();
expect( label ).toBeTruthy();
} );
} );

describe( 'Value', () => {
Expand Down Expand Up @@ -208,6 +220,26 @@ describe( 'UnitControl', () => {

expect( state ).toBe( '50pt' );
} );

it( 'should set correct unit if single units', () => {
let state = '50%';
const setState = ( value ) => ( state = value );

render(
<UnitControl
value={ state }
unit="%"
units={ [ { value: '%', label: '%' } ] }
onChange={ setState }
/>
);

const input = getInput();
input.focus();
fireEvent.change( input, { target: { value: 62 } } );

expect( state ).toBe( '62%' );
} );
} );

describe( 'Unit Parser', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default function UnitSelectControl( {
value = 'px',
...props
} ) {
if ( ! hasUnits( options ) ) {
if ( ! hasUnits( options ) || options.length === 1 ) {
return (
<UnitLabel
className="components-unit-control__unit-label"
Expand Down
2 changes: 1 addition & 1 deletion packages/components/src/unit-control/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export function getParsedValue( value, unit, units ) {
* @return {boolean} Whether units are defined.
*/
export function hasUnits( units ) {
return ! isEmpty( units ) && units.length > 1 && units !== false;
return ! isEmpty( units ) && units !== false;
}

/**
Expand Down