UNPKG

@wix/css-property-parser

Version:

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

70 lines (69 loc) 2.22 kB
import { isCssVariable, isGlobalKeyword, getValidKeyword } from '../utils/shared-utils.js'; import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js'; import { WRITING_MODE_KEYWORDS } from '../types.js'; /** * Parses CSS writing-mode property values * * Syntax: horizontal-tb | vertical-rl | vertical-lr | inherit | initial | unset | revert * * @param value - The CSS writing-mode value to parse * @returns Parsed WritingModeValue or null if invalid * * @example * ```typescript * parse('horizontal-tb') // { type: 'keyword', keyword: 'horizontal-tb' } * parse('vertical-rl') // { type: 'keyword', keyword: 'vertical-rl' } * parse('vertical-lr') // { type: 'keyword', keyword: 'vertical-lr' } * parse('inherit') // { type: 'keyword', keyword: 'inherit' } * parse('var(--writing-mode)') // { type: 'variable', variable: 'writing-mode' } * ``` */ export function parse(value) { if (!value || typeof value !== 'string') { return null; } const trimmed = value.trim(); if (trimmed === '') { return null; } // CSS variables - parse and return directly if (isCssVariable(trimmed)) { return parseCSSVariable(trimmed); } // Handle global keywords if (isGlobalKeyword(trimmed)) { return { type: 'keyword', keyword: trimmed.toLowerCase() }; } // Handle writing-mode specific keywords const keywordResult = getValidKeyword(trimmed.toLowerCase(), WRITING_MODE_KEYWORDS); if (keywordResult) { return { type: 'keyword', keyword: keywordResult }; } return null; } /** * Converts a parsed WritingModeValue back to its CSS string representation * * @param value - The parsed writing-mode value * @returns CSS string representation or null if invalid */ export function toCSSValue(value) { if (!value) { return null; } // Handle CSS variables if (value.type === 'variable') { return cssVariableToCSSValue(value); } // Handle keyword values (both writing-mode-specific and global) if (value.type === 'keyword') { return value.keyword; } return null; }