@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
72 lines (71 loc) • 2.28 kB
JavaScript
import { isCssVariable, isGlobalKeyword, getValidKeyword } from '../utils/shared-utils.js';
import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js';
import { OBJECT_FIT_KEYWORDS } from '../types.js';
/**
* Parses CSS object-fit property values
*
* Syntax: fill | contain | cover | none | scale-down | inherit | initial | unset | revert
*
* @param value - The CSS object-fit value to parse
* @returns Parsed ObjectFitValue or null if invalid
*
* @example
* ```typescript
* parse('fill') // { type: 'keyword', keyword: 'fill' }
* parse('contain') // { type: 'keyword', keyword: 'contain' }
* parse('cover') // { type: 'keyword', keyword: 'cover' }
* parse('none') // { type: 'keyword', keyword: 'none' }
* parse('scale-down') // { type: 'keyword', keyword: 'scale-down' }
* parse('inherit') // { type: 'keyword', keyword: 'inherit' }
* parse('var(--my-fit)') // { type: 'variable', variable: 'my-fit' }
* ```
*/
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 object-fit specific keywords
const keywordResult = getValidKeyword(trimmed.toLowerCase(), OBJECT_FIT_KEYWORDS);
if (keywordResult) {
return {
type: 'keyword',
keyword: keywordResult
};
}
return null;
}
/**
* Converts a parsed ObjectFitValue back to its CSS string representation
*
* @param value - The parsed object-fit 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 object-fit-specific and global)
if (value.type === 'keyword') {
return value.keyword;
}
return null;
}