UNPKG

@chakra-v2/styled-system

Version:

Style function for css-in-js building component libraries

88 lines (85 loc) 3.05 kB
import { getFilterTemplate, getBackdropFilterTemplate, getRingTemplate, getTransformTemplate, getTransformGpuTemplate, getFlexDirectionTemplate } from './templates.mjs'; import { gradientTransform, isCSSFunction, globalSet } from './parse-gradient.mjs'; function isCssVar(value) { return /^var\(--.+\)$/.test(value); } const analyzeCSSValue = (value) => { const num = parseFloat(value.toString()); const unit = value.toString().replace(String(num), ""); return { unitless: !unit, value: num, unit }; }; const wrap = (str) => (value) => `${str}(${value})`; const transformFunctions = { filter(value, theme) { return value !== "auto" ? value : getFilterTemplate(theme); }, backdropFilter(value, theme) { return value !== "auto" ? value : getBackdropFilterTemplate(theme); }, ring(value, theme) { return getRingTemplate(transformFunctions.px(value), theme); }, bgClip(value) { return value === "text" ? { color: "transparent", backgroundClip: "text" } : { backgroundClip: value }; }, transform(value, theme) { if (value === "auto") return getTransformTemplate(theme); if (value === "auto-gpu") return getTransformGpuTemplate(theme); return value; }, vh(value, theme) { return value === "$100vh" ? `var(--${theme.config.cssVarPrefix}-vh)` : value; }, px(value) { if (value == null) return value; const { unitless } = analyzeCSSValue(value); return unitless || typeof value === "number" ? `${value}px` : value; }, fraction(value) { return !(typeof value === "number") || value > 1 ? value : `${value * 100}%`; }, float(value, theme) { const map = { left: "right", right: "left" }; return theme.direction === "rtl" ? map[value] : value; }, degree(value) { if (isCssVar(value) || value == null) return value; const unitless = typeof value === "string" && !value.endsWith("deg"); return typeof value === "number" || unitless ? `${value}deg` : value; }, gradient: gradientTransform, blur: wrap("blur"), opacity: wrap("opacity"), brightness: wrap("brightness"), contrast: wrap("contrast"), dropShadow: wrap("drop-shadow"), grayscale: wrap("grayscale"), hueRotate: (value) => wrap("hue-rotate")(transformFunctions.degree(value)), invert: wrap("invert"), saturate: wrap("saturate"), sepia: wrap("sepia"), bgImage(value) { if (value == null) return value; const prevent = isCSSFunction(value) || globalSet.has(value); return !prevent ? `url(${value})` : value; }, outline(value) { const isNoneOrZero = String(value) === "0" || String(value) === "none"; return value !== null && isNoneOrZero ? { outline: "2px solid transparent", outlineOffset: "2px" } : { outline: value }; }, flexDirection(value, theme) { const { space, divide } = getFlexDirectionTemplate(theme)[value] ?? {}; const result = { flexDirection: value }; if (space) result[space] = 1; if (divide) result[divide] = 1; return result; } }; export { transformFunctions };