-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathparser.js
67 lines (61 loc) · 1.87 KB
/
parser.js
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
const importRegexp = /^:import\((.+)\)$/
export default class Parser {
constructor( pathFetcher ) {
this.pathFetcher = pathFetcher
this.plugin = this.plugin.bind( this )
this.exportTokens = {}
this.translations = {}
}
plugin( css, result ) {
return this.fetchAllImports( css )
.then( _ => this.extractExports( css ) )
}
fetchAllImports( css ) {
let imports = []
css.each( node => {
if ( node.type == "rule" && node.selector.match( importRegexp ) ) {
imports.push( this.fetchImport( node, css.source.input.from ) )
}
} )
return Promise.all( imports )
.then( fetchedState => {
return Promise.all( fetchedState.map(
( {loaderData, propResolver} ) =>
this.pathFetcher.load( loaderData ).then( propResolver )
) )
} )
}
extractExports( css ) {
css.each( node => {
if ( node.type == "rule" && node.selector == ":export" ) this.handleExport( node )
} )
}
handleExport( exportNode ) {
exportNode.each( decl => {
if ( decl.type == 'decl' ) {
Object.keys( this.translations ).forEach( translation => {
decl.value = decl.value.replace( translation, this.translations[translation] )
} )
this.exportTokens[decl.prop] = decl.value
}
} )
exportNode.removeSelf()
}
fetchImport( importNode, relativeTo ) {
let file = importNode.selector.match( importRegexp )[1]
console.log("FETCHING " + file)
return this.pathFetcher.fetch( file, relativeTo )
.then( state => {
state.propResolver = exports => {
console.log("RESOLVING " + file)
importNode.each( decl => {
if ( decl.type == 'decl' ) {
this.translations[decl.value] = exports[decl.prop]
}
} )
importNode.removeSelf()
}
return state
})
}
}