Skip to content

Commit a21ba2e

Browse files
committed
Improve nodes transform
1 parent 02cc32b commit a21ba2e

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

index.js

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,41 @@
11
import { svg, shape } from 'css-doodle/generator';
22
import valueParser from 'postcss-value-parser';
33

4+
const KEYWORDS = ['@svg', '@shape'];
5+
46
export default function plugin() {
57
return {
68
postcssPlugin: "postcss-doodle",
79
Declaration(decl) {
8-
let parsed = valueParser(decl.value);
9-
for (let node of parsed.nodes) {
10-
if (node.type === 'function' && isKeyword(node.value)) {
11-
let { result, args } = getInput(node.nodes);
12-
node.type = 'word'
13-
if (node.value === '@svg') {
14-
node.value = wrapSVG(svg(result));
15-
}
16-
if (node.value === '@shape') {
17-
node.value = shape(...args);
18-
}
19-
}
10+
try {
11+
let parsed = valueParser(decl.value);
12+
parsed.nodes = transformNodes(parsed.nodes);
13+
decl.value = parsed.toString();
14+
} catch (e) {
15+
// fail silently
2016
}
21-
decl.value = parsed.toString();
2217
}
2318
}
2419
}
2520

2621
plugin.postcss = true;
2722

23+
function transformNodes(nodes) {
24+
return nodes.map(node => {
25+
if (node.type === 'function' && KEYWORDS.includes(node.value)) {
26+
const { result, args } = getInput(node.nodes);
27+
node.type = 'word';
28+
if (node.value === '@svg') {
29+
node.value = wrapSVG(svg(result));
30+
}
31+
if (node.value === '@shape') {
32+
node.value = shape(...args);
33+
}
34+
}
35+
return node;
36+
});
37+
}
38+
2839
function getInput(nodes) {
2940
let result = '', argResult = '';
3041
let args = [];
@@ -34,7 +45,7 @@ function getInput(nodes) {
3445
let value = `${node.value}(${getInput(node.nodes).result})`;
3546
result += value;
3647
argResult += value;
37-
} else {
48+
} else {
3849
if (node.type === 'div' && node.value === ',') {
3950
args.push(argResult);
4051
argResult = '';
@@ -50,10 +61,6 @@ function getInput(nodes) {
5061
return { result, args };
5162
}
5263

53-
function isKeyword(name) {
54-
return name === '@svg' || name === '@shape';
55-
}
56-
5764
function wrapSVG(input) {
5865
return `url(data:image/svg+xml;utf8,${ encodeURIComponent(input) })`;
5966
}

0 commit comments

Comments
 (0)