|
| 1 | +/** |
| 2 | + * respect https://github.com/cuth/postcss-pxtorem |
| 3 | + */ |
| 4 | +import unitless from '@emotion/unitless'; |
| 5 | +import type { CSSObject } from '..'; |
| 6 | +import type { Transformer } from './interface'; |
| 7 | + |
| 8 | +interface Options { |
| 9 | + /** |
| 10 | + * The root font size. |
| 11 | + * @default 16 |
| 12 | + */ |
| 13 | + rootValue?: number; |
| 14 | + /** |
| 15 | + * The decimal numbers to allow the REM units to grow to. |
| 16 | + * @default 5 |
| 17 | + */ |
| 18 | + precision?: number; |
| 19 | + /** |
| 20 | + * Whether to allow px to be converted in media queries. |
| 21 | + * @default false |
| 22 | + */ |
| 23 | + mediaQuery?: boolean; |
| 24 | +} |
| 25 | + |
| 26 | +const pxRegex = /url\([^)]+\)|var\([^)]+\)|(\d*\.?\d+)px/g; |
| 27 | + |
| 28 | +function toFixed(number: number, precision: number) { |
| 29 | + const multiplier = Math.pow(10, precision + 1), |
| 30 | + wholeNumber = Math.floor(number * multiplier); |
| 31 | + return (Math.round(wholeNumber / 10) * 10) / multiplier; |
| 32 | +} |
| 33 | + |
| 34 | +const transform = (options: Options = {}): Transformer => { |
| 35 | + const { rootValue = 16, precision = 5, mediaQuery = false } = options; |
| 36 | + |
| 37 | + const pxReplace = (m: string, $1: any) => { |
| 38 | + if (!$1) return m; |
| 39 | + const pixels = parseFloat($1); |
| 40 | + // covenant: pixels <= 1, not transform to rem @zombieJ |
| 41 | + if (pixels <= 1) return m; |
| 42 | + const fixedVal = toFixed(pixels / rootValue, precision); |
| 43 | + return `${fixedVal}rem`; |
| 44 | + }; |
| 45 | + |
| 46 | + const visit = (cssObj: CSSObject): CSSObject => { |
| 47 | + const clone: CSSObject = { ...cssObj }; |
| 48 | + |
| 49 | + Object.entries(cssObj).forEach(([key, value]) => { |
| 50 | + if (typeof value === 'string' && value.includes('px')) { |
| 51 | + const newValue = value.replace(pxRegex, pxReplace); |
| 52 | + clone[key] = newValue; |
| 53 | + } |
| 54 | + |
| 55 | + // no unit |
| 56 | + if (!unitless[key] && typeof value === 'number' && value !== 0) { |
| 57 | + clone[key] = `${value}px`.replace(pxRegex, pxReplace); |
| 58 | + } |
| 59 | + |
| 60 | + // Media queries |
| 61 | + const mergedKey = key.trim(); |
| 62 | + if (mergedKey.startsWith('@') && mergedKey.includes('px') && mediaQuery) { |
| 63 | + const newKey = key.replace(pxRegex, pxReplace); |
| 64 | + |
| 65 | + clone[newKey] = clone[key]; |
| 66 | + delete clone[key]; |
| 67 | + } |
| 68 | + }); |
| 69 | + |
| 70 | + return clone; |
| 71 | + }; |
| 72 | + |
| 73 | + return { visit }; |
| 74 | +}; |
| 75 | + |
| 76 | +export default transform; |
0 commit comments