@wordpress/components
Version:
UI components for WordPress.
104 lines (88 loc) • 2.81 kB
JavaScript
/**
* External dependencies
*/
import { Dimensions } from 'react-native';
/**
* WordPress dependencies
*/
import { useContext, useEffect, useState, useMemo, useCallback } from '@wordpress/element';
/**
* Internal dependencies
*/
import GlobalStylesContext from '../global-styles-context';
const getValueAndUnit = (value, unit) => {
var _ref, _ref$match;
const regex = /(\d+\.?\d*)(.*)/;
const splitValue = (_ref = `${value}`) === null || _ref === void 0 ? void 0 : (_ref$match = _ref.match(regex)) === null || _ref$match === void 0 ? void 0 : _ref$match.filter(v => v !== '');
if (splitValue) {
return {
valueToConvert: splitValue[1],
valueUnit: unit || splitValue[2]
};
}
return undefined;
};
const convertUnitToMobile = (containerSize, globalStyles, value, unit) => {
const {
width,
height
} = containerSize;
const {
valueToConvert,
valueUnit
} = getValueAndUnit(value, unit) || {};
const {
fontSize = 16
} = globalStyles || {};
if (valueToConvert === undefined) {
return undefined;
}
switch (valueUnit) {
case 'rem':
case 'em':
return valueToConvert * fontSize;
case '%':
return Number(valueToConvert / 100) * width;
case 'px':
return Number(valueToConvert);
case 'vw':
const vw = width / 100;
return Math.round(valueToConvert * vw);
case 'vh':
const vh = height / 100;
return Math.round(valueToConvert * vh);
default:
return Number(valueToConvert / 100) * width;
}
};
const useConvertUnitToMobile = (value, unit) => {
const {
globalStyles: styles
} = useContext(GlobalStylesContext);
const [windowSizes, setWindowSizes] = useState(Dimensions.get('window'));
useEffect(() => {
const dimensionsChangeSubscription = Dimensions.addEventListener('change', onDimensionsChange);
return () => {
dimensionsChangeSubscription.remove();
}; // Disable reason: deferring this refactor to the native team.
// see https://github.com/WordPress/gutenberg/pull/41166
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onDimensionsChange = useCallback(_ref2 => {
let {
window
} = _ref2;
setWindowSizes(window);
}, []);
return useMemo(() => {
const {
valueToConvert,
valueUnit
} = getValueAndUnit(value, unit) || {};
return convertUnitToMobile(windowSizes, styles, valueToConvert, valueUnit); // Disable reason: deferring this refactor to the native team.
// see https://github.com/WordPress/gutenberg/pull/41166
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [windowSizes, value, unit]);
};
export { convertUnitToMobile, useConvertUnitToMobile, getValueAndUnit };
//# sourceMappingURL=use-unit-converter-to-mobile.native.js.map