Skip to content

Commit 242dc71

Browse files
committed
feat(pxtorem): add configuration interface and validation for rootValue and unitPrecision
1 parent 1ffbad5 commit 242dc71

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export interface Config {
2+
rootValue: number
3+
unitPrecision: number
4+
}

packages/pxtorem/src/index.ts

+29-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,38 @@
11
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+
}
228

3-
export default () => {
429
return {
530
Length({ unit, value }: LengthValue): { unit: LengthUnit, value: number } | undefined {
631
if (unit === 'px') {
7-
return { unit: 'rem', value: value / 16 }
32+
return { unit: 'rem', value: toFixed(value / rootValue, unitPrecision) }
833
}
934
}
1035
}
1136
}
37+
38+
export default pxtorem
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
export function validatePositiveInteger(value: number | undefined, name: string) {
2+
if (typeof value !== 'number' || isNaN(value)) {
3+
throw new Error(`Invalid ${name}: must be a valid number.`)
4+
}
5+
6+
if (value < 0) {
7+
throw new Error(`Invalid ${name}: must not be negative.`)
8+
}
9+
10+
if (!Number.isInteger(value)) {
11+
throw new Error(`Invalid ${name}: must not be a decimal.`)
12+
}
13+
}

0 commit comments

Comments
 (0)