generated from react-component/footer
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathpx2rem.ts
315 lines (280 loc) · 8 KB
/
px2rem.ts
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/**
* respect https://github.com/cuth/postcss-pxtorem
*/
// @ts-ignore
import unitless from '@emotion/unitless';
import { defuArrayFn } from 'defu';
import type { CSSObject } from '..';
import type { Transformer } from './interface';
interface ConvertUnit {
source: string | RegExp;
target: string;
}
interface Options {
/**
* The root font size.
* @default 16
*/
rootValue?: number;
/**
* The decimal numbers to allow the REM units to grow to.
* @default 5
*/
precision?: number;
/**
* Whether to allow px to be converted in media queries.
* @default false
*/
mediaQuery?: boolean;
/**
* The selector blackList.
*
*/
selectorBlackList?: {
/**
* The selector black list.
*/
match?: (string | RegExp)[];
/**
* Whether to deep into the children.
* @default true
*/
deep?: boolean;
};
/**
* The property list to convert.
* @default ['*']
* @example
* ['font-size', 'margin']
*/
propList?: string[];
/**
* The minimum pixel value to transform.
* @default 1
*/
minPixelValue?: number;
/**
* Convert unit on end.
* @default null
* @example
* ```js
* {
* source: /px$/i,
* target: 'px'
* }
* ```
*/
convertUnit?: ConvertUnit | ConvertUnit[] | false | null;
}
const pxRegex = /"[^"]+"|'[^']+'|url\([^)]+\)|--[\w-]+|(\d*\.?\d+)px/g;
export const filterPropList = {
exact(list: string[]) {
return list.filter((m) => m.match(/^[^!*]+$/));
},
contain(list: string[]) {
return list.filter((m) => m.match(/^\*.+\*$/)).map((m) => m.slice(1, -1));
},
endWith(list: string[]) {
return list.filter((m) => m.match(/^\*[^*]+$/)).map((m) => m.slice(1));
},
startWith(list: string[]) {
return list
.filter((m) => m.match(/^[^!*]+\*$/))
.map((m) => m.slice(0, Math.max(0, m.length - 1)));
},
notExact(list: string[]) {
return list.filter((m) => m.match(/^![^*].*$/)).map((m) => m.slice(1));
},
notContain(list: string[]) {
return list.filter((m) => m.match(/^!\*.+\*$/)).map((m) => m.slice(2, -1));
},
notEndWith(list: string[]) {
return list.filter((m) => m.match(/^!\*[^*]+$/)).map((m) => m.slice(2));
},
notStartWith(list: string[]) {
return list.filter((m) => m.match(/^![^*]+\*$/)).map((m) => m.slice(1, -1));
},
};
function createPropListMatcher(propList: string[]) {
const hasWild = propList.includes('*');
const matchAll = hasWild && propList.length === 1;
const lists = {
exact: filterPropList.exact(propList),
contain: filterPropList.contain(propList),
startWith: filterPropList.startWith(propList),
endWith: filterPropList.endWith(propList),
notExact: filterPropList.notExact(propList),
notContain: filterPropList.notContain(propList),
notStartWith: filterPropList.notStartWith(propList),
notEndWith: filterPropList.notEndWith(propList),
};
return function (prop: string) {
if (matchAll) return true;
return (
(hasWild ||
lists.exact.includes(prop) ||
lists.contain.some((m) => prop.includes(m)) ||
lists.startWith.some((m) => prop.indexOf(m) === 0) ||
lists.endWith.some(
(m) => prop.indexOf(m) === prop.length - m.length,
)) &&
!(
lists.notExact.includes(prop) ||
lists.notContain.some((m) => prop.includes(m)) ||
lists.notStartWith.some((m) => prop.indexOf(m) === 0) ||
lists.notEndWith.some((m) => prop.indexOf(m) === prop.length - m.length)
)
);
};
}
function createPxReplace(
rootValue: number,
precision: NonNullable<Options['precision']>,
minPixelValue: NonNullable<Options['minPixelValue']>,
) {
return (m: string, $1: string | null) => {
if (!$1) return m;
const pixels = Number.parseFloat($1);
if (pixels <= minPixelValue) return m;
const fixedVal = toFixed(pixels / rootValue, precision);
return fixedVal === 0 ? '0' : `${fixedVal}rem`;
};
}
function toFixed(number: number, precision: number) {
const multiplier = 10 ** (precision + 1);
const wholeNumber = Math.floor(number * multiplier);
return (Math.round(wholeNumber / 10) * 10) / multiplier;
}
function is(val: unknown, type: string) {
return Object.prototype.toString.call(val) === `[object ${type}]`;
}
function isRegExp(data: unknown): data is RegExp {
return is(data, 'RegExp');
}
function isString(data: unknown): data is string {
return is(data, 'String');
}
function isObject(data: unknown): data is object {
return is(data, 'Object');
}
function isNumber(data: unknown): data is number {
return is(data, 'Number');
}
function blacklistedSelector(blacklist: (string | RegExp)[], selector: string) {
if (!isString(selector)) return;
return blacklist.some((t) => {
if (isString(t)) {
return selector.includes(t);
}
return selector.match(t);
});
}
const SKIP_SYMBOL = Symbol('skip_transform');
function defineSkipSymbol(obj: object) {
Reflect.defineProperty(obj, SKIP_SYMBOL, {
value: true,
enumerable: false,
writable: false,
configurable: false,
});
}
function getSkipSymbol(obj: object) {
return Reflect.get(obj, SKIP_SYMBOL);
}
const uppercasePattern = /([A-Z])/g;
function hyphenateStyleName(name: string): string {
return name.replace(uppercasePattern, '-$1').toLowerCase();
}
function convertUnitFn(value: string, convert: ConvertUnit) {
const { source, target } = convert;
if (isRegExp(source)) {
return value.replace(new RegExp(source), target);
}
return value.replace(new RegExp(`${source}$`), target);
}
const DEFAULT_OPTIONS: Required<Options> = {
rootValue: 16,
precision: 5,
mediaQuery: false,
minPixelValue: 1,
propList: ['*'],
selectorBlackList: { match: [], deep: true },
convertUnit: null,
};
function resolveOptions(options: Options, defaults = DEFAULT_OPTIONS) {
return defuArrayFn(options, defaults);
}
const transform = (options: Options = {}): Transformer => {
const opts = resolveOptions(options);
const {
rootValue,
precision,
minPixelValue,
propList,
mediaQuery,
convertUnit,
selectorBlackList,
} = opts;
const pxReplace = createPxReplace(rootValue, precision, minPixelValue);
const satisfyPropList = createPropListMatcher(propList);
const visit = (cssObj: CSSObject): CSSObject => {
const skip = getSkipSymbol(cssObj);
const clone: CSSObject = { ...cssObj };
if (skip) {
if (selectorBlackList.deep) {
Object.values(clone).forEach((value) => {
if (value && isObject(value)) {
defineSkipSymbol(value);
}
});
}
return clone;
}
Object.entries(cssObj).forEach(([key, value]) => {
if (!isObject(value)) {
if (!satisfyPropList(hyphenateStyleName(key))) {
// Current style property is not in the propList
// Skip
return;
}
if (isString(value) && value.includes('px')) {
const newValue = value.replace(pxRegex, pxReplace);
clone[key] = newValue;
}
// no unit
if (!unitless[key] && isNumber(value) && value !== 0) {
clone[key] = `${value}px`.replace(pxRegex, pxReplace);
}
if (convertUnit && isString(clone[key])) {
const newValue = clone[key] as string;
if (Array.isArray(convertUnit)) {
clone[key] = convertUnit.reduce((c, conv) => {
return convertUnitFn(c, conv);
}, newValue);
} else {
clone[key] = convertUnitFn(newValue, convertUnit);
}
}
} else {
if (blacklistedSelector(selectorBlackList.match || [], key)) {
defineSkipSymbol(value);
return;
}
// Media queries
const mergedKey = key.trim();
if (
mergedKey.startsWith('@') &&
mergedKey.includes('px') &&
mediaQuery
) {
const newKey = key.replace(pxRegex, pxReplace);
clone[newKey] = clone[key];
delete clone[key];
}
}
});
return clone;
};
return { visit };
};
export default transform;