forked from csstools/postcss-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
111 lines (89 loc) · 2.43 KB
/
Copy pathindex.ts
File metadata and controls
111 lines (89 loc) · 2.43 KB
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
import type { PluginCreator } from 'postcss';
import { hasFallback, hasSupportsAtRuleAncestor } from '@csstools/utilities';
import { DirectionFlow } from './lib/types';
import { transform } from './transform';
import { predicate } from './has-feature';
export type { DirectionFlow } from './lib/types';
/** postcss-logical-viewport-units plugin options */
export type pluginOptions = {
/** Preserve the original notation. default: false */
preserve?: boolean,
/** Sets the direction for inline. default: left-to-right */
inlineDirection?: DirectionFlow,
};
const HAS_VIEWPORT_UNITS_REGEX = /(?:vi|vb)\b/i;
const creator: PluginCreator<pluginOptions> = (opts?: pluginOptions) => {
const options = Object.assign(
// Default options
{
inlineDirection: DirectionFlow.LeftToRight,
preserve: true,
},
// Provided options
opts,
);
switch (options.inlineDirection) {
case DirectionFlow.LeftToRight:
case DirectionFlow.RightToLeft:
case DirectionFlow.TopToBottom:
case DirectionFlow.BottomToTop:
break;
default:
throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(DirectionFlow).join(', ')}`);
}
const isHorizontal = [DirectionFlow.LeftToRight, DirectionFlow.RightToLeft].includes(options.inlineDirection);
const replacements: { vi: 'vw' | 'vh', vb: 'vw' | 'vh' } = {
vb: 'vh',
vi: 'vw',
};
if (!isHorizontal) {
replacements.vb = 'vw';
replacements.vi = 'vh';
}
return {
postcssPlugin: 'postcss-logical-viewport-units',
Declaration(decl, { atRule }): void {
{
if (!HAS_VIEWPORT_UNITS_REGEX.test(decl.value)) {
return;
}
if (hasFallback(decl)) {
return;
}
// Is wrapped in a relevant `@supports`
if (hasSupportsAtRuleAncestor(decl, predicate)) {
return;
}
}
const modifiedValue = transform(decl.value, replacements);
if (modifiedValue === decl.value) {
return;
}
decl.cloneBefore({
value: modifiedValue,
});
if (!options.preserve) {
decl.remove();
return;
}
if (!decl.variable) {
return;
}
const supports = atRule({
name: 'supports',
params: '(top: 1vi)',
source: decl.source,
});
const parent = decl.parent;
if (!parent) {
return;
}
const parentClone = parent.cloneAfter({ nodes: [] });
parentClone.append(decl);
supports.append(parentClone);
parent.after(supports);
},
};
};
creator.postcss = true;
export default creator;