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

[RNMobile] Create cross platform useResizeObserver() hook #19918

Merged
merged 12 commits into from
Mar 13, 2020
21 changes: 21 additions & 0 deletions packages/compose/src/hooks/use-container-match/compare-widths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export default function compareWidths( operator, queryWidth, containerWidth ) {
switch ( operator ) {
case '<':
return containerWidth < queryWidth;
case '<=':
return containerWidth <= queryWidth;
case '===' :
case '==' :
case '=' :
return containerWidth === queryWidth;
case '!==' :
case '!=' :
return containerWidth !== queryWidth;
case '>' :
return containerWidth > queryWidth;
case '>=':
return containerWidth >= queryWidth;
default:
throw new Error( `Unsupported operator: ${ operator }` );
}
}
38 changes: 38 additions & 0 deletions packages/compose/src/hooks/use-container-match/index.native.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* WordPress dependencies
*/
import { useState, useCallback } from '@wordpress/element';
/**
* External dependencies
*/
import { mapValues } from 'lodash';

/**
* Internal dependencies
*/
import compareWidths from './compare-widths';

const useContainerMatch = ( queries ) => {
lukewalczak marked this conversation as resolved.
Show resolved Hide resolved
const [ currentContainerWidth, setContainerWidth ] = useState( null );
const [ containerMatches, setContainerMatches ] = useState( null );

const matchWidth = ( containerWidth ) => mapValues( queries, ( query ) => {
const [ queryWidth, operator = '>=' ] = query.split( ' ' ).reverse();
return compareWidths( operator, queryWidth, containerWidth );
} );

const onLayout = useCallback( ( { nativeEvent } ) => {
const { width } = nativeEvent.layout;

if ( width !== currentContainerWidth ) {
setContainerWidth( width );
matchWidth( width );
setContainerMatches( matchWidth( width ) );
}
}, [] );

return [ containerMatches, onLayout ];
};

export default useContainerMatch;

1 change: 1 addition & 0 deletions packages/compose/src/index.native.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export { default as withPreferredColorScheme } from './higher-order/with-preferr

// Hooks
export { default as usePreferredColorScheme } from './hooks/use-preferred-color-scheme';
export { default as useContainerMatch } from './hooks/use-container-match';