UNPKG

@wix/css-property-parser

Version:

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

74 lines (73 loc) 2.4 kB
// Percentage data type parser // Handles parsing of CSS percentage values according to MDN specification // https://developer.mozilla.org/en-US/docs/Web/CSS/percentage import { parse as parseNumber } from './number.js'; import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js'; import { isCssVariable } from '../utils/shared-utils.js'; import { parseCSSFunction, cssFunctionToCSSValue } from '../utils/css-function-parser.js'; // 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 */ export function parse(value) { if (!value || typeof value !== 'string') { return null; } const trimmed = value.trim(); if (trimmed === '') return null; // CSS variables - ALWAYS CHECK FIRST if (isCssVariable(trimmed)) { return parseCSSVariable(trimmed); } // Handle CSS math functions: calc(), clamp(), min(), max() const functionResult = parseCSSFunction(trimmed); if (functionResult) { return functionResult; } // Match percentage pattern const match = trimmed.match(PERCENTAGE_REGEX); if (!match) { return null; } const [, valueStr] = match; const numberValue = parseNumber(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 */ export function toCSSValue(parsed) { if (!parsed) { return null; } // Handle CSS variables if ('CSSvariable' in parsed) { return cssVariableToCSSValue(parsed); } // Handle CSS math function expressions if ('expression' in parsed) { return cssFunctionToCSSValue(parsed); } // Handle regular percentage values if ('value' in parsed && 'unit' in parsed) { return `${parsed.value}${parsed.unit}`; } return null; }