UNPKG

@chakra-v2/styled-system

Version:

Style function for css-in-js building component libraries

47 lines (45 loc) 1.39 kB
function replaceWhiteSpace(value, replaceValue = "-") { return value.replace(/\s+/g, replaceValue); } function escape(value) { const valueStr = replaceWhiteSpace(value.toString()); return escapeSymbol(escapeDot(valueStr)); } function escapeDot(value) { if (value.includes("\\.")) return value; const isDecimal = !Number.isInteger(parseFloat(value.toString())); return isDecimal ? value.replace(".", `\\.`) : value; } function escapeSymbol(value) { return value.replace(/[!-,/:-@[-^`{-~]/g, "\\$&"); } function addPrefix(value, prefix = "") { return [prefix, value].filter(Boolean).join("-"); } function toVarReference(name, fallback) { return `var(${name}${fallback ? `, ${fallback}` : ""})`; } function toVarDefinition(value, prefix = "") { return escape(`--${addPrefix(value, prefix)}`); } function cssVar(name, fallback, cssVarPrefix) { const cssVariable = toVarDefinition(name, cssVarPrefix); return { variable: cssVariable, reference: toVarReference(cssVariable, fallback) }; } function defineCssVars(scope, keys) { const vars = {}; for (const key of keys) { if (Array.isArray(key)) { const [name, fallback] = key; vars[name] = cssVar(`${scope}-${name}`, fallback); continue; } vars[key] = cssVar(`${scope}-${key}`); } return vars; } export { addPrefix, cssVar, defineCssVars, toVarDefinition, toVarReference };