|
1 | 1 | import { type LengthValue, type LengthUnit } from 'lightningcss'
|
| 2 | +import { validatePositiveInteger } from './utils/errorHandler' |
| 3 | +import type { Config } from './contracts/config.type' |
| 4 | + |
| 5 | +const defultConfig: Config = { |
| 6 | + rootValue: 16, |
| 7 | + unitPrecision: 4 |
| 8 | +} |
| 9 | + |
| 10 | +/** |
| 11 | + * Convert pixel units to rem units. |
| 12 | + * @param {Object} config - The configuration object. |
| 13 | + * @param {number} [config.rootValue=16] - The root value for conversion. (default is 16) |
| 14 | + * @param {number} [config.unitPrecision=4] - The decimal precision for the converted value. (default is 4) |
| 15 | + * @returns {Function} `Length` function to convert pixel values to rem values used by LightningCSS. |
| 16 | + */ |
| 17 | +function pxtorem(config: Partial<Config> = {}) { |
| 18 | + const { rootValue, unitPrecision } = { ...defultConfig, ...config } |
| 19 | + |
| 20 | + validatePositiveInteger(rootValue, 'rootValue') |
| 21 | + validatePositiveInteger(unitPrecision, 'unitPrecision') |
| 22 | + |
| 23 | + const toFixed = (value: number, precision: number): number => { |
| 24 | + const factor = Math.pow(10, precision) |
| 25 | + |
| 26 | + return Math.round(value * factor) / factor |
| 27 | + } |
2 | 28 |
|
3 |
| -export default () => { |
4 | 29 | return {
|
5 | 30 | Length({ unit, value }: LengthValue): { unit: LengthUnit, value: number } | undefined {
|
6 | 31 | if (unit === 'px') {
|
7 |
| - return { unit: 'rem', value: value / 16 } |
| 32 | + return { unit: 'rem', value: toFixed(value / rootValue, unitPrecision) } |
8 | 33 | }
|
9 | 34 | }
|
10 | 35 | }
|
11 | 36 | }
|
| 37 | + |
| 38 | +export default pxtorem |
0 commit comments