-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathindex.ts
86 lines (65 loc) · 1.63 KB
/
index.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
import type { PluginCreator } from 'postcss';
import valueParser from 'postcss-value-parser';
import mappings from './mappings';
function transform(value: string) {
const { nodes } = valueParser(value);
if (nodes.length === 1) {
return value;
}
const values = nodes
.filter((node) => node.type === 'word') // only display values
.map((node) => node.value.toLowerCase()); // to lower case
if (values.length <= 1) {
return value;
}
const match = mappings.get(values.join(','));
if (!match) {
return value;
}
return match;
}
/** postcss-normalize-display-values plugin options */
export type pluginOptions = {
/** Preserve the original notation. default: true */
preserve?: boolean,
};
const creator: PluginCreator<pluginOptions> = (opts?: pluginOptions) => {
const preserve = 'preserve' in Object(opts) ? Boolean(opts?.preserve) : true;
return {
postcssPlugin: 'postcss-normalize-display-values',
prepare() {
const cache = new Map();
return {
Declaration(decl) {
if (decl.prop.toLowerCase() !== 'display') {
return;
}
const value = decl.value;
if (!value) {
return;
}
if (cache.has(value)) {
if (decl.value !== cache.get(value)) {
decl.cloneBefore({ value: cache.get(value) });
if (!preserve) {
decl.remove();
}
}
return;
}
const result = transform(value);
cache.set(value, result);
if (decl.value === result) {
return;
}
decl.cloneBefore({ value: result });
if (!preserve) {
decl.remove();
}
},
};
},
};
};
creator.postcss = true;
export default creator;