88 The above copyright notice and this permission notice shall be
99 included in all copies or substantial portions of this Source Code Form.
1010*/
11- import { parse as parseAst , Value } from 'css-tree' ;
11+ import { parse as parseAst , CssNode , CssNodePlain , List , Value } from 'css-tree' ;
1212import { Input } from 'postcss' ;
1313
1414import { AstError , ParseError } from './errors' ;
@@ -28,6 +28,50 @@ export interface InterpolationOptions {
2828 prefix : string ;
2929}
3030
31+ interface MaybeParent {
32+ children : List < CssNode > | CssNodePlain [ ] ;
33+ }
34+
35+ const assign = ( parent : Nodes . Container , nodes : CssNode [ ] ) => {
36+ for ( const node of nodes ) {
37+ let newNode : Nodes . Container | Nodes . Node ;
38+
39+ switch ( node . type ) {
40+ case 'Function' :
41+ newNode = new Nodes . Func ( { node } ) ;
42+ break ;
43+ case 'Dimension' :
44+ case 'Number' :
45+ newNode = new Nodes . Numeric ( { node } ) ;
46+ break ;
47+ case 'Operator' :
48+ newNode = new Nodes . Operator ( { node } ) ;
49+ break ;
50+ case 'Parentheses' :
51+ newNode = new Nodes . Parens ( { node } ) ;
52+ break ;
53+ case 'UnicodeRange' :
54+ newNode = new Nodes . UnicodeRange ( { node } ) ;
55+ break ;
56+ default :
57+ newNode = new Nodes . Word ( { node } ) ;
58+ break ;
59+ }
60+
61+ const maybeParent = node as unknown as MaybeParent ;
62+
63+ if ( maybeParent . children ) {
64+ let children : CssNode [ ] ;
65+ if ( maybeParent . children instanceof List ) children = maybeParent . children . toArray ( ) ;
66+ else ( { children } = maybeParent as any ) ;
67+
68+ assign ( newNode as Nodes . Container , children ) ;
69+ }
70+
71+ parent . add ( newNode ) ;
72+ }
73+ } ;
74+
3175export const parse = ( css : string , opts ?: ParseOptions ) => {
3276 // @ts -ignore
3377 // eslint-disable-next-line
@@ -55,23 +99,7 @@ export const parse = (css: string, opts?: ParseOptions) => {
5599
56100 if ( ! nodes . length ) throw new AstError ( ) ;
57101
58- for ( const node of nodes ) {
59- switch ( node . type ) {
60- case 'Dimension' :
61- case 'Number' :
62- root . add ( new Nodes . Numeric ( { node } ) ) ;
63- break ;
64- case 'Operator' :
65- root . add ( new Nodes . Operator ( { node } ) ) ;
66- break ;
67- case 'UnicodeRange' :
68- root . add ( new Nodes . UnicodeRange ( { node } ) ) ;
69- break ;
70- default :
71- root . add ( new Nodes . Word ( { node } ) ) ;
72- break ;
73- }
74- }
102+ assign ( root , nodes ) ;
75103
76104 return root ;
77105} ;
0 commit comments