@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) • 3.13 kB
JavaScript
// Shared Sizing Property Evaluator
// Handles width, height, min-width, min-height, max-width, max-height
// Root Type Pattern: CSSLengthValue | CSSPercentageValue | [PropertyKeywords]
import { isGlobalKeyword, isCssVariable, isNonNegative } from '../utils/shared-utils.js';
import { parse as parseLength, toCSSValue as lengthToCSSValue } from './length.js';
import { parse as parsePercentage, toCSSValue as percentageToCSSValue } from './percentage.js';
import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js';
/**
* Generic sizing property parser
* @param value - CSS value string to parse
* @param keywords - Array of valid keywords for this specific property
* @param requireNonNegative - Whether to enforce non-negative values (default: true)
* @returns Parsed sizing value or null if invalid
*/
export function parseSizingProperty(value, keywords, requireNonNegative = true) {
if (!value || typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (trimmed === '') {
return null;
}
// CSS variables - parse them if valid
if (isCssVariable(trimmed)) {
return parseCSSVariable(trimmed);
}
// Handle global keywords (inherit, initial, unset, revert, revert-layer)
if (isGlobalKeyword(trimmed)) {
return { type: 'keyword', keyword: trimmed.toLowerCase() };
}
// Handle property-specific keywords
const lowerValue = trimmed.toLowerCase();
if (keywords.includes(lowerValue)) {
return { type: 'keyword', keyword: lowerValue };
}
// Try to parse as percentage first (before length, since length includes %)
const percentageResult = parsePercentage(trimmed);
if (percentageResult) {
if (requireNonNegative && !isNonNegative(percentageResult)) {
return null;
}
return percentageResult;
}
// Try to parse as length
const lengthResult = parseLength(trimmed);
if (lengthResult) {
if (requireNonNegative && !isNonNegative(lengthResult)) {
return null;
}
return lengthResult;
}
return null;
}
/**
* Generic sizing property toCSSValue converter
* @param parsed - Parsed sizing value
* @returns CSS string or null if invalid
*/
export function sizingToCSSValue(parsed) {
if (!parsed) {
return null;
}
// Handle CSS variables - use the proper CSS variable serializer
if ('CSSvariable' in parsed) {
return cssVariableToCSSValue(parsed);
}
// Handle keywords
if ('keyword' in parsed) {
return parsed.keyword;
}
// Handle length values (including calc expressions)
if ('unit' in parsed) {
return lengthToCSSValue(parsed);
}
// Handle percentage values (including calc expressions)
if ('value' in parsed && !('unit' in parsed)) {
return percentageToCSSValue(parsed);
}
// Handle calc expressions that could be length or percentage
if ('expression' in parsed) {
return lengthToCSSValue(parsed) || percentageToCSSValue(parsed);
}
return null;
}