Files
lcp-visualizer/blocks/components/LCPDimensionControl.js
Jeremy Rangel dd4bd0caf5 Initial
2025-01-21 18:41:51 -08:00

56 lines
1.9 KiB
JavaScript

import { __ } from '@wordpress/i18n';
import { SelectControl, TextControl } from '@wordpress/components';
const LCPDimensionControl = ({ label, value, onChange, unitTypes }) => {
// Parse the current value into number and unit
const parseValue = (val) => {
const match = val?.match(/^(\d+)(.*)$/);
return match ? {
number: parseInt(match[1], 10),
unit: match[2] || 'px'
} : { number: 300, unit: 'px' };
};
const { number, unit } = parseValue(value);
// Default units
const allUnits = [
{ label: 'Pixels (px)', value: 'px' },
{ label: 'Percentage (%)', value: '%' },
{ label: 'Viewport Width (vw)', value: 'vw' },
{ label: 'Viewport Height (vh)', value: 'vh' }
];
// Filter units based on unitTypes prop or use allUnits if unitTypes is not passed
const units = unitTypes && unitTypes.length > 0
? allUnits.filter(unit => unitTypes.includes(unit.value))
: allUnits;
return (
<div className="lcp-dimension-control">
<label className="components-base-control__label">{label}</label>
<div style={{ display: 'flex', gap: '8px', alignItems: 'flex-start' }}>
<TextControl
type="number"
value={number}
onChange={(newNumber) => {
onChange(`${newNumber}${unit}`);
}}
min={0}
style={{ width: '80px' }}
/>
<SelectControl
value={unit}
options={units}
onChange={(newUnit) => {
onChange(`${number}${newUnit}`);
}}
style={{ minWidth: '100px' }}
/>
</div>
</div>
);
};
export default LCPDimensionControl;