@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
64 lines (63 loc) • 2.1 kB
JavaScript
// Font Stretch property parser
// Handles parsing of CSS font-stretch property values
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-stretch
import { isCssVariable, isGlobalKeyword, getValidKeyword } from '../utils/shared-utils.js';
import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js';
import { parse as parsePercentage, toCSSValue as percentageToCSSValue } from './percentage.js';
// Import centralized types
import { FONT_STRETCH_KEYWORDS } from '../types.js';
/**
* Parse a CSS font-stretch property string
*/
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 font-stretch keywords
const fontStretchKeyword = getValidKeyword(trimmed, FONT_STRETCH_KEYWORDS);
if (fontStretchKeyword) {
return { type: 'keyword', keyword: fontStretchKeyword };
}
// Try parsing as percentage (50% - 200% are valid)
const percentageResult = parsePercentage(trimmed);
if (percentageResult && 'value' in percentageResult) {
const val = percentageResult.value;
// CSS font-stretch allows 50% to 200%
if (val >= 50 && val <= 200) {
return percentageResult;
}
}
return null;
}
/**
* Convert FontStretchValue back to CSS string
*/
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;
}
// Handle percentage values
if ('value' in parsed && 'unit' in parsed) {
return percentageToCSSValue(parsed);
}
return null;
}