2020-05-11 16:07:22 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { createContext, useContext } from '@wordpress/element';
|
|
|
|
import { useContainerQueries } from '@woocommerce/base-hooks';
|
|
|
|
import classNames from 'classnames';
|
|
|
|
|
2023-01-05 07:56:05 +00:00
|
|
|
export type ContainerWidthContextProps = {
|
|
|
|
hasContainerWidth: boolean;
|
|
|
|
containerClassName: string;
|
|
|
|
isMobile: boolean;
|
|
|
|
isSmall: boolean;
|
|
|
|
isMedium: boolean;
|
|
|
|
isLarge: boolean;
|
|
|
|
};
|
2020-05-11 16:07:22 +00:00
|
|
|
|
2023-01-05 07:56:05 +00:00
|
|
|
const ContainerWidthContext: React.Context< ContainerWidthContextProps > =
|
|
|
|
createContext< ContainerWidthContextProps >( {
|
|
|
|
hasContainerWidth: false,
|
|
|
|
containerClassName: '',
|
|
|
|
isMobile: false,
|
|
|
|
isSmall: false,
|
|
|
|
isMedium: false,
|
|
|
|
isLarge: false,
|
|
|
|
} );
|
2020-05-11 16:07:22 +00:00
|
|
|
|
2023-01-05 07:56:05 +00:00
|
|
|
export const useContainerWidthContext = (): ContainerWidthContextProps => {
|
2020-05-11 16:07:22 +00:00
|
|
|
return useContext( ContainerWidthContext );
|
|
|
|
};
|
|
|
|
|
2023-01-05 07:56:05 +00:00
|
|
|
interface ContainerWidthContextProviderProps {
|
|
|
|
children: JSX.Element | JSX.Element[];
|
|
|
|
className: string;
|
|
|
|
}
|
|
|
|
|
2020-05-11 16:07:22 +00:00
|
|
|
/**
|
|
|
|
* Provides an interface to useContainerQueries so children can see what size is being used by the
|
|
|
|
* container.
|
|
|
|
*/
|
|
|
|
export const ContainerWidthContextProvider = ( {
|
|
|
|
children,
|
|
|
|
className = '',
|
2023-01-05 07:56:05 +00:00
|
|
|
}: ContainerWidthContextProviderProps ): JSX.Element => {
|
2020-05-11 16:07:22 +00:00
|
|
|
const [ resizeListener, containerClassName ] = useContainerQueries();
|
|
|
|
|
|
|
|
const contextValue = {
|
|
|
|
hasContainerWidth: containerClassName !== '',
|
|
|
|
containerClassName,
|
|
|
|
isMobile: containerClassName === 'is-mobile',
|
|
|
|
isSmall: containerClassName === 'is-small',
|
|
|
|
isMedium: containerClassName === 'is-medium',
|
|
|
|
isLarge: containerClassName === 'is-large',
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<ContainerWidthContext.Provider value={ contextValue }>
|
|
|
|
<div className={ classNames( className, containerClassName ) }>
|
|
|
|
{ resizeListener }
|
|
|
|
{ children }
|
|
|
|
</div>
|
|
|
|
</ContainerWidthContext.Provider>
|
2020-09-07 17:31:10 +00:00
|
|
|
);
|
2020-05-11 16:07:22 +00:00
|
|
|
};
|