/
themebuider.js
251 lines (208 loc) · 7.81 KB
/
themebuider.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
const fs = require('fs');
const path = require('path');
const semver = require('semver');
const runCommand = require('../utility/run-command');
const lock = require('../utility/file-lock');
const commands = {
BUILD_THEME: 'build-theme',
BUILD_VARS: 'export-theme-vars',
BUILD_META: 'export-theme-meta'
};
const themeBuilderPackagePath = path.join(__dirname, '..', 'node_modules', 'devextreme-themebuilder');
const scssCompiler = {
render: (scss) => {
return new Promise((resolve, reject) => {
require('node-sass').render({
data: scss
}, (error, result) => {
if(error) {
reject(error);
} else {
resolve(result.css.toString());
}
});
});
}
};
const createPath = filePath => {
const directoryName = path.dirname(filePath);
directoryName
.split(/\\|\//)
.reduce((currentPath, folder) => {
currentPath += folder + path.sep;
if(!fs.existsSync(currentPath)) {
fs.mkdirSync(currentPath);
}
return currentPath;
}, '');
};
const readFile = fileName => new Promise((resolve, reject) => {
fs.readFile(require.resolve(fileName), 'utf8', (error, data) => {
error ? reject(error) : resolve(data);
});
});
const camelCase = str => str.replace(/[-](\w|$)/g, (_, letter) => {
return letter.toUpperCase();
});
const camelize = (object) => {
let result = {};
for(let key in object) {
if(object.hasOwnProperty(key)) {
const newKey = camelCase(key);
result[newKey] = object[key];
}
}
return result;
};
const readInput = options => new Promise(resolve => {
const fileName = options.inputFile;
if(!fileName) resolve();
fs.readFile(fileName, (error, data) => {
if(error) {
console.error(`Unable to read the ${fileName} file.`);
} else {
const extension = path.extname(fileName);
if(extension !== '.json') {
options.data = data;
} else {
const inputObject = JSON.parse(data);
Object.assign(options, inputObject);
}
}
resolve();
});
});
const getMeta = (fullMeta, base, filter, baseParametersList) => {
let result = {};
for(const key in fullMeta) {
if(base && baseParametersList.indexOf(key) === -1) continue;
if(filter && filter.length > 0 && filter.indexOf(key) === -1) continue;
result[key] = fullMeta[key];
}
return result;
};
const installThemeBuilder = async version => {
const packageJsonPath = path.join(themeBuilderPackagePath, 'package.json');
const cwd = path.join(__dirname, '..');
const npmrc = './.npmrc';
const installationNpmrc = path.join(cwd, '.npmrc');
let removeNpmrc = false;
if(fs.existsSync(packageJsonPath) && require(packageJsonPath).version === version) {
return;
}
if(fs.existsSync(npmrc)) {
removeNpmrc = true;
fs.copyFileSync(npmrc, installationNpmrc);
}
await runCommand('npm', [
'install',
'--no-save',
`devextreme-themebuilder@${version}`
], {
cwd,
stdio: 'ignore'
});
if(removeNpmrc) {
fs.unlinkSync(installationNpmrc);
}
};
const getDevExtremeVersion = () => {
const installedDevExtremePackageJson = path.join(process.cwd(), 'node_modules', 'devextreme', 'package.json');
if(fs.existsSync(installedDevExtremePackageJson)) {
return require(installedDevExtremePackageJson).version;
}
return;
};
const setWidgetsOption = (options, version) => {
const widgets = options.widgets;
const widgetsArgumentMinVersion = '19.2.3';
const widgetsOptionAvailable = version === 'latest' || semver.gte(version, widgetsArgumentMinVersion);
if(widgets && !widgetsOptionAvailable) {
console.log(`The "--widgets" argument is supported only starting with v${widgetsArgumentMinVersion} and will be ignored.`);
}
if(typeof widgets === 'string') {
options.widgets = widgets.split(',');
}
};
const getVarsFilter = (options) => {
const vars = options.vars || [];
return (vars instanceof Array) ? vars : vars.split(',');
};
const runThemeBuilder = async rawOptions => {
const options = camelize(rawOptions);
await readInput(options);
options.reader = readFile;
options.sassCompiler = scssCompiler;
options.lessCompiler = require('less/lib/less-node');
options.lessCompiler.options = options.lessCompiler.options || {};
options.lessCompiler.options['math'] = 'always';
options.lessCompiler.options['paths'] = [ path.join(themeBuilderPackagePath, 'data', 'less', 'bundles') ];
if(options.assetsBasePath) {
options.lessCompiler.options['rootpath'] = options.assetsBasePath;
}
const version = options.version || getDevExtremeVersion() || 'latest';
await lock.acquire();
try {
console.log(`Using version ${version}.`);
await installThemeBuilder(version);
} catch(e) {
console.log(`The devextreme-themebuilder npm package of v${version} was not installed. Please verify you are using v18.2.5 or higher and examine the installation error log to further troubleshoot the issue.`);
return;
}
const themeBuilder = require('devextreme-themebuilder/modules/builder');
const baseParameters = require('devextreme-themebuilder/modules/base-parameters');
lock.release();
setWidgetsOption(options, version);
let content = '';
const result = await themeBuilder.buildTheme(options);
const filter = getVarsFilter(options);
createPath(options.out);
if(options.command === commands.BUILD_THEME) {
content = result.css;
if(result.swatchSelector) {
console.log(`Add the '${result.swatchSelector}' class to the container to apply swatch styles to its nested elements.`);
}
if(result.unusedWidgets && result.unusedWidgets.length) {
console.log('Styles for the following widgets were not included in the resulting theme because these widgets don\'t use CSS styles:\n');
result.unusedWidgets.forEach(w => console.log(`${w}\n`));
}
} else if(options.command === commands.BUILD_VARS) {
const metadata = getMeta(result.compiledMetadata, options.base, filter, baseParameters);
for(const metadataKey in metadata) {
const formatKey = options.fileFormat === 'scss' ? metadataKey.replace('@', '$') : metadataKey;
content += formatKey + ': ' + metadata[metadataKey] + ';\n';
}
} else if(options.command === commands.BUILD_META) {
const metadata = getMeta(result.compiledMetadata, options.base, filter, baseParameters);
let exportedMeta = [];
for(const metadataKey in metadata) {
exportedMeta.push({ key: metadataKey, value: metadata[metadataKey] });
}
const meta = {
baseTheme: [ options.themeName, options.colorScheme.replace(/-/g, '.') ].join('.'),
items: exportedMeta,
version: result.version
};
if(result.widgets) {
Object.assign(meta, { widgets: result.widgets });
}
content = JSON.stringify(meta, ' ', 4);
}
fs.writeFile(options.out, content, 'utf8', error => {
if(error) {
console.log(`Unable to write the ${options.out} file. ${error.message}`);
} else {
console.log(`The result was written to the ${options.out} file.`);
}
});
};
const isThemeBuilderCommand = command => {
for(const commandKey in commands) {
if(commands[commandKey] === command) return true;
}
return false;
};
module.exports = {
run: runThemeBuilder,
isThemeBuilderCommand: isThemeBuilderCommand
};