UNPKG

@nex-ui/system

Version:

A lightweight and performant styling library based on Emotion, focusing on component architecture and developer experience.

90 lines (87 loc) 3.54 kB
import { forEach, isString, reduce } from '@nex-ui/utils'; import { extractTokenPlaceholders, isValidTokenCategory, pathToTokenName } from './utils.mjs'; function includeColorPalette(value) { const colorPaletteRegExp = /(?:colors\.)?colorPalette(?:\.\d+)?/; return colorPaletteRegExp.test(value); } function includeColorOpacityModifier(value) { return /\//.test(value); } function resolveColorPalette(colorPalette, value) { if (!colorPalette) { console.error('[Nex UI] system: The color palette was not provided.'); return value; } return value.replace('colorPalette', colorPalette); } function colorMix(color, percent) { return `color-mix(in srgb, ${color} ${percent}%, transparent)`; } const createNormalize = ({ getPropertiesByAlias, getCategoryByProperty, getToken })=>{ function normalizePropValue({ propValue: originalPropValue, category, colorPalette }) { let propValue = originalPropValue; let opacity = null; if (category === 'colors') { if (includeColorOpacityModifier(propValue)) { const pair = propValue.split('/'); const percent = Number(pair[1]); if (pair.length === 2 && !isNaN(percent) && percent >= 0 && percent <= 100) { [propValue, opacity] = pair; } } if (includeColorPalette(propValue)) { propValue = resolveColorPalette(colorPalette, propValue); } } const tokenName = pathToTokenName([ category, propValue ]); const token = getToken(tokenName); if (opacity) { return colorMix(token?.value ?? propValue, opacity); } return token?.value ?? propValue; } function normalze({ propKey, propValue, colorPalette }) { const result = {}; const properties = getPropertiesByAlias(propKey) ?? [ propKey ]; forEach(properties, (property)=>{ if (isString(propValue) && !propValue.startsWith('_EMO_animation')) { // Only string values are supported. Avoid using numbers, as they may inadvertently map to tokens. const matches = extractTokenPlaceholders(propValue); if (matches.length) { // Handle token reference syntax replacements result[property] = reduce(matches, (acc, match)=>{ const placeholder = match[0]; const [category, ...rest] = match[1].split('.'); if (isValidTokenCategory(category)) { return acc.replace(placeholder, normalizePropValue({ colorPalette, category: category, propValue: rest.join('.') })); } return acc; }, propValue); return; } const category = getCategoryByProperty(property); if (category) { result[property] = normalizePropValue({ colorPalette, category, propValue }); return; } } result[property] = propValue; }); return result; } return normalze; }; export { createNormalize };