1
1
import { svg , shape } from 'css-doodle/generator' ;
2
2
import valueParser from 'postcss-value-parser' ;
3
3
4
+ const KEYWORDS = [ '@svg' , '@shape' ] ;
5
+
4
6
export default function plugin ( ) {
5
7
return {
6
8
postcssPlugin : "postcss-doodle" ,
7
9
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
20
16
}
21
- decl . value = parsed . toString ( ) ;
22
17
}
23
18
}
24
19
}
25
20
26
21
plugin . postcss = true ;
27
22
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
+
28
39
function getInput ( nodes ) {
29
40
let result = '' , argResult = '' ;
30
41
let args = [ ] ;
@@ -34,7 +45,7 @@ function getInput(nodes) {
34
45
let value = `${ node . value } (${ getInput ( node . nodes ) . result } )` ;
35
46
result += value ;
36
47
argResult += value ;
37
- } else {
48
+ } else {
38
49
if ( node . type === 'div' && node . value === ',' ) {
39
50
args . push ( argResult ) ;
40
51
argResult = '' ;
@@ -50,10 +61,6 @@ function getInput(nodes) {
50
61
return { result, args } ;
51
62
}
52
63
53
- function isKeyword ( name ) {
54
- return name === '@svg' || name === '@shape' ;
55
- }
56
-
57
64
function wrapSVG ( input ) {
58
65
return `url(data:image/svg+xml;utf8,${ encodeURIComponent ( input ) } )` ;
59
66
}
0 commit comments