@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
82 lines (81 loc) • 3 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
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseMarginProperty = parseMarginProperty;
exports.marginToCSSValue = marginToCSSValue;
const length_1 = require('../evaluators/length.cjs');
const percentage_1 = require('../evaluators/percentage.cjs');
const css_variable_1 = require('../evaluators/css-variable.cjs');
const shared_utils_1 = require('../utils/shared-utils.cjs');
// ========================================
// 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
*/
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 ((0, shared_utils_1.isCssVariable)(trimmed)) {
return (0, css_variable_1.parse)(trimmed);
}
// Global keywords first
if ((0, shared_utils_1.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 = (0, percentage_1.parse)(trimmed);
if (percentageResult) {
return percentageResult; // Negative values are allowed for margins
}
const lengthResult = (0, length_1.parse)(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
*/
function marginToCSSValue(parsed) {
if (!parsed) {
return null;
}
// Handle CSS variables
if ('CSSvariable' in parsed) {
return (0, css_variable_1.toCSSValue)(parsed);
}
// Handle keywords
if ('keyword' in parsed) {
return parsed.keyword;
}
// Handle length/percentage by delegating to the appropriate toCSSValue function
const lengthValue = (0, length_1.toCSSValue)(parsed);
if (lengthValue) {
return lengthValue;
}
const percentageValue = (0, percentage_1.toCSSValue)(parsed);
if (percentageValue) {
return percentageValue;
}
return null;
}