@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
85 lines (84 loc) • 2.71 kB
JavaScript
;
// Number data type parser
// Handles parsing of CSS numeric values according to MDN specification
// https://developer.mozilla.org/en-US/docs/Web/CSS/number
// and reconstruction back to CSS string
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = parse;
exports.toCSSValue = toCSSValue;
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');
/**
* Parses a CSS number value into structured components
* Following MDN specification: https://developer.mozilla.org/en-US/docs/Web/CSS/number
* @param value - The CSS number value string
* @returns Parsed number 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 global keywords per MDN
if ((0, shared_utils_1.isGlobalKeyword)(trimmed)) {
return {
type: 'keyword',
keyword: trimmed.toLowerCase()
};
}
// Handle calc() expressions
const calcResult = (0, css_function_parser_1.parseCalcFunction)(trimmed);
if (calcResult) {
return calcResult;
}
// MDN number pattern: integer or fractional, no unit
// Supports scientific notation as per CSS spec
const numberPattern = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
if (!numberPattern.test(trimmed)) {
return null;
}
const numValue = parseFloat(trimmed);
if (isNaN(numValue)) {
return null;
}
// Normalize -0 to 0
const normalizedValue = numValue === 0 ? 0 : numValue;
return {
type: 'number',
value: normalizedValue
};
}
/**
* Converts a parsed number back to a CSS value string
* @param parsed - The parsed number 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 keywords
if ('keyword' in parsed) {
return parsed.keyword;
}
// Handle calc expressions
if ('expression' in parsed) {
return (0, css_function_parser_1.cssFunctionToCSSValue)(parsed);
}
// Handle regular number values (no unit per MDN)
if ('value' in parsed) {
return parsed.value.toString();
}
return null;
}