@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
81 lines (80 loc) • 2.56 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
import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js';
import { isCssVariable, isGlobalKeyword } from '../utils/shared-utils.js';
import { parseCalcFunction, cssFunctionToCSSValue } from '../utils/css-function-parser.js';
/**
* 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
*/
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 global keywords per MDN
if (isGlobalKeyword(trimmed)) {
return {
type: 'keyword',
keyword: trimmed.toLowerCase()
};
}
// Handle calc() expressions
const calcResult = 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
*/
export function toCSSValue(parsed) {
if (!parsed) {
return null;
}
// Handle CSS variables
if ('CSSvariable' in parsed) {
return cssVariableToCSSValue(parsed);
}
// Handle keywords
if ('keyword' in parsed) {
return parsed.keyword;
}
// Handle calc expressions
if ('expression' in parsed) {
return cssFunctionToCSSValue(parsed);
}
// Handle regular number values (no unit per MDN)
if ('value' in parsed) {
return parsed.value.toString();
}
return null;
}