UNPKG

@wix/css-property-parser

Version:

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

79 lines (78 loc) 2.7 kB
// CSS text-transform property parser // Handles parsing of CSS text-transform property according to MDN specification // https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform import { isCssVariable, isGlobalKeyword } from '../utils/shared-utils.js'; import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js'; // Import and re-export centralized types import { TEXT_TRANSFORM_KEYWORDS } from '../types.js'; /** * Checks if a string is a valid text-transform keyword */ function isTextTransformKeyword(value) { return TEXT_TRANSFORM_KEYWORDS.includes(value.toLowerCase()); } /** * Validates keyword combinations according to CSS specification */ function areKeywordsCombinationValid(keywords) { // All keywords must be valid text-transform keywords if (!keywords.every(kw => isTextTransformKeyword(kw))) { return false; } // 'none' cannot be combined with other keywords if (keywords.includes('none') && keywords.length > 1) { return false; } // Case transformation keywords cannot be combined const caseKeywords = keywords.filter(kw => ['uppercase', 'lowercase', 'capitalize'].includes(kw)); if (caseKeywords.length > 1) { return false; } return true; } /** * Parses a CSS text-transform property string into structured components * Follows MDN specification: https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform */ export function parse(value) { if (!value || typeof value !== 'string') { return null; } const trimmed = value.trim(); if (trimmed === '') { return null; } // CSS variables can be parsed directly if (isCssVariable(trimmed)) { return parseCSSVariable(trimmed); } // Handle global keywords if (isGlobalKeyword(trimmed)) { return { type: 'keyword', keyword: trimmed.toLowerCase() }; } // Handle text-transform keywords (single or multiple) const keywords = trimmed.toLowerCase().split(/\s+/).filter(Boolean); // Validate keyword combination if (keywords.length > 0 && areKeywordsCombinationValid(keywords)) { return { type: 'keyword', keyword: keywords.join(' ') }; } return null; } /** * Converts a parsed text-transform back to a CSS value string * @param parsed - The parsed text-transform object * @returns CSS value string or null if invalid */ export function toCSSValue(parsed) { if (!parsed) { return null; } // Handle CSS variables if ('CSSvariable' in parsed) { return cssVariableToCSSValue(parsed); } if ('keyword' in parsed) { return parsed.keyword; } return null; }