-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrpx2vw.js
46 lines (40 loc) · 1.02 KB
/
rpx2vw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const rpxRegex = /"[^"]+"|'[^']+'|url\([^\)]+\)|(\d*\.?\d+)rpx/g;
const defaults = {
viewportWidth: 750,
viewportUnit: 'vw',
fontViewportUnit: 'vw',
unitPrecision: 5,
};
function toFixed(number, precision) {
const multiplier = Math.pow(10, precision + 1);
const wholeNumber = Math.floor(number * multiplier);
return (Math.round(wholeNumber / 10) * 10) / multiplier;
}
// transform rpx to vw
function createRpxReplace(opts, viewportUnit, viewportSize) {
return function (m, $1) {
if (!$1) {
return m;
}
const pixels = parseFloat($1);
const parsedVal = toFixed(
(pixels / viewportSize) * 100,
opts.unitPrecision
);
return parsedVal + viewportUnit;
};
}
function rpx2vw(str, options = {}) {
const opts = Object.assign({}, defaults, options);
if (typeof str !== 'string') {
return str;
}
if (str.indexOf('rpx') === -1) {
return str;
}
return str.replace(
rpxRegex,
createRpxReplace(opts, opts.viewportUnit, opts.viewportWidth)
);
}
export default rpx2vw;