@wix/css-property-parser
Version:
A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance
83 lines (82 loc) • 2.31 kB
JavaScript
// Blend Mode data type parser
// Handles parsing of CSS blend mode values according to MDN specification
// https://developer.mozilla.org/en-US/docs/Web/CSS/blend-mode
import { isCssVariable, isGlobalKeyword } from '../utils/shared-utils.js';
import { parse as parseCSSVariable } from './css-variable.js';
// CSS blend mode values
const BLEND_MODE_VALUES = [
'normal',
'multiply',
'screen',
'overlay',
'darken',
'lighten',
'color-dodge',
'color-burn',
'hard-light',
'soft-light',
'difference',
'exclusion',
'hue',
'saturation',
'color',
'luminosity'
];
/**
* Parses a CSS blend mode value into structured components
* @param input - The CSS blend mode string
* @returns Parsed blend mode object or null if invalid
*/
export function parse(input) {
if (!input || typeof input !== 'string') {
return null;
}
const trimmed = input.trim();
if (trimmed === '') {
return null;
}
// Check for CSS variables - parse them if valid
if (isCssVariable(trimmed)) {
return parseCSSVariable(trimmed);
}
const lowerValue = trimmed.toLowerCase();
// Check for global keywords first
if (isGlobalKeyword(lowerValue)) {
return {
type: 'blend-mode',
mode: lowerValue
};
}
// Check for blend mode values
if (BLEND_MODE_VALUES.includes(lowerValue)) {
return {
type: 'blend-mode',
mode: lowerValue
};
}
return null;
}
/**
* Converts a parsed blend mode back to a CSS value string
* @param parsed - The parsed blend mode object
* @returns CSS value string or null if invalid
*/
export function toCSSValue(parsed) {
if (!parsed) {
return null;
}
// Handle CSS variables
if ('CSSvariable' in parsed) {
if (parsed.defaultValue) {
return `var(${parsed.CSSvariable}, ${parsed.defaultValue})`;
}
return `var(${parsed.CSSvariable})`;
}
// Handle blend mode values - cast to CSSBlendModeValue after type guard
const blendModeValue = parsed;
// Validate the parsed blend mode
if (typeof blendModeValue.mode !== 'string' || blendModeValue.mode.trim() === '') {
return null;
}
return blendModeValue.mode;
}