4 * Copyright 2015 Google Inc. All rights reserved.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * https://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License
24 // Include Gulp & Tools We'll Use
26 import path from 'path';
27 import mergeStream from 'merge-stream';
28 import del from 'del';
29 import vinylPaths from 'vinyl-paths';
30 import runSequence from 'run-sequence';
31 import browserSync from 'browser-sync';
32 import through from 'through2';
33 import swig from 'swig';
34 import gulp from 'gulp';
35 import closureCompiler from 'gulp-closure-compiler';
36 import gulpLoadPlugins from 'gulp-load-plugins';
37 import uniffe from './utils/uniffe.js';
38 import pkg from './package.json';
40 const $ = gulpLoadPlugins();
41 const reload = browserSync.reload;
42 const hostedLibsUrlPrefix = 'https://code.getmdl.io';
43 const templateArchivePrefix = 'mdl-template-';
44 const bucketProd = 'gs://www.getmdl.io';
45 const bucketStaging = 'gs://mdl-staging';
46 const bucketCode = 'gs://code.getmdl.io';
47 const banner = ['/**',
48 ' * <%= pkg.name %> - <%= pkg.description %>',
49 ' * @version v<%= pkg.version %>',
50 ' * @license <%= pkg.license %>',
51 ' * @copyright 2015 Google, Inc.',
52 ' * @link https://github.com/google/material-design-lite',
58 const AUTOPREFIXER_BROWSERS = [
72 'src/mdlComponentHandler.js',
73 // Polyfills/dependencies
74 'src/third_party/**/*.js',
76 'src/button/button.js',
77 'src/checkbox/checkbox.js',
78 'src/icon-toggle/icon-toggle.js',
80 'src/progress/progress.js',
82 'src/slider/slider.js',
83 'src/snackbar/snackbar.js',
84 'src/spinner/spinner.js',
85 'src/switch/switch.js',
87 'src/textfield/textfield.js',
88 'src/tooltip/tooltip.js',
89 // Complex components (which reuse base components)
90 'src/layout/layout.js',
91 'src/data-table/data-table.js',
92 // And finally, the ripples
93 'src/ripple/ripple.js'
96 // ***** Development tasks ****** //
99 gulp.task('lint', () => {
104 .pipe(reload({stream: true, once: true}))
107 .pipe($.jshint.reporter('jshint-stylish'))
108 .pipe($.jscs.reporter())
109 .pipe($.if(!browserSync.active, $.jshint.reporter('fail')))
110 .pipe($.if(!browserSync.active, $.jscs.reporter('fail')));
113 // ***** Production build tasks ****** //
116 // TODO: Update image paths in final CSS to match root/images
117 gulp.task('images', () => {
118 return gulp.src('src/**/*.{svg,png,jpg}')
120 .pipe($.cache($.imagemin({
124 .pipe(gulp.dest('dist/images'))
125 .pipe($.size({title: 'images'}));
128 // Compile and Automatically Prefix Stylesheets (dev)
129 gulp.task('styles:dev', () => {
130 return gulp.src('src/**/*.scss')
133 onError: console.error.bind(console, 'Sass error:')
135 .pipe($.cssInlineImages({
138 .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
139 .pipe(gulp.dest('.tmp/styles'))
140 .pipe($.size({title: 'styles'}));
143 // Compile and Automatically Prefix Stylesheet Templates (production)
144 gulp.task('styletemplates', () => {
145 // For best performance, don't add Sass partials to `gulp.src`
146 return gulp.src('src/template.scss')
147 // Generate Source Maps
148 .pipe($.sourcemaps.init())
151 onError: console.error.bind(console, 'Sass error:')
153 .pipe($.cssInlineImages({webRoot: 'src'}))
154 .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
155 .pipe(gulp.dest('.tmp'))
156 // Concatenate Styles
157 .pipe($.concat('material.css.template'))
158 .pipe(gulp.dest('dist'))
160 .pipe($.if('*.css.template', $.csso()))
161 .pipe($.concat('material.min.css.template'))
162 .pipe($.header(banner, {pkg}))
163 .pipe($.sourcemaps.write('.'))
164 .pipe(gulp.dest('dist'))
165 .pipe($.size({title: 'styles'}));
168 // Compile and Automatically Prefix Stylesheets (production)
169 gulp.task('styles', () => {
170 // For best performance, don't add Sass partials to `gulp.src`
171 return gulp.src('src/material-design-lite.scss')
172 // Generate Source Maps
173 .pipe($.sourcemaps.init())
176 onError: console.error.bind(console, 'Sass error:')
178 .pipe($.cssInlineImages({webRoot: 'src'}))
179 .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
180 .pipe(gulp.dest('.tmp'))
181 // Concatenate Styles
182 .pipe($.concat('material.css'))
183 .pipe($.header(banner, {pkg}))
184 .pipe(gulp.dest('dist'))
186 .pipe($.if('*.css', $.csso()))
187 .pipe($.concat('material.min.css'))
188 .pipe($.header(banner, {pkg}))
189 .pipe($.sourcemaps.write('.'))
190 .pipe(gulp.dest('dist'))
191 .pipe($.size({title: 'styles'}));
194 // Only generate CSS styles for the MDL grid
195 gulp.task('styles-grid', () => {
196 return gulp.src('src/material-design-lite-grid.scss')
199 onError: console.error.bind(console, 'Sass error:')
201 .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
202 .pipe(gulp.dest('.tmp'))
203 // Concatenate Styles
204 .pipe($.concat('material-grid.css'))
205 .pipe($.header(banner, {pkg}))
206 .pipe(gulp.dest('dist'))
208 .pipe($.if('*.css', $.csso()))
209 .pipe($.concat('material-grid.min.css'))
210 .pipe($.header(banner, {pkg}))
211 .pipe(gulp.dest('dist'))
212 .pipe($.size({title: 'styles-grid'}));
215 // Build with Google's Closure Compiler, requires Java 1.7+ installed.
216 gulp.task('closure', () => {
217 return gulp.src(SOURCES)
218 .pipe(closureCompiler({
219 compilerPath: 'node_modules/google-closure-compiler/compiler.jar',
220 fileName: 'material.closure.min.js',
222 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
223 compilation_level: 'ADVANCED_OPTIMIZATIONS',
224 language_in: 'ECMASCRIPT6_STRICT',
225 language_out: 'ECMASCRIPT5_STRICT',
226 warning_level: 'VERBOSE'
227 // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
230 .pipe(gulp.dest('./dist'));
233 // Concatenate And Minify JavaScript
234 gulp.task('scripts', ['lint'], () => {
235 return gulp.src(SOURCES)
236 .pipe($.if(/mdlComponentHandler\.js/, $.util.noop(), uniffe()))
237 .pipe($.sourcemaps.init())
238 // Concatenate Scripts
239 .pipe($.concat('material.js'))
240 .pipe($.iife({useStrict: true}))
241 .pipe(gulp.dest('dist'))
245 sourceMapIncludeSources: true
247 .pipe($.header(banner, {pkg}))
248 .pipe($.concat('material.min.js'))
250 .pipe($.sourcemaps.write('.'))
251 .pipe(gulp.dest('dist'))
252 .pipe($.size({title: 'scripts'}));
255 // Clean Output Directory
256 gulp.task('clean', () => del(['dist', '.publish']));
258 // Copy package manger and LICENSE files to dist
259 gulp.task('metadata', () => {
265 .pipe(gulp.dest('dist'));
268 // Build Production Files, the Default Task
269 gulp.task('default', ['clean'], cb => {
271 ['styles', 'styles-grid'],
277 // Build production files and microsite
278 gulp.task('all', ['clean'], cb => {
281 ['styles-grid', 'styles:gen'],
285 'templates', 'images', 'metadata'],
290 // ***** Testing tasks ***** //
292 gulp.task('mocha', ['styles'], () => {
293 return gulp.src('test/index.html')
294 .pipe($.mochaPhantomjs({reporter: 'tap'}));
297 gulp.task('mocha:closure', ['closure'], () => {
298 return gulp.src('test/index.html')
299 .pipe($.replace('src="../dist/material.js"',
300 'src="../dist/material.closure.min.js"'))
301 .pipe($.rename('temp.html'))
302 .pipe(gulp.dest('test'))
303 .pipe($.mochaPhantomjs({reporter: 'tap'}))
304 .on('finish', () => del.sync('test/temp.html'))
305 .on('error', () => del.sync('test/temp.html'));
314 gulp.task('test:visual', () => {
318 startPath: 'test/visual/index.html'
321 gulp.watch('test/visual/**', reload);
324 // ***** Landing page tasks ***** //
327 * Site metadata for use with templates.
333 * Generates an HTML file based on a template and file metadata.
335 function applyTemplate() {
336 return through.obj((file, enc, cb) => {
340 content: file.contents.toString()
343 const templateFile = path.join(
344 __dirname, 'docs', '_templates', `${file.page.layout}.html`);
345 const tpl = swig.compileFile(templateFile, {cache: false});
347 file.contents = new Buffer(tpl(data));
353 * Generates an index.html file for each README in MDL/src directory.
355 gulp.task('components', ['demos'], () => {
356 return gulp.src('src/**/README.md', {base: 'src'})
357 // Add basic front matter.
358 .pipe($.header('---\nlayout: component\nbodyclass: component\ninclude_prefix: ../../\n---\n\n'))
359 .pipe($.frontMatter({
365 return through.obj((file, enc, cb) => {
366 file.page.component = file.relative.split('/')[0];
370 .pipe(applyTemplate())
371 .pipe($.rename(path => path.basename = 'index'))
372 .pipe(gulp.dest('dist/components'));
376 * Copies demo files from MDL/src directory.
378 gulp.task('demoresources', () => {
384 .pipe($.if('*.scss', $.sass({
386 onError: console.error.bind(console, 'Sass error:')
388 .pipe($.cssInlineImages({webRoot: 'src'}))
389 .pipe($.if('*.css', $.autoprefixer(AUTOPREFIXER_BROWSERS)))
390 .pipe(gulp.dest('dist/components'));
394 * Generates demo files for testing made of all the snippets and the demo file
397 gulp.task('demos', ['demoresources'], () => {
399 * Retrieves the list of component folders.
401 function getComponentFolders() {
402 return fs.readdirSync('src')
403 .filter(file => fs.statSync(path.join('src', file)).isDirectory());
406 const tasks = getComponentFolders().map(component => {
408 path.join('src', component, 'snippets', '*.html'),
409 path.join('src', component, 'demo.html')
411 .pipe($.concat('/demo.html'))
412 // Add basic front matter.
413 .pipe($.header('---\nlayout: demo\nbodyclass: demo\ninclude_prefix: ../../\n---\n\n'))
414 .pipe($.frontMatter({
420 return through.obj((file, enc, cb) => {
421 file.page.component = component;
425 .pipe(applyTemplate())
426 .pipe(gulp.dest(path.join('dist', 'components', component)));
429 return mergeStream(tasks);
433 * Generates an HTML file for each md file in _pages directory.
435 gulp.task('pages', ['components'], () => {
436 return gulp.src('docs/_pages/*.md')
437 .pipe($.frontMatter({
442 .pipe(applyTemplate())
443 .pipe($.replace('$$version$$', pkg.version))
444 .pipe($.replace('$$hosted_libs_prefix$$', hostedLibsUrlPrefix))
445 .pipe($.replace('$$template_archive_prefix$$', templateArchivePrefix))
446 /* Replacing code blocks class name to match Prism's. */
447 .pipe($.replace('class="lang-', 'class="language-'))
448 /* Translate html code blocks to "markup" because that's what Prism uses. */
449 .pipe($.replace('class="language-html', 'class="language-markup'))
450 .pipe($.rename(path => {
451 if (path.basename !== 'index') {
452 path.dirname = path.basename;
453 path.basename = 'index';
456 .pipe(gulp.dest('dist'));
460 * Copies assets from MDL and _assets directory.
462 gulp.task('assets', () => {
465 'node_modules/clippy/build/clippy.swf',
466 'node_modules/swfobject-npm/swfobject/src/swfobject.js',
467 'node_modules/prismjs/prism.js',
468 'node_modules/prismjs/components/prism-markup.min.js',
469 'node_modules/prismjs/components/prism-javascript.min.js',
470 'node_modules/prismjs/components/prism-css.min.js',
471 'node_modules/prismjs/components/prism-bash.min.js',
472 'node_modules/prismjs/dist/prism-default/prism-default.css'
474 .pipe($.if(/\.js/i, $.replace('$$version$$', pkg.version)))
475 .pipe($.if(/\.js/i, $.replace('$$hosted_libs_prefix$$', hostedLibsUrlPrefix)))
476 .pipe($.if(/\.(svg|jpg|png)$/i, $.imagemin({
480 .pipe($.if(/\.css/i, $.autoprefixer(AUTOPREFIXER_BROWSERS)))
481 .pipe($.if(/\.css/i, $.csso()))
482 .pipe($.if(/\.js/i, $.uglify({
483 preserveComments: 'some',
485 sourceMapIncludeSources: true
487 .pipe(gulp.dest('dist/assets'));
491 * Defines the list of resources to watch for changes.
494 gulp.watch(['src/**/*.js', '!src/**/README.md'],
495 ['scripts', 'demos', 'components', reload]);
496 gulp.watch(['src/**/*.{scss,css}'],
497 ['styles', 'styles-grid', 'styletemplates', reload]);
498 gulp.watch(['src/**/*.html'], ['pages', reload]);
499 gulp.watch(['src/**/*.{svg,png,jpg}'], ['images', reload]);
500 gulp.watch(['src/**/README.md'], ['pages', reload]);
501 gulp.watch(['templates/**/*'], ['templates', reload]);
502 gulp.watch(['docs/**/*'], ['pages', 'assets', reload]);
503 gulp.watch(['package.json', 'bower.json', 'LICENSE'], ['metadata']);
507 * Serves the landing page from "out" directory.
509 gulp.task('serve:browsersync', () => {
520 gulp.task('serve', () => {
529 gulp.src('dist/index.html')
530 .pipe($.open({uri: 'http://localhost:5000'}));
533 // Generate release archive containing just JS, CSS, Source Map deps
534 gulp.task('zip:mdl', () => {
536 'dist/material?(.min)@(.js|.css)?(.map)',
541 .pipe($.zip('mdl.zip'))
542 .pipe(gulp.dest('dist'));
546 * Returns the list of children directories inside the given directory.
547 * @param {string} dir the parent directory
548 * @return {Array<string>} list of child directories
550 function getSubDirectories(dir) {
551 return fs.readdirSync(dir)
552 .filter(file => fs.statSync(path.join(dir, file)).isDirectory());
555 // Generate release archives containing the templates and assets for templates.
556 gulp.task('zip:templates', () => {
557 const templates = getSubDirectories('dist/templates');
559 // Generate a zip file for each template.
560 const generateZips = templates.map(template => {
562 `dist/templates/${template}/**/*.*`,
565 .pipe($.rename(path => {
566 path.dirname = path.dirname.replace(`dist/templates/${template}`, '');
568 .pipe($.zip(`${templateArchivePrefix}${template}.zip`))
569 .pipe(gulp.dest('dist'));
572 return mergeStream(generateZips);
580 gulp.task('genCodeFiles', () => {
582 'dist/material.*@(js|css)?(.map)',
584 `dist/${templateArchivePrefix}*.zip`
586 .pipe($.tap(file => {
587 codeFiles += ` dist/${path.basename(file.path)}`;
591 // Push the latest version of code resources (CSS+JS) to Google Cloud Storage.
592 // Public-read objects in GCS are served by a Google provided and supported
593 // global, high performance caching/content delivery network (CDN) service.
594 // This task requires gsutil to be installed and configured.
595 // For info on gsutil: https://cloud.google.com/storage/docs/gsutil.
596 gulp.task('pushCodeFiles', () => {
597 const dest = bucketCode;
598 console.log(`Publishing ${pkg.version} to CDN (${dest})`);
600 // Build cache control and gsutil cmd to copy
601 // each object into a GCS bucket. The dest is a version specific path.
602 // The gsutil -m option requests parallel copies.
603 // The gsutil -h option is used to set metadata headers
604 // (cache control, in this case).
605 // Code files should NEVER be touched after uploading, therefore
606 // 30 days caching is a safe value.
607 const cacheControl = '-h "Cache-Control:public,max-age=2592000"';
608 const gsutilCpCmd = 'gsutil -m cp -z js,css,map ';
609 const gsutilCacheCmd = `gsutil -m setmeta -R ${cacheControl}`;
611 // Upload the goodies to a separate GCS bucket with versioning.
612 // Using a sep bucket avoids the risk of accidentally blowing away
613 // old versions in the microsite bucket.
616 `${gsutilCpCmd}${codeFiles} ${dest}/${pkg.version}`,
617 `${gsutilCacheCmd} ${dest}/${pkg.version}`
621 gulp.task('publish:code', cb => {
623 ['zip:mdl', 'zip:templates'],
630 * Function to publish staging or prod version from local tree,
631 * or to promote staging to prod, per passed arg.
632 * @param {string} pubScope the scope to publish to.
634 function mdlPublish(pubScope) {
639 if (pubScope === 'staging') {
640 // Set staging specific vars here.
643 dest = bucketStaging;
644 } else if (pubScope === 'prod') {
645 // Set prod specific vars here.
649 } else if (pubScope === 'promote') {
650 // Set promote (essentially prod) specific vars here.
652 src = `${bucketStaging}/*`;
656 let infoMsg = `Publishing ${pubScope}/${pkg.version} to GCS (${dest})`;
658 infoMsg += ` from ${src}`;
660 console.log(infoMsg);
662 // Build gsutil commands:
663 // The gsutil -h option is used to set metadata headers.
664 // The gsutil -m option requests parallel copies.
665 // The gsutil -R option is used for recursive file copy.
666 const cacheControl = `-h "Cache-Control:public,max-age=${cacheTtl}"`;
667 const gsutilCacheCmd = `gsutil -m setmeta ${cacheControl} ${dest}/**`;
668 const gsutilCpCmd = `gsutil -m cp -r -z html,css,js,svg ${src} ${dest}`;
670 gulp.src('').pipe($.shell([gsutilCpCmd, gsutilCacheCmd]));
673 // Push the local build of the MDL microsite and release artifacts to the
674 // production Google Cloud Storage bucket for general serving to the web.
675 // Public-read objects in GCS are served by a Google provided and supported
676 // global, high performance caching/content delivery network (CDN) service.
677 // This task requires gsutil to be installed and configured.
678 // For info on gsutil: https://cloud.google.com/storage/docs/gsutil.
680 gulp.task('publish:prod', () => {
684 // Promote the staging version of the MDL microsite and release artifacts
685 // to the production Google Cloud Storage bucket for general serving.
686 // Public-read objects in GCS are served by a Google provided and supported
687 // global, high performance caching/content delivery network (CDN) service.
688 // This task requires gsutil to be installed and configured.
689 // For info on gsutil: https://cloud.google.com/storage/docs/gsutil.
691 gulp.task('publish:promote', () => {
692 mdlPublish('promote');
695 // Push the staged version of the MDL microsite and release artifacts
696 // to a production Google Cloud Storage bucket for staging and pre-production testing.
698 // This task requires gsutil to be installed and configured.
699 // For info on gsutil: https://cloud.google.com/storage/docs/gsutil.
701 gulp.task('publish:staging', () => {
702 mdlPublish('staging');
705 gulp.task('_release', () => {
707 'dist/material?(.min)@(.js|.css)?(.map)',
718 .pipe(gulp.dest('_release'));
721 gulp.task('publish:release', ['_release'], () => {
722 return gulp.src('_release')
727 .pipe(vinylPaths(del));
730 gulp.task('templates:styles', () => {
731 return gulp.src('templates/**/*.css')
732 .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
733 // FIXME: This crashes. It's a bug in gulp-csso,
736 .pipe(gulp.dest('dist/templates'));
739 gulp.task('templates:static', () => {
740 return gulp.src('templates/**/*.html')
741 .pipe($.replace('$$version$$', pkg.version))
742 .pipe($.replace('$$hosted_libs_prefix$$', hostedLibsUrlPrefix))
743 .pipe(gulp.dest('dist/templates'));
746 // This task can be used if you want to test the templates against locally
747 // built version of the MDL libraries.
748 gulp.task('templates:localtestingoverride', () => {
749 return gulp.src('templates/**/*.html')
750 .pipe($.replace('$$version$$', '.'))
751 .pipe($.replace('$$hosted_libs_prefix$$', ''))
752 .pipe(gulp.dest('dist/templates'));
755 gulp.task('templates:images', () => {
756 return gulp.src('templates/*/images/**/*')
761 .pipe(gulp.dest('dist/templates'));
764 gulp.task('templates:fonts', () => {
765 return gulp.src('templates/*/fonts/**/*')
766 .pipe(gulp.dest('dist/templates/'));
769 gulp.task('templates', [
776 gulp.task('styles:gen', ['styles'], () => {
777 const MaterialCustomizer = require('./docs/_assets/customizer.js');
778 const templatePath = path.join(__dirname, 'dist', 'material.min.css.template');
779 // TODO: This task needs refactoring once we turn MaterialCustomizer
780 // into a proper Node module.
781 const mc = new MaterialCustomizer();
782 mc.template = fs.readFileSync(templatePath).toString();
784 let stream = gulp.src('');
786 mc.paletteIndices.forEach(primary => {
787 mc.paletteIndices.forEach(accent => {
788 if (primary === accent) {
792 if (mc.forbiddenAccents.indexOf(accent) !== -1) {
796 const primaryName = primary.toLowerCase().replace(' ', '_');
797 const accentName = accent.toLowerCase().replace(' ', '_');
799 stream = stream.pipe($.file(
800 `material.${primaryName}-${accentName}.min.css`,
801 mc.processTemplate(primary, accent)
806 stream.pipe(gulp.dest('dist'));