Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
FogNetwork
GitHub Repository: FogNetwork/Tsunami
Path: blob/main/lib/css.js
1036 views
1
// -------------------------------------------------------------
2
// WARNING: this file is used by both the client and the server.
3
// Do not use any browser or node-specific API!
4
// -------------------------------------------------------------
5
const csstree = require('css-tree');
6
7
class CSSRewriter {
8
constructor(ctx) {
9
this.ctx = ctx;
10
};
11
process(source, config = {}) {
12
const ast = csstree.parse(source, {
13
context: config.context || 'stylesheet',
14
parseCustomProperty: true,
15
});
16
const urls = csstree.findAll(ast, node =>
17
node.type == 'Url'
18
);
19
const imports = csstree.findAll(ast, node =>
20
node.type == 'Atrule' && node.name == 'import' && node.prelude && node.prelude.type == 'AtrulePrelude' && node.prelude.children.head.data.type == 'String'
21
);
22
urls.forEach(({ value }) => {
23
switch(value.type) {
24
case 'String':
25
const quote = value.value.substring(0, 1);
26
value.value = quote + this.ctx.url.wrap(value.value.slice(1).slice(0, -1), config) + quote;
27
break;
28
case 'Raw':
29
value.value = this.ctx.url.wrap(value.value, config);
30
break;
31
};
32
});
33
imports.forEach(({ prelude }) => {
34
const { data } = prelude.children.head;
35
const quote = data.value.substring(0, 1);
36
data.value = quote + this.ctx.url.wrap(data.value.slice(1).slice(0, -1), config) + quote;
37
});
38
return csstree.generate(ast);
39
};
40
source(processed, config = {}) {
41
const ast = csstree.parse(processed, {
42
context: config.context || 'stylesheet',
43
parseCustomProperty: true,
44
});
45
const urls = csstree.findAll(ast, node =>
46
node.type == 'Url'
47
);
48
const imports = csstree.findAll(ast, node =>
49
node.type == 'Atrule' && node.name == 'import' && node.prelude && node.prelude.type == 'AtrulePrelude' && node.prelude.children.head.data.type == 'String'
50
);
51
urls.forEach(({ value }) => {
52
switch(value.type) {
53
case 'String':
54
const quote = value.value.substring(0, 1);
55
value.value = quote + this.ctx.url.unwrap(value.value.slice(1).slice(0, -1), config) + quote;
56
break;
57
case 'Raw':
58
value.value = this.ctx.url.unwrap(value.value, config);
59
break;
60
};
61
});
62
imports.forEach(({ prelude }) => {
63
const { data } = prelude.children.head;
64
const quote = data.value.substring(0, 1);
65
data.value = quote + this.ctx.url.unwrap(data.value.slice(1).slice(0, -1), config) + quote;
66
});
67
return csstree.generate(ast);
68
};
69
};
70
71
module.exports = CSSRewriter;
72
73