UNPKG

@wix/css-property-parser

Version:

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

87 lines (86 loc) 2.67 kB
"use strict"; // Angle data type parser // Handles parsing of CSS angle values according to MDN specification // https://developer.mozilla.org/en-US/docs/Web/CSS/angle 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'); // Common angle unit patterns const ANGLE_UNIT_REGEX = /^(-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)(deg|grad|rad|turn)$/i; /** * Parses a CSS angle value into structured components * @param value - The CSS angle value string * @returns Parsed angle 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 calc() expressions const calcResult = (0, css_function_parser_1.parseCalcFunction)(trimmed); if (calcResult) { return calcResult; } // Handle zero (can be unitless) if (trimmed === '0') { return { type: 'angle', value: 0, unit: 'deg' }; } // Match angle with unit const match = trimmed.match(ANGLE_UNIT_REGEX); if (!match) { return null; } const [, valueStr, unitStr] = match; const numberValue = (0, number_1.parse)(valueStr); if (!numberValue || !('value' in numberValue)) { return null; } const unit = unitStr.toLowerCase(); return { type: 'angle', value: numberValue.value, unit }; } /** * Converts a parsed angle back to a CSS value string * @param parsed - The parsed angle 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 calc expressions if ('expression' in parsed) { return (0, css_function_parser_1.cssFunctionToCSSValue)(parsed); } // Handle regular angle values if ('value' in parsed && 'unit' in parsed) { // Special case: zero can be unitless if (parsed.value === 0) { return '0'; } return `${parsed.value}${parsed.unit}`; } return null; }