@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
88 lines (87 loc) • 2.79 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
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = parse;
exports.toCSSValue = toCSSValue;
const number_1 = require('./number.cjs');
const shared_utils_1 = require('../utils/shared-utils.cjs');
const css_variable_1 = require('./css-variable.cjs');
const css_function_parser_1 = require('../utils/css-function-parser.cjs');
// 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
*/
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 ((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: '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 = (0, number_1.parse)(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
*/
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 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