UNPKG

@wix/css-property-parser

Version:

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

63 lines (62 loc) 1.98 kB
// Font Weight property parser // Handles parsing of CSS font-weight property values // https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight import { isCssVariable, isGlobalKeyword, getValidKeyword } from '../utils/shared-utils.js'; import { parse as parseCSSVariable, toCSSValue as cssVariableToCSSValue } from './css-variable.js'; import { parse as parseNumber } from './number.js'; // Import centralized types import { FONT_WEIGHT_KEYWORDS } from '../types.js'; /** * Parse a CSS font-weight 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-weight keywords const fontWeightKeyword = getValidKeyword(trimmed, FONT_WEIGHT_KEYWORDS); if (fontWeightKeyword) { return { type: 'keyword', keyword: fontWeightKeyword }; } // Try parsing as number (100-900, typically in steps of 100) const numberResult = parseNumber(trimmed); if (numberResult && 'value' in numberResult) { const val = numberResult.value; // Font weight must be 1-1000 per CSS spec if (val >= 1 && val <= 1000) { return { value: val }; } } return null; } /** * Convert FontWeightValue 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; } if ('value' in parsed) { return parsed.value.toString(); } return null; }