This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstyles.js
113 lines (85 loc) · 2.31 KB
/
styles.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import Path from 'path';
import Url from 'url';
import Vinyl from 'vinyl';
import Fs from 'pn/fs';
const searchCssUrl = /url\((['"]?)(.+?)\1\)/g,
cssUrlExcludes = /^(\/|data:|http:|https:)/,
urlExcludes = /^(\/\/|http:|https:)/;
function resolveCssUrls(base, path) {
return (match, quote, content) => {
if (cssUrlExcludes.test(content)) {
return match;
}
const sourceName = Path.basename(content),
sourcePath = Path.resolve(Path.dirname(path), Path.dirname(content)),
newSourceRelativePath = Path.relative(base, sourcePath),
newUrl = `url(${quote}${Path.join(newSourceRelativePath, sourceName)}${quote})`;
return newUrl;
};
}
export default class Styles {
base = './';
critical = [];
styles = [];
concated = null;
includesAsync = false;
constructor(base, critical, styles, includesAsync) {
if (typeof base == 'string') {
this.base = base;
}
if (Array.isArray(critical)) {
this.critical = critical;
}
if (Array.isArray(styles)) {
this.styles = styles;
}
this.includesAsync = Boolean(includesAsync);
}
async loadCritical(htmlFileDirname) {
await this.getStyles(this.critical, htmlFileDirname);
return this;
}
async concat(publicPath, filename) {
const publicFilename = Path.join(publicPath, filename),
dest = Path.join(this.base, publicFilename);
const internalStyles = this.styles
.filter(({ href }) => !urlExcludes.test(href));
const styles = await this.getStyles(internalStyles, Path.dirname(dest));
const concatedStyles = styles
.map(({ styles }) => styles)
.join('\n');
this.concated = {
href: publicFilename,
styles: concatedStyles,
file: new Vinyl({
path: dest,
contents: new Buffer(concatedStyles)
}),
importCSS: [publicFilename]
};
return this.concated;
}
async getStyle(href, overrideBase = false) {
const { pathname } = Url.parse(href),
path = Path.join(overrideBase || this.base, pathname);
const styles = await Fs.readFile(path, 'utf8');
return {
path, styles
};
}
getStyles(styles, urlsBase) {
return Promise.all(
styles.map(async (style) => {
const { path, styles } = await this.getStyle(style.href, urlsBase);
style.styles = styles.trim().replace(
searchCssUrl,
resolveCssUrls(
urlsBase,
path
)
);
return style;
})
);
}
}