diff options
author | Sebastian <sebasjm@gmail.com> | 2021-08-23 16:46:06 -0300 |
---|---|---|
committer | Sebastian <sebasjm@gmail.com> | 2021-08-23 16:48:30 -0300 |
commit | 38acabfa6089ab8ac469c12b5f55022fb96935e5 (patch) | |
tree | 453dbf70000cc5e338b06201af1eaca8343f8f73 /@linaria/packages/babel/src/utils/toCSS.ts | |
parent | f26125e039143b92dc0d84e7775f508ab0cdcaa8 (diff) | |
download | node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.tar.gz node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.tar.bz2 node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.zip |
Diffstat (limited to '@linaria/packages/babel/src/utils/toCSS.ts')
-rw-r--r-- | @linaria/packages/babel/src/utils/toCSS.ts | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/@linaria/packages/babel/src/utils/toCSS.ts b/@linaria/packages/babel/src/utils/toCSS.ts new file mode 100644 index 0000000..b396087 --- /dev/null +++ b/@linaria/packages/babel/src/utils/toCSS.ts @@ -0,0 +1,57 @@ +import { unitless } from '../units'; +import type { JSONValue } from '../types'; +import isSerializable from './isSerializable'; +import isBoxedPrimitive from './isBoxedPrimitive'; + +const hyphenate = (s: string) => { + if (s.startsWith('--')) { + // It's a custom property which is already well formatted. + return s; + } + return ( + s + // Hyphenate CSS property names from camelCase version from JS string + .replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`) + // Special case for `-ms` because in JS it starts with `ms` unlike `Webkit` + .replace(/^ms-/, '-ms-') + ); +}; + +// Some tools such as polished.js output JS objects +// To support them transparently, we convert JS objects to CSS strings +export default function toCSS(o: JSONValue): string { + if (Array.isArray(o)) { + return o.map(toCSS).join('\n'); + } + + if (isBoxedPrimitive(o)) { + return o.valueOf().toString(); + } + + return Object.entries(o) + .filter( + ([, value]) => + // Ignore all falsy values except numbers + typeof value === 'number' || value + ) + .map(([key, value]) => { + if (isSerializable(value)) { + return `${key} { ${toCSS(value)} }`; + } + + return `${hyphenate(key)}: ${ + typeof value === 'number' && + value !== 0 && + // Strip vendor prefixes when checking if the value is unitless + !( + key.replace( + /^(Webkit|Moz|O|ms)([A-Z])(.+)$/, + (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}` + ) in unitless + ) + ? `${value}px` + : value + };`; + }) + .join(' '); +} |