-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (95 loc) · 2.45 KB
/
index.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const defaults = {
rootValue: 750,
unitPrecision: 5,
selectorBlackList: [],
propList: ["font", "font-size", "line-height", "letter-spacing"],
replace: true,
mediaQuery: false,
minPixelValue: 0,
exclude: null
};
// function toFixed(number, precision) {
// const multiplier = Math.pow(10, precision + 1),
// wholeNumber = Math.floor(number * multiplier);
// return (Math.round(wholeNumber / 10) * 10) / multiplier;
// }
function createPxReplace(rootValue, unitPrecision, minPixelValue) {
return (m, $1) => {
if (!$1) return m;
const pixels = parseFloat($1);
if (pixels < minPixelValue) return m;
const fixedVal = rootValue / 375 * pixels
return fixedVal === 0 ? "0" : fixedVal + "rpx";
};
}
const _type = s =>
Object.prototype.toString
.call(s)
.slice(8, -1)
.toLowerCase();
const types = [
"String",
"Array",
"Undefined",
"Boolean",
"Number",
"Function",
"Symbol",
"Object"
];
const type = types.reduce((acc, str) => {
acc["is" + str] = val => _type(val) === str.toLowerCase();
return acc;
}, {});
/**
* @type {import('postcss').PluginCreator}
*/
module.exports = (options = {}) => {
// Work with options here
const opts = Object.assign({}, defaults, options);
const exclude = opts.exclude;
let isExcludeFile = false;
let pxReplace;
return {
postcssPlugin: 'postcss-pxtorpx',
/*
Root (root, postcss) {
// Transform CSS AST here
}
*/
Once(css) {
const filePath = css.source.input.file;
if (
exclude &&
((type.isFunction(exclude) && exclude(filePath)) ||
(type.isString(exclude) && filePath.indexOf(exclude) !== -1) ||
filePath.match(exclude) !== null)
) {
isExcludeFile = true;
} else {
isExcludeFile = false;
}
const rootValue =
typeof opts.rootValue === "function"
? opts.rootValue(css.source.input)
: opts.rootValue;
pxReplace = createPxReplace(
rootValue,
opts.unitPrecision,
opts.minPixelValue
);
},
Declaration (decl) {
// The faster way to find Declaration node
if (decl.value.indexOf('px') === -1)
return
const value = decl.value.replace(/"[^"]+"|'[^']+'|url\([^)]+\)|var\([^)]+\)|(\d*\.?\d+)px/g, pxReplace);
if (opts.replace) {
decl.value = value;
} else {
decl.cloneAfter({ value: value });
}
}
}
}
module.exports.postcss = true