@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
75 lines (74 loc) • 2.59 kB
JavaScript
// Text-align property parser
// Handles parsing of CSS text-align property according to MDN specification
// https://developer.mozilla.org/en-US/docs/Web/CSS/text-align
import { parse as parseString, toCSSValue as stringToCSSValue } from './string.js';
import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js';
import { isCssVariable, isGlobalKeyword, isKeywordInArray } from '../utils/shared-utils.js';
import { TEXT_ALIGN_KEYWORDS } from '../types.js';
/**
* Checks if a string is a valid text-align keyword
*/
function isTextAlignKeyword(value) {
return isKeywordInArray(value, TEXT_ALIGN_KEYWORDS);
}
/**
* Parses a CSS text-align property string into structured components
* Follows MDN specification: https://developer.mozilla.org/en-US/docs/Web/CSS/text-align
*/
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-align specific keywords
if (isTextAlignKeyword(trimmed)) {
return { type: 'keyword', keyword: trimmed.toLowerCase() };
}
// Handle string values (for custom alignment characters in table cells)
const stringResult = parseString(trimmed);
if (stringResult) {
// Handle CSS variables from string parser
if ('CSSvariable' in stringResult) {
return stringResult;
}
return stringResult;
}
return null;
}
/**
* Converts a parsed text-align value back to a CSS string
*/
export function toCSSValue(parsed) {
if (!parsed) {
return null;
}
// Handle CSS variables
if ('CSSvariable' in parsed) {
return cssVariableToCSSValue(parsed);
}
// Handle keywords
if ('keyword' in parsed) {
// Runtime validation: ensure keyword is actually valid for text-align
if (isGlobalKeyword(parsed.keyword) || isKeywordInArray(parsed.keyword, TEXT_ALIGN_KEYWORDS)) {
return parsed.keyword;
}
// Invalid keyword - return null instead of invalid CSS
return null;
}
// Handle string values (delegate to string evaluator)
if ('value' in parsed && 'quote' in parsed) {
return stringToCSSValue(parsed);
}
return null;
}