UNPKG

@wix/css-property-parser

Version:

A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance

81 lines (80 loc) 2.98 kB
// CSS physical border radius shared evaluator // Eliminates code duplication across all physical border radius properties // Supports border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius import { parse as parseLength } from './length.js'; import { parse as parsePercentage } from './percentage.js'; import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js'; import { isCssVariable, isGlobalKeyword, isNonNegative } from '../utils/shared-utils.js'; /** * Shared parser for all physical border radius properties * Handles length, percentage, CSS functions, keywords, and variables with non-negative validation * * @param value - The CSS value to parse * @returns Parsed value or null if invalid * * @example * parsePhysicalBorderRadiusProperty('10px') // { type: 'length', value: 10, unit: 'px' } * parsePhysicalBorderRadiusProperty('50%') // { type: 'percentage', value: 50, unit: '%' } * parsePhysicalBorderRadiusProperty('inherit') // { type: 'keyword', keyword: 'inherit' } */ export function parsePhysicalBorderRadiusProperty(value) { if (!value || typeof value !== 'string') { return null; } const trimmed = value.trim(); if (!trimmed) { return null; } // CSS variables if (isCssVariable(trimmed)) { return parseCSSVariable(trimmed); } // Global keywords if (isGlobalKeyword(trimmed)) { return { type: 'keyword', keyword: trimmed.toLowerCase() }; } // Try percentage first (to handle cases like '50%') const percentageResult = parsePercentage(trimmed); if (percentageResult && isNonNegative(percentageResult)) { return percentageResult; } // Try length const lengthResult = parseLength(trimmed); if (lengthResult && isNonNegative(lengthResult)) { return lengthResult; } return null; } /** * Shared toCSSValue function for all physical border radius properties * Converts parsed values back to CSS string representation * * @param parsed - The parsed value to convert * @returns CSS string or null if invalid * * @example * physicalBorderRadiusToCSSValue({ type: 'length', value: 10, unit: 'px' }) // '10px' * physicalBorderRadiusToCSSValue({ type: 'percentage', value: 50, unit: '%' }) // '50%' * physicalBorderRadiusToCSSValue({ type: 'keyword', keyword: 'inherit' }) // 'inherit' */ export function physicalBorderRadiusToCSSValue(parsed) { if (!parsed) { return null; } if ('CSSvariable' in parsed) { return cssVariableToCSSValue(parsed); } if ('keyword' in parsed) { return parsed.keyword; } if (parsed.type === 'length') { return `${parsed.value}${parsed.unit}`; } if (parsed.type === 'percentage') { return `${parsed.value}%`; } if (parsed.type === 'function') { return `${parsed.function}(${parsed.expression})`; } return null; }