@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.21 kB
JavaScript
import { isCssVariable, isGlobalKeyword, getValidKeyword } from '../utils/shared-utils.js';
import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js';
import { WHITE_SPACE_KEYWORDS } from '../types.js';
/**
* Parses CSS white-space property values
*
* Syntax: normal | nowrap | pre | pre-wrap | pre-line | break-spaces | inherit | initial | unset | revert
*
* @param value - The CSS white-space value to parse
* @returns Parsed WhiteSpaceValue or null if invalid
*
* @example
* ```typescript
* parse('normal') // { type: 'keyword', keyword: 'normal' }
* parse('nowrap') // { type: 'keyword', keyword: 'nowrap' }
* parse('pre-wrap') // { type: 'keyword', keyword: 'pre-wrap' }
* parse('inherit') // { type: 'keyword', keyword: 'inherit' }
* parse('var(--my-whitespace)') // { type: 'css-variable', variable: 'my-whitespace' }
* ```
*/
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 white-space specific keywords
const keywordResult = getValidKeyword(trimmed.toLowerCase(), WHITE_SPACE_KEYWORDS);
if (keywordResult) {
return {
type: 'keyword',
keyword: keywordResult
};
}
return null;
}
/**
* Converts a parsed WhiteSpaceValue back to its CSS string representation
*
* @param value - The parsed white-space 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 white-space-specific and global)
if (value.type === 'keyword') {
return value.keyword;
}
return null;
}