UNPKG

@wix/css-property-parser

Version:

A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance

78 lines (77 loc) 2.55 kB
"use strict"; // Percentage data type parser // Handles parsing of CSS percentage values according to MDN specification // https://developer.mozilla.org/en-US/docs/Web/CSS/percentage Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = parse; exports.toCSSValue = toCSSValue; const number_1 = require('./number.cjs'); const css_variable_1 = require('./css-variable.cjs'); const shared_utils_1 = require('../utils/shared-utils.cjs'); const css_function_parser_1 = require('../utils/css-function-parser.cjs'); // Percentage pattern - number followed by % const PERCENTAGE_REGEX = /^(-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)%$/i; /** * Parses a CSS percentage value into structured components * @param value - The CSS percentage value string * @returns Parsed percentage object or null if invalid */ function parse(value) { if (!value || typeof value !== 'string') { return null; } const trimmed = value.trim(); if (trimmed === '') return null; // CSS variables - ALWAYS CHECK FIRST if ((0, shared_utils_1.isCssVariable)(trimmed)) { return (0, css_variable_1.parse)(trimmed); } // Handle CSS math functions: calc(), clamp(), min(), max() const functionResult = (0, css_function_parser_1.parseCSSFunction)(trimmed); if (functionResult) { return functionResult; } // Match percentage pattern const match = trimmed.match(PERCENTAGE_REGEX); if (!match) { return null; } const [, valueStr] = match; const numberValue = (0, number_1.parse)(valueStr); if (!numberValue) { return null; } // Check if it's a simple number value (not calc expression or keyword) if (!('value' in numberValue)) { return null; } return { type: 'percentage', value: numberValue.value, unit: '%' }; } /** * Converts a parsed percentage back to a CSS value string * @param parsed - The parsed 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); } // Handle CSS math function expressions if ('expression' in parsed) { return (0, css_function_parser_1.cssFunctionToCSSValue)(parsed); } // Handle regular percentage values if ('value' in parsed && 'unit' in parsed) { return `${parsed.value}${parsed.unit}`; } return null; }