@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
84 lines (83 loc) • 2.64 kB
JavaScript
// Time data type parser
// Handles parsing of CSS <time> values according to MDN specification
// https://developer.mozilla.org/en-US/docs/Web/CSS/time
// Supports seconds (s) and milliseconds (ms) units
import { parse as parseNumber } from './number.js';
import { isCssVariable } from '../utils/shared-utils.js';
import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js';
import { parseCalcFunction, cssFunctionToCSSValue } from '../utils/css-function-parser.js';
// Time unit patterns
const TIME_UNIT_REGEX = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)(s|ms)$/i;
/**
* Parses a CSS time value into structured components
* @param value - The CSS time value string
* @returns Parsed time object or null if invalid
*/
export function parse(value) {
if (!value || typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (trimmed === '')
return null;
// Check for CSS variables - use centralized resolver
if (isCssVariable(trimmed)) {
return parseCSSVariable(trimmed);
}
// Handle calc() expressions
const calcResult = parseCalcFunction(trimmed);
if (calcResult) {
return calcResult;
}
// Handle zero (can be unitless)
if (trimmed === '0') {
return {
type: 'time',
value: 0,
unit: 's' // Default to seconds for unitless zero
};
}
// Parse time with unit
const match = trimmed.match(TIME_UNIT_REGEX);
if (!match)
return null;
const [, numberPart, unit] = match;
const numberValue = parseNumber(numberPart);
if (!numberValue || !('value' in numberValue)) {
return null;
}
const lowerUnit = unit.toLowerCase();
return {
type: 'time',
value: numberValue.value,
unit: lowerUnit
};
}
/**
* Converts a parsed time back to a CSS value string
* @param parsed - The parsed time 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 calc expressions
if ('expression' in parsed) {
return cssFunctionToCSSValue(parsed);
}
// Handle regular time 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;
}
// Internal helper functions (not exporte