-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathon-css-declaration.ts
55 lines (45 loc) · 1.23 KB
/
on-css-declaration.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
import type { Declaration, Result } from 'postcss';
import valueParser from 'postcss-value-parser';
export function onCSSDeclaration(decl: Declaration, result: Result , options: { preserve: boolean }): void {
// alignment
const alignment = decl.prop.match(PLACE_MATCH_REGEX)?.[1].toLowerCase();
if (!alignment) {
return;
}
// value ast and child nodes
let value;
try {
value = valueParser(decl.value);
} catch {
decl.warn(
result,
`Failed to parse value '${decl.value}'. Leaving the original value intact.`,
);
}
if (typeof value === 'undefined') {
return;
}
let alignmentValues: Array<string> = [];
if (!value.nodes.length) {
alignmentValues = [valueParser.stringify(value.nodes)];
} else {
alignmentValues = value.nodes.filter((node) => {
return node.type === 'word' || node.type === 'function';
}).map((node) => {
return valueParser.stringify(node);
});
}
decl.cloneBefore({
prop: `align-${alignment}`,
value: alignmentValues[0],
});
decl.cloneBefore({
prop: `justify-${alignment}`,
value: alignmentValues[1] || alignmentValues[0],
});
// conditionally remove place-[alignment]
if (!options.preserve) {
decl.remove();
}
}
export const PLACE_MATCH_REGEX = /^place-(content|items|self)/i;