@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
61 lines (60 loc) • 2.14 kB
JavaScript
;
// Length-Percentage data type parser
// Handles parsing of CSS <length-percentage> values according to MDN specification
// https://developer.mozilla.org/en-US/docs/Web/CSS/length-percentage
// Accepts both length values (px, em, rem, etc.) and percentage values
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = parse;
exports.toCSSValue = toCSSValue;
const length_1 = require('./length.cjs');
const percentage_1 = require('./percentage.cjs');
const shared_utils_1 = require('../utils/shared-utils.cjs');
const css_variable_1 = require('./css-variable.cjs');
/**
* Parses a CSS <length-percentage> value into structured components
* @param value - The CSS length-percentage value
* @returns Parsed length-percentage object or null if invalid
*/
function parse(value) {
if (!value || typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (trimmed === '')
return null;
// Check for CSS variables - use centralized resolver
if ((0, shared_utils_1.isCssVariable)(trimmed)) {
return (0, css_variable_1.parse)(trimmed);
}
// Try parsing as percentage first (since it's more specific - ends with %)
const percentageResult = (0, percentage_1.parse)(trimmed);
if (percentageResult) {
return percentageResult;
}
// Try parsing as length
const lengthResult = (0, length_1.parse)(trimmed);
if (lengthResult) {
return lengthResult;
}
return null;
}
/**
* Converts a parsed length-percentage back to a CSS value string
* @param parsed - The parsed length-percentage object
* @returns CSS value string or null if invalid
*/
function toCSSValue(parsed) {
if (!parsed) {
return null;
}
// Handle CSS variables
if ('CSSvariable' in parsed) {
return (0, css_variable_1.toCSSValue)(parsed);
}
// Check if it's a percentage value (unit is '%')
if ('unit' in parsed && parsed.unit === '%') {
return (0, percentage_1.toCSSValue)(parsed);
}
// Otherwise, try as length value
return (0, length_1.toCSSValue)(parsed);
}