<commit_before>/* global __dirname */

(function (pkg, gulp, jshint, jscs, stylish, mocha, connect, less, requirejs, uglify, replace, header, yargs, rimraf, mkdirp, recursive) {
    'use strict';

    var environment = yargs.argv.env || 'development',
        headerTemplate =
            '/**\n' +
            ' * ${pkg.name}\n' +
            ' * ${pkg.description}\n' +
            ' * \n' +
            ' * @version ${pkg.version}\n' +
            ' * @link ${pkg.homepage}\n' +
            ' * @license ${pkg.license}\n' +
            ' */\n\n';

    gulp.task(
        'qa:lint',
        function () {
            return gulp
                .src([
                    '*.js',
                    'public/app/**/*.js',
                    'test/**/*.js'
                ])
                .pipe(jshint())
                .pipe(jscs())
                .pipe(stylish.combineWithHintResults())
                .pipe(jshint.reporter('jshint-stylish'));
        }
    );

    gulp.task(
        'qa:test',
        [
            'qa:lint'
        ],
        function () {
            return gulp
                .src('test/runner.html')
                .pipe(mocha());
        }
    );

    gulp.task(
        'qa',
        [
            'qa:lint',
            'qa:test'
        ]
    );

    gulp.task(
        'build:clean',
        function (callback) {
            rimraf('public/css', callback);
        }
    );

    gulp.task(
        'build:less',
        function () {
            return gulp
                .src('public/less/main.less')
                .pipe(less({
                    paths: [ 'public/less' ]
                }))
                .pipe(gulp.dest('public/css'));
        }
    );

    gulp.task(
        'build',
        [
            'build:clean',
            'build:less'
        ]
    );

    gulp.task(
        'package:clean',
        function (callback) {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            rimraf('dist/' + environment, function () {
                mkdirp('dist/' + environment, callback);
            });
        }
    );

    gulp.task(
        'package:less',
        function () {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            return gulp
                .src('public/less/main.less')
                .pipe(less({
                    paths: [ 'public/less' ],
                    optimize: true
                }))
                .pipe(gulp.dest('dist/' + environment));
        }
    );

    gulp.task(
        'package:javascript',
        function () {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            // Dynamically generate the `include` list, because most of the modules are dynamically `require`d.
            recursive('public/app', function (err, files) {
                return gulp
                    .src('public/app/main.js')
                    .pipe(requirejs({
                        mainConfigFile: 'public/app/main.js',
                        name: '../lib/requirejs/require',
                        optimize: 'none',
                        out: 'application.js',
                        include: files.map(function (file) {
                            // Strip common path prefix; return .js files without extension, and others via text plugin.
                            file = file.replace(/^public\/app\//, '');
                            return file.match(/\.js$/) ? file.replace(/\.js$/, '') : 'text!' + file;
                        })
                    }))
                    .pipe(replace(/var environment = 'development';/g, 'var environment = "' + environment + '";'))
                    .pipe(uglify())
                    .pipe(header(headerTemplate, { pkg: pkg }))
                    .pipe(gulp.dest('dist/' + environment));
            });
        }
    );

    gulp.task(
        'package:html',
        function () {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            return gulp
                .src('public/index.html')
                .pipe(replace(/src="\/lib\/requirejs\/require\.js"/g, 'src="/application.js"'))
                .pipe(replace(/href="\/css\/main\.css"/g, 'href="/main.css"'))
                .pipe(gulp.dest('dist/' + environment));
        }
    );

    gulp.task(
        'package:images',
        function () {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            return gulp
                .src('public/images/**/*')
                .pipe(gulp.dest('dist/' + environment + '/images'));
        }
    );

    gulp.task(
        'package',
        [
            'package:clean',
            'package:less',
            'package:javascript',
            'package:html',
            'package:images'
        ]
    );

    gulp.task(
        'server',
        function () {
            connect.server({
                port: 8888,
                root: 'public',
                fallback: 'public/index.html'
            });
        }
    );

    gulp.task(
        'dist-server',
        function () {
            connect.server({
                port: 8889,
                root: 'dist/' + environment,
                fallback: 'dist/' + environment + '/index.html'
            });
        }
    );

    gulp.task(
        'watch:qa',
        function () {
            return gulp
                .watch(
                    [
                        '*.js',
                        'public/app/**',
                        'test/**/*.js'
                    ],
                    [
                        'qa'
                    ]
                );
        }
    );

    gulp.task(
        'watch:less',
        function () {
            return gulp
                .watch(
                    [
                        'public/less/**/*.less',
                        'public/app/ui/**/*.less'
                    ],
                    [
                        'build:less'
                    ]
                );
        }
    );

    gulp.task(
        'watch',
        [
            'watch:qa',
            'watch:less'
        ]
    );

    gulp.task(
        'default',
        [
            'qa',
            'build',
            'watch'
        ]
    );
}(
    require('./package.json'),
    require('gulp'),
    require('gulp-jshint'),
    require('gulp-jscs'),
    require('gulp-jscs-stylish'),
    require('gulp-mocha-phantomjs'),
    require('gulp-connect'),
    require('gulp-less'),
    require('gulp-requirejs-optimize'),
    require('gulp-uglify'),
    require('gulp-replace'),
    require('gulp-header'),
    require('yargs'),
    require('rimraf'),
    require('mkdirp'),
    require('recursive-readdir')
));
<commit_msg>Add missing task dependencies.<commit_after>/* global __dirname */

(function (pkg, gulp, jshint, jscs, stylish, mocha, connect, less, requirejs, uglify, replace, header, yargs, rimraf, mkdirp, recursive) {
    'use strict';

    var environment = yargs.argv.env || 'development',
        headerTemplate =
            '/**\n' +
            ' * ${pkg.name}\n' +
            ' * ${pkg.description}\n' +
            ' * \n' +
            ' * @version ${pkg.version}\n' +
            ' * @link ${pkg.homepage}\n' +
            ' * @license ${pkg.license}\n' +
            ' */\n\n';

    gulp.task(
        'qa:lint',
        function () {
            return gulp
                .src([
                    '*.js',
                    'public/app/**/*.js',
                    'test/**/*.js'
                ])
                .pipe(jshint())
                .pipe(jscs())
                .pipe(stylish.combineWithHintResults())
                .pipe(jshint.reporter('jshint-stylish'));
        }
    );

    gulp.task(
        'qa:test',
        [
            'qa:lint'
        ],
        function () {
            return gulp
                .src('test/runner.html')
                .pipe(mocha());
        }
    );

    gulp.task(
        'qa',
        [
            'qa:lint',
            'qa:test'
        ]
    );

    gulp.task(
        'build:clean',
        function (callback) {
            rimraf('public/css', callback);
        }
    );

    gulp.task(
        'build:less',
        [
            'build:clean'
        ],
        function () {
            return gulp
                .src('public/less/main.less')
                .pipe(less({
                    paths: [ 'public/less' ]
                }))
                .pipe(gulp.dest('public/css'));
        }
    );

    gulp.task(
        'build',
        [
            'build:clean',
            'build:less'
        ]
    );

    gulp.task(
        'package:clean',
        function (callback) {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            rimraf('dist/' + environment, function () {
                mkdirp('dist/' + environment, callback);
            });
        }
    );

    gulp.task(
        'package:less',
        [
            'package:clean'
        ],
        function () {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            return gulp
                .src('public/less/main.less')
                .pipe(less({
                    paths: [ 'public/less' ],
                    optimize: true
                }))
                .pipe(gulp.dest('dist/' + environment));
        }
    );

    gulp.task(
        'package:javascript',
        [
            'package:clean'
        ],
        function () {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            // Dynamically generate the `include` list, because most of the modules are dynamically `require`d.
            recursive('public/app', function (err, files) {
                return gulp
                    .src('public/app/main.js')
                    .pipe(requirejs({
                        mainConfigFile: 'public/app/main.js',
                        name: '../lib/requirejs/require',
                        optimize: 'none',
                        out: 'application.js',
                        include: files.map(function (file) {
                            // Strip common path prefix; return .js files without extension, and others via text plugin.
                            file = file.replace(/^public\/app\//, '');
                            return file.match(/\.js$/) ? file.replace(/\.js$/, '') : 'text!' + file;
                        })
                    }))
                    .pipe(replace(/var environment = 'development';/g, 'var environment = "' + environment + '";'))
                    .pipe(uglify())
                    .pipe(header(headerTemplate, { pkg: pkg }))
                    .pipe(gulp.dest('dist/' + environment));
            });
        }
    );

    gulp.task(
        'package:html',
        [
            'package:clean'
        ],
        function () {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            return gulp
                .src('public/index.html')
                .pipe(replace(/src="\/lib\/requirejs\/require\.js"/g, 'src="/application.js"'))
                .pipe(replace(/href="\/css\/main\.css"/g, 'href="/main.css"'))
                .pipe(gulp.dest('dist/' + environment));
        }
    );

    gulp.task(
        'package:images',
        [
            'package:clean'
        ],
        function () {
            if (environment === 'development') {
                throw new Error('Cannot use "package" tasks in development environment');
            }
            return gulp
                .src('public/images/**/*')
                .pipe(gulp.dest('dist/' + environment + '/images'));
        }
    );

    gulp.task(
        'package',
        [
            'package:clean',
            'package:less',
            'package:javascript',
            'package:html',
            'package:images'
        ]
    );

    gulp.task(
        'server',
        function () {
            connect.server({
                port: 8888,
                root: 'public',
                fallback: 'public/index.html'
            });
        }
    );

    gulp.task(
        'dist-server',
        function () {
            connect.server({
                port: 8889,
                root: 'dist/' + environment,
                fallback: 'dist/' + environment + '/index.html'
            });
        }
    );

    gulp.task(
        'watch:qa',
        function () {
            return gulp
                .watch(
                    [
                        '*.js',
                        'public/app/**',
                        'test/**/*.js'
                    ],
                    [
                        'qa'
                    ]
                );
        }
    );

    gulp.task(
        'watch:less',
        function () {
            return gulp
                .watch(
                    [
                        'public/less/**/*.less',
                        'public/app/ui/**/*.less'
                    ],
                    [
                        'build:less'
                    ]
                );
        }
    );

    gulp.task(
        'watch',
        [
            'watch:qa',
            'watch:less'
        ]
    );

    gulp.task(
        'default',
        [
            'qa',
            'build',
            'watch'
        ]
    );
}(
    require('./package.json'),
    require('gulp'),
    require('gulp-jshint'),
    require('gulp-jscs'),
    require('gulp-jscs-stylish'),
    require('gulp-mocha-phantomjs'),
    require('gulp-connect'),
    require('gulp-less'),
    require('gulp-requirejs-optimize'),
    require('gulp-uglify'),
    require('gulp-replace'),
    require('gulp-header'),
    require('yargs'),
    require('rimraf'),
    require('mkdirp'),
    require('recursive-readdir')
));
<|endoftext|>


<commit_before>var AdminTable = function () {
    "use strict";
    return {
        //main function
        init: function (id, options) {

            var bindFilters = function(filters, id) {
                for(var i=0; i < filters.length; i++) {
                    switch (filters[i].type) {
                        case 'dropdown':
                            $('#' + id + '-dropdown-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-dropdown-' + i).on('change', function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                table.column(sequance).search(val).draw();
                            });
                            break;
                        case 'text':
                        case 'price':
                            $('#' + id + '-' + filters[i].type + '-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-' + filters[i].type + '-' + i).keyup(function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                table.column(sequance).search(val).draw();
                            });
                            break;
                        case 'date':
                            $('#' + id + '-date-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-date-' + i).datepicker({
                                format: 'dd.mm.yyyy',
                                todayHighlight: true,
                            });
                            $('#' + id + '-date-' + i).on('change', function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                var rule = $(this).data('rule');
                                table.column(sequance).search('').draw();
                                if (val.length > 0) {
                                    var tmp = val.split('.');
                                    val = new Date(tmp[2], tmp[1]-1, tmp[0]);
                                    customFilters().date(val.getTime(), rule, sequance, table);
                                } else {
                                    table.column(sequance).search('').draw();
                                }
                            });
                            break;
                        case 'datetime':
                            $('#' + id + '-datetime-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-datetime-' + i).datetimepicker({
                                format: "dd.mm.yyyy hh:ii",
                                autoclose: true,
                                minuteStep: 1
                            });
                            $('#' + id + '-datetime-' + i).on('change', function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                var rule = $(this).data('rule');
                                table.column(sequance).search('').draw();
                                if (val.length > 0) {
                                    var tmp = val.split('.');
                                    var tmpYear = tmp[2].split(' ');
                                    var tmpTime = tmpYear[1].split(':');

                                    val = new Date(tmpYear[0], tmp[1]-1, tmp[0], tmpTime[0], tmpTime[1]);

                                    customFilters().datetime(val.getTime(), rule, sequance, table);
                                } else {
                                    table.column(sequance).search('').draw();
                                }
                            });
                            break;
                        case 'bool':
                            $('#' + id + '-bool-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-bool-' + i).on('change', function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                customFilters().bool(val, sequance, table);
                            });
                            break;
                    }
                }
                $('#reset-' + id).on('click', function() {
                    for(i=0; i < filters.length; i++) {
                        if (filters[i].type == 'dropdown') {
                            $('#' + id + '-dropdown-' + i).val('-1');
                        } else {
                            $('#' + id + '-' + filters[i].type + '-' + i).val('');
                        }
                        table.column(filters[i].sequanceNumber).search('');
                    }
                    table.draw();
                });
            };

            var customFilters = function() {
                return {
                    date: function(filterValue, rule, sequance, table) {
                        $.fn.dataTable.ext.search = [];
                        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
                            var value = table.data()[dataIndex][sequance];
                            if (value['@data-order'] !== undefined)
                            {
                                value = value['@data-order'];
                            }
                            var tmp = value.split('-');
                            value = new Date(tmp[0], (tmp[1]-1), tmp[2]);

                            value = value.getTime();

                            var valid = false;
                            switch (rule) {
                                case '>':
                                    valid = (filterValue > value);
                                    break;
                                case '<':
                                    valid = (filterValue < value);
                                    break;
                                case '<=':
                                    valid = (filterValue <= value);
                                    break;
                                case '>=':
                                    valid = (filterValue >= value);
                                    break;

                            }

                            return valid;
                        });
                        table.column(sequance).draw();
                    },
                    datetime: function(filterValue, rule, sequance, table) {
                        $.fn.dataTable.ext.search = [];
                        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
                            var value = table.data()[dataIndex][sequance];

                            if (value['display'] !== undefined) {
                                value = value['display'];
                            }

                            var tmp = value.split('.');
                            var tmpYear = tmp[2].split(' ');
                            var tmpTime = tmpYear[1].split(':');

                            value = new Date(tmpYear[0], tmp[1]-1, tmp[0], tmpTime[0], tmpTime[1]);

                            value = value.getTime();

                            var valid = false;
                            switch (rule) {
                                case '>':
                                    valid = (filterValue > value);
                                    break;
                                case '<':
                                    valid = (filterValue < value);
                                    break;
                                case '<=':
                                    valid = (filterValue <= value);
                                    break;
                                case '>=':
                                    valid = (filterValue >= value);
                                    break;

                            }

                            return valid;
                        });
                        table.column(sequance).draw();
                    },
                    bool: function(filterValue, sequance, table) {
                        $.fn.dataTable.ext.search = [];
                        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
                            var value = table.data()[dataIndex][sequance];
                            if (filterValue.length < 1)
                                return true;
                            if (value['@data-search'] !== undefined) {
                                value = value['@data-search'];
                            }
                            return (filterValue == value);
                        });
                        table.column(sequance).draw();
                    }
                }
            };

            if ($('#'+id).length !== 0) {
                var sortConfig = [];
                for(var i=0; i < options.sortConfig.length; i++) {
                    sortConfig.push({
                        "targets": options.sortConfig[i],
                        "orderable": false
                    });
                }
                var table = $('#'+id).DataTable({
                    "lengthMenu": [20, 40, 60],
                    "dom": 'C<"clear">lfrtip',
                    colVis: {
                        exclude: [ options.exclColumns ]
                    },
                    paging: true,
                    "autoWidth": true,
                    "order": [[ 0, "asc" ]],
                    "columnDefs": sortConfig
                });

                if (typeof options.filters != 'undefined' && options.filters.length > 0) {
                    bindFilters(options.filters, id);
                }

                var tbl = new $.fn.dataTable.FixedHeader(table);
                //new $.fn.dataTable.KeyTable(table);

                $(window).resize(function() {
                    tbl._fnUpdateClones(true);
                    tbl._fnUpdatePositions();
                });
            }
        }
    };
}();<commit_msg>OH-129 fix js filters<commit_after>var AdminTable = function () {
    "use strict";
    return {
        //main function
        init: function (id, options) {

            var bindFilters = function(filters, id) {
                for(var i=0; i < filters.length; i++) {
                    switch (filters[i].type) {
                        case 'dropdown':
                            $('#' + id + '-dropdown-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-dropdown-' + i).on('change', function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                table.column(sequance).search(val).draw();
                            });
                            break;
                        case 'text':
                        case 'price':
                            $('#' + id + '-' + filters[i].type + '-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-' + filters[i].type + '-' + i).keyup(function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                table.column(sequance).search(val).draw();
                            });
                            break;
                        case 'date':
                            $('#' + id + '-date-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-date-' + i).datepicker({
                                format: 'dd.mm.yyyy',
                                todayHighlight: true,
                            });
                            $('#' + id + '-date-' + i).on('change', function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                var rule = $(this).data('rule');
                                table.column(sequance).search('').draw();
                                if (val.length > 0) {
                                    var tmp = val.split('.');
                                    val = new Date(tmp[2], tmp[1]-1, tmp[0]);
                                    customFilters().date(val.getTime(), rule, sequance, table);
                                } else {
                                    table.column(sequance).search('').draw();
                                }
                            });
                            break;
                        case 'datetime':
                            $('#' + id + '-datetime-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-datetime-' + i).datetimepicker({
                                format: "dd.mm.yyyy hh:ii",
                                autoclose: true,
                                minuteStep: 1
                            });
                            $('#' + id + '-datetime-' + i).on('change', function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                var rule = $(this).data('rule');
                                table.column(sequance).search('').draw();
                                if (val.length > 0) {
                                    var tmp = val.split('.');
                                    var tmpYear = tmp[2].split(' ');
                                    var tmpTime = tmpYear[1].split(':');

                                    val = new Date(tmpYear[0], tmp[1]-1, tmp[0], tmpTime[0], tmpTime[1]);

                                    customFilters().datetime(val.getTime(), rule, sequance, table);
                                } else {
                                    table.column(sequance).search('').draw();
                                }
                            });
                            break;
                        case 'bool':
                            $('#' + id + '-bool-' + i).data('sequance', filters[i].sequanceNumber);
                            $('#' + id + '-bool-' + i).on('change', function(){
                                var val = $(this).val();
                                var sequance = $(this).data('sequance');
                                customFilters().bool(val, sequance, table);
                            });
                            break;
                    }
                }
                $('#reset-' + id).on('click', function() {
                    for(i=0; i < filters.length; i++) {
                        if (filters[i].type == 'dropdown') {
                            $('#' + id + '-dropdown-' + i).val('-1');
                        } else {
                            $('#' + id + '-' + filters[i].type + '-' + i).val('');
                        }
                        table.column(filters[i].sequanceNumber).search('');
                    }
                    $.fn.dataTable.ext.search = [];
                    table.draw();
                    return false;
                });
            };

            var customFilters = function() {
                return {
                    date: function(filterValue, rule, sequance, table) {
                        $.fn.dataTable.ext.search = [];
                        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
                            var value = table.data()[dataIndex][sequance];
                            if (value['@data-order'] !== undefined)
                            {
                                value = value['@data-order'];
                            }
                            var tmp = value.split('-');
                            value = new Date(tmp[0], (tmp[1]-1), tmp[2]);

                            value = value.getTime();

                            var valid = false;
                            switch (rule) {
                                case '>':
                                    valid = (filterValue > value);
                                    break;
                                case '<':
                                    valid = (filterValue < value);
                                    break;
                                case '<=':
                                    valid = (filterValue <= value);
                                    break;
                                case '>=':
                                    valid = (filterValue >= value);
                                    break;

                            }

                            return valid;
                        });
                        table.column(sequance).draw();
                    },
                    datetime: function(filterValue, rule, sequance, table) {
                        $.fn.dataTable.ext.search = [];
                        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
                            var value = table.data()[dataIndex][sequance];

                            if (value['display'] !== undefined) {
                                value = value['display'];
                            }

                            var tmp = value.split('.');
                            var tmpYear = tmp[2].split(' ');
                            var tmpTime = tmpYear[1].split(':');

                            value = new Date(tmpYear[0], tmp[1]-1, tmp[0], tmpTime[0], tmpTime[1]);

                            value = value.getTime();

                            var valid = false;
                            switch (rule) {
                                case '>':
                                    valid = (filterValue > value);
                                    break;
                                case '<':
                                    valid = (filterValue < value);
                                    break;
                                case '<=':
                                    valid = (filterValue <= value);
                                    break;
                                case '>=':
                                    valid = (filterValue >= value);
                                    break;

                            }

                            return valid;
                        });
                        table.column(sequance).draw();
                    },
                    bool: function(filterValue, sequance, table) {
                        $.fn.dataTable.ext.search = [];
                        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
                            var value = table.data()[dataIndex][sequance];
                            if (filterValue.length < 1)
                                return true;
                            if (value['@data-search'] !== undefined) {
                                value = value['@data-search'];
                            }
                            return (filterValue == value);
                        });
                        table.column(sequance).draw();
                    }
                }
            };

            if ($('#'+id).length !== 0) {
                var sortConfig = [];
                for(var i=0; i < options.sortConfig.length; i++) {
                    sortConfig.push({
                        "targets": options.sortConfig[i],
                        "orderable": false
                    });
                }
                var table = $('#'+id).DataTable({
                    "lengthMenu": [20, 40, 60],
                    "dom": 'C<"clear">lfrtip',
                    colVis: {
                        exclude: [ options.exclColumns ]
                    },
                    paging: true,
                    "autoWidth": true,
                    "order": [[ 0, "asc" ]],
                    "columnDefs": sortConfig
                });

                if (typeof options.filters != 'undefined' && options.filters.length > 0) {
                    bindFilters(options.filters, id);
                }

                var tbl = new $.fn.dataTable.FixedHeader(table);
                //new $.fn.dataTable.KeyTable(table);

                $(window).resize(function() {
                    tbl._fnUpdateClones(true);
                    tbl._fnUpdatePositions();
                });
            }
        }
    };
}();<|endoftext|>


<commit_before>var gulp = require('gulp')
<commit_msg>create the 'test' task<commit_after>var gulp = require('gulp')
var mocha = require('gulp-mocha')

gulp.task('test', function () {
  gulp.src('./tests/connect-sequence.spec.js').pipe(mocha())
})
<|endoftext|>


<commit_before>/*
  Convert milliseconds to something that doesn't suck
*/
var getDuration = function(timestamp){
    var millis = Date.now() - timestamp*1000;
    var dur = [];
    var units = [
        {label:"millis",    mod:1000},
        {label:"seconds",   mod:60},
        {label:"minutes",   mod:60},
        {label:"hours",     mod:24},
        {label:"days",      mod:31}
    ];
    // calculate the individual unit values
    units.forEach(function(u){
        var val = millis % u.mod;
        millis = (millis - val) / u.mod;
        if (val > 0)
            dur.push({"label": u.label, "val": val});
    });
    // convert object to string representation
    dur.toString = function(){
        return dur.reverse().slice(0,2).map(function(d){
            return d.val + " " + (d.val==1?d.label.slice(0,-1):d.label);
        }).join(', ');
    };
    return dur;
};<commit_msg>shorten time abbrevs<commit_after>/*
  Convert milliseconds to something that doesn't suck
*/
var getDuration = function(timestamp){
    var millis = Date.now() - timestamp*1000;
    var dur = [];
    var units = [
        {label:"millis",    mod:1000},
        {label:"seconds",   mod:60},
        {label:"mins",   mod:60},
        {label:"hours",     mod:24},
        {label:"days",      mod:31}
    ];
    // calculate the individual unit values
    units.forEach(function(u){
        var val = millis % u.mod;
        millis = (millis - val) / u.mod;
        if (val > 0)
            dur.push({"label": u.label, "val": val});
    });
    // convert object to string representation
    dur.toString = function(){
        return dur.reverse().slice(0,2).map(function(d){
            return d.val + " " + (d.val==1?d.label.slice(0,-1):d.label);
        }).join(', ');
    };
    return dur;
};<|endoftext|>


<commit_before>/*
 * Copyright 2015 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Build process for closure-compiler-npm package
 *
 * Since the package doesn't require building, this file runs
 * tests and auto-increments the version number. Auto-increment
 * is used to support continuous delivery.
 *
 * @author Chad Killingsworth (chadkillingsworth@gmail.com)
 */

'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var mocha = require('gulp-mocha');
var git = require('simple-git')(__dirname);
var Semver = require('semver');
var fs = require('fs');
var packageInfo = require('./package.json');
var currentVer = new Semver(packageInfo.version);

gulp.task('test', function() {
  return gulp.src('./test/**.js', {read: false})
      .pipe(mocha());
});
gulp.task('default', ['test']);

/**
 * Check the git diff for package.json to return whether it included
 * a change to the version number.
 * @return {Promise<boolean>}
 */
var didLastCommitChangeVersionNumber = function() {
  return new Promise(function (resolve, reject) {
    git.diff(['HEAD^', 'HEAD', 'package.json'], function(err, data) {
      if (err) {
        return reject(err);
      }

      var versionData = (data || '').match(/^[+-]\s*"version": "[^"]+",$/mg);
      var versionChanged = versionData === null ? false : versionData.length === 2;
      return resolve(versionChanged);
    });
  });
};

/**
 * If the previous commit didn't include a version number change,
 * calculate what the new version should be.
 *
 * @param {boolean} alreadyChanged
 * @returns {Promise<Semver>}
 */
var getNextVersionNumber = function(alreadyChanged) {
  return new Promise(function(resolve, reject) {
    if (alreadyChanged) {
      gutil.log('Most recent commit incremented version number. No changes needed.');
      return resolve(currentVer);
    }

    var Compiler = require('./lib/node/closure-compiler');
    var compiler = new Compiler({version: true});
    compiler.run(function(code, data, err) {
      if (code !== 0) {
        return reject(new Error('Non-zero exit code: ' + code));
      }

      var versionNum = (data || '').match(/Version:\sv(.*)$/m);
      if (versionNum.length !== 2) {
        return resolve(new Error('Unable to parse compiler version number'));
      }
      var compilerVer = new Semver(versionNum[1] + '.0.0');

      if (compilerVer.compare(currentVer) > 0) {
        gutil.log('New compiler version detected. Increment major version.');
        return resolve(compilerVer);
      }

      var nextVersion = new Semver(packageInfo.version);
      nextVersion.inc('minor');
      gutil.log('Changes detected. Increment minor version.');
      return resolve(nextVersion);
    });
  });
};

/**
 * Given a semver object, update package.json (if needed) to the
 * new version number. If changed, add and commit package.json.
 *
 * @param {Semver} newVersion
 * @returns {Promise<boolean>}
 */
var updatePackageToNewVersion = function(newVersion) {
  return new Promise(function(resolve, reject) {
    if (currentVer.compare(newVersion) >= 0) {
      return resolve(false);
    }

    packageInfo.version = newVersion.version;
    fs.writeFileSync('./package.json', JSON.stringify(packageInfo, null, 2) + '\n');

    git.add('package.json', function(err, data) {})
        .commit('Increment version number to ' + newVersion.version, function(err, data) {
          gutil.log('New version committed: ' + newVersion.version);
          return resolve(true);
        });
  });
};

/**
 * Task to determine whether a bump in the version number is needed.
 * This task is intended to be called by a continuous integration system
 * that will auto-push any changes back to the main repository.
 */
gulp.task('release-if-changed', function(callback) {
  var nodeVersion = new Semver(process.version);
  if (nodeVersion.compare(new Semver('5.0.0')) < 0) {
    return callback();
  }

  didLastCommitChangeVersionNumber()
      .then(getNextVersionNumber)
      .then(updatePackageToNewVersion)
      .catch(function(err) {
        throw err;
      });
});
<commit_msg>Tag releases<commit_after>/*
 * Copyright 2015 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Build process for closure-compiler-npm package
 *
 * Since the package doesn't require building, this file runs
 * tests and auto-increments the version number. Auto-increment
 * is used to support continuous delivery.
 *
 * @author Chad Killingsworth (chadkillingsworth@gmail.com)
 */

'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var mocha = require('gulp-mocha');
var git = require('simple-git')(__dirname);
var Semver = require('semver');
var fs = require('fs');
var packageInfo = require('./package.json');
var currentVer = new Semver(packageInfo.version);

gulp.task('test', function() {
  return gulp.src('./test/**.js', {read: false})
      .pipe(mocha());
});
gulp.task('default', ['test']);

/**
 * Check the git diff for package.json to return whether it included
 * a change to the version number.
 * @return {Promise<boolean>}
 */
var didLastCommitChangeVersionNumber = function() {
  return new Promise(function (resolve, reject) {
    git.diff(['HEAD^', 'HEAD', 'package.json'], function(err, data) {
      if (err) {
        return reject(err);
      }

      var versionData = (data || '').match(/^[+-]\s*"version": "[^"]+",$/mg);
      var versionChanged = versionData === null ? false : versionData.length === 2;
      return resolve(versionChanged);
    });
  });
};

/**
 * If the previous commit didn't include a version number change,
 * calculate what the new version should be.
 *
 * @param {boolean} alreadyChanged
 * @returns {Promise<Semver>}
 */
var getNextVersionNumber = function(alreadyChanged) {
  return new Promise(function(resolve, reject) {
    if (alreadyChanged) {
      gutil.log('Most recent commit incremented version number. No changes needed.');
      return resolve(currentVer);
    }

    var Compiler = require('./lib/node/closure-compiler');
    var compiler = new Compiler({version: true});
    compiler.run(function(code, data, err) {
      if (code !== 0) {
        return reject(new Error('Non-zero exit code: ' + code));
      }

      var versionNum = (data || '').match(/Version:\sv(.*)$/m);
      if (versionNum.length !== 2) {
        return resolve(new Error('Unable to parse compiler version number'));
      }
      var compilerVer = new Semver(versionNum[1] + '.0.0');

      if (compilerVer.compare(currentVer) > 0) {
        gutil.log('New compiler version detected. Increment major version.');
        return resolve(compilerVer);
      }

      var nextVersion = new Semver(packageInfo.version);
      nextVersion.inc('minor');
      gutil.log('Changes detected. Increment minor version.');
      return resolve(nextVersion);
    });
  });
};

/**
 * Given a semver object, update package.json (if needed) to the
 * new version number. If changed, add and commit package.json.
 *
 * @param {Semver} newVersion
 * @returns {Promise<boolean>}
 */
var updatePackageToNewVersion = function(newVersion) {
  return new Promise(function(resolve, reject) {
    if (currentVer.compare(newVersion) >= 0) {
      return resolve(false);
    }

    packageInfo.version = newVersion.version;
    fs.writeFileSync('./package.json', JSON.stringify(packageInfo, null, 2) + '\n');

    git.add('package.json', function(err, data) {})
        .commit('Increment version number to ' + newVersion.version, function(err, data) {})
        .addTag(newVersion.version, function() {
          gutil.log('New version committed: ' + newVersion.version);
          return resolve(true);
        });
  });
};

/**
 * Task to determine whether a bump in the version number is needed.
 * This task is intended to be called by a continuous integration system
 * that will auto-push any changes back to the main repository.
 */
gulp.task('release-if-changed', function(callback) {
  var nodeVersion = new Semver(process.version);
  if (nodeVersion.compare(new Semver('5.0.0')) < 0) {
    return callback();
  }

  didLastCommitChangeVersionNumber()
      .then(getNextVersionNumber)
      .then(updatePackageToNewVersion)
      .catch(function(err) {
        throw err;
      });
});
<|endoftext|>


<commit_before>'use strict'

var fs = require('fs');
var seneca = require('seneca')();
var async = require('async');

var dojos = JSON.parse(fs.readFileSync('./data/users.json', 'utf8'));
var plugin = "load-users";
var config = require('config');
var ENTITY_NS = "cd/users";

seneca.use('mongo-store', config.db)

seneca.ready(function() {
  seneca.add({ role: plugin, cmd: 'insert' }, function (args, done) {

    function createUser(user, cb){
      seneca.make$(ENTITY_NS).save$(user, function(err, response) {
        if(err){
          return cb(err);
        }

        return cb(null, response);
      });
    }

    var loadUsers = function (done) {
      async.eachSeries(dojos, createUser , done);
    };

    async.series([
      loadUsers
    ], done);

  });

  seneca.act({ role: plugin, cmd: 'insert', timeout: false }, function(err){
    if(err){
      throw err;
    } else{
      console.log("complete");
    }
  });

});
<commit_msg>Modify loadUsers.js script - now registers users and reset passwords<commit_after>'use strict'

var fs = require('fs');
var seneca = require('seneca')();
var async = require('async');

var users = JSON.parse(fs.readFileSync('./data/users-test.json', 'utf8'));
var plugin = "load-users";
var config = require('config');
var ENTITY_NS = "cd/users-test";

seneca.use('mongo-store', config.db)
seneca.use('user');

seneca.ready(function() {
  var userpin = seneca.pin({role:'user',cmd:'*'});
  var userent = seneca.make('sys/user');

  seneca.add({ role: plugin, cmd: 'register-users' }, function (args, done) {

    function registerUser(user, cb){
      console.log("registering %s", user.email);
      user.name = user.username;
      userpin.register(user, function(err, out){
        if(err){
          return cb(err);
        } else {
          return cb(null, out.ok);
        }
      });
    }

    function resetUser(user, cb){
      console.log("resetting %s", user.email);
      userpin.create_reset({email: user.email}, function(err, out){
        if(err){
          return cb(err);
        } else {
          userpin.execute_reset({
            token: out.reset.id,
            password: "a",
            repeat: "a"
          }, function(err, out){
            if(err){
              return cb(err);
            } else {
              return cb(null, out.ok);
            }
          })
        }

      })
    }

    function registerUsers(done){
      async.eachSeries(users, registerUser, done);
    }

    function resetUsers(done){

      userent.list$(function(err, users){
        async.eachSeries(users, resetUser, done);
      })
    }

    async.series([registerUsers, resetUsers], done);
  });

  seneca.act({ role: plugin, cmd: 'register-users', timeout: false},
    function(err){
      if(err){
        throw err;
      } else{
        console.log("complete");
      }
    });
});<|endoftext|>


<commit_before>"use strict";
define(["smoothly", "recorder"], function(Smoothly, Recorder) {
  var Turtle = function(element, w, h) {
    function xCenter() { return w / 2 }
    function yCenter() { return h / 2 }
    function setSize(width, height) {
      w = width
      h = height
      element.css({position: "relative", width: w, height: h})
      element.find("canvas").attr("width", w).attr("height", h)
    }
    var pendown = true

    var paper = createCanvas(0)
    var turtle = createCanvas(1)
    setSize(w, h)
    var cursor = {} // keys: image, width, height, left, top

    paper.save()
    turtle.save()

    init()

    function fontWithSize(size) {
      return size + "px Courier"
    }

    function init() {
      clearTurtle()
      paper.setTransform(1, 0, 0, 1, 0, 0)
      turtle.setTransform(1, 0, 0, 1, 0, 0)
      paper.clearRect(0, 0, w, h)
      turtle.clearRect(0, 0, w, h)
      paper.translate(xCenter(), yCenter())
      turtle.translate(xCenter(), yCenter())
      setBackground("white")
      paper.font=fontWithSize(20)
      setColor("black")
      drawTurtle()
    }
    function setBackground(color) {
      element.css("background-color", color);
    }
    function turtleToHome() {
      clearTurtle()
      paper.setTransform(1, 0, 0, 1, 0, 0)
      turtle.setTransform(1, 0, 0, 1, 0, 0)
      paper.translate(xCenter(), yCenter());
      turtle.translate(xCenter(), yCenter());
      drawTurtle()
    }
    function createCanvas(zIndex) {
      var canvas = $("<canvas></canvas>")
      canvas.css({position: "absolute", left: 0, right: 0})
      canvas.css({"z-index": zIndex})
      element.append(canvas)
      return canvas.get(0).getContext('2d');
    }
    function clearTurtle() {
      if ("image" in cursor) {
        turtle.clearRect(cursor.clearOffset, cursor.clearOffset, cursor.clearSize, cursor.clearSize)
      } else {
        turtle.clearRect(-11, -11, 23, 23)
      }
    }
    function drawTurtle() {
      if ("image" in cursor) {
        turtle.drawImage(cursor.image, cursor.left, cursor.top)
      } else {
        turtle.beginPath();
        turtle.moveTo(0, -10);
        turtle.lineTo(5, 10);
        turtle.lineTo(-5, 10);
        turtle.lineTo(0, -10);
        turtle.stroke();
      }
    }
    function setColor(color) {
      paper.strokeStyle=color
      paper.fillStyle=color
    }

    var api = {
      resize: function(newWidth, newHeight) {
        setSize(newWidth, newHeight)
        init()
      },
      fd: function(dist) {
        Smoothly.step(dist, 5, function(step) {
          if (pendown) {
            paper.beginPath()
            paper.moveTo(0, 0)
            paper.lineTo(0, -step)
            paper.stroke()
          }
          clearTurtle()
          paper.translate(0, -step)
          turtle.translate(0, -step)
          drawTurtle()
        })
      },
      lt: function(angle) {
        this.rt(-angle)
      },
      rt: function(angle) {
        Smoothly.step(angle, 10, function(a) {
          clearTurtle()
          paper.rotate(a * Math.PI / 180)
          turtle.rotate(a * Math.PI / 180)
          drawTurtle()
        })
      },
      pendown: Smoothly.do(function() {
        pendown = true
      }),
      penup: Smoothly.do(function() {
        pendown = false
      }),
      spin: function(degrees, delay) {
        this.lt(360)
      },
      setshape: function(name) {
        var image = new Image()
        image.onload = function() {
          clearTurtle()
          cursor.image = image
          cursor.height = this.height
          cursor.width = this.width
          cursor.left = -this.width / 2
          cursor.top = -this.height / 2
          cursor.clearSize = Math.sqrt(Math.pow(this.height, 2) + Math.pow(this.width, 2)) + 1
          cursor.clearOffset = -cursor.clearSize / 2
          drawTurtle()
        }
        image.src = "images/" + name + ".png"
      },
      background: function(color) {
        Smoothly.do(function() {
          setBackground(color)
        })()
      },
      color: function(color) {
        Smoothly.do(function() {
          setColor(color)
        })()
      },
      text: function(text) {
        Smoothly.do(function() {
          paper.fillText(text, 0, 0)
        })()
      },
      font: function(font) {
        if (typeof font == "number") {
          font = fontWithSize(font)
        }
        Smoothly.do(function() {
          paper.font = font
        })()
      },
      clear: function() {
        recorder._recorder.reset()
        Smoothly.do(function() {
          init()
        })()
      },
      home: Smoothly.do(function() {
        turtleToHome()
      })
    }
    var recorder = Recorder(api)
    return recorder
  }

  return Turtle
})
<commit_msg>pendown on clear<commit_after>"use strict";
define(["smoothly", "recorder"], function(Smoothly, Recorder) {
  var Turtle = function(element, w, h) {
    function xCenter() { return w / 2 }
    function yCenter() { return h / 2 }
    function setSize(width, height) {
      w = width
      h = height
      element.css({position: "relative", width: w, height: h})
      element.find("canvas").attr("width", w).attr("height", h)
    }
    var pendown = true

    var paper = createCanvas(0)
    var turtle = createCanvas(1)
    setSize(w, h)
    var cursor = {} // keys: image, width, height, left, top

    paper.save()
    turtle.save()

    init()

    function fontWithSize(size) {
      return size + "px Courier"
    }

    function init() {
      clearTurtle()
      paper.setTransform(1, 0, 0, 1, 0, 0)
      turtle.setTransform(1, 0, 0, 1, 0, 0)
      paper.clearRect(0, 0, w, h)
      turtle.clearRect(0, 0, w, h)
      paper.translate(xCenter(), yCenter())
      turtle.translate(xCenter(), yCenter())
      setBackground("white")
      paper.font=fontWithSize(20)
      setColor("black")
      drawTurtle()
    }
    function setBackground(color) {
      element.css("background-color", color);
    }
    function turtleToHome() {
      clearTurtle()
      paper.setTransform(1, 0, 0, 1, 0, 0)
      turtle.setTransform(1, 0, 0, 1, 0, 0)
      paper.translate(xCenter(), yCenter());
      turtle.translate(xCenter(), yCenter());
      drawTurtle()
    }
    function createCanvas(zIndex) {
      var canvas = $("<canvas></canvas>")
      canvas.css({position: "absolute", left: 0, right: 0})
      canvas.css({"z-index": zIndex})
      element.append(canvas)
      return canvas.get(0).getContext('2d');
    }
    function clearTurtle() {
      if ("image" in cursor) {
        turtle.clearRect(cursor.clearOffset, cursor.clearOffset, cursor.clearSize, cursor.clearSize)
      } else {
        turtle.clearRect(-11, -11, 23, 23)
      }
    }
    function drawTurtle() {
      if ("image" in cursor) {
        turtle.drawImage(cursor.image, cursor.left, cursor.top)
      } else {
        turtle.beginPath();
        turtle.moveTo(0, -10);
        turtle.lineTo(5, 10);
        turtle.lineTo(-5, 10);
        turtle.lineTo(0, -10);
        turtle.stroke();
      }
    }
    function setColor(color) {
      paper.strokeStyle=color
      paper.fillStyle=color
    }

    var api = {
      resize: function(newWidth, newHeight) {
        setSize(newWidth, newHeight)
        init()
      },
      fd: function(dist) {
        Smoothly.step(dist, 5, function(step) {
          if (pendown) {
            paper.beginPath()
            paper.moveTo(0, 0)
            paper.lineTo(0, -step)
            paper.stroke()
          }
          clearTurtle()
          paper.translate(0, -step)
          turtle.translate(0, -step)
          drawTurtle()
        })
      },
      lt: function(angle) {
        this.rt(-angle)
      },
      rt: function(angle) {
        Smoothly.step(angle, 10, function(a) {
          clearTurtle()
          paper.rotate(a * Math.PI / 180)
          turtle.rotate(a * Math.PI / 180)
          pendown = true
          drawTurtle()
        })
      },
      pendown: Smoothly.do(function() {
        pendown = true
      }),
      penup: Smoothly.do(function() {
        pendown = false
      }),
      spin: function(degrees, delay) {
        this.lt(360)
      },
      setshape: function(name) {
        var image = new Image()
        image.onload = function() {
          clearTurtle()
          cursor.image = image
          cursor.height = this.height
          cursor.width = this.width
          cursor.left = -this.width / 2
          cursor.top = -this.height / 2
          cursor.clearSize = Math.sqrt(Math.pow(this.height, 2) + Math.pow(this.width, 2)) + 1
          cursor.clearOffset = -cursor.clearSize / 2
          drawTurtle()
        }
        image.src = "images/" + name + ".png"
      },
      background: function(color) {
        Smoothly.do(function() {
          setBackground(color)
        })()
      },
      color: function(color) {
        Smoothly.do(function() {
          setColor(color)
        })()
      },
      text: function(text) {
        Smoothly.do(function() {
          paper.fillText(text, 0, 0)
        })()
      },
      font: function(font) {
        if (typeof font == "number") {
          font = fontWithSize(font)
        }
        Smoothly.do(function() {
          paper.font = font
        })()
      },
      clear: function() {
        recorder._recorder.reset()
        Smoothly.do(function() {
          init()
        })()
      },
      home: Smoothly.do(function() {
        turtleToHome()
      })
    }
    var recorder = Recorder(api)
    return recorder
  }

  return Turtle
})
<|endoftext|>


<commit_before>// gulpfile.js

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    minifyCSS = require('gulp-minify-css'),
    rename = require('gulp-rename'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    gutil = require('gulp-util'),

    chalk = gutil.colors,
    destination = gulp.dest,
    greenChalk = chalk.green,
    highlightChalk = chalk.underline.cyan.bgMagenta,
    log = gutil.log,
    timestamp = (new Date()).toString(),

    input = {
      'js': './source/js/**/*.js',
      'mainscss': './source/scss/raptor.scss',
      'scss': './source/scss/**/*.scss',
      'vendorjs': './assets/javascripts/vendors/**/*.js'
    },
    output = {
      'stylesheets': './assets/stylesheets',
      'javascripts': './assets/javascripts'
    };

/// Prevents `watch` from breaking because of errors
/// SOURCE: http://stackoverflow.com/a/23973536
function handleError(error) {
  console.log(error.toString());
  this.emit('end');
}

gulp.task('raptor-css', function() {
  log('Generating', highlightChalk('RAPTORSMACSS'), 'based stylesheet at', greenChalk(timestamp));
  return gulp.src(input.mainscss)
    .pipe(sourcemaps.init())
      .pipe(sass({
        style: 'expanded'
      }))
      .on('error', handleError)
      .pipe(destination(output.stylesheets))
      .pipe(rename({
        suffix: '.min'
      }))
      .pipe(minifyCSS())
    .pipe(sourcemaps.write('./'))
    .pipe(destination(output.stylesheets));
});

gulp.task('raptor-js', function() {
  log('Generating', highlightChalk('RAPTORSMACSS'), 'based JavaScript file at', greenChalk(timestamp));
  return gulp.src([input.vendorjs, input.js])
    .pipe(sourcemaps.init())
      .pipe(concat('raptor.js'))
      .on('error', handleError)
      .pipe(destination(output.javascripts))
    .pipe(sourcemaps.write('./'))
    .pipe(destination(output.javascripts));
});

gulp.task('watch', function() {
  log('Watching for changes in the', highlightChalk('RAPTORSMACSS'), 'SCSS and JS files...');
  gulp.watch(input.scss, ['raptor-css']);
  gulp.watch(input.js, ['raptor-js']);
});

gulp.task('raptor-build', ['raptor-css', 'raptor-js']);

gulp.task('default', ['raptor-build', 'watch']);
<commit_msg>task(gulpfile): Further update Gulpfile<commit_after>// gulpfile.js

////= RAPTORSMACSS Gulp Tasks
//======================================================================//

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    minifyCSS = require('gulp-minify-css'),
    rename = require('gulp-rename'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    gutil = require('gulp-util');

var chalk = gutil.colors,
    destination = gulp.dest,
    greenChalk = chalk.green,
    redChalk = chalk.red,
    highlightChalk = chalk.cyan.underline.bgBlue,
    log = gutil.log,
    timestamp = (new Date()).toString();

var input = {
      'js': './source/js/**/*.js',
      'mainscss': './source/scss/raptor.scss',
      'scss': './source/scss/**/*.scss',
      'vendorjs': './assets/javascripts/vendors/**/*.js'
    },
    output = {
      'stylesheets': './assets/stylesheets',
      'javascripts': './assets/javascripts'
    };

//== Functions ==========================================================/

/// Prevents `watch` from breaking because of errors
/// SOURCE: http://stackoverflow.com/a/23973536
function handleError(error) {
  console.log(error.toString());
  this.emit('end');
}

//== Style Task =========================================================/

gulp.task('raptor-style', function() {
  log('Generating', highlightChalk('RAPTORSMACSS'), 'based', redChalk('stylesheet'), 'at', greenChalk(timestamp));
  return gulp.src(input.mainscss)
    .pipe(sourcemaps.init())
      .pipe(sass({
        outputStyle: 'expanded'
      }))
      .on('error', handleError)
      .pipe(destination(output.stylesheets))
      .pipe(rename({
        suffix: '.min'
      }))
      .pipe(minifyCSS())
    .pipe(sourcemaps.write('./'))
    .pipe(destination(output.stylesheets));
});

//== Script Task ========================================================/

gulp.task('raptor-script', function() {
  log('Generating', highlightChalk('RAPTORSMACSS'), 'based', redChalk('JavaScript'), 'file at', greenChalk(timestamp));
  return gulp.src([input.vendorjs, input.js])
    .pipe(sourcemaps.init())
      .pipe(concat('raptor.js'))
      .on('error', handleError)
      .pipe(destination(output.javascripts))
    .pipe(sourcemaps.write('./'))
    .pipe(destination(output.javascripts));
});

//== Management Tasks ===================================================/

gulp.task('watch', function() {
  log('Watching for changes in the', highlightChalk('RAPTORSMACSS'), redChalk('SCSS'), 'and', redChalk('JS'), 'files...');
  gulp.watch(input.scss, ['raptor-style']);
  gulp.watch(input.js, ['raptor-script']);
});

gulp.task('default', ['watch', 'raptor-style', 'raptor-script']);

gulp.task('build', ['raptor-style', 'raptor-script']);

gulp.task('raptor', ['watch', 'raptor-style', 'raptor-script']);
<|endoftext|>


<commit_before>const selectizeOptions =
{
    delimiter: ', ',
    create: false,
    persist: false,
    preload: true,
    plugins: ['clear_selection']
};
const iCheckOptions =
{
    checkboxClass: 'icheckbox_square-red',
    radioClass: 'iradio_square-red'
};

Chart.defaults.global.legend.display = false;
Chart.defaults.global.title.display = true;
const chartBackgroundColors =
[
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)',
    'rgba(255, 159, 64, 0.2)'
];
const chartBorderColors =
[
    'rgba(255,99,132, 1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
    'rgba(75, 192, 192, 1)',
    'rgba(153, 102, 255, 1)',
    'rgba(255, 159, 64, 1)'
];

Nette.showFormErrors = function (form, errors)
{
    $(form).find('ul.form-errors, span.form-error').remove();

    for (var i = 0; i < errors.length; i++)
    {
        $(errors[i].element).parent().parent().find('th').append('' + errors[i].message + '');
    }

    if (errors.length > 0)
    {
        var elem = errors[0].element;

        if (elem.nodeName == 'SELECT')
        {
            $(elem).parent().find('input[type="text"]').trigger('click');
            return;
        }
        $(elem).focus();
    }
};

function debounce(func, wait, immediate) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

function getCountryCode(code)
{
    switch(code)
    {
        case 'cs': return 'cz';
        case 'en': return 'gb';
        default: return code;
    }
}

jQuery.fn.fade = function()
{
    this.fadeTo('slow', 0, 'linear').slideUp('slow', 'linear', function() { $(this).remove(); });
};

function flashFadeOut()
{
    $('.flash').delay(2000).fade();
}

function refreshPlugins(context, recaptcha)
{
    if (typeof recaptcha !== 'undefined' && recaptcha)
    {
        g_ReCaptchaOnLoad();
    }

    var checkInputs = $(context).find('input[type="radio"]:not(.rating), input[type="checkbox"]');
    checkInputs.iCheck(iCheckOptions);
    checkInputs.on('ifChanged', function (event)
    {
        event = document.createEvent('HTMLEvents');
        event.initEvent('change', true, true);
        event.eventName = 'change';

        this.dispatchEvent(event);
    });

    var selectInputs = $(context).find('select:not(#localeInput)');
    selectInputs.selectize(selectizeOptions);

    if (recaptcha)
    {
        g_ReCaptchaOnLoad();
    }
}

$(document).ready(function ()
{
    flashFadeOut();

    $.nette.ext('flash', {
        complete: flashFadeOut
    });
    $.nette.init();

    var searchInput = $('#searchInput');
    searchInput.keyup(
        debounce(function()
        {
            var value = $(this).val();

            if (value.length < 3)
            {
                return;
            }

            $.nette.ajax(
            {
                traditional: true,
                url: searchUrl,
                method: 'GET',
                data:
                {
                    search: value
                }
            });
        }, 300));

    var localeInput = $('#localeInput');
    localeInput.selectize({
        labelField: 'name',
        valueField: 'code',
        render: {
            item: function(item, escape) {
                return '
 ' + escape(item.name) + '
';
            },
            option: function(item, escape) {
                return '
 ' + escape(item.name) + '
';
            }
        },
    });
    localeInput.change(function()
    {
        var array = window.location.pathname.split('/');
        array[1] = this.value;
        window.location.href = array.join('/');
    });

    refreshPlugins(document.body);
});
<commit_msg>removed forgotten code in js<commit_after>const selectizeOptions =
{
    delimiter: ', ',
    create: false,
    persist: false,
    preload: true,
    plugins: ['clear_selection']
};
const iCheckOptions =
{
    checkboxClass: 'icheckbox_square-red',
    radioClass: 'iradio_square-red'
};

Chart.defaults.global.legend.display = false;
Chart.defaults.global.title.display = true;
const chartBackgroundColors =
[
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)',
    'rgba(255, 159, 64, 0.2)'
];
const chartBorderColors =
[
    'rgba(255,99,132, 1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
    'rgba(75, 192, 192, 1)',
    'rgba(153, 102, 255, 1)',
    'rgba(255, 159, 64, 1)'
];

Nette.showFormErrors = function (form, errors)
{
    $(form).find('ul.form-errors, span.form-error').remove();

    for (var i = 0; i < errors.length; i++)
    {
        $(errors[i].element).parent().parent().find('th').append('' + errors[i].message + '');
    }

    if (errors.length > 0)
    {
        var elem = errors[0].element;

        if (elem.nodeName == 'SELECT')
        {
            $(elem).parent().find('input[type="text"]').trigger('click');
            return;
        }
        $(elem).focus();
    }
};

function debounce(func, wait, immediate) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

function getCountryCode(code)
{
    switch(code)
    {
        case 'cs': return 'cz';
        case 'en': return 'gb';
        default: return code;
    }
}

jQuery.fn.fade = function()
{
    this.fadeTo('slow', 0, 'linear').slideUp('slow', 'linear', function() { $(this).remove(); });
};

function flashFadeOut()
{
    $('.flash').delay(2000).fade();
}

function refreshPlugins(context, recaptcha)
{
    if (typeof recaptcha !== 'undefined' && recaptcha)
    {
        g_ReCaptchaOnLoad();
    }

    var checkInputs = $(context).find('input[type="radio"]:not(.rating), input[type="checkbox"]');
    checkInputs.iCheck(iCheckOptions);
    checkInputs.on('ifChanged', function (event)
    {
        event = document.createEvent('HTMLEvents');
        event.initEvent('change', true, true);
        event.eventName = 'change';

        this.dispatchEvent(event);
    });

    var selectInputs = $(context).find('select:not(#localeInput)');
    selectInputs.selectize(selectizeOptions);

}

$(document).ready(function ()
{
    flashFadeOut();

    $.nette.ext('flash', {
        complete: flashFadeOut
    });
    $.nette.init();

    var searchInput = $('#searchInput');
    searchInput.keyup(
        debounce(function()
        {
            var value = $(this).val();

            if (value.length < 3)
            {
                return;
            }

            $.nette.ajax(
            {
                traditional: true,
                url: searchUrl,
                method: 'GET',
                data:
                {
                    search: value
                }
            });
        }, 300));

    var localeInput = $('#localeInput');
    localeInput.selectize({
        labelField: 'name',
        valueField: 'code',
        render: {
            item: function(item, escape) {
                return '
 ' + escape(item.name) + '
';
            },
            option: function(item, escape) {
                return '
 ' + escape(item.name) + '
';
            }
        },
    });
    localeInput.change(function()
    {
        var array = window.location.pathname.split('/');
        array[1] = this.value;
        window.location.href = array.join('/');
    });

    refreshPlugins(document.body);
});
<|endoftext|>


<commit_before>define(['chart-pings'], function(pings) {

    var element = d3.select('#chart').append('svg:svg')
    var elementWidth = parseInt(element.style('width'))
    var elementHeight = parseInt(element.style('height'))

    var maxPing = 5000 // TODO DRY

    var yScale = d3.scale.linear().domain([0, maxPing]).range([0, elementHeight])

    // TODO It is not displayed correctly if results in a float
    var barWidth = elementWidth / pings.max()

    var selections = (function() {
        var enter, update, exit
        return {
            entered: function() { return enter },
            updated: function() { return update },
            exited: function() { return exit },
            update: function() {
                update = element.selectAll('rect')
                    .data(pings.all(), function(ping, i) { return ping.start() })
                enter = update.enter().append('svg:rect')
                exit = update.exit()
            }
        }
    })()

    selections.update()

    setInterval(function() {
        var updated = selections.updated()
        updated
            .attr('x', function(ping, i) { return i * barWidth })
            .attr('y', function(ping) { return yScale(maxPing - ping.lag()) })
            .attr('height', function(ping) { return yScale(ping.lag()) })
            .style('fill-opacity', function(ping) { return ping.end() ? 1 : 0.7 })
    }, 50)

    return {
        addPing: function() {

            var ping = pings.add()

            selections.update()

            var entered = selections.entered()
            entered.attr('width', barWidth)

            selections.exited().remove()

            return ping
        }
    }
})
<commit_msg>Make the chart move constantly<commit_after>define(['chart-pings'], function(pings) {

    var element = d3.select('#chart').append('svg:svg')
    var elementWidth = parseInt(element.style('width'))
    var elementHeight = parseInt(element.style('height'))

    var maxPing = 5000 // TODO DRY
    var pingInterval = 500 // TODO DRY

    var yScale = d3.scale.linear().domain([0, maxPing]).range([0, elementHeight])
    var xScale = d3.scale.linear().range([0, elementWidth])

    // TODO It is not displayed correctly if results in a float
    var barWidth = elementWidth / pings.max()

    var selections = (function() {
        var entered, updated, exited
        return {
            entered: function() { return entered },
            updated: function() { return updated },
            exited: function() { return exited },
            update: function() {
                updated = element.selectAll('rect')
                    .data(pings.all(), function(ping, i) { return ping.start() })
                entered = updated.enter()
                exited = updated.exit()
            }
        }
    })()

    selections.update()

    setInterval(function() {

        selections.updated()
            .attr('y', function(ping) { return yScale(maxPing - ping.lag()) })
            .attr('height', function(ping) { return yScale(ping.lag()) })
            .style('fill-opacity', function(ping) { return ping.end() ? 1 : 0.7 })

        var now = new Date().getTime()
        xScale.domain([now - pings.max() * pingInterval, now])
        ;[selections.updated(), selections.exited()].forEach(function(selection) {
            selection.attr('x', function(ping) { return xScale(ping.start()) })
        })

    }, 60)

    return {
        addPing: function() {

            var ping = pings.add()

            selections.update()

            selections.entered().append('svg:rect')
                .attr('width', barWidth)

            selections.exited().transition()
                .duration(pingInterval) // TODO DRY
                .remove()

            return ping
        }
    }
})
<|endoftext|>


<commit_before>/* eslint-disable import/no-commonjs, import/no-unassigned-import, max-nested-callbacks */
// Note: Node 8 compat, please!
require('hard-rejection/register')

const fs = require('fs')
const childProcess = require('child_process')
const path = require('path')
const {series, parallel, src, dest, watch} = require('gulp')
const newer = require('gulp-newer')
const babel = require('gulp-babel')
const gutil = require('gulp-util')
const changed = require('gulp-changed')
const filter = require('gulp-filter')
const plumber = require('gulp-plumber')
const ts = require('gulp-typescript')
const sourcemaps = require('gulp-sourcemaps')
const through = require('through2')
const chalk = require('chalk')
const globby = require('globby')
const mergeStream = require('merge-stream')
const {promisify} = require('util')

const stat = promisify(fs.stat)
const isWindows = /^win/.test(process.platform)

const compareModified = async (stream, sourceFile, targetPath) => {
  const targetStat = await stat(targetPath)

  if (sourceFile.stat && Math.floor(sourceFile.stat.mtimeMs) > Math.floor(targetStat.mtimeMs)) {
    stream.push(sourceFile)
  }
}

const tsPaths = globby.sync(['./packages/@sanity/*/tsconfig.json'])
const tsProjects = tsPaths.map(conf => ts.createProject(conf))
const scripts = [
  './packages/@sanity/*/src/**/*.{js,ts,tsx}',
  './packages/sanity-plugin-*/src/**/*.{js,ts,tsx}',
  './packages/groq/src/**/*.{js,ts,tsx}'
]

const assets = [
  './packages/@sanity/*/src/**/*',
  './packages/sanity-plugin-*/src/**/*',
  './packages/groq/src/**/*'
]

const srcOpts = {base: 'packages'}

const getProjectEnv = projectPath => {
  const npmPath = path.join(projectPath, 'node_modules', '.bin')
  /* eslint-disable no-process-env */
  const paths = [npmPath].concat(process.env.PATH.split(path.delimiter)).filter(Boolean)
  return Object.assign({}, process.env, {
    PATH: paths.join(path.delimiter)
  })
  /* eslint-enable no-process-env */
}

let srcEx
let srcRootEx
let libFragment

if (path.win32 === path) {
  srcEx = /(@sanity\\[^\\]+)\\src\\/
  srcRootEx = /(groq|sanity-plugin-[^\\]+)\\src\\/
  libFragment = '$1\\lib\\'
} else {
  srcEx = new RegExp('(@sanity/[^/]+)/src/')
  srcRootEx = /(groq|sanity-plugin-[^/]+)\/src\//
  libFragment = '$1/lib/'
}

const logCompile = from => (file, enc, cb) => {
  gutil.log(`[${from}] Compiling`, `'${chalk.cyan(file._path || file.path)}'...`)
  cb(null, file)
}

const mapToDest = orgPath => {
  const outPath = orgPath.replace(srcEx, libFragment).replace(srcRootEx, libFragment)
  return outPath
}

const packagesPath = 'packages'
const pkgPath = (cwd, sourcePath) => path.relative(path.join(cwd, 'packages'), sourcePath)
const getLogErrorHandler = () => plumber({errorHandler: err => gutil.log(err.stack)})
const watchJavaScript = series(buildJavaScript, function watchJS() {
  watch(scripts, watchJavaScriptRebuild)
})

const watchAssets = series(buildAssets, function watchAsset() {
  watch(assets, buildAssets)
})

const watchTypeScript = series(buildTypeScript, function watchTS() {
  tsProjects.forEach(project => {
    const builder = function() {
      return rebuildTypeScriptProject(project)
    }

    Object.defineProperty(builder, 'name', {
      value: `buildTypeScript[${path.basename(project.projectDirectory)}]`
    })

    watch(`${project.projectDirectory}/src/**/*.{ts,tsx}`, builder)
  })
})

exports.default = parallel(buildJavaScript, buildTypeScript)
exports.build = parallel(buildJavaScript, buildTypeScript)
exports.watchTypeScript = watchTypeScript
exports.watch = parallel(watchJavaScript, watchTypeScript, watchAssets)

function buildJavaScript() {
  const assetFilter = filter(['**/*.{js,ts,tsx}'], {restore: true})
  return src(assets, srcOpts)
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(assetFilter)
    .pipe(
      changed(packagesPath, {
        transformPath: inp => mapToDest(inp),
        hasChanged: compareModified
      })
    )
    .pipe(through.obj(logCompile('JS')))
    .pipe(babel())
    .pipe(assetFilter.restore)
    .pipe(
      through.obj((file, enc, callback) => {
        file._path = file.path
        file.path = mapToDest(file.path)
        callback(null, file)
      })
    )
    .pipe(dest(packagesPath))
}

function watchJavaScriptRebuild() {
  return src(scripts, srcOpts)
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(
      through.obj((file, enc, callback) => {
        file._path = file.path
        file.path = mapToDest(file.path)
        callback(null, file)
      })
    )
    .pipe(newer(packagesPath))
    .pipe(through.obj(logCompile('JS')))
    .pipe(babel())
    .pipe(dest(packagesPath))
}

function rebuildTypeScriptProject(project) {
  return project
    .src()
    .pipe(through.obj(logCompile('TS')))
    .pipe(getLogErrorHandler())
    .pipe(project())
    .js.pipe(getLogErrorHandler())
    .pipe(dest(project.options.outDir))
}

function buildTypeScript() {
  return mergeStream(
    ...tsProjects.map(project => {
      const compilation = project
        .src()
        .pipe(through.obj(logCompile('D.TS')))
        .pipe(project())
      return compilation.dts
        .pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: './'}))
        .pipe(dest(project.options.outDir))
    })
  )
}

function buildAssets() {
  return src(assets, srcOpts)
    .pipe(filter(['**/*.*', '!**/*.js', '!**/*.ts', '!**/*.tsx']))
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(
      through.obj((file, enc, callback) => {
        file._path = file.path
        file.path = mapToDest(file.path)
        callback(null, file)
      })
    )
    .pipe(newer(packagesPath))
    .pipe(
      through.obj((file, enc, callback) => {
        gutil.log('Copying  ', `'${chalk.green(pkgPath(file.cwd, file._path))}'...`)
        callback(null, file)
      })
    )
    .pipe(dest(packagesPath))
}

const STUDIOS = [
  {name: 'test-studio', port: '3333'},
  {name: 'movies-studio', port: '3334'},
  {name: 'example-studio', port: '3335'},
  {name: 'blog-studio', port: '3336'},
  {name: 'ecommerce-studio', port: '3337'},
  {name: 'clean-studio', port: '3338'}
]

STUDIOS.forEach(studio => {
  exports[studio.name] = series(
    parallel(buildJavaScript, buildTypeScript, buildAssets),
    parallel(exports.watch, function runStudio(cb) {
      const projectPath = path.join(__dirname, 'packages', studio.name)
      const proc = childProcess.spawn(
        'sanity',
        ['start', '--host', '0.0.0.0', '--port', studio.port],
        {
          shell: isWindows,
          cwd: projectPath,
          env: getProjectEnv(projectPath)
        }
      )

      proc.stdout.pipe(process.stdout)
      proc.stderr.pipe(process.stderr)
    })
  )
})

exports.storybook = series(
  parallel(buildJavaScript, buildTypeScript, buildAssets),
  parallel(exports.watch, function runStorybook(cb) {
    const projectPath = path.join(__dirname, 'packages', 'storybook')
    const proc = childProcess.spawn('npm', ['start'], {
      shell: isWindows,
      cwd: projectPath,
      env: getProjectEnv(projectPath)
    })

    proc.stdout.pipe(process.stdout)
    proc.stderr.pipe(process.stderr)
  })
)
<commit_msg>[chore] Gulp: Only recompile changed files (#1541)<commit_after>/* eslint-disable import/no-commonjs, import/no-unassigned-import, max-nested-callbacks */
// Note: Node 8 compat, please!
require('hard-rejection/register')

const fs = require('fs')
const childProcess = require('child_process')
const path = require('path')
const {series, parallel, src, dest, watch} = require('gulp')
const newer = require('gulp-newer')
const babel = require('gulp-babel')
const gutil = require('gulp-util')
const changed = require('gulp-changed')
const filter = require('gulp-filter')
const plumber = require('gulp-plumber')
const ts = require('gulp-typescript')
const sourcemaps = require('gulp-sourcemaps')
const through = require('through2')
const chalk = require('chalk')
const globby = require('globby')
const mergeStream = require('merge-stream')
const {promisify} = require('util')

const stat = promisify(fs.stat)
const isWindows = /^win/.test(process.platform)

const compareModified = async (stream, sourceFile, targetPath) => {
  const targetStat = await stat(targetPath)

  if (sourceFile.stat && Math.floor(sourceFile.stat.mtimeMs) > Math.floor(targetStat.mtimeMs)) {
    stream.push(sourceFile)
  }
}

const tsPaths = globby.sync(['./packages/@sanity/*/tsconfig.json'])
const tsProjects = tsPaths.map(conf => ts.createProject(conf))
const scripts = [
  './packages/@sanity/*/src/**/*.{js,ts,tsx}',
  './packages/sanity-plugin-*/src/**/*.{js,ts,tsx}',
  './packages/groq/src/**/*.{js,ts,tsx}'
]

const assets = [
  './packages/@sanity/*/src/**/*',
  './packages/sanity-plugin-*/src/**/*',
  './packages/groq/src/**/*'
]

const srcOpts = {base: 'packages'}

const getProjectEnv = projectPath => {
  const npmPath = path.join(projectPath, 'node_modules', '.bin')
  /* eslint-disable no-process-env */
  const paths = [npmPath].concat(process.env.PATH.split(path.delimiter)).filter(Boolean)
  return Object.assign({}, process.env, {
    PATH: paths.join(path.delimiter)
  })
  /* eslint-enable no-process-env */
}

let srcEx
let srcRootEx
let libFragment

if (path.win32 === path) {
  srcEx = /(@sanity\\[^\\]+)\\src\\/
  srcRootEx = /(groq|sanity-plugin-[^\\]+)\\src\\/
  libFragment = '$1\\lib\\'
} else {
  srcEx = new RegExp('(@sanity/[^/]+)/src/')
  srcRootEx = /(groq|sanity-plugin-[^/]+)\/src\//
  libFragment = '$1/lib/'
}

const logCompile = from => (file, enc, cb) => {
  gutil.log(`[${from}] Compiling`, `'${chalk.cyan(file._path || file.path)}'...`)
  cb(null, file)
}

const mapToDefinitionPath = baseDir => {
  const packagesRoot = path.join(__dirname, 'packages')
  return orgPath => {
    return path
      .join(baseDir, 'lib', orgPath.replace(packagesRoot, ''))
      .replace(/\.d\.d\.tsx?$/, '.d.ts')
  }
}

const mapToDest = orgPath => {
  const outPath = orgPath
    .replace(srcEx, libFragment)
    .replace(srcRootEx, libFragment)
    .replace(/\.tsx?$/, '.js')

  return outPath
}

const packagesPath = 'packages'
const pkgPath = (cwd, sourcePath) => path.relative(path.join(cwd, 'packages'), sourcePath)
const getLogErrorHandler = () => plumber({errorHandler: err => gutil.log(err.stack)})
const watchJavaScript = series(buildJavaScript, function watchJS() {
  watch(scripts, watchJavaScriptRebuild)
})

const watchAssets = series(buildAssets, function watchAsset() {
  watch(assets, buildAssets)
})

const watchTypeScript = series(buildTypeScript, function watchTS() {
  tsProjects.forEach(project => {
    const builder = function() {
      return rebuildTypeScriptProject(project)
    }

    Object.defineProperty(builder, 'name', {
      value: `buildTypeScript[${path.basename(project.projectDirectory)}]`
    })

    watch(`${project.projectDirectory}/src/**/*.{ts,tsx}`, builder)
  })
})

exports.default = parallel(buildJavaScript, buildTypeScript)
exports.build = parallel(buildJavaScript, buildTypeScript)
exports.watchTypeScript = watchTypeScript
exports.watch = parallel(watchJavaScript, watchTypeScript, watchAssets)

function buildJavaScript() {
  const assetFilter = filter(['**/*.{js,ts,tsx}'], {restore: true})
  return src(assets, srcOpts)
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(assetFilter)
    .pipe(
      changed(packagesPath, {
        transformPath: mapToDest,
        hasChanged: compareModified
      })
    )
    .pipe(through.obj(logCompile('JS')))
    .pipe(babel())
    .pipe(assetFilter.restore)
    .pipe(
      through.obj((file, enc, callback) => {
        file._path = file.path
        file.path = mapToDest(file.path)
        callback(null, file)
      })
    )
    .pipe(dest(packagesPath))
}

function watchJavaScriptRebuild() {
  return src(scripts, srcOpts)
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(
      through.obj((file, enc, callback) => {
        file._path = file.path
        file.path = mapToDest(file.path)
        callback(null, file)
      })
    )
    .pipe(newer(packagesPath))
    .pipe(through.obj(logCompile('JS')))
    .pipe(babel())
    .pipe(dest(packagesPath))
}

function rebuildTypeScriptProject(project) {
  return project
    .src()
    .pipe(through.obj(logCompile('TS')))
    .pipe(getLogErrorHandler())
    .pipe(project())
    .js.pipe(getLogErrorHandler())
    .pipe(dest(project.options.outDir))
}

function buildTypeScript() {
  return mergeStream(
    ...tsProjects.map(project => {
      const compilation = project
        .src()
        .pipe(
          changed(packagesPath, {
            transformPath: mapToDefinitionPath(project.projectDirectory),
            hasChanged: compareModified,
            extension: '.d.ts'
          })
        )
        .pipe(through.obj(logCompile('D.TS')))
        .pipe(project())
      return compilation.dts
        .pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: './'}))
        .pipe(dest(project.options.outDir))
    })
  )
}

function buildAssets() {
  return src(assets, srcOpts)
    .pipe(filter(['**/*.*', '!**/*.js', '!**/*.ts', '!**/*.tsx']))
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(
      through.obj((file, enc, callback) => {
        file._path = file.path
        file.path = mapToDest(file.path)
        callback(null, file)
      })
    )
    .pipe(newer(packagesPath))
    .pipe(
      through.obj((file, enc, callback) => {
        gutil.log('Copying  ', `'${chalk.green(pkgPath(file.cwd, file._path))}'...`)
        callback(null, file)
      })
    )
    .pipe(dest(packagesPath))
}

const STUDIOS = [
  {name: 'test-studio', port: '3333'},
  {name: 'movies-studio', port: '3334'},
  {name: 'example-studio', port: '3335'},
  {name: 'blog-studio', port: '3336'},
  {name: 'ecommerce-studio', port: '3337'},
  {name: 'clean-studio', port: '3338'}
]

STUDIOS.forEach(studio => {
  exports[studio.name] = series(
    parallel(buildJavaScript, buildTypeScript, buildAssets),
    parallel(exports.watch, function runStudio(cb) {
      const projectPath = path.join(__dirname, 'packages', studio.name)
      const proc = childProcess.spawn(
        'sanity',
        ['start', '--host', '0.0.0.0', '--port', studio.port],
        {
          shell: isWindows,
          cwd: projectPath,
          env: getProjectEnv(projectPath)
        }
      )

      proc.stdout.pipe(process.stdout)
      proc.stderr.pipe(process.stderr)
    })
  )
})

exports.storybook = series(
  parallel(buildJavaScript, buildTypeScript, buildAssets),
  parallel(exports.watch, function runStorybook(cb) {
    const projectPath = path.join(__dirname, 'packages', 'storybook')
    const proc = childProcess.spawn('npm', ['start'], {
      shell: isWindows,
      cwd: projectPath,
      env: getProjectEnv(projectPath)
    })

    proc.stdout.pipe(process.stdout)
    proc.stderr.pipe(process.stderr)
  })
)
<|endoftext|>