@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
78 lines (77 loc) • 2.9 kB
JavaScript
// Shared margin property parser - Phase 2 simple properties
// Handles parsing of all individual margin properties according to MDN specification
// All margin properties share the same syntax: <length-percentage> | auto | global-keywords
import { parse as parseLength, toCSSValue as lengthToCSSValue } from '../evaluators/length.js';
import { parse as parsePercentage, toCSSValue as percentageToCSSValue } from '../evaluators/percentage.js';
import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from '../evaluators/css-variable.js';
import { isCssVariable, isGlobalKeyword } from '../utils/shared-utils.js';
// ========================================
// Shared Margin Evaluator
// ========================================
/**
* Shared parser for all individual margin properties
* All margin properties (margin-top, margin-right, margin-bottom, margin-left)
* have identical syntax: <length-percentage> | auto | global-keywords
*
* @param value - The CSS margin property string
* @returns Parsed margin value or null if invalid
*/
export function parseMarginProperty(value) {
if (!value || typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (trimmed === '') {
return null;
}
// CSS variables return parsed variable object
if (isCssVariable(trimmed)) {
return parseCSSVariable(trimmed);
}
// Global keywords first
if (isGlobalKeyword(trimmed)) {
return { type: 'keyword', keyword: trimmed.toLowerCase() };
}
// Auto keyword for margin properties
if (trimmed.toLowerCase() === 'auto') {
return { type: 'keyword', keyword: 'auto' };
}
// Try atomic types (ORDER MATTERS: percentage before length for % detection)
const percentageResult = parsePercentage(trimmed);
if (percentageResult) {
return percentageResult; // Negative values are allowed for margins
}
const lengthResult = parseLength(trimmed);
if (lengthResult) {
return lengthResult; // Negative values are allowed for margins
}
return null;
}
/**
* Shared toCSSValue function for all individual margin properties
* @param parsed - The parsed margin value
* @returns CSS value string or null if invalid
*/
export function marginToCSSValue(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 length/percentage by delegating to the appropriate toCSSValue function
const lengthValue = lengthToCSSValue(parsed);
if (lengthValue) {
return lengthValue;
}
const percentageValue = percentageToCSSValue(parsed);
if (percentageValue) {
return percentageValue;
}
return null;
}