fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

View File

@@ -0,0 +1,60 @@
/**
* WordPress dependencies
*/
import { getBlockType } from '@wordpress/blocks';
export const WIDE_ALIGNMENTS = {
alignments: {
wide: 'wide',
full: 'full'
},
excludeBlocks: ['core/heading'],
notInnerContainers: ['core/image', 'core/separator', 'core/media-text', 'core/pullquote']
};
export const ALIGNMENT_BREAKPOINTS = {
wide: 1024,
large: 820,
medium: 768,
small: 680,
mobile: 480
};
const isFullWidth = align => align === WIDE_ALIGNMENTS.alignments.full;
const isWideWidth = align => align === WIDE_ALIGNMENTS.alignments.wide;
const isWider = (width, breakpoint) => width > ALIGNMENT_BREAKPOINTS[breakpoint];
const isContainerRelated = blockName => {
if (WIDE_ALIGNMENTS.notInnerContainers.includes(blockName)) {
return false;
}
if (hasFullWidthSupport(blockName)) {
return true;
}
return hasParentFullWidthSupport(blockName);
};
/**
* Whether the block has support for full width alignment.
*
* @param {string} blockName
* @return {boolean} Return whether the block supports full width alignment.
*/
function hasFullWidthSupport(blockName) {
const blockType = getBlockType(blockName);
const blockAlign = blockType?.supports?.align;
return !!Array.isArray(blockAlign) && blockAlign.includes(WIDE_ALIGNMENTS.alignments.full);
}
/**
* Whether the block's parent has support for full width alignment.
*
* @param {string} blockName
* @return {boolean} Return whether the block's parent supports full width alignment.
*/
function hasParentFullWidthSupport(blockName) {
const blockType = getBlockType(blockName);
return !!blockType?.parent?.some(hasFullWidthSupport);
}
export const alignmentHelpers = {
isFullWidth,
isWideWidth,
isWider,
isContainerRelated
};
//# sourceMappingURL=alignments.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["getBlockType","WIDE_ALIGNMENTS","alignments","wide","full","excludeBlocks","notInnerContainers","ALIGNMENT_BREAKPOINTS","large","medium","small","mobile","isFullWidth","align","isWideWidth","isWider","width","breakpoint","isContainerRelated","blockName","includes","hasFullWidthSupport","hasParentFullWidthSupport","blockType","blockAlign","supports","Array","isArray","parent","some","alignmentHelpers"],"sources":["@wordpress/components/src/mobile/utils/alignments.native.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { getBlockType } from '@wordpress/blocks';\n\nexport const WIDE_ALIGNMENTS = {\n\talignments: {\n\t\twide: 'wide',\n\t\tfull: 'full',\n\t},\n\texcludeBlocks: [ 'core/heading' ],\n\tnotInnerContainers: [\n\t\t'core/image',\n\t\t'core/separator',\n\t\t'core/media-text',\n\t\t'core/pullquote',\n\t],\n};\n\nexport const ALIGNMENT_BREAKPOINTS = {\n\twide: 1024,\n\tlarge: 820,\n\tmedium: 768,\n\tsmall: 680,\n\tmobile: 480,\n};\n\nconst isFullWidth = ( align ) => align === WIDE_ALIGNMENTS.alignments.full;\n\nconst isWideWidth = ( align ) => align === WIDE_ALIGNMENTS.alignments.wide;\n\nconst isWider = ( width, breakpoint ) =>\n\twidth > ALIGNMENT_BREAKPOINTS[ breakpoint ];\n\nconst isContainerRelated = ( blockName ) => {\n\tif ( WIDE_ALIGNMENTS.notInnerContainers.includes( blockName ) ) {\n\t\treturn false;\n\t}\n\n\tif ( hasFullWidthSupport( blockName ) ) {\n\t\treturn true;\n\t}\n\n\treturn hasParentFullWidthSupport( blockName );\n};\n\n/**\n * Whether the block has support for full width alignment.\n *\n * @param {string} blockName\n * @return {boolean} Return whether the block supports full width alignment.\n */\nfunction hasFullWidthSupport( blockName ) {\n\tconst blockType = getBlockType( blockName );\n\tconst blockAlign = blockType?.supports?.align;\n\treturn (\n\t\t!! Array.isArray( blockAlign ) &&\n\t\tblockAlign.includes( WIDE_ALIGNMENTS.alignments.full )\n\t);\n}\n/**\n * Whether the block's parent has support for full width alignment.\n *\n * @param {string} blockName\n * @return {boolean} Return whether the block's parent supports full width alignment.\n */\nfunction hasParentFullWidthSupport( blockName ) {\n\tconst blockType = getBlockType( blockName );\n\treturn !! blockType?.parent?.some( hasFullWidthSupport );\n}\n\nexport const alignmentHelpers = {\n\tisFullWidth,\n\tisWideWidth,\n\tisWider,\n\tisContainerRelated,\n};\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,YAAY,QAAQ,mBAAmB;AAEhD,OAAO,MAAMC,eAAe,GAAG;EAC9BC,UAAU,EAAE;IACXC,IAAI,EAAE,MAAM;IACZC,IAAI,EAAE;EACP,CAAC;EACDC,aAAa,EAAE,CAAE,cAAc,CAAE;EACjCC,kBAAkB,EAAE,CACnB,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB;AAElB,CAAC;AAED,OAAO,MAAMC,qBAAqB,GAAG;EACpCJ,IAAI,EAAE,IAAI;EACVK,KAAK,EAAE,GAAG;EACVC,MAAM,EAAE,GAAG;EACXC,KAAK,EAAE,GAAG;EACVC,MAAM,EAAE;AACT,CAAC;AAED,MAAMC,WAAW,GAAKC,KAAK,IAAMA,KAAK,KAAKZ,eAAe,CAACC,UAAU,CAACE,IAAI;AAE1E,MAAMU,WAAW,GAAKD,KAAK,IAAMA,KAAK,KAAKZ,eAAe,CAACC,UAAU,CAACC,IAAI;AAE1E,MAAMY,OAAO,GAAGA,CAAEC,KAAK,EAAEC,UAAU,KAClCD,KAAK,GAAGT,qBAAqB,CAAEU,UAAU,CAAE;AAE5C,MAAMC,kBAAkB,GAAKC,SAAS,IAAM;EAC3C,IAAKlB,eAAe,CAACK,kBAAkB,CAACc,QAAQ,CAAED,SAAU,CAAC,EAAG;IAC/D,OAAO,KAAK;EACb;EAEA,IAAKE,mBAAmB,CAAEF,SAAU,CAAC,EAAG;IACvC,OAAO,IAAI;EACZ;EAEA,OAAOG,yBAAyB,CAAEH,SAAU,CAAC;AAC9C,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA,SAASE,mBAAmBA,CAAEF,SAAS,EAAG;EACzC,MAAMI,SAAS,GAAGvB,YAAY,CAAEmB,SAAU,CAAC;EAC3C,MAAMK,UAAU,GAAGD,SAAS,EAAEE,QAAQ,EAAEZ,KAAK;EAC7C,OACC,CAAC,CAAEa,KAAK,CAACC,OAAO,CAAEH,UAAW,CAAC,IAC9BA,UAAU,CAACJ,QAAQ,CAAEnB,eAAe,CAACC,UAAU,CAACE,IAAK,CAAC;AAExD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASkB,yBAAyBA,CAAEH,SAAS,EAAG;EAC/C,MAAMI,SAAS,GAAGvB,YAAY,CAAEmB,SAAU,CAAC;EAC3C,OAAO,CAAC,CAAEI,SAAS,EAAEK,MAAM,EAAEC,IAAI,CAAER,mBAAoB,CAAC;AACzD;AAEA,OAAO,MAAMS,gBAAgB,GAAG;EAC/BlB,WAAW;EACXE,WAAW;EACXC,OAAO;EACPG;AACD,CAAC"}

View File

@@ -0,0 +1,294 @@
/**
* Converts string to object { value, unit }.
*
* @param {string} cssUnit
* @return {Object} parsedUnit
*/
function parseUnit(cssUnit) {
const match = cssUnit?.trim().match(/^(0?[-.]?\d*\.?\d+)(r?e[m|x]|v[h|w|min|max]+|p[x|t|c]|[c|m]m|%|in|ch|Q|lh)$/);
if (!isNaN(cssUnit) && !isNaN(parseFloat(cssUnit))) {
return {
value: parseFloat(cssUnit),
unit: 'px'
};
}
return match ? {
value: parseFloat(match[1]) || match[1],
unit: match[2]
} : {
value: cssUnit,
unit: undefined
};
}
/**
* Evaluate a math expression.
*
* @param {string} expression
* @return {number} evaluated expression.
*/
function calculate(expression) {
try {
return Function(`'use strict'; return (${expression})`)();
} catch (err) {
return null;
}
}
/**
* Calculates the css function value for the supported css functions such as max, min, clamp and calc.
*
* @param {string} functionUnitValue string should be in a particular format (for example min(12px,12px) ) no nested loops.
* @param {Object} options
* @return {string} unit containing the unit in PX.
*/
function getFunctionUnitValue(functionUnitValue, options) {
const functionUnit = functionUnitValue.split(/[(),]/g).filter(Boolean);
const units = functionUnit.slice(1).map(unit => parseUnit(getPxFromCssUnit(unit, options)).value).filter(Boolean);
switch (functionUnit[0]) {
case 'min':
return Math.min(...units) + 'px';
case 'max':
return Math.max(...units) + 'px';
case 'clamp':
if (units.length !== 3) {
return null;
}
if (units[1] < units[0]) {
return units[0] + 'px';
}
if (units[1] > units[2]) {
return units[2] + 'px';
}
return units[1] + 'px';
case 'calc':
return units[0] + 'px';
}
}
/**
* Take a css function such as min, max, calc, clamp and returns parsedUnit
*
* How this works for the nested function is that it first replaces the inner function call.
* Then it tackles the outer onces.
* So for example: min( max(25px, 35px), 40px )
* in the first pass we would replace max(25px, 35px) with 35px.
* then we would try to evaluate min( 35px, 40px )
* and then finally return 35px.
*
* @param {string} cssUnit
* @return {Object} parsedUnit object.
*/
function parseUnitFunction(cssUnit) {
while (true) {
const currentCssUnit = cssUnit;
const regExp = /(max|min|calc|clamp)\(([^()]*)\)/g;
const matches = regExp.exec(cssUnit) || [];
if (matches[0]) {
const functionUnitValue = getFunctionUnitValue(matches[0]);
cssUnit = cssUnit.replace(matches[0], functionUnitValue);
}
// If the unit hasn't been modified or we have a single value break free.
if (cssUnit === currentCssUnit || parseFloat(cssUnit)) {
break;
}
}
return parseUnit(cssUnit);
}
/**
* Return true if we think this is a math expression.
*
* @param {string} cssUnit the cssUnit value being evaluted.
* @return {boolean} Whether the cssUnit is a math expression.
*/
function isMathExpression(cssUnit) {
for (let i = 0; i < cssUnit.length; i++) {
if (['+', '-', '/', '*'].includes(cssUnit[i])) {
return true;
}
}
return false;
}
/**
* Evaluates the math expression and return a px value.
*
* @param {string} cssUnit the cssUnit value being evaluted.
* @return {string} return a converfted value to px.
*/
function evalMathExpression(cssUnit) {
let errorFound = false;
// Convert every part of the expression to px values.
// The following regex matches numbers that have a following unit
// E.g. 5.25rem, 1vw
const cssUnitsBits = cssUnit.match(/\d+\.?\d*[a-zA-Z]+|\.\d+[a-zA-Z]+/g);
if (cssUnitsBits) {
for (const unit of cssUnitsBits) {
// Standardize the unit to px and extract the value.
const parsedUnit = parseUnit(getPxFromCssUnit(unit));
if (!parseFloat(parsedUnit.value)) {
errorFound = true;
// End early since we are dealing with a null value.
break;
}
cssUnit = cssUnit.replace(unit, parsedUnit.value);
}
} else {
errorFound = true;
}
// For mixed math expressions wrapped within CSS expressions
const expressionsMatches = cssUnit.match(/(max|min|clamp)/g);
if (!errorFound && expressionsMatches) {
const values = cssUnit.split(',');
for (const currentValue of values) {
// Check for nested calc() and remove them to calculate the value.
const rawCurrentValue = currentValue.replace(/\s|calc/g, '');
if (isMathExpression(rawCurrentValue)) {
const calculatedExpression = calculate(rawCurrentValue);
if (calculatedExpression) {
const calculatedValue = calculatedExpression.toFixed(0) + 'px';
cssUnit = cssUnit.replace(currentValue, calculatedValue);
}
}
}
const parsedValue = parseUnitFunction(cssUnit);
return !parsedValue ? null : parsedValue.value + parsedValue.unit;
}
if (errorFound) {
return null;
}
const calculatedResult = calculate(cssUnit);
return calculatedResult ? calculatedResult.toFixed(0) + 'px' : null;
}
/**
* Convert a parsedUnit object to px value.
*
* @param {Object} parsedUnit
* @param {Object} options
* @return {string} or {null} returns the converted with in a px value format.
*/
function convertParsedUnitToPx(parsedUnit, options) {
const PIXELS_PER_INCH = 96;
const ONE_PERCENT = 0.01;
const defaultProperties = {
fontSize: 16,
lineHeight: 16,
width: 375,
height: 812,
type: 'font'
};
const setOptions = Object.assign({}, defaultProperties, options);
const relativeUnits = {
em: setOptions.fontSize,
rem: setOptions.fontSize,
vh: setOptions.height * ONE_PERCENT,
vw: setOptions.width * ONE_PERCENT,
vmin: (setOptions.width < setOptions.height ? setOptions.width : setOptions.height) * ONE_PERCENT,
vmax: (setOptions.width > setOptions.height ? setOptions.width : setOptions.height) * ONE_PERCENT,
'%': (setOptions.type === 'font' ? setOptions.fontSize : setOptions.width) * ONE_PERCENT,
ch: 8,
// The advance measure (width) of the glyph "0" of the element's font. Approximate
ex: 7.15625,
// X-height of the element's font. Approximate.
lh: setOptions.lineHeight
};
relativeUnits.svw = relativeUnits.vmin;
relativeUnits.lvw = relativeUnits.vmax;
relativeUnits.dvw = relativeUnits.vw;
relativeUnits.svh = relativeUnits.vmin;
relativeUnits.lvh = relativeUnits.vmax;
relativeUnits.dvh = relativeUnits.vh;
relativeUnits.vi = relativeUnits.vh;
relativeUnits.svi = relativeUnits.vmin;
relativeUnits.lvi = relativeUnits.vmax;
relativeUnits.dvi = relativeUnits.vw;
relativeUnits.vb = relativeUnits.vh;
relativeUnits.svb = relativeUnits.vmin;
relativeUnits.lvb = relativeUnits.vmax;
relativeUnits.dvb = relativeUnits.vh;
relativeUnits.svmin = relativeUnits.vmin;
relativeUnits.lvmin = relativeUnits.vmin;
relativeUnits.dvmin = relativeUnits.vmin;
relativeUnits.svmax = relativeUnits.vmax;
relativeUnits.lvmax = relativeUnits.vmax;
relativeUnits.dvmax = relativeUnits.vmax;
const absoluteUnits = {
in: PIXELS_PER_INCH,
cm: PIXELS_PER_INCH / 2.54,
mm: PIXELS_PER_INCH / 25.4,
pt: PIXELS_PER_INCH / 72,
pc: PIXELS_PER_INCH / 6,
px: 1,
Q: PIXELS_PER_INCH / 2.54 / 40
};
if (relativeUnits[parsedUnit.unit]) {
return (relativeUnits[parsedUnit.unit] * parsedUnit.value).toFixed(0) + 'px';
}
if (absoluteUnits[parsedUnit.unit]) {
return (absoluteUnits[parsedUnit.unit] * parsedUnit.value).toFixed(0) + 'px';
}
return null;
}
/**
* Returns the px value of a cssUnit.
*
* @param {string} cssUnit
* @param {Object} options
* @return {string} returns the cssUnit value in a simple px format.
*/
export function getPxFromCssUnit(cssUnit, options = {}) {
if (Number.isFinite(cssUnit)) {
return cssUnit.toFixed(0) + 'px';
}
if (cssUnit === undefined) {
return null;
}
let parsedUnit = parseUnit(cssUnit);
if (!parsedUnit.unit) {
parsedUnit = parseUnitFunction(cssUnit);
}
if (isMathExpression(cssUnit) && !parsedUnit.unit) {
return evalMathExpression(cssUnit);
}
return convertParsedUnitToPx(parsedUnit, options);
}
// Use simple cache.
const cache = {};
/**
* Returns the px value of a cssUnit. The memoized version of getPxFromCssUnit;
*
* @param {string} cssUnit
* @param {Object} options
* @return {string} returns the cssUnit value in a simple px format.
*/
function memoizedGetPxFromCssUnit(cssUnit, options = {}) {
const hash = cssUnit + hashOptions(options);
if (!cache[hash]) {
cache[hash] = getPxFromCssUnit(cssUnit, options);
}
return cache[hash];
}
function hashOptions(options) {
let hash = '';
if (options.hasOwnProperty('fontSize')) {
hash = ':' + options.width;
}
if (options.hasOwnProperty('lineHeight')) {
hash = ':' + options.lineHeight;
}
if (options.hasOwnProperty('width')) {
hash = ':' + options.width;
}
if (options.hasOwnProperty('height')) {
hash = ':' + options.height;
}
if (options.hasOwnProperty('type')) {
hash = ':' + options.type;
}
return hash;
}
export default memoizedGetPxFromCssUnit;
//# sourceMappingURL=get-px-from-css-unit.native.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
export function removeNonDigit(text, decimalNum) {
const regex = decimalNum > 0 ? /^(\d+\.?\,?(\d+)?)/ : /([\d]+)/;
const result = text.match(regex);
return result ? result[0] : '';
}
export function toFixed(num, decimalNum = 0) {
const decimalOffset = decimalNum < 0 ? 0 : decimalNum;
return Number.parseFloat(Number.parseFloat(num).toFixed(decimalOffset));
}
//# sourceMappingURL=index.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["removeNonDigit","text","decimalNum","regex","result","match","toFixed","num","decimalOffset","Number","parseFloat"],"sources":["@wordpress/components/src/mobile/utils/index.native.js"],"sourcesContent":["export function removeNonDigit( text, decimalNum ) {\n\tconst regex = decimalNum > 0 ? /^(\\d+\\.?\\,?(\\d+)?)/ : /([\\d]+)/;\n\tconst result = text.match( regex );\n\treturn result ? result[ 0 ] : '';\n}\n\nexport function toFixed( num, decimalNum = 0 ) {\n\tconst decimalOffset = decimalNum < 0 ? 0 : decimalNum;\n\treturn Number.parseFloat(\n\t\tNumber.parseFloat( num ).toFixed( decimalOffset )\n\t);\n}\n"],"mappings":"AAAA,OAAO,SAASA,cAAcA,CAAEC,IAAI,EAAEC,UAAU,EAAG;EAClD,MAAMC,KAAK,GAAGD,UAAU,GAAG,CAAC,GAAG,oBAAoB,GAAG,SAAS;EAC/D,MAAME,MAAM,GAAGH,IAAI,CAACI,KAAK,CAAEF,KAAM,CAAC;EAClC,OAAOC,MAAM,GAAGA,MAAM,CAAE,CAAC,CAAE,GAAG,EAAE;AACjC;AAEA,OAAO,SAASE,OAAOA,CAAEC,GAAG,EAAEL,UAAU,GAAG,CAAC,EAAG;EAC9C,MAAMM,aAAa,GAAGN,UAAU,GAAG,CAAC,GAAG,CAAC,GAAGA,UAAU;EACrD,OAAOO,MAAM,CAACC,UAAU,CACvBD,MAAM,CAACC,UAAU,CAAEH,GAAI,CAAC,CAACD,OAAO,CAAEE,aAAc,CACjD,CAAC;AACF"}

View File

@@ -0,0 +1,24 @@
/**
* External dependencies
*/
import { Keyboard, Dimensions } from 'react-native';
/**
* WordPress dependencies
*/
import { useEffect, useState } from '@wordpress/element';
export default function useIsFloatingKeyboard() {
const windowWidth = Dimensions.get('window').width;
const [floating, setFloating] = useState(false);
useEffect(() => {
const onKeyboardWillChangeFrame = event => {
setFloating(event.endCoordinates.width !== windowWidth);
};
const keyboardChangeSubscription = Keyboard.addListener('keyboardWillChangeFrame', onKeyboardWillChangeFrame);
return () => {
keyboardChangeSubscription.remove();
};
}, [windowWidth]);
return floating;
}
//# sourceMappingURL=use-is-floating-keyboard.native.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["Keyboard","Dimensions","useEffect","useState","useIsFloatingKeyboard","windowWidth","get","width","floating","setFloating","onKeyboardWillChangeFrame","event","endCoordinates","keyboardChangeSubscription","addListener","remove"],"sources":["@wordpress/components/src/mobile/utils/use-is-floating-keyboard.native.js"],"sourcesContent":["/**\n * External dependencies\n */\nimport { Keyboard, Dimensions } from 'react-native';\n\n/**\n * WordPress dependencies\n */\nimport { useEffect, useState } from '@wordpress/element';\n\nexport default function useIsFloatingKeyboard() {\n\tconst windowWidth = Dimensions.get( 'window' ).width;\n\n\tconst [ floating, setFloating ] = useState( false );\n\n\tuseEffect( () => {\n\t\tconst onKeyboardWillChangeFrame = ( event ) => {\n\t\t\tsetFloating( event.endCoordinates.width !== windowWidth );\n\t\t};\n\n\t\tconst keyboardChangeSubscription = Keyboard.addListener(\n\t\t\t'keyboardWillChangeFrame',\n\t\t\tonKeyboardWillChangeFrame\n\t\t);\n\t\treturn () => {\n\t\t\tkeyboardChangeSubscription.remove();\n\t\t};\n\t}, [ windowWidth ] );\n\n\treturn floating;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,QAAQ,EAAEC,UAAU,QAAQ,cAAc;;AAEnD;AACA;AACA;AACA,SAASC,SAAS,EAAEC,QAAQ,QAAQ,oBAAoB;AAExD,eAAe,SAASC,qBAAqBA,CAAA,EAAG;EAC/C,MAAMC,WAAW,GAAGJ,UAAU,CAACK,GAAG,CAAE,QAAS,CAAC,CAACC,KAAK;EAEpD,MAAM,CAAEC,QAAQ,EAAEC,WAAW,CAAE,GAAGN,QAAQ,CAAE,KAAM,CAAC;EAEnDD,SAAS,CAAE,MAAM;IAChB,MAAMQ,yBAAyB,GAAKC,KAAK,IAAM;MAC9CF,WAAW,CAAEE,KAAK,CAACC,cAAc,CAACL,KAAK,KAAKF,WAAY,CAAC;IAC1D,CAAC;IAED,MAAMQ,0BAA0B,GAAGb,QAAQ,CAACc,WAAW,CACtD,yBAAyB,EACzBJ,yBACD,CAAC;IACD,OAAO,MAAM;MACZG,0BAA0B,CAACE,MAAM,CAAC,CAAC;IACpC,CAAC;EACF,CAAC,EAAE,CAAEV,WAAW,CAAG,CAAC;EAEpB,OAAOG,QAAQ;AAChB"}

View File

@@ -0,0 +1,90 @@
/**
* 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) => {
const regex = /(\d+\.?\d*)(.*)/;
const splitValue = `${value}`?.match(regex)?.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(({
window
}) => {
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

File diff suppressed because one or more lines are too long