UNPKG

@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.83 kB
// Shared Gap Property Evaluator // Handles column-gap, row-gap // Root Type Pattern: CSSLengthValue | CSSPercentageValue | NormalKeyword 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 gap property parser * @param value - CSS value string to parse * @returns Parsed gap value or null if invalid */ export function parseGapProperty(value) { if (!value || typeof value !== 'string') { return null; } const trimmed = value.trim(); if (trimmed === '') { return null; } // CSS variables can be parsed 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 gap-specific keyword: normal if (trimmed.toLowerCase() === 'normal') { return { type: 'keyword', keyword: 'normal' }; } // Try to parse as percentage first (before length, since length includes %) const percentageResult = parsePercentage(trimmed); if (percentageResult) { // Gap percentages must be non-negative if (!isNonNegative(percentageResult)) { return null; } return percentageResult; } // Try to parse as length const lengthResult = parseLength(trimmed); if (lengthResult) { // Gap lengths must be non-negative if (!isNonNegative(lengthResult)) { return null; } return lengthResult; } return null; } /** * Generic gap property toCSSValue converter * @param parsed - Parsed gap value * @returns CSS string or null if invalid */ export function gapToCSSValue(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 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; }