/
include.js
178 lines (127 loc) · 4.63 KB
/
include.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import memoize from 'ramda/src/memoize';
import groupBy from 'ramda/src/groupBy';
import identity from 'ramda/src/identity';
import parseUrls from 'css-url-parser';
import parsePath from 'path-parse';
import escapeRegExp from 'escape-string-regexp';
import options from '../helpers/options';
import { coreKey } from '../helpers/keys';
import once from './once';
/**
* @constant includeMap
* @type {Object}
*/
const includeMap = [
{ extensions: ['js'], tag: 'script', attrs: { type: 'text/javascript' } },
{ extensions: ['css'], tag: 'style', attrs: { type: 'text/css' } }
];
/**
* @method fetchInclude
* @param {String} file
* @return {Promise}
*/
const fetchInclude = memoize(file => {
const cssPath = parsePath(file).dir;
const transformPaths = content => {
const urls = parseUrls(content);
// Update the URLs to make them relative to the CSS document.
return urls.length ? urls.map(url => {
const replacer = new RegExp(escapeRegExp(url), 'ig');
return content.replace(replacer, `${cssPath}/${url}`);
}).toString() : content;
};
return new Promise(resolve => {
global.fetch(file).then(response => response.text())
.then(response => transformPaths(response))
.then(resolve)
.catch(() => resolve(''));
});
});
/**
* @method ext
* @param {String} path
* @return {Object}
*/
const ext = path => {
return { path, extension: path.split('.').pop() };
};
/**
* @method fetchIncludes
* @param {Array} files
* @return {Promise}
*/
const fetchIncludes = files => {
// Group all of the files by their extension.
const groupedFiles = groupBy(file => file.extension)(files.map(ext));
const mappedFiles = Object.keys(groupedFiles).map(extension => {
const nodeData = includeMap.find(model => model.extensions.includes(extension));
const files = groupedFiles[extension].map(model => model.path);
const containerNode = document.createElement(nodeData.tag);
// Apply all of the attributes defined in the `includeMap` to the node.
Object.keys(nodeData.attrs).map(key => containerNode.setAttribute(key, nodeData.attrs[key]));
// Load each file individually and then concatenate them.
return Promise.all(files.map(fetchInclude)).then(fileData => {
// Concatenate all of the content from the documents.
containerNode.innerHTML = fileData.reduce((acc, fileDatum) => `${acc} ${fileDatum}`).trim();
return containerNode.innerHTML.length ? containerNode : null;
});
});
return Promise.all(mappedFiles);
};
/**
* @method attachFiles
* @param flags {Number}
* @return {Function}
*/
const attachFiles = flags => once(props => {
return new Promise(resolve => {
const { node, files } = props;
const boundary = node.shadowRoot;
if (files.length !== 0) {
if (flags & options.ASYNC) {
node.classList.add('styling');
node.classList.remove('styled');
}
fetchIncludes(files).then(nodes => {
// Remove any `null` values which means the content of the file was empty, and then append
// them to the component's shadow boundary.
nodes.filter(identity).forEach(node => boundary.appendChild(node));
if (flags & options.ASYNC) {
node.classList.add('styled');
node.classList.remove('styling');
}
resolve();
});
}
});
}, options.RESET);
/**
* @method mergeStylesInto
* @param {String[]|String} files
* @return {Function}
*/
const mergeStylesInto = files => {
return async props => {
const { readFileSync } = require('fs');
const cssFiles = await Promise.all(files.filter(file => ext(file).extension === 'css').map(async file => {
return readFileSync(file);
}));
return { ...props, [coreKey]: { ...props[coreKey], css: cssFiles.join('\n') } };
};
};
/**
* @param {String[]|String} files
* @param {Number} [flags = options.DEFAULT]
* @return {Function}
*/
export default (files, flags = options.DEFAULT) => {
const attach = attachFiles(flags);
const merge = mergeStylesInto([].concat(files));
return props => {
return props.universal ? merge(props) : do {
// Attach the documents using the `once` middleware.
const attached = attach({ ...props, files: [].concat(files) });
flags & options.ASYNC ? props : attached.then(() => props);
};
};
};