vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

366 lines
10 KiB

  1. var fs = require('fs');
  2. var async = require('async');
  3. var gulp = require('gulp');
  4. var gutil = require('gulp-util');
  5. var concat = require('gulp-concat');
  6. var cleanCSS = require('gulp-clean-css');
  7. var rename = require("gulp-rename");
  8. var webpack = require('webpack');
  9. var uglify = require('uglify-js');
  10. var rimraf = require('rimraf');
  11. var argv = require('yargs').argv;
  12. var opn = require('opn');
  13. var exec = require('child_process').exec;
  14. var spawn = require('child_process').spawn;
  15. var webserver = require('gulp-webserver');
  16. var ejs = require('ejs');
  17. var geminiConfig = require('./test/gemini/gemini.config.js');
  18. var ENTRY = './index.js';
  19. var HEADER = './lib/header.js';
  20. var DIST = './dist';
  21. var VIS_JS = 'vis.js';
  22. var VIS_MAP = 'vis.map';
  23. var VIS_MIN_JS = 'vis.min.js';
  24. var VIS_CSS = 'vis.css';
  25. var VIS_MIN_CSS = 'vis.min.css';
  26. var INDIVIDUAL_JS_BUNDLES = [{
  27. entry: './index-timeline-graph2d.js',
  28. filename: 'vis-timeline-graph2d.min.js'
  29. }, {
  30. entry: './index-network.js',
  31. filename: 'vis-network.min.js'
  32. }, {
  33. entry: './index-graph3d.js',
  34. filename: 'vis-graph3d.min.js'
  35. }];
  36. var INDIVIDUAL_CSS_BUNDLES = [{
  37. entry: ['./lib/shared/**/*.css', './lib/timeline/**/*.css'],
  38. filename: 'vis-timeline-graph2d.min.css'
  39. }, {
  40. entry: ['./lib/shared/**/*.css', './lib/network/**/*.css'],
  41. filename: 'vis-network.min.css'
  42. }];
  43. // generate banner with today's date and correct version
  44. function createBanner() {
  45. var today = gutil.date(new Date(), 'yyyy-mm-dd'); // today, formatted as yyyy-mm-dd
  46. var version = require('./package.json').version;
  47. return String(fs.readFileSync(HEADER))
  48. .replace('@@date', today)
  49. .replace('@@version', version);
  50. }
  51. var bannerPlugin = new webpack.BannerPlugin(createBanner(), {
  52. entryOnly: true,
  53. raw: true
  54. });
  55. var webpackModule = {
  56. loaders: [{
  57. test: /\.js$/,
  58. exclude: /node_modules/,
  59. loader: 'babel-loader',
  60. query: {
  61. cacheDirectory: true, // use cache to improve speed
  62. babelrc: true // use the .baberc file
  63. }
  64. }],
  65. // exclude requires of moment.js language files
  66. wrappedContextRegExp: /$^/
  67. };
  68. var webpackConfig = {
  69. entry: ENTRY,
  70. output: {
  71. library: 'vis',
  72. libraryTarget: 'umd',
  73. path: DIST,
  74. filename: VIS_JS,
  75. sourcePrefix: ' '
  76. },
  77. module: webpackModule,
  78. plugins: [bannerPlugin],
  79. cache: true,
  80. // generate details s tests: root + 'tests/',ourcempas of webpack modules
  81. devtool: 'source-map'
  82. //debug: true,
  83. //bail: true
  84. };
  85. var uglifyConfig = {
  86. outSourceMap: VIS_MAP,
  87. output: {
  88. comments: /@license/
  89. }
  90. };
  91. // create a single instance of the compiler to allow caching
  92. var compiler = webpack(webpackConfig);
  93. function handleCompilerCallback(err, stats) {
  94. if (err) {
  95. gutil.log(err.toString());
  96. }
  97. if (stats && stats.compilation && stats.compilation.errors) {
  98. // output soft errors
  99. stats.compilation.errors.forEach(function(err) {
  100. gutil.log(err.toString());
  101. });
  102. if (err || stats.compilation.errors.length > 0) {
  103. gutil.beep(); // TODO: this does not work on my system
  104. }
  105. }
  106. }
  107. function startDevWebserver(options, cb) {
  108. var opt = options || {};
  109. return gulp.src('./').pipe(webserver(Object.assign(opt, {
  110. path: '/',
  111. port: geminiConfig.webserver.port,
  112. middleware: function(req, res, next) {
  113. var dynamicTestBase = '/test/gemini/tests/dynamic/';
  114. var url = req.url;
  115. if (url.startsWith(dynamicTestBase)) {
  116. // get testcase from url
  117. var testName = url.split(dynamicTestBase)[1];
  118. // if testcase exists open settings
  119. var testConfig = require('.' + req.url + '.test');
  120. testConfig.name = testName;
  121. // render and send
  122. var templateFile = '.' + dynamicTestBase + 'dynamic.tmpl.html';
  123. ejs.renderFile(templateFile, testConfig, {}, function(err, html){
  124. if (err) {
  125. res.statusCode = 500;
  126. res.write('error rendering "'+ templateFile + '" (' + err + ')');
  127. res.end();
  128. return err;
  129. }
  130. res.writeHead(200, {
  131. 'Content-Length': Buffer.byteLength(html),
  132. 'Content-Type': 'text/html; charset=utf-8'
  133. });
  134. res.write(html);
  135. res.end();
  136. });
  137. }
  138. next();
  139. }
  140. })));
  141. }
  142. // Starts a static webserver that serve files from the root-dir of the project
  143. // during development. This is also used for gemini-testing.
  144. gulp.task('webserver', function(cb) {
  145. startDevWebserver({
  146. livereload: true,
  147. directoryListing: true,
  148. open: true
  149. }, cb);
  150. });
  151. function runGemini(mode, cb) {
  152. var completed = false;
  153. var hasError = false;
  154. // start development webserver to server the test-files
  155. var server = startDevWebserver();
  156. // start phantomjs in webdriver mode
  157. var phantomjsProcess = spawn('phantomjs', [
  158. '--webdriver=' + geminiConfig.phantomjs.port
  159. ]);
  160. // read output from the phantomjs process
  161. phantomjsProcess.stdout.on('data', function(data) {
  162. if (data.toString().indexOf('running on port') >= 0) {
  163. gutil.log("Started phantomjs webdriver");
  164. var geminiProcess = spawn('gemini', [mode, geminiConfig.gemini.tests]);
  165. geminiProcess.stdout.on('data', function(data) {
  166. var msg = data.toString().replace(/\n$/g, '');
  167. if (msg.startsWith('✓')) {
  168. gutil.log(gutil.colors.green(msg));
  169. } else if (msg.startsWith('✘')) {
  170. hasError = true;
  171. gutil.log(gutil.colors.red(msg));
  172. } else {
  173. gutil.log(msg);
  174. }
  175. });
  176. geminiProcess.stderr.on('data', function(data) {
  177. if (!(data.toString().indexOf('DeprecationWarning:') >= 0)) {
  178. hasError = true;
  179. gutil.log(gutil.colors.red(
  180. data.toString().replace(/\n$/g, '')
  181. ));
  182. }
  183. });
  184. geminiProcess.on('close', function(code) {
  185. completed = true;
  186. phantomjsProcess.kill();
  187. });
  188. }
  189. });
  190. // Log all error output from the phantomjs process to the console
  191. phantomjsProcess.stderr.on('data', function(data) {
  192. gutil.log(gutil.colors.red(data));
  193. });
  194. // Cleanup after phantomjs closes
  195. phantomjsProcess.on('close', function(code) {
  196. gutil.log("Phantomjs webdriver stopped");
  197. if (code && !completed) {
  198. // phantomjs closed with an error
  199. server.emit('kill');
  200. return cb(new Error('✘ phantomjs failed with code: ' + code + '\n' +
  201. 'Check that port ' + geminiConfig.phantomjs.port +
  202. ' is free and that there are no other ' +
  203. 'instances of phantomjs running. (`killall phantomjs`)'));
  204. }
  205. if (hasError) {
  206. // The tests returned with an error. Show the report. Keep dev-webserver running for debugging.
  207. gutil.log(gutil.colors.red("Opening error-report in webbrowser"));
  208. opn(geminiConfig.gemini.reports + 'index.html');
  209. } else {
  210. // The tests returned no error. Kill the dev-webserver and exit
  211. server.emit('kill');
  212. gutil.log("Webbrowser stopped");
  213. cb();
  214. }
  215. });
  216. }
  217. // Update the screenshots. Do this everytime you introduced a new test or introduced a major change.
  218. gulp.task('gemini-update', function(cb) {
  219. runGemini('update', cb);
  220. });
  221. // Test the current (dist) version against the existing screenshots.
  222. gulp.task('gemini-test', function(cb) {
  223. runGemini('test', cb);
  224. });
  225. // clean the dist/img directory
  226. gulp.task('clean', function(cb) {
  227. rimraf(DIST + '/img', cb);
  228. });
  229. gulp.task('bundle-js', function(cb) {
  230. // update the banner contents (has a date in it which should stay up to date)
  231. bannerPlugin.banner = createBanner();
  232. compiler.run(function(err, stats) {
  233. handleCompilerCallback(err, stats);
  234. cb();
  235. });
  236. });
  237. // create individual bundles for timeline+graph2d, network, graph3d
  238. gulp.task('bundle-js-individual', function(cb) {
  239. // update the banner contents (has a date in it which should stay up to date)
  240. bannerPlugin.banner = createBanner();
  241. async.each(INDIVIDUAL_JS_BUNDLES, function(item, callback) {
  242. var webpackTimelineConfig = {
  243. entry: item.entry,
  244. output: {
  245. library: 'vis',
  246. libraryTarget: 'umd',
  247. path: DIST,
  248. filename: item.filename,
  249. sourcePrefix: ' '
  250. },
  251. module: webpackModule,
  252. plugins: [bannerPlugin, new webpack.optimize.UglifyJsPlugin()],
  253. cache: true
  254. };
  255. var compiler = webpack(webpackTimelineConfig);
  256. compiler.run(function(err, stats) {
  257. handleCompilerCallback(err, stats);
  258. callback();
  259. });
  260. }, cb);
  261. });
  262. // bundle and minify css
  263. gulp.task('bundle-css', function() {
  264. return gulp.src('./lib/**/*.css')
  265. .pipe(concat(VIS_CSS))
  266. .pipe(gulp.dest(DIST))
  267. // TODO: nicer to put minifying css in a separate task?
  268. .pipe(cleanCSS())
  269. .pipe(rename(VIS_MIN_CSS))
  270. .pipe(gulp.dest(DIST));
  271. });
  272. // bundle and minify individual css
  273. gulp.task('bundle-css-individual', function(cb) {
  274. async.each(INDIVIDUAL_CSS_BUNDLES, function(item, callback) {
  275. return gulp.src(item.entry)
  276. .pipe(concat(item.filename))
  277. .pipe(cleanCSS())
  278. .pipe(rename(item.filename))
  279. .pipe(gulp.dest(DIST))
  280. .on('end', callback);
  281. }, cb);
  282. });
  283. gulp.task('copy', ['clean'], function() {
  284. var network = gulp.src('./lib/network/img/**/*')
  285. .pipe(gulp.dest(DIST + '/img/network'));
  286. return network;
  287. });
  288. gulp.task('minify', ['bundle-js'], function(cb) {
  289. var result = uglify.minify([DIST + '/' + VIS_JS], uglifyConfig);
  290. // note: we add a newline '\n' to the end of the minified file to prevent
  291. // any issues when concatenating the file downstream (the file ends
  292. // with a comment).
  293. fs.writeFileSync(DIST + '/' + VIS_MIN_JS, result.code + '\n');
  294. fs.writeFileSync(DIST + '/' + VIS_MAP, result.map.replace(/"\.\/dist\//g,
  295. '"'));
  296. cb();
  297. });
  298. gulp.task('bundle', ['bundle-js', 'bundle-js-individual', 'bundle-css',
  299. 'bundle-css-individual', 'copy'
  300. ]);
  301. // read command line arguments --bundle and --minify
  302. var bundle = 'bundle' in argv;
  303. var minify = 'minify' in argv;
  304. var watchTasks = [];
  305. if (bundle || minify) {
  306. // do bundling and/or minifying only when specified on the command line
  307. watchTasks = [];
  308. if (bundle) watchTasks.push('bundle');
  309. if (minify) watchTasks.push('minify');
  310. } else {
  311. // by default, do both bundling and minifying
  312. watchTasks = ['bundle', 'minify'];
  313. }
  314. // The watch task (to automatically rebuild when the source code changes)
  315. gulp.task('watch', watchTasks, function() {
  316. gulp.watch(['index.js', 'lib/**/*'], watchTasks);
  317. });
  318. // The default task (called when you run `gulp`)
  319. gulp.task('default', ['clean', 'bundle', 'minify']);