This repository has been archived by the owner on Jan 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
417 lines (379 loc) · 14.7 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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
module.exports = function (gulp) {
/* Dependencies (A-Z) */
var _ = require('lodash-node');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var cached = require('gulp-cached');
var del = require('del');
var gulpif = require('gulp-if');
var filter = require('gulp-filter');
var imagemin = require('gulp-imagemin');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
var fs = require('fs');
var karma = require('gulp-karma');
var less = require('gulp-less');
var markdownIt = require('markdown-it');
var moduleUtility = require('./lib/module-utility');
var newer = require('gulp-newer');
var nunjucksRender = require('./lib/nunjucks-render');
var path = require('path');
var plumber = require('gulp-plumber');
var pngquant = require('imagemin-pngquant');
var prism = require('./lib/prism');
var recess = require('gulp-recess');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var rjs = require('requirejs');
var runGulpSequence = require('run-sequence').use(gulp);
var sourcemaps = require('gulp-sourcemaps');
var zip = require('gulp-zip');
/* Shared configuration (A-Z) */
var config = require('./lib/config.js');
var filesToCopy = config.filesToCopy;
var paths = config.paths;
var pkg = require('./package.json');
function configure(options) {
config = _.extend(config, options);
}
function taskSettings(options) {
return _.extend({}, config, options || {});
}
function configureNunjucks() {
var env = nunjucksRender.nunjucks.configure(paths.src, {watch: false});
env.addFilter('match', require('./lib/nunjucks-filter-match'));
env.addFilter('prettyJson', require('./lib/nunjucks-filter-pretty-json'));
}
function getFileContents(path) {
if (fs.existsSync(path)) {
return fs.readFileSync(path, 'utf8');
} else {
return '';
}
}
function highlightCode(code, lang) {
if (!code.length) {
return code;
}
code = prism.highlight(code, prism.languages[lang]);
code = '<pre class="language-' + lang + '"><code>' + code + '</code></pre>';
return code;
}
function htmlModuleData(file) {
var pathToRoot = path.relative(file.relative, '.');
pathToRoot = pathToRoot.substring(0, pathToRoot.length - 2);
return {
module: {
id: path.dirname(file.relative),
name: parsePath(file.relative).basename,
html: file.contents.toString()
},
paths: {
assets: pathToRoot + 'assets/',
root: pathToRoot
},
pkg: pkg
};
}
function listDirectories(cwd) {
return fs.readdirSync(cwd)
.filter(function (file) {
return fs.statSync(cwd + file).isDirectory();
});
}
function parsePath(filepath) {
var extname = path.extname(filepath);
return {
dirname: path.dirname(filepath),
basename: path.basename(filepath, extname),
extname: extname
};
}
function srcFiles(filetype) {
return gulp.src(paths.srcFiles, {base: paths.src})
.pipe(filter('**/*.' + filetype));
}
function reloadBrowser(options) {
// only reload browserSync if active, otherwise causes an error.
return gulpif(browserSync.active, browserSync.reload(options));
}
function createModule() {
return function () {
return moduleUtility.create();
};
}
function editModule() {
return function () {
return moduleUtility.edit();
};
}
function runSequence() {
var args = Array.prototype.slice.call(arguments);
return function (cb) {
if ('function' !== typeof args[args.length - 1]) {
args[args.length] = cb;
}
runGulpSequence.apply(this, args);
};
}
function buildHtml() {
return function () {
configureNunjucks();
var moduleIndex = moduleUtility.getModuleIndex();
return srcFiles('html')
.pipe(plumber()) // prevent pipe break on nunjucks render error
.pipe(nunjucksRender(function (file) {
return _.extend(
htmlModuleData(file),
{moduleIndex: moduleIndex}
);
}))
.pipe(plumber.stop())
.pipe(gulp.dest(paths.dist))
.pipe(reloadBrowser({stream: true}));
};
}
function buildModuleInfo() {
return function () {
var markdown = new markdownIt({
highlight: function(str, lang) {
return prism.highlight(str, prism.languages[lang || 'markup']);
}
});
['Components', 'Views'].forEach(function (moduleType) {
listDirectories(paths['src' + moduleType])
.filter(function (name) {
return (name.substr(0, 1) !== '_');
})
.map(function (name) {
var srcBasename = paths['src' + moduleType] + name + '/' + name;
var distBasename = paths['dist' + moduleType] + name + '/' + name;
var moduleInfo = {
name: name,
readme: markdown.render(getFileContents(paths['src' + moduleType] + name + '/README.md')),
html: highlightCode(getFileContents(distBasename + '.html'), 'markup'),
'demo html': highlightCode(getFileContents(distBasename + '-demo.html'), 'markup'),
css: highlightCode(getFileContents(distBasename + '.css'), 'css'),
template: highlightCode(getFileContents(srcBasename + '.html'), 'twig'),
less: highlightCode(getFileContents(srcBasename + '.less'), 'css'),
js: highlightCode(getFileContents(srcBasename + '.js'), 'javascript')
};
fs.writeFileSync(distBasename + '-info.json', JSON.stringify(moduleInfo, null, 4));
});
});
};
}
function buildPreviews() {
return function () {
configureNunjucks();
var templateHtml = fs.readFileSync(paths.srcViews + '_component-preview/component-preview.html', 'utf8');
return gulp.src(paths.srcComponents + '*/*.html', {base: paths.src})
.pipe(plumber()) // prevent pipe break on nunjucks render error
.pipe(nunjucksRender(htmlModuleData))
.pipe(nunjucksRender(htmlModuleData, templateHtml))
.pipe(plumber.stop())
.pipe(rename(function (p) {
p.basename += '-preview';
}))
.pipe(gulp.dest(paths.dist));
};
}
function buildJs(options) {
return function (cb) {
var settings = taskSettings(options);
var amdConfig = _.extend(
require('../../src/amd-config.json'),
{
baseUrl: paths.src,
generateSourceMaps: settings.sourceMaps || true, // http://requirejs.org/docs/optimization.html#sourcemaps
include: ['index'],
name: 'vendor/almond/almond',
optimize: settings.uglify || 'uglify2',
out: settings.paths.distAssets + 'index.js',
preserveLicenseComments: false
}
);
rjs.optimize(amdConfig);
if (browserSync.active) {
browserSync.reload();
}
cb();
};
}
function buildLess(options) {
return function () {
var settings = taskSettings(options);
return srcFiles('less')
.pipe(plumber()) // prevent pipe break on less parsing
.pipe(sourcemaps.init())
.pipe(less({
globalVars: {
pathToAssets: '"assets/"'
}
}))
.pipe(recess())
.pipe(recess.reporter())
.pipe(autoprefixer({browsers: settings.autoprefixBrowsers}))
.pipe(sourcemaps.write('.', {includeContent: true, sourceRoot: ''}))
.pipe(plumber.stop())
.pipe(rename(function (p) {
if (p.dirname === '.') {
p.dirname = 'assets';
} // output root src files to assets dir
}))
.pipe(gulp.dest(paths.dist)) // write the css and source maps
.pipe(filter('**/*.css')) // filtering stream to only css files
.pipe(reloadBrowser({stream: true}));
};
}
function copyFiles() {
return function () {
filesToCopy.map(function (file) {
return gulp.src(file.filepath)
.pipe(gulp.dest(file.toDir));
});
};
}
/**
* Copy all files from `assets/` directories in source root & modules. Only copies file when newer.
* The `assets/` string is removed from the original path as the destination is an `assets/` dir itself.
*/
function copyAssets() {
return function () {
paths.assetFiles.map(function (path) {
return gulp.src(path, {base: paths.src})
.pipe(filter(['**/*', '!**/*.less']))
.pipe(newer(paths.distAssets))
.pipe(rename(function (p) {
p.dirname = p.dirname
.split('/')
.filter(function (dir) {
return (dir !== 'assets');
})
.join('/');
}))
.pipe(gulp.dest(paths.distAssets));
});
};
}
function cleanDist() {
return function (cb) {
del([paths.dist], cb);
};
}
/**
* All images placed in a `assets-raw/images/` folder will be optimised (if newer) and placed in `assets/images/`.
* Examples:
* src/assets-raw/images/img.png >> src/assets/images/img.png
* src/components/my-component/assets-raw/images/img.png >> src/components/my-component/assets/images/img.png
* src/views/my-view/assets-raw/images/img.png >> src/views/my-view/assets/images/img.png
* If you don't want an image to be processed place it directly into `assets` instead of `assets-raw`.
*/
function runImagemin(options) {
return function () {
var settings = taskSettings(options);
var relRawImageDirPath = settings.rawImagesPath || 'assets-raw/images';
var relRawImageFilePath = relRawImageDirPath + '/**/*.{gif,jpg,jpeg,png,svg}';
function renameImageDir(path) {
return path.replace(relRawImageDirPath, 'assets/images');
}
return gulp.src([
settings.paths.src + relRawImageFilePath,
settings.paths.srcComponents + '*/' + relRawImageFilePath,
settings.paths.srcViews + '*/' + relRawImageFilePath
], {base: settings.paths.src})
// only process image if the raw image is newer (need to check against renamed output file)
.pipe(newer({
dest: settings.paths.src,
map: function (relativePath) {
return renameImageDir(relativePath);
}
}))
.pipe(imagemin({
progressive: true,
svgoPlugins: [],
use: [pngquant()]
}))
// output the processed image in the assets output dir
.pipe(rename(function (path) {
path.dirname = renameImageDir(path.dirname);
}))
.pipe(gulp.dest(settings.paths.src));
};
}
function jshintNode() {
return function () {
return gulp.src(['*.js'])
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter(require('jshint-stylish')));
};
}
function jshintSrc() {
return function () {
return srcFiles('js')
.pipe(cached('hinting')) // filter down to changed files only
.pipe(jscs())
.pipe(jshint(paths.src + '.jshintrc'))
.pipe(jshint.reporter(require('jshint-stylish')));
};
}
function test() {
return function (action) {
return function () {
return gulp.src([
// files you put in this array override the files array in karma.conf.js
])
.pipe(karma({
configFile: paths.karmaConfig,
action: action
}))
.on('error', function (err) {
throw err;
});
};
};
}
function serve() {
return function () {
browserSync(config.browserSync);
};
}
function watch() {
return function () {
gulp.watch(paths.assetFiles, ['copy_assets']);
gulp.watch(paths.htmlFiles, ['build_html', 'build_previews']);
gulp.watch(paths.jsFiles, ['build_js']);
gulp.watch(paths.lessFiles, ['build_less']);
};
}
function zipDist() {
return function () {
return gulp.src(paths.dist + '**/*')
.pipe(zip(pkg.name + '.zip'))
.pipe(gulp.dest(paths.dist));
};
}
return {
tasks: {
buildHtml: buildHtml,
buildModuleInfo: buildModuleInfo,
buildPreviews: buildPreviews,
buildJs: buildJs,
buildLess: buildLess,
copyAssets: copyAssets,
copyFiles: copyFiles,
createModule: createModule,
cleanDist: cleanDist,
editModule: editModule,
runImagemin: runImagemin,
jshintNode: jshintNode,
jshintSrc: jshintSrc,
test: test,
serve: serve,
runSequence: runSequence,
watch: watch,
zipDist: zipDist
},
configure: configure
};
};