forked from SAP/less-openui5
/
index.js
402 lines (331 loc) · 13.4 KB
/
index.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
"use strict";
const path = require("path");
const css = require("@adobe/css-tools");;
const diff = require("./diff");
const scope = require("./scope");
const fileUtilsFactory = require("./fileUtils");
const Compiler = require("./Compiler");
const themingParametersDataUri = require("./themingParameters/dataUri");
// Workaround for a performance issue in the "css" parser module when used in combination
// with the "colors" module that enhances the String prototype.
// See: https://github.com/reworkcss/css/issues/88
//
// This function removes all properties added by "colors" and returns a function
// that restores them afterwards.
// To be used before/after calling "css.parse"
function cleanupStringPrototype() {
const customGetters = {}; const customProps = {}; const s = ""; let key;
for (key in s) {
if (!Object.prototype.hasOwnProperty.call(s, key)) {
const getter = String.prototype.__lookupGetter__(key);
if (typeof getter === "function") {
customGetters[key] = getter;
} else {
customProps[key] = String.prototype[key];
}
if (typeof Reflect !== "undefined") {
Reflect.deleteProperty(String.prototype, key);
} else {
delete String.prototype[key];
}
}
}
return function restore() {
for (key in customGetters) {
if (Object.prototype.hasOwnProperty.call(customGetters, key)) {
String.prototype.__defineGetter__(key, customGetters[key]);
}
}
for (key in customProps) {
if (Object.prototype.hasOwnProperty.call(customProps, key)) {
// eslint-disable-next-line no-extend-native
String.prototype[key] = customProps[key];
}
}
};
}
function dotThemingFileToPath(s) {
if (s.indexOf(".") > -1) {
s = "../" + s.replace(/\./g, "/");
}
return s;
}
const Builder = function(options) {
this.themeCacheMapping = {};
this.customFs = options ? options.fs : null;
this.fileUtils = fileUtilsFactory(this.customFs);
};
Builder.prototype.getThemeCache = function(rootPath) {
return this.themeCacheMapping[rootPath];
};
Builder.prototype.setThemeCache = function(rootPath, cache) {
return this.themeCacheMapping[rootPath] = cache;
};
Builder.prototype.clearCache = function() {
this.themeCacheMapping = {};
};
Builder.prototype.cacheTheme = function(result) {
const that = this;
// Theme can only be cached if list of imports is available
if (result.imports.length === 0) {
return Promise.resolve(result);
}
// Rootpath of theme is always the first entry
const rootpath = result.imports[0];
return that.fileUtils.statFiles(result.imports).then(function(stats) {
that.setThemeCache(rootpath, {
result: result,
stats: stats
});
return result;
});
};
/**
* Runs a theme build
* @param {object} options
* @param {object} options.compiler compiler object as passed to less
* @param {boolean} options.cssVariables whether or not to enable css variables output
* @param {string} options.lessInput less string input
* @param {string} options.lessInputPath less file input
* @returns {{css: string, cssRtl: string, variables: {}, imports: [], cssSkeleton: string, cssSkeletonRtl: string, cssVariables: string, cssVariablesSource: string }}
*/
Builder.prototype.build = function(options) {
const that = this;
// Assign default options
options = Object.assign({
lessInput: null,
lessInputPath: null,
rtl: true,
rootPaths: [],
parser: {},
compiler: {},
library: {},
scope: {}
}, options);
if (options.compiler.sourceMap) {
return Promise.reject(new Error("compiler.sourceMap option is not supported!"));
}
if (options.compiler.cleancss) {
return Promise.reject(new Error("compiler.cleancss option is not supported! Please use 'clean-css' directly."));
}
// Set default of "relativeUrls" parser option to "true" (less default is "false")
if (!Object.prototype.hasOwnProperty.call(options.parser, "relativeUrls")) {
options.parser.relativeUrls = true;
}
const compiler = new Compiler({
options,
fileUtils: this.fileUtils,
customFs: this.customFs
});
function addInlineParameters(result) {
return themingParametersDataUri.addInlineParameters({result, options});
}
function getScopeVariables(options) {
const sScopeName = options.scopeName;
const oVariablesBase = options.baseVariables;
const oVariablesEmbedded = options.embeddedVariables;
const oVariablesDiff = {};
for (const sKey in oVariablesEmbedded) {
if (sKey in oVariablesBase) {
if (oVariablesBase[sKey] != oVariablesEmbedded[sKey]) {
oVariablesDiff[sKey] = oVariablesEmbedded[sKey];
}
}
}
// Merge variables
const oVariables = {};
oVariables["default"] = oVariablesBase;
oVariables["scopes"] = {};
oVariables["scopes"][sScopeName] = oVariablesDiff;
return oVariables;
}
function compileWithScope(scopeOptions) {
// 1. Compile base + embedded files (both default + RTL variants)
return Promise.all([
that.fileUtils.readFile(scopeOptions.embeddedCompareFilePath, options.rootPaths).then(function(config) {
if (!config) {
throw new Error("Could not find embeddedCompareFile at path '" + scopeOptions.embeddedCompareFilePath + "'");
}
return compiler.compile(config);
}),
that.fileUtils.readFile(scopeOptions.embeddedFilePath, options.rootPaths).then(function(config) {
if (!config) {
throw new Error("Could not find embeddedFile at path '" + scopeOptions.embeddedFilePath + "'");
}
return compiler.compile(config);
})
]).then(function(results) {
return {
embeddedCompare: results[0],
embedded: results[1]
};
}).then(function(results) {
const sScopeName = scopeOptions.selector;
function applyScope(embeddedCompareCss, embeddedCss, bRtl) {
const restoreStringPrototype = cleanupStringPrototype();
// Create diff object between embeddedCompare and embedded
const oBase = css.parse(embeddedCompareCss);
const oEmbedded = css.parse(embeddedCss);
restoreStringPrototype();
const oDiff = diff(oBase, oEmbedded);
// Create scope
const sScopeSelector = "." + sScopeName;
const oScope = scope(oDiff.diff, sScopeSelector);
let oCssScopeRoot;
if (oDiff.stack) {
oCssScopeRoot = scope.scopeCssRoot(oDiff.stack.stylesheet.rules, sScopeName);
if (oCssScopeRoot) {
oScope.stylesheet.rules.unshift(oCssScopeRoot);
}
}
// Append scope + stack to embeddedCompareFile (actually target file, which is currently always the same i.e. "library.css")
// The stack gets appended to the embeddedFile only
let sAppend = css.stringify(oScope, {
compress: options.compiler && options.compiler.compress === true
});
if (scopeOptions.baseFilePath !== options.lessInputPath && oDiff.stack && oDiff.stack.stylesheet.rules.length > 0) {
sAppend += "\n" + css.stringify(oDiff.stack, {
compress: options.compiler && options.compiler.compress === true
});
}
return sAppend + "\n";
}
results.embeddedCompare.css += applyScope(results.embeddedCompare.css, results.embedded.css);
if (options.rtl) {
results.embeddedCompare.cssRtl += applyScope(results.embeddedCompare.cssRtl, results.embedded.cssRtl, true);
}
if (options.cssVariables) {
results.embeddedCompare.cssVariables += applyScope(results.embeddedCompare.cssVariables, results.embedded.cssVariables);
results.embeddedCompare.cssSkeleton += applyScope(results.embeddedCompare.cssSkeleton, results.embedded.cssSkeleton);
if (options.rtl) {
results.embeddedCompare.cssSkeletonRtl += applyScope(results.embeddedCompare.cssSkeletonRtl, results.embedded.cssSkeletonRtl, true);
}
}
// Create diff between embeddedCompare and embeded variables
results.embeddedCompare.variables = getScopeVariables({
baseVariables: results.embeddedCompare.variables,
embeddedVariables: results.embedded.variables,
scopeName: sScopeName
});
results.embeddedCompare.allVariables = getScopeVariables({
baseVariables: results.embeddedCompare.allVariables,
embeddedVariables: results.embedded.allVariables,
scopeName: sScopeName
});
const concatImports = function(aImportsBase, aImportsEmbedded) {
const aConcats = aImportsBase.concat(aImportsEmbedded);
return aConcats.filter(function(sImport, sIndex) {
return aConcats.indexOf(sImport) == sIndex;
});
};
if (scopeOptions.baseFilePath !== options.lessInputPath) {
results.embeddedCompare.imports = concatImports(results.embedded.imports, results.embeddedCompare.imports);
} else {
results.embeddedCompare.imports = concatImports(results.embeddedCompare.imports, results.embedded.imports);
}
// 6. Resolve promise with complete result object (css, cssRtl, variables, imports)
return results.embeddedCompare;
});
}
function readDotTheming(dotThemingInputPath) {
return that.fileUtils.readFile(dotThemingInputPath, options.rootPaths).then(function(result) {
let dotTheming;
let dotThemingFilePath;
if (result) {
dotTheming = JSON.parse(result.content);
dotThemingFilePath = result.path;
}
if (dotTheming && dotTheming.mCssScopes) {
// Currently only the "library" target is supported
const cssScope = dotTheming.mCssScopes["library"];
if (cssScope) {
const aScopes = cssScope.aScopes;
const oScopeConfig = aScopes[0]; // Currenlty only one scope is supported
const sBaseFile = dotThemingFileToPath(cssScope.sBaseFile);
const sEmbeddedCompareFile = dotThemingFileToPath(oScopeConfig.sEmbeddedCompareFile);
const sEmbeddedFile = dotThemingFileToPath(oScopeConfig.sEmbeddedFile);
// Currently, only support the use case when "sBaseFile" equals "sEmbeddedCompareFile"
if (sBaseFile !== sEmbeddedCompareFile) {
throw new Error("Unsupported content in \"" + dotThemingInputPath + "\": " +
"\"sBaseFile\" (\"" + cssScope.sBaseFile + "\") must be identical with " +
"\"sEmbeddedCompareFile\" (\"" + oScopeConfig.sEmbeddedCompareFile + "\")");
}
const baseFilePath = path.posix.join(themeDir, sBaseFile) + ".source.less";
const embeddedCompareFilePath = path.posix.join(themeDir, sEmbeddedCompareFile) + ".source.less";
const embeddedFilePath = path.posix.join(themeDir, sEmbeddedFile) + ".source.less";
// 1. Compile base + embedded files (both default + RTL variants)
return compileWithScope({
selector: oScopeConfig.sSelector,
embeddedFilePath: embeddedFilePath,
embeddedCompareFilePath: embeddedCompareFilePath,
baseFilePath: baseFilePath
}).then(function(embeddedCompare) {
embeddedCompare.imports.push(dotThemingFilePath);
return embeddedCompare;
});
}
}
// No css diffing and scoping
return that.fileUtils.readFile(options.lessInputPath, options.rootPaths).then((config) => {
return compiler.compile(config);
});
});
}
if (options.lessInput && options.lessInputPath) {
return Promise.reject(new Error("Please only provide either `lessInput` or `lessInputPath` but not both."));
}
if (!options.lessInput && !options.lessInputPath) {
return Promise.reject(new Error("Missing required option. Please provide either `lessInput` or `lessInputPath`."));
}
if (options.lessInput) {
return compiler.compile({
content: options.lessInput
}).then(addInlineParameters).then(that.cacheTheme.bind(that));
} else {
// TODO: refactor
// eslint-disable-next-line no-var
var themeDir = path.posix.dirname(options.lessInputPath);
// Always use the sap/ui/core library to lookup .theming files
let coreThemeDir;
if (options.library && typeof options.library.name === "string") {
const libraryNamespace = options.library.name.replace(/\./g, "/");
coreThemeDir = themeDir.replace(libraryNamespace, "sap/ui/core");
} else {
coreThemeDir = themeDir.replace(/^.*\/themes\//, "/sap/ui/core/themes/");
}
const dotThemingInputPath = path.posix.join(coreThemeDir, ".theming");
return that.fileUtils.findFile(options.lessInputPath, options.rootPaths).then(function(fileInfo) {
if (!fileInfo) {
throw new Error("`lessInputPath` " + options.lessInputPath + " could not be found.");
}
// check theme has been already cached
let themeCache;
if (fileInfo.path) {
themeCache = that.getThemeCache(fileInfo.path);
}
const scopeOptions = options.scope;
// Compile theme if not cached or RTL is requested and missing in cache
if (!themeCache || (options.rtl && !themeCache.result.cssRtl)) {
if (scopeOptions.selector && scopeOptions.embeddedFilePath && scopeOptions.embeddedCompareFilePath && scopeOptions.baseFilePath) {
return compileWithScope(scopeOptions).then(addInlineParameters).then(that.cacheTheme.bind(that));
}
return readDotTheming(dotThemingInputPath).then(addInlineParameters).then(that.cacheTheme.bind(that));
} else {
return that.fileUtils.statFiles(themeCache.result.imports).then(function(newStats) {
for (let i = 0; i < newStats.length; i++) {
// check if .theming and less files have changed since last less compilation
if (!newStats[i] || newStats[i].stat.mtime.getTime() !== themeCache.stats[i].stat.mtime.getTime()) {
if (scopeOptions.selector && scopeOptions.embeddedFilePath && scopeOptions.embeddedCompareFilePath && scopeOptions.baseFilePath) {
return compileWithScope(scopeOptions).then(addInlineParameters).then(that.cacheTheme.bind(that));
}
return readDotTheming(dotThemingInputPath).then(addInlineParameters).then(that.cacheTheme.bind(that));
}
}
// serve from cache
return themeCache.result;
});
}
});
}
};
module.exports.Builder = Builder;