<commit_before>import Backbone from 'backbone';
import $ from 'jquery';
import _ from 'underscore';

// Views
import SaveDialog from './../saveDialog';
import FolderView from './../folderView';
import PlayView from './../playView';
import UploadDialog from './../uploadDialog';
import Ios from './ios';

// Collections
import FileCollection from './../../collections/fileCollection';

// Models
import File from './../../models/fileModel';
import GadgetronStreamConfiguration from './../../models/gadgetronStreamConfigurationModel'

// Extra
import config from './../../../../config.json';

Backbone.$ = $;
var saveDialog;
var self;

// Dashboard view
var Dashboard = Backbone.View.extend({
    initialize: function(attributes, options){
        this.redirectEvent = attributes.redirectEvent;
    },
    template: _.template($("#dashboard").html()),
    render: function() {
        self = this;
        var dashboardTemplate = this.template(this.model);
        this.$el.html(dashboardTemplate);
        $(this.el).hide();
        return this;
    },
    // render all Folder Views
    renderFolderViews: function(){
        var height = window.innerHeight - 3 * $('nav').outerHeight() - 4 - 4 * 20;

        // Render Configurations
        this.configurationFolderView = new FolderView({
            title: 'Configuration-Data',
            className: 'configuration-file',
            dirs: [ config.config_dir ],
            height: height/3,
            row: '#configuration-row',
            playButtonClickEvent: this.playButtonClickEvent,
            addButtonClickEvent: this.addButtonClickEvent,
            uploadButtonClickEvent: this.uploadButtonClickEvent,
            buttons: ['add', 'upload']
        });
        $('#dashboard-configuration').html(this.configurationFolderView.render().el);

        // Render Dat/H5-Folder
        this.datFolderView = new FolderView({
            title: 'DAT/H5-Data',
            className: 'dat-file',
            dirs: [ config.upload_dir + '/dat/', config.upload_dir + '/h5/'],
            height: height/3,
            uploadButtonClickEvent: this.uploadButtonClickEvent
        });
        $('#dashboard-dat').html(this.datFolderView.render().el);

        // Render XSL-Folder
        this.xslFolderView = new FolderView({
            title: 'XSL-Data',
            className: 'xsl-file',
            dirs: [ config.upload_dir + '/xsl/'],
            height: height/3,
            uploadButtonClickEvent: this.uploadButtonClickEvent
        });
        $('#dashboard-xsl').html(this.xslFolderView.render().el);

        // Render Result-Folder
        this.resultFolderView = new FolderView({
            title: 'Result-Data',
            className: 'result-file',
            dirs: [ config.result_dir + '/'],
            height: height/3,
            buttons: [],
            row: '#result-row'
        });
        $('#dashboard-results').html(this.resultFolderView.render().el);
    },
    // handels upload button click event
    uploadButtonClickEvent: function(event){
        var type = $(event.target.parentNode).data('type');
        var typeTitle;
        var title = 'Upload';
        var fileextension;
        var fileCollection;
        switch (type) {
            case 'configuration-file':
                title = `Configuration ${title}`;
                typeTitle = 'config';
                fileextension = '.xml';
                fileCollection = self.configurationFolderView.collection;
                break;
            case 'dat-file':
                title = `DAT/H5 ${title}`;
                fileextension = '.dat,.h5';
                fileCollection = self.datFolderView.collection;
                break;
            case 'xsl-file':
                title = `XSL ${title}`;
                fileextension = '.xsl';
                fileCollection = self.xslFolderView.collection;
                break;
            default:
                break;
        }
        // opens upload dialog
        self.uploadDialog = new UploadDialog({collection: fileCollection, fileextension, title, typeTitle});
        self.uploadDialog.show();
    },
    // handels add button click event
    addButtonClickEvent: function(event){
        // opens save dialog
        var saveDialog = new SaveDialog({title: 'Create new configuration', saveEvent: self.saveEvent});
        saveDialog.render();
    },
    // handels save event
    saveEvent: function(event, value){
        if(value){
            // check if value has xml extenstion
            var splittedFileName = value.split('.');
            if(splittedFileName.length > 1){
                if(splittedFileName.pop() != 'xml'){
                    return false;
                }
            }
            else{
                value = value + ".xml";
            }
            // search for configuration
            if(self.configurationFolderView.collection.where({name: value}).length > 0){
                $('#filename-group').addClass('has-error');
            }
            else{
                // create new configuration model
                var newConfiguration = new GadgetronStreamConfiguration();
                var fileName = newConfiguration.createModel(value)
                self.configurationFolderView.collection.add(newConfiguration);
                self.collection.add(newConfiguration);
                // redirect to new configuration
                self.redirectEvent('#gadgetronStreamConfiguration/' + fileName);
                $('#modal').modal('hide');
            }
        }
        else{
            $('#filename-group').addClass('has-error');
        }
    },
    // handles play button click event
    playButtonClickEvent: function(event, model){
        // show play dialog
        if(this.playView){
            this.playView.model = model;
            this.playView.datFolderCollection = self.datFolderView.collection;
            this.playView.xslFolderCollection = self.xslFolderView.collection;
            this.playView.resultFolderCollection = self.resultFolderView.collection;
        }
        else{
            this.playView = new PlayView({model,
                datFolderCollection: self.datFolderView.collection,
                xslFolderCollection: self.xslFolderView.collection,
                resultFolderCollection: self.resultFolderView.collection
            });
        }
        this.playView.show();
    },
    close: function(){
        this.remove();
        this.unbind();
    },
    onShow: function(){
        this.renderFolderViews();
        $(this.el).show();
    }
});

module.exports = Dashboard;<commit_msg>add py and sh extension<commit_after>import Backbone from 'backbone';
import $ from 'jquery';
import _ from 'underscore';

// Views
import SaveDialog from './../saveDialog';
import FolderView from './../folderView';
import PlayView from './../playView';
import UploadDialog from './../uploadDialog';
import Ios from './ios';

// Collections
import FileCollection from './../../collections/fileCollection';

// Models
import File from './../../models/fileModel';
import GadgetronStreamConfiguration from './../../models/gadgetronStreamConfigurationModel'

// Extra
import config from './../../../../config.json';

Backbone.$ = $;
var saveDialog;
var self;

// Dashboard view
var Dashboard = Backbone.View.extend({
    initialize: function(attributes, options){
        this.redirectEvent = attributes.redirectEvent;
    },
    template: _.template($("#dashboard").html()),
    render: function() {
        self = this;
        var dashboardTemplate = this.template(this.model);
        this.$el.html(dashboardTemplate);
        $(this.el).hide();
        return this;
    },
    // render all Folder Views
    renderFolderViews: function(){
        var height = window.innerHeight - 3 * $('nav').outerHeight() - 4 - 4 * 20;

        // Render Configurations
        this.configurationFolderView = new FolderView({
            title: 'Configuration-Data',
            className: 'configuration-file',
            dirs: [ config.config_dir ],
            height: height/3,
            row: '#configuration-row',
            playButtonClickEvent: this.playButtonClickEvent,
            addButtonClickEvent: this.addButtonClickEvent,
            uploadButtonClickEvent: this.uploadButtonClickEvent,
            buttons: ['add', 'upload']
        });
        $('#dashboard-configuration').html(this.configurationFolderView.render().el);

        // Render Dat/H5-Folder
        this.datFolderView = new FolderView({
            title: 'DAT/H5-Data',
            className: 'dat-file',
            dirs: [ config.upload_dir + '/dat/', config.upload_dir + '/h5/'],
            height: height/3,
            uploadButtonClickEvent: this.uploadButtonClickEvent
        });
        $('#dashboard-dat').html(this.datFolderView.render().el);

        // Render XSL-Folder
        this.xslFolderView = new FolderView({
            title: 'XSL-Data',
            className: 'xsl-file',
            dirs: [ config.upload_dir + '/xsl/'],
            height: height/3,
            uploadButtonClickEvent: this.uploadButtonClickEvent
        });
        $('#dashboard-xsl').html(this.xslFolderView.render().el);

        // Render Result-Folder
        this.resultFolderView = new FolderView({
            title: 'Result-Data',
            className: 'result-file',
            dirs: [ config.result_dir + '/'],
            height: height/3,
            buttons: [],
            row: '#result-row'
        });
        $('#dashboard-results').html(this.resultFolderView.render().el);
    },
    // handels upload button click event
    uploadButtonClickEvent: function(event){
        var type = $(event.target.parentNode).data('type');
        var typeTitle;
        var title = 'Upload';
        var fileextension;
        var fileCollection;
        switch (type) {
            case 'configuration-file':
                title = `Configuration ${title}`;
                typeTitle = 'config';
                fileextension = '.xml,.sh,.py';
                fileCollection = self.configurationFolderView.collection;
                break;
            case 'dat-file':
                title = `DAT/H5 ${title}`;
                fileextension = '.dat,.h5';
                fileCollection = self.datFolderView.collection;
                break;
            case 'xsl-file':
                title = `XSL ${title}`;
                fileextension = '.xsl';
                fileCollection = self.xslFolderView.collection;
                break;
            default:
                break;
        }
        // opens upload dialog
        self.uploadDialog = new UploadDialog({collection: fileCollection, fileextension, title, typeTitle});
        self.uploadDialog.show();
    },
    // handels add button click event
    addButtonClickEvent: function(event){
        // opens save dialog
        var saveDialog = new SaveDialog({title: 'Create new configuration', saveEvent: self.saveEvent});
        saveDialog.render();
    },
    // handels save event
    saveEvent: function(event, value){
        if(value){
            // check if value has xml extenstion
            var splittedFileName = value.split('.');
            if(splittedFileName.length > 1){
                if(splittedFileName.pop() != 'xml'){
                    return false;
                }
            }
            else{
                value = value + ".xml";
            }
            // search for configuration
            if(self.configurationFolderView.collection.where({name: value}).length > 0){
                $('#filename-group').addClass('has-error');
            }
            else{
                // create new configuration model
                var newConfiguration = new GadgetronStreamConfiguration();
                var fileName = newConfiguration.createModel(value)
                self.configurationFolderView.collection.add(newConfiguration);
                self.collection.add(newConfiguration);
                // redirect to new configuration
                self.redirectEvent('#gadgetronStreamConfiguration/' + fileName);
                $('#modal').modal('hide');
            }
        }
        else{
            $('#filename-group').addClass('has-error');
        }
    },
    // handles play button click event
    playButtonClickEvent: function(event, model){
        // show play dialog
        if(this.playView){
            this.playView.model = model;
            this.playView.datFolderCollection = self.datFolderView.collection;
            this.playView.xslFolderCollection = self.xslFolderView.collection;
            this.playView.resultFolderCollection = self.resultFolderView.collection;
        }
        else{
            this.playView = new PlayView({model,
                datFolderCollection: self.datFolderView.collection,
                xslFolderCollection: self.xslFolderView.collection,
                resultFolderCollection: self.resultFolderView.collection
            });
        }
        this.playView.show();
    },
    close: function(){
        this.remove();
        this.unbind();
    },
    onShow: function(){
        this.renderFolderViews();
        $(this.el).show();
    }
});

module.exports = Dashboard;<|endoftext|>


<commit_before>/*
 * Copyright (c) $year, Den Norske Turistforening (DNT)
 *
 * https://github.com/Turistforeningen/turadmin
 */

define(function (require, exports, module) {
    "use strict";

    // Dependencies
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        RouteModel = require('models/route'),
        LinksManagerView = require('views/links/manager'),
        state = require('state'),
        User = require('models/user'),
        user = new User();

    require('bootstrap');
    require('ckeditor-core');
    require('select2');

    // Module
    return Backbone.View.extend({

        turtyper: {
            'Fottur': ['Alpint', 'Bærtur', 'Fisketur', 'Fjelltur', 'Grottetur', 'Hyttetur', 'Skogstur', 'Sopptur', 'Telttur', 'Topptur', 'Trilletur'],
            'Skitur': ['Alpint', 'Hyttetur', 'Langrenn', 'Snowboard', 'Snøhuletur', 'Telemark', 'Telttur', 'Topptur'],
            'Sykkeltur': ['Downhillsykling', 'Landeveissykling', 'Terrengsykling'],
            'Padletur': ['Kajakktur', 'Kanotur'],
            'Bretur': ['Alpint', 'Hyttetur', 'Telttur', 'Topptur'],
            'Klatretur': ['Alpint', 'Telttur', 'Topptur']
        },

        passerForOptions: ['Barn', 'Voksen', 'Senior'],

        tilrettelagtForOptions: ['Barnevogn', 'Rullestol'],

        el: '[data-view="route-details"]',

        bindings: {
            '[name="route-details-field-navn"]': {
                observe: 'navn',
                setOptions: {
                    validate: true
                }
            },
            '[name="route-details-field-beskrivelse"]': {
                observe: 'beskrivelse',
                setOptions: {
                    validate: true
                }
            },
            '[name="route-details-field-tilkomst_generell"]': 'tilkomstGenerell',
            '[name="route-details-field-tilkomst_kollektivtransport"]': 'tilkomstKollektivtransport',
            '[name="route-details-field-typetur"]': {
                observe: 'turtype',
                setOptions: {
                    validate: true
                }
            },
            '[name="route-details-field-gradering"]': {
                observe: 'gradering',
                setOptions: {
                    validate: true
                }
            },
            'select.form-control.route-details-field-tidsbruk-normal-dager': 'tidsbrukDager',
            'select.form-control.route-details-field-tidsbruk-normal-timer': 'tidsbrukTimer',
            'select.form-control.route-details-field-tidsbruk-normal-minutter': 'tidsbrukMinutter',
            '.route-details-field-sesong input': {
                observe: 'sesong',
                onGet: function(val) {
                    if (!!val && val.length) {
                        for (var i = 0; i < val.length; i++) {
                            // Validation need month number as string, to compare with field value
                            val[i] = '' + val[i];
                        }
                    }
                    return val;
                },
                onSet: function(val) {
                    // Season month conversion to integer is moved to route.js model
                    // for (var i = 0; i < val.length; i++) {
                    //     val[i] = parseInt(val[i], 10);
                    // }
                    return val;
                },
                setOptions: {
                    validate: true
                }
            },
            '[name="route-details-field-passer_for_barn"]': {
                observe: 'passer_for',
                onGet: 'onGetPasserForBarn',
                onSet: 'onSetPasserForBarn'
            }
        },

        events: {
            'click #checkbox_kollektivMulig': 'toggleKollektivFieldVisibility',
            'click #route-details-field-sesong-select-all': 'selectAllSeasons',
            'click #route-details-field-sesong-deselect-all': 'deselectAllSeasons',
            'click .route-details-field-sesong input[type="checkbox"]': 'updateSeasonSelection',
            'click .route-details-field-tags-primary label': 'setPrimaryTag'
        },

        initialize: function (options) {

            this.model = options.route || new RouteModel();

            this.model.on('change:navn', this.updateRouteNamePlaceholders, this);
            this.model.on('change:tidsbrukDager', this.toggleHoursAndMinutesVisiblity, this);
            this.model.on('change:turtype', this.updateFlereTurtyperOptions, this);

            // Bind these methods to this scope
            _.bindAll(this, 'onGetPasserForBarn', 'onSetPasserForBarn');

            this.user = user;

            if (!!this.model.get('navn') && this.model.get('navn').length > 0) {
                this.updateRouteNamePlaceholders();
            }

            if (!!this.model.get('tidsbrukDager')) {
                this.toggleHoursAndMinutesVisiblity();
            }

            if (this.model.getRouteType() !== '') {
                var $routeTypeElement = this.$('input[value="' + this.model.getRouteType() + '"]');
                $routeTypeElement.parent('label').addClass('active');
            }

            if (!!this.model.get('gradering')) {
                var $graderingElement = this.$('input[value="' + this.model.get('gradering') + '"]');
                $graderingElement.parent('label').addClass('active');
            }

            if (this.model.get('kollektiv') === '') {
                this.$('#route-details-field-tilkomst_kollektivtransport_description').addClass('hidden');
            }

        },

        updateFlereTurtyperOptions: function () {

            if (!!this.model.get('turtype')) {
                $('.form-group.route-details-field-tags-other').removeClass('hidden');
            }

            var $flereTurtyperInput = this.$('[name="route-details-field-flere-typer"]');

            if ($flereTurtyperInput.hasClass('select2-offscreen')) {
                $flereTurtyperInput.select2('val', '');
                $flereTurtyperInput.select2('destroy');
            }

            var turtype = this.model.get('turtype');

            $flereTurtyperInput.select2({
                formatNoMatches: function () { return 'Type tur ikke valgt eller ingen treff'; },
                tags: (!!turtype && turtype !== '') ? this.turtyper[turtype] : [], // If turtype is not set, no tags are available
                createSearchChoice: function () { return null; } // This will prevent the user from entering custom tags
            }).on('change', $.proxy(this.onFlereTurtyperChange, this));

        },

        onFlereTurtyperChange: function (e) {
            var flereTurtyper = e.val;
            this.model.set('flereTurtyper', flereTurtyper);
        },

        toggleHoursAndMinutesVisiblity: function () {
            var val = this.model.get('tidsbrukDager');
            if (val === '1') {
                this.$('.form-group.route-details-field-tidsbruk-normal-timer-minutter').removeClass('hidden');
            } else {
                this.$('.form-group.route-details-field-tidsbruk-normal-timer-minutter').addClass('hidden');
            }
        },

        toggleKollektivFieldVisibility: function (e) {
            if (e.currentTarget.checked) {
                this.$('#route-details-field-tilkomst_kollektivtransport').removeClass('hidden');
                this.$('#route-details-field-tilkomst_kollektivtransport_description').removeClass('hidden');
            } else {
                this.$('#route-details-field-tilkomst_kollektivtransport').addClass('hidden');
                this.$('#route-details-field-tilkomst_kollektivtransport_description').addClass('hidden');
                this.model.set('kollektiv', '');
            }
        },

        selectAllSeasons: function () {
            this.$('#route-details-field-sesong-deselect-all').removeClass('hidden');
            this.$('#route-details-field-sesong-select-all').addClass('hidden');
            this.model.set('sesong', [1,2,3,4,5,6,7,8,9,10,11,12]);
        },

        deselectAllSeasons: function () {
            this.$('#route-details-field-sesong-deselect-all').addClass('hidden');
            this.$('#route-details-field-sesong-select-all').removeClass('hidden');
            this.model.set('sesong', []);
        },

        updateSeasonSelection: function () {
            var checked = this.$('.route-details-field-sesong input[type="checkbox"]:checked');
            var seasons = [];
            for (var i = 0; i < checked.length; i =  i + 1) {
                var val = this.$(checked[i]).val();
                seasons.push(val);
            }

            this.model.set('sesong', seasons);

        },

        onGetPasserForBarn: function (val, options) {
            var passerFor = val || [];
            return (passerFor.indexOf('Barn') > -1) ? true : false;
        },

        onSetPasserForBarn: function (val, options) {
            var passerForBarn = val;
            return (passerForBarn === true) ? ['Barn'] : [];
        },

        updateRouteNamePlaceholders: function () {
            var routeName = this.model.get('navn');
            $('[data-placeholder-for="route-name"]').html(routeName);
        },

        render: function () {

            this.updateFlereTurtyperOptions();
            this.$('[name="route-details-field-flere-typer"]').select2('val', this.model.getAdditionalRouteTypes());

            $('input[name="route-details-field-tilrettelagt_for"]').select2({
                tags: this.tilrettelagtForOptions,
                createSearchChoice: function () { return null; } // This will prevent the user from entering custom tags
            }).on('change', $.proxy(function (e) {
                var tilrettelagt_for = e.val;
                this.model.set('tilrettelagt_for', tilrettelagt_for);
            }, this));

            this.$('[name="route-details-field-tilrettelagt_for"]').select2('val', this.model.get('tilrettelagt_for'));

            var userGroups = this.user.get('grupper');
            var select2Options;

            if (!!userGroups && userGroups.length > 0) {
                var select2UserGroups = [];

                for (var i = 0; i < userGroups.length; i++) {
                    select2UserGroups[i] = {};
                    select2UserGroups[i].id = userGroups[i].object_id;
                    select2UserGroups[i].text = userGroups[i].navn; || 'Gruppe uten navn'
                }

                if (user.get('er_admin') === true) {

                    var state = require('state'); // NOTE: Should be enough to have this defined on top, but apparently it's not
                    var externalGroups = state.externalGroups;
                    var select2ExternalGroups = [];

                    for (var j = 0; j < externalGroups.length; j++) {
                        select2ExternalGroups[j] = {};
                        select2ExternalGroups[j].id = externalGroups[j]._id;
                        select2ExternalGroups[j].text = externalGroups[j].navn || 'Gruppe uten navn';
                    }

                    select2Options = [
                        {
                            text: 'Grupper jeg er medlem av',
                            children: select2UserGroups
                        },
                        {
                            text: 'Eksterne grupper',
                            children: select2ExternalGroups
                        }
                    ];

                } else {
                    select2Options = select2UserGroups;
                }

                $('input[name="route-details-field-grupper"]').select2({
                    data: {
                        results: select2Options
                    },
                    multiple: true,
                    createSearchChoice: function () { return null; } // This will prevent the user from entering custom tags
                }).on('change', $.proxy(function (e) {
                    var routeGroups = e.val;
                    this.model.set('grupper', routeGroups);
                }, this));

                // For new routes (with no id), set default eier to the users primary group
                if (!this.model.get('id') && this.user.get('gruppe')) {
                    this.$('input[name="route-details-field-grupper"]').select2('val', [this.user.get('gruppe')]);

                } else if (this.model.get('id') && this.model.get('grupper')) {
                    this.$('[name="route-details-field-grupper"]').select2('val', this.model.get('grupper'));
                }

            } else {
                // If user does not belong to any groups, do not show groups field.
                this.$('.form-group.route-details-field-grupper').remove();
            }

            // Links Manager
            var linksManagerView = new LinksManagerView({
                model: this.model,
                linksField: 'lenker',
                el: '[data-view="route-details-lenker"]',
                cols: 7,
                fields: ['tittel', 'url']
            }).render();

            // Beskrivelse
            var descriptionEditor = CKEDITOR.replace($('textarea[name="route-details-field-beskrivelse"]')[0], {
                language: 'no',
                // Define the toolbar groups as it is a more accessible solution.
                toolbarGroups: [
                    {name: 'basicstyles', groups: ['basicstyles']},
                    {name: 'paragraph', groups: ['list']},
                    {name: 'styles', groups: ['styles']}
                ],
                format_tags: 'p;h2;h3',
                // Remove the redundant buttons from toolbar groups defined above.
                removeButtons: 'Subscript,Superscript,Strike,Styles',
                // Remove elements path in footer
                removePlugins: 'elementspath',
                // Whether to use HTML entities in the output.
                entities: false
            });

            descriptionEditor.on('change', $.proxy(function (e) {
                var data = e.editor.getData();
                this.model.set('beskrivelse', data);
            }, this));

            var publicTransportation = this.model.get('kollektiv');

            if (!!publicTransportation && publicTransportation.length > 0) {
                this.$('.route-details-field-tilkomst_kollektivtransport input[type="checkbox"]').prop('checked', true);
                this.$('.route-details-field-tilkomst_kollektivtransport textarea').removeClass('hidden');
            }

            this.stickit(); // Uses view.bindings and view.model to setup bindings
            Backbone.Validation.bind(this);

            if ($('.route-details-field-sesong input[type="checkbox"]:not(:checked)').length === 0) {
                this.$('#route-details-field-sesong-deselect-all').removeClass('hidden');
                this.$('#route-details-field-sesong-select-all').addClass('hidden');
            }

        },

        remove: function() {
            // Remove the validation binding
            // See: http://thedersen.com/projects/backbone-validation/#using-form-model-validation/unbinding
            Backbone.Validation.unbind(this);
            return Backbone.View.prototype.remove.apply(this, arguments);
        }
    });
});
<commit_msg>Fixed syntax errors & incorrect spaces<commit_after>/*
 * Copyright (c) $year, Den Norske Turistforening (DNT)
 *
 * https://github.com/Turistforeningen/turadmin
 */

define(function (require, exports, module) {
    "use strict";

    // Dependencies
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        RouteModel = require('models/route'),
        LinksManagerView = require('views/links/manager'),
        state = require('state'),
        User = require('models/user'),
        user = new User();

    require('bootstrap');
    require('ckeditor-core');
    require('select2');

    // Module
    return Backbone.View.extend({

        turtyper: {
            'Fottur': ['Alpint', 'Bærtur', 'Fisketur', 'Fjelltur', 'Grottetur', 'Hyttetur', 'Skogstur', 'Sopptur', 'Telttur', 'Topptur', 'Trilletur'],
            'Skitur': ['Alpint', 'Hyttetur', 'Langrenn', 'Snowboard', 'Snøhuletur', 'Telemark', 'Telttur', 'Topptur'],
            'Sykkeltur': ['Downhillsykling', 'Landeveissykling', 'Terrengsykling'],
            'Padletur': ['Kajakktur', 'Kanotur'],
            'Bretur': ['Alpint', 'Hyttetur', 'Telttur', 'Topptur'],
            'Klatretur': ['Alpint', 'Telttur', 'Topptur']
        },

        passerForOptions: ['Barn', 'Voksen', 'Senior'],

        tilrettelagtForOptions: ['Barnevogn', 'Rullestol'],

        el: '[data-view="route-details"]',

        bindings: {
            '[name="route-details-field-navn"]': {
                observe: 'navn',
                setOptions: {
                    validate: true
                }
            },
            '[name="route-details-field-beskrivelse"]': {
                observe: 'beskrivelse',
                setOptions: {
                    validate: true
                }
            },
            '[name="route-details-field-tilkomst_generell"]': 'tilkomstGenerell',
            '[name="route-details-field-tilkomst_kollektivtransport"]': 'tilkomstKollektivtransport',
            '[name="route-details-field-typetur"]': {
                observe: 'turtype',
                setOptions: {
                    validate: true
                }
            },
            '[name="route-details-field-gradering"]': {
                observe: 'gradering',
                setOptions: {
                    validate: true
                }
            },
            'select.form-control.route-details-field-tidsbruk-normal-dager': 'tidsbrukDager',
            'select.form-control.route-details-field-tidsbruk-normal-timer': 'tidsbrukTimer',
            'select.form-control.route-details-field-tidsbruk-normal-minutter': 'tidsbrukMinutter',
            '.route-details-field-sesong input': {
                observe: 'sesong',
                onGet: function(val) {
                    if (!!val && val.length) {
                        for (var i = 0; i < val.length; i++) {
                            // Validation need month number as string, to compare with field value
                            val[i] = '' + val[i];
                        }
                    }
                    return val;
                },
                onSet: function(val) {
                    // Season month conversion to integer is moved to route.js model
                    // for (var i = 0; i < val.length; i++) {
                    //     val[i] = parseInt(val[i], 10);
                    // }
                    return val;
                },
                setOptions: {
                    validate: true
                }
            },
            '[name="route-details-field-passer_for_barn"]': {
                observe: 'passer_for',
                onGet: 'onGetPasserForBarn',
                onSet: 'onSetPasserForBarn'
            }
        },

        events: {
            'click #checkbox_kollektivMulig': 'toggleKollektivFieldVisibility',
            'click #route-details-field-sesong-select-all': 'selectAllSeasons',
            'click #route-details-field-sesong-deselect-all': 'deselectAllSeasons',
            'click .route-details-field-sesong input[type="checkbox"]': 'updateSeasonSelection',
            'click .route-details-field-tags-primary label': 'setPrimaryTag'
        },

        initialize: function (options) {

            this.model = options.route || new RouteModel();

            this.model.on('change:navn', this.updateRouteNamePlaceholders, this);
            this.model.on('change:tidsbrukDager', this.toggleHoursAndMinutesVisiblity, this);
            this.model.on('change:turtype', this.updateFlereTurtyperOptions, this);

            // Bind these methods to this scope
            _.bindAll(this, 'onGetPasserForBarn', 'onSetPasserForBarn');

            this.user = user;

            if (!!this.model.get('navn') && this.model.get('navn').length > 0) {
                this.updateRouteNamePlaceholders();
            }

            if (!!this.model.get('tidsbrukDager')) {
                this.toggleHoursAndMinutesVisiblity();
            }

            if (this.model.getRouteType() !== '') {
                var $routeTypeElement = this.$('input[value="' + this.model.getRouteType() + '"]');
                $routeTypeElement.parent('label').addClass('active');
            }

            if (!!this.model.get('gradering')) {
                var $graderingElement = this.$('input[value="' + this.model.get('gradering') + '"]');
                $graderingElement.parent('label').addClass('active');
            }

            if (this.model.get('kollektiv') === '') {
                this.$('#route-details-field-tilkomst_kollektivtransport_description').addClass('hidden');
            }

        },

        updateFlereTurtyperOptions: function () {

            if (!!this.model.get('turtype')) {
                $('.form-group.route-details-field-tags-other').removeClass('hidden');
            }

            var $flereTurtyperInput = this.$('[name="route-details-field-flere-typer"]');

            if ($flereTurtyperInput.hasClass('select2-offscreen')) {
                $flereTurtyperInput.select2('val', '');
                $flereTurtyperInput.select2('destroy');
            }

            var turtype = this.model.get('turtype');

            $flereTurtyperInput.select2({
                formatNoMatches: function () { return 'Type tur ikke valgt eller ingen treff'; },
                tags: (!!turtype && turtype !== '') ? this.turtyper[turtype] : [], // If turtype is not set, no tags are available
                createSearchChoice: function () { return null; } // This will prevent the user from entering custom tags
            }).on('change', $.proxy(this.onFlereTurtyperChange, this));

        },

        onFlereTurtyperChange: function (e) {
            var flereTurtyper = e.val;
            this.model.set('flereTurtyper', flereTurtyper);
        },

        toggleHoursAndMinutesVisiblity: function () {
            var val = this.model.get('tidsbrukDager');
            if (val === '1') {
                this.$('.form-group.route-details-field-tidsbruk-normal-timer-minutter').removeClass('hidden');
            } else {
                this.$('.form-group.route-details-field-tidsbruk-normal-timer-minutter').addClass('hidden');
            }
        },

        toggleKollektivFieldVisibility: function (e) {
            if (e.currentTarget.checked) {
                this.$('#route-details-field-tilkomst_kollektivtransport').removeClass('hidden');
                this.$('#route-details-field-tilkomst_kollektivtransport_description').removeClass('hidden');
            } else {
                this.$('#route-details-field-tilkomst_kollektivtransport').addClass('hidden');
                this.$('#route-details-field-tilkomst_kollektivtransport_description').addClass('hidden');
                this.model.set('kollektiv', '');
            }
        },

        selectAllSeasons: function () {
            this.$('#route-details-field-sesong-deselect-all').removeClass('hidden');
            this.$('#route-details-field-sesong-select-all').addClass('hidden');
            this.model.set('sesong', [1,2,3,4,5,6,7,8,9,10,11,12]);
        },

        deselectAllSeasons: function () {
            this.$('#route-details-field-sesong-deselect-all').addClass('hidden');
            this.$('#route-details-field-sesong-select-all').removeClass('hidden');
            this.model.set('sesong', []);
        },

        updateSeasonSelection: function () {
            var checked = this.$('.route-details-field-sesong input[type="checkbox"]:checked');
            var seasons = [];
            for (var i = 0; i < checked.length; i =  i + 1) {
                var val = this.$(checked[i]).val();
                seasons.push(val);
            }

            this.model.set('sesong', seasons);

        },

        onGetPasserForBarn: function (val, options) {
            var passerFor = val || [];
            return (passerFor.indexOf('Barn') > -1) ? true : false;
        },

        onSetPasserForBarn: function (val, options) {
            var passerForBarn = val;
            return (passerForBarn === true) ? ['Barn'] : [];
        },

        updateRouteNamePlaceholders: function () {
            var routeName = this.model.get('navn');
            $('[data-placeholder-for="route-name"]').html(routeName);
        },

        render: function () {

            this.updateFlereTurtyperOptions();
            this.$('[name="route-details-field-flere-typer"]').select2('val', this.model.getAdditionalRouteTypes());

            $('input[name="route-details-field-tilrettelagt_for"]').select2({
                tags: this.tilrettelagtForOptions,
                createSearchChoice: function () { return null; } // This will prevent the user from entering custom tags
            }).on('change', $.proxy(function (e) {
                var tilrettelagt_for = e.val;
                this.model.set('tilrettelagt_for', tilrettelagt_for);
            }, this));

            this.$('[name="route-details-field-tilrettelagt_for"]').select2('val', this.model.get('tilrettelagt_for'));

            var userGroups = this.user.get('grupper');
            var select2Options;

            if (!!userGroups && userGroups.length > 0) {
                var select2UserGroups = [];

                for (var i = 0; i < userGroups.length; i++) {
                    select2UserGroups[i] = {};
                    select2UserGroups[i].id = userGroups[i].object_id;
                    select2UserGroups[i].text = userGroups[i].navn || 'Gruppe uten navn';
                }

                if (user.get('er_admin') === true) {

                    var state = require('state'); // NOTE: Should be enough to have this defined on top, but apparently it's not
                    var externalGroups = state.externalGroups;
                    var select2ExternalGroups = [];

                    for (var j = 0; j < externalGroups.length; j++) {
                        select2ExternalGroups[j] = {};
                        select2ExternalGroups[j].id = externalGroups[j]._id;
                        select2ExternalGroups[j].text = externalGroups[j].navn || 'Gruppe uten navn';
                    }

                    select2Options = [
                        {
                            text: 'Grupper jeg er medlem av',
                            children: select2UserGroups
                        },
                        {
                            text: 'Eksterne grupper',
                            children: select2ExternalGroups
                        }
                    ];

                } else {
                    select2Options = select2UserGroups;
                }

                $('input[name="route-details-field-grupper"]').select2({
                    data: {
                        results: select2Options
                    },
                    multiple: true,
                    createSearchChoice: function () { return null; } // This will prevent the user from entering custom tags
                }).on('change', $.proxy(function (e) {
                    var routeGroups = e.val;
                    this.model.set('grupper', routeGroups);
                }, this));

                // For new routes (with no id), set default eier to the users primary group
                if (!this.model.get('id') && this.user.get('gruppe')) {
                    this.$('input[name="route-details-field-grupper"]').select2('val', [this.user.get('gruppe')]);

                } else if (this.model.get('id') && this.model.get('grupper')) {
                    this.$('[name="route-details-field-grupper"]').select2('val', this.model.get('grupper'));
                }

            } else {
                // If user does not belong to any groups, do not show groups field.
                this.$('.form-group.route-details-field-grupper').remove();
            }

            // Links Manager
            var linksManagerView = new LinksManagerView({
                model: this.model,
                linksField: 'lenker',
                el: '[data-view="route-details-lenker"]',
                cols: 7,
                fields: ['tittel', 'url']
            }).render();

            // Beskrivelse
            var descriptionEditor = CKEDITOR.replace($('textarea[name="route-details-field-beskrivelse"]')[0], {
                language: 'no',
                // Define the toolbar groups as it is a more accessible solution.
                toolbarGroups: [
                    {name: 'basicstyles', groups: ['basicstyles']},
                    {name: 'paragraph', groups: ['list']},
                    {name: 'styles', groups: ['styles']}
                ],
                format_tags: 'p;h2;h3',
                // Remove the redundant buttons from toolbar groups defined above.
                removeButtons: 'Subscript,Superscript,Strike,Styles',
                // Remove elements path in footer
                removePlugins: 'elementspath',
                // Whether to use HTML entities in the output.
                entities: false
            });

            descriptionEditor.on('change', $.proxy(function (e) {
                var data = e.editor.getData();
                this.model.set('beskrivelse', data);
            }, this));

            var publicTransportation = this.model.get('kollektiv');

            if (!!publicTransportation && publicTransportation.length > 0) {
                this.$('.route-details-field-tilkomst_kollektivtransport input[type="checkbox"]').prop('checked', true);
                this.$('.route-details-field-tilkomst_kollektivtransport textarea').removeClass('hidden');
            }

            this.stickit(); // Uses view.bindings and view.model to setup bindings
            Backbone.Validation.bind(this);

            if ($('.route-details-field-sesong input[type="checkbox"]:not(:checked)').length === 0) {
                this.$('#route-details-field-sesong-deselect-all').removeClass('hidden');
                this.$('#route-details-field-sesong-select-all').addClass('hidden');
            }

        },

        remove: function() {
            // Remove the validation binding
            // See: http://thedersen.com/projects/backbone-validation/#using-form-model-validation/unbinding
            Backbone.Validation.unbind(this);
            return Backbone.View.prototype.remove.apply(this, arguments);
        }
    });
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @providesModule ReactDOMFrameScheduling
 * @flow
 */

'use strict';

// This is a built-in polyfill for requestIdleCallback. It works by scheduling
// a requestAnimationFrame, storing the time for the start of the frame, then
// scheduling a postMessage which gets scheduled after paint. Within the
// postMessage handler do as much work as possible until time + frame rate.
// By separating the idle call into a separate event tick we ensure that
// layout, paint and other browser work is counted against the available time.
// The frame rate is dynamically adjusted.

import type {Deadline} from 'react-reconciler';

var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');

if (__DEV__) {
  var warning = require('fbjs/lib/warning');

  if (
    ExecutionEnvironment.canUseDOM &&
    typeof requestAnimationFrame !== 'function'
  ) {
    warning(
      false,
      'React depends on requestAnimationFrame. Make sure that you load a ' +
        'polyfill in older browsers. http://fb.me/react-polyfills',
    );
  }
}

const hasNativePerformanceNow =
  typeof performance === 'object' && typeof performance.now === 'function';

let now;
if (hasNativePerformanceNow) {
  now = function() {
    return performance.now();
  };
} else {
  now = function() {
    return Date.now();
  };
}

// TODO: There's no way to cancel, because Fiber doesn't atm.
let rIC: (callback: (deadline: Deadline) => void) => number;

if (!ExecutionEnvironment.canUseDOM) {
  rIC = function(frameCallback: (deadline: Deadline) => void): number {
    setTimeout(() => {
      frameCallback({
        timeRemaining() {
          return Infinity;
        },
      });
    });
    return 0;
  };
} else if (typeof requestIdleCallback !== 'function') {
  // Polyfill requestIdleCallback.

  var scheduledRAFCallback = null;
  var scheduledRICCallback = null;

  var isIdleScheduled = false;
  var isAnimationFrameScheduled = false;

  var frameDeadline = 0;
  // We start out assuming that we run at 30fps but then the heuristic tracking
  // will adjust this value to a faster fps if we get more frequent animation
  // frames.
  var previousFrameTime = 33;
  var activeFrameTime = 33;

  var frameDeadlineObject;
  if (hasNativePerformanceNow) {
    frameDeadlineObject = {
      timeRemaining() {
        // We assume that if we have a performance timer that the rAF callback
        // gets a performance timer value. Not sure if this is always true.
        return frameDeadline - performance.now();
      },
    };
  } else {
    frameDeadlineObject = {
      timeRemaining() {
        // Fallback to Date.now()
        return frameDeadline - Date.now();
      },
    };
  }

  // We use the postMessage trick to defer idle work until after the repaint.
  var messageKey = '__reactIdleCallback$' + Math.random().toString(36).slice(2);
  var idleTick = function(event) {
    if (event.source !== window || event.data !== messageKey) {
      return;
    }
    isIdleScheduled = false;
    var callback = scheduledRICCallback;
    scheduledRICCallback = null;
    if (callback !== null) {
      callback(frameDeadlineObject);
    }
  };
  // Assumes that we have addEventListener in this environment. Might need
  // something better for old IE.
  window.addEventListener('message', idleTick, false);

  var animationTick = function(rafTime) {
    isAnimationFrameScheduled = false;
    var nextFrameTime = rafTime - frameDeadline + activeFrameTime;
    if (
      nextFrameTime < activeFrameTime &&
      previousFrameTime < activeFrameTime
    ) {
      if (nextFrameTime < 8) {
        // Defensive coding. We don't support higher frame rates than 120hz.
        // If we get lower than that, it is probably a bug.
        nextFrameTime = 8;
      }
      // If one frame goes long, then the next one can be short to catch up.
      // If two frames are short in a row, then that's an indication that we
      // actually have a higher frame rate than what we're currently optimizing.
      // We adjust our heuristic dynamically accordingly. For example, if we're
      // running on 120hz display or 90hz VR display.
      // Take the max of the two in case one of them was an anomaly due to
      // missed frame deadlines.
      activeFrameTime = nextFrameTime < previousFrameTime
        ? previousFrameTime
        : nextFrameTime;
    } else {
      previousFrameTime = nextFrameTime;
    }
    frameDeadline = rafTime + activeFrameTime;
    if (!isIdleScheduled) {
      isIdleScheduled = true;
      window.postMessage(messageKey, '*');
    }
    var callback = scheduledRAFCallback;
    scheduledRAFCallback = null;
    if (callback !== null) {
      callback(rafTime);
    }
  };

  rIC = function(callback: (deadline: Deadline) => void): number {
    // This assumes that we only schedule one callback at a time because that's
    // how Fiber uses it.
    scheduledRICCallback = callback;
    if (!isAnimationFrameScheduled) {
      // If rAF didn't already schedule one, we need to schedule a frame.
      // TODO: If this rAF doesn't materialize because the browser throttles, we
      // might want to still have setTimeout trigger rIC as a backup to ensure
      // that we keep performing work.
      isAnimationFrameScheduled = true;
      requestAnimationFrame(animationTick);
    }
    return 0;
  };
} else {
  rIC = requestIdleCallback;
}

exports.now = now;
exports.rIC = rIC;
<commit_msg>Delete unused code in ReactDOMFrameScheduling (#11301)<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @providesModule ReactDOMFrameScheduling
 * @flow
 */

'use strict';

// This is a built-in polyfill for requestIdleCallback. It works by scheduling
// a requestAnimationFrame, storing the time for the start of the frame, then
// scheduling a postMessage which gets scheduled after paint. Within the
// postMessage handler do as much work as possible until time + frame rate.
// By separating the idle call into a separate event tick we ensure that
// layout, paint and other browser work is counted against the available time.
// The frame rate is dynamically adjusted.

import type {Deadline} from 'react-reconciler';

var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');

if (__DEV__) {
  var warning = require('fbjs/lib/warning');

  if (
    ExecutionEnvironment.canUseDOM &&
    typeof requestAnimationFrame !== 'function'
  ) {
    warning(
      false,
      'React depends on requestAnimationFrame. Make sure that you load a ' +
        'polyfill in older browsers. http://fb.me/react-polyfills',
    );
  }
}

const hasNativePerformanceNow =
  typeof performance === 'object' && typeof performance.now === 'function';

let now;
if (hasNativePerformanceNow) {
  now = function() {
    return performance.now();
  };
} else {
  now = function() {
    return Date.now();
  };
}

// TODO: There's no way to cancel, because Fiber doesn't atm.
let rIC: (callback: (deadline: Deadline) => void) => number;

if (!ExecutionEnvironment.canUseDOM) {
  rIC = function(frameCallback: (deadline: Deadline) => void): number {
    setTimeout(() => {
      frameCallback({
        timeRemaining() {
          return Infinity;
        },
      });
    });
    return 0;
  };
} else if (typeof requestIdleCallback !== 'function') {
  // Polyfill requestIdleCallback.

  var scheduledRICCallback = null;

  var isIdleScheduled = false;
  var isAnimationFrameScheduled = false;

  var frameDeadline = 0;
  // We start out assuming that we run at 30fps but then the heuristic tracking
  // will adjust this value to a faster fps if we get more frequent animation
  // frames.
  var previousFrameTime = 33;
  var activeFrameTime = 33;

  var frameDeadlineObject;
  if (hasNativePerformanceNow) {
    frameDeadlineObject = {
      timeRemaining() {
        // We assume that if we have a performance timer that the rAF callback
        // gets a performance timer value. Not sure if this is always true.
        return frameDeadline - performance.now();
      },
    };
  } else {
    frameDeadlineObject = {
      timeRemaining() {
        // Fallback to Date.now()
        return frameDeadline - Date.now();
      },
    };
  }

  // We use the postMessage trick to defer idle work until after the repaint.
  var messageKey = '__reactIdleCallback$' + Math.random().toString(36).slice(2);
  var idleTick = function(event) {
    if (event.source !== window || event.data !== messageKey) {
      return;
    }
    isIdleScheduled = false;
    var callback = scheduledRICCallback;
    scheduledRICCallback = null;
    if (callback !== null) {
      callback(frameDeadlineObject);
    }
  };
  // Assumes that we have addEventListener in this environment. Might need
  // something better for old IE.
  window.addEventListener('message', idleTick, false);

  var animationTick = function(rafTime) {
    isAnimationFrameScheduled = false;
    var nextFrameTime = rafTime - frameDeadline + activeFrameTime;
    if (
      nextFrameTime < activeFrameTime &&
      previousFrameTime < activeFrameTime
    ) {
      if (nextFrameTime < 8) {
        // Defensive coding. We don't support higher frame rates than 120hz.
        // If we get lower than that, it is probably a bug.
        nextFrameTime = 8;
      }
      // If one frame goes long, then the next one can be short to catch up.
      // If two frames are short in a row, then that's an indication that we
      // actually have a higher frame rate than what we're currently optimizing.
      // We adjust our heuristic dynamically accordingly. For example, if we're
      // running on 120hz display or 90hz VR display.
      // Take the max of the two in case one of them was an anomaly due to
      // missed frame deadlines.
      activeFrameTime = nextFrameTime < previousFrameTime
        ? previousFrameTime
        : nextFrameTime;
    } else {
      previousFrameTime = nextFrameTime;
    }
    frameDeadline = rafTime + activeFrameTime;
    if (!isIdleScheduled) {
      isIdleScheduled = true;
      window.postMessage(messageKey, '*');
    }
  };

  rIC = function(callback: (deadline: Deadline) => void): number {
    // This assumes that we only schedule one callback at a time because that's
    // how Fiber uses it.
    scheduledRICCallback = callback;
    if (!isAnimationFrameScheduled) {
      // If rAF didn't already schedule one, we need to schedule a frame.
      // TODO: If this rAF doesn't materialize because the browser throttles, we
      // might want to still have setTimeout trigger rIC as a backup to ensure
      // that we keep performing work.
      isAnimationFrameScheduled = true;
      requestAnimationFrame(animationTick);
    }
    return 0;
  };
} else {
  rIC = requestIdleCallback;
}

exports.now = now;
exports.rIC = rIC;
<|endoftext|>


<commit_before>'use strict';

import plugins  from 'gulp-load-plugins';
import yargs    from 'yargs';
import browser  from 'browser-sync';
import gulp     from 'gulp';
import panini   from 'panini';
import rimraf   from 'rimraf';
import sherpa   from 'style-sherpa';
import yaml     from 'js-yaml';
import fs       from 'fs';

// Load all Gulp plugins into one variable
const $ = plugins();

// Check for --production flag
const PRODUCTION = !!(yargs.argv.production);

// Load settings from settings.yml
const { COMPATIBILITY, PORT, UNCSS_OPTIONS, PATHS } = loadConfig();

function loadConfig() {
  let ymlFile = fs.readFileSync('config.yml', 'utf8');
  return yaml.load(ymlFile);
}

// Build the "dist" folder by running all of the below tasks
gulp.task('build',
 gulp.series(clean, gulp.parallel(sass, babelscript, plainscript, fonts)));

// Build the site, run the server, and watch for file changes
gulp.task('default',
  gulp.series('build', server, watch));

// Delete the "dist" folder
// This happens every time a build starts
function clean(done) {
  rimraf(PATHS.dist, done);
}

// Copy fonts
function fonts() {
  return gulp.src(PATHS.fonts)
    .pipe(gulp.dest(PATHS.dist + '/fonts'));
}

// Compile Sass into CSS
// In production, the CSS is compressed
function sass() {
  return gulp.src('scss/app.scss')
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      includePaths: PATHS.sass
    })
      .on('error', $.sass.logError))
    .pipe($.autoprefixer({
      browsers: COMPATIBILITY
    }))
    .pipe($.if(PRODUCTION, $.rename({ suffix: '.min' })))
    .pipe($.if(PRODUCTION, $.cssnano()))
    .pipe($.if(!PRODUCTION, $.sourcemaps.write()))
    .pipe(gulp.dest(PATHS.dist + '/css'))
    .pipe(browser.reload({ stream: true }));
}

// Combine Babel (ES6) JavaScript into one file
// In production, the file is minified
function babelscript() {
  return gulp.src(PATHS.babelscript)
    .pipe($.sourcemaps.init())
    .pipe($.babel())
    .pipe($.concat('app.js'))
    .pipe($.if(PRODUCTION, $.rename({ suffix: '.min' })))
    .pipe($.if(PRODUCTION, $.uglify()
      .on('error', e => { console.log(e); })
    ))
    .pipe($.if(!PRODUCTION, $.sourcemaps.write()))
    .pipe(gulp.dest(PATHS.dist + '/js'));
}

// Combine plain JavaScript (non-ES6) into one file
// In production, the file is minified
function plainscript() {
  return gulp.src(PATHS.plainscript)
    .pipe($.sourcemaps.init())
    .pipe($.concat('custom.js'))
    .pipe($.if(PRODUCTION, $.rename({ suffix: '.min' })))
    .pipe($.if(PRODUCTION, $.uglify()
      .on('error', e => { console.log(e); })
    ))
    .pipe($.if(!PRODUCTION, $.sourcemaps.write()))
    .pipe(gulp.dest(PATHS.dist + '/js'));
}

// Start a server with BrowserSync to preview the site in
function server(done) {
  browser.init({
      proxy: "https://bugitor.dev"
  });
  done();
}

// Watch for changes to static assets, pages, Sass, and JavaScript
function watch() {
  gulp.watch(PATHS.assets, copy);
  gulp.watch('scss/**/*.scss', sass);
  gulp.watch('js/**/*.js', gulp.series(javascript, browser.reload));
}
<commit_msg>Forgot to remove references to panini and style-sherpa<commit_after>'use strict';

import plugins  from 'gulp-load-plugins';
import yargs    from 'yargs';
import browser  from 'browser-sync';
import gulp     from 'gulp';
import rimraf   from 'rimraf';
import yaml     from 'js-yaml';
import fs       from 'fs';

// Load all Gulp plugins into one variable
const $ = plugins();

// Check for --production flag
const PRODUCTION = !!(yargs.argv.production);

// Load settings from settings.yml
const { COMPATIBILITY, PORT, UNCSS_OPTIONS, PATHS } = loadConfig();

function loadConfig() {
  let ymlFile = fs.readFileSync('config.yml', 'utf8');
  return yaml.load(ymlFile);
}

// Build the "dist" folder by running all of the below tasks
gulp.task('build',
 gulp.series(clean, gulp.parallel(sass, babelscript, plainscript, fonts)));

// Build the site, run the server, and watch for file changes
gulp.task('default',
  gulp.series('build', server, watch));

// Delete the "dist" folder
// This happens every time a build starts
function clean(done) {
  rimraf(PATHS.dist, done);
}

// Copy fonts
function fonts() {
  return gulp.src(PATHS.fonts)
    .pipe(gulp.dest(PATHS.dist + '/fonts'));
}

// Compile Sass into CSS
// In production, the CSS is compressed
function sass() {
  return gulp.src('scss/app.scss')
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      includePaths: PATHS.sass
    })
      .on('error', $.sass.logError))
    .pipe($.autoprefixer({
      browsers: COMPATIBILITY
    }))
    .pipe($.if(PRODUCTION, $.rename({ suffix: '.min' })))
    .pipe($.if(PRODUCTION, $.cssnano()))
    .pipe($.if(!PRODUCTION, $.sourcemaps.write()))
    .pipe(gulp.dest(PATHS.dist + '/css'))
    .pipe(browser.reload({ stream: true }));
}

// Combine Babel (ES6) JavaScript into one file
// In production, the file is minified
function babelscript() {
  return gulp.src(PATHS.babelscript)
    .pipe($.sourcemaps.init())
    .pipe($.babel())
    .pipe($.concat('app.js'))
    .pipe($.if(PRODUCTION, $.rename({ suffix: '.min' })))
    .pipe($.if(PRODUCTION, $.uglify()
      .on('error', e => { console.log(e); })
    ))
    .pipe($.if(!PRODUCTION, $.sourcemaps.write()))
    .pipe(gulp.dest(PATHS.dist + '/js'));
}

// Combine plain JavaScript (non-ES6) into one file
// In production, the file is minified
function plainscript() {
  return gulp.src(PATHS.plainscript)
    .pipe($.sourcemaps.init())
    .pipe($.concat('custom.js'))
    .pipe($.if(PRODUCTION, $.rename({ suffix: '.min' })))
    .pipe($.if(PRODUCTION, $.uglify()
      .on('error', e => { console.log(e); })
    ))
    .pipe($.if(!PRODUCTION, $.sourcemaps.write()))
    .pipe(gulp.dest(PATHS.dist + '/js'));
}

// Start a server with BrowserSync to preview the site in
function server(done) {
  browser.init({
      proxy: "https://bugitor.dev"
  });
  done();
}

// Watch for changes to static assets, pages, Sass, and JavaScript
function watch() {
  gulp.watch(PATHS.assets, copy);
  gulp.watch('scss/**/*.scss', sass);
  gulp.watch('js/**/*.js', gulp.series(javascript, browser.reload));
}
<|endoftext|>


<commit_before>// Gulp & utils
import path from 'path';
import gulp from 'gulp';
import runSequence from 'run-sequence';
import del from 'del';
import plumber from 'gulp-plumber';
import notify from 'gulp-notify';

// JS
import browserify from 'browserify';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import eslint from 'gulp-eslint';
import uglify from 'gulp-uglify';
import sourcemaps from 'gulp-sourcemaps';
import gutil from 'gulp-util';

// CSS
import postcss from 'gulp-postcss';
import cssnext from 'postcss-cssnext';
import nested from 'postcss-nested';
import nano from 'gulp-cssnano';

const staticFiles = [
  'manifest.json',
  'icons/*.png'
].map((i) => path.resolve('src/', i));

const cssFiles = [
  'src/css/index.css'
];

const toLintFiles = [
  'src/js/**/*.js',
  '*.js'
];

const postCssPlugins = [
  cssnext,
  nested
];

const maybeNotifyErrors = () => {
  return notify.onError({
    title: 'Compile Error',
    message: '<%= error.message %>'
  });
};

/*
*
* `gulp clean`
* Remove the build/ folder (used before build)
*
*/
gulp.task('clean', () => {
  return del(['dist/']);
});

/*
*
* `gulp static`
* Simply copy files like images/json to the build folder
*
*/
gulp.task('static', () => {
  return gulp.src(staticFiles, { base: './src' })
  .pipe(gulp.dest('./dist'));
});

/*
*
* `gulp js`
* Run babeljs + browserify on the js background.js/content.js files
*
*/
gulp.task('js-content', () => {
  return browserify({
    entries: 'src/js/content.js',
    debug: true
  })
  .transform('babelify')
  .transform('config-browserify')
  .bundle()
  .on('error', maybeNotifyErrors())
  .pipe(source('content.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({ loadMaps: true }))
  .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('./dist/js'));
});

gulp.task('js-injected', () => {
  return browserify({
    entries: 'src/js/inject.js',
    debug: true
  })
  .transform('babelify')
  .transform('config-browserify')
  .bundle()
  .on('error', maybeNotifyErrors())
  .pipe(source('inject.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({ loadMaps: true }))
  .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('./dist/js'));
});

gulp.task('js-background', () => {
  return browserify({
    entries: 'src/js/background.js',
    debug: true
  })
  .transform('babelify')
  .transform('config-browserify')
  .bundle()
  .on('error', maybeNotifyErrors())
  .pipe(source('background.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({ loadMaps: true }))
  .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('./dist/js'));
});

gulp.task('js', ['js-content', 'js-injected', 'js-background']);

/**
 * `gulp css`
 * Compile the css files using PostCSS + cssnext
 */
gulp.task('css', function () {
  return gulp.src(cssFiles)
    .pipe(postcss(postCssPlugins))
    .pipe(gutil.env.type === 'production' ? gutil.noop() : plumber())
    .pipe(gutil.env.type === 'production' ? nano() : gutil.noop())
    .pipe(gulp.dest('./dist/css'));
});

/**
 * `gulp lint`
 * Lint the JS files (Gulpfile as well)
 */
gulp.task('lint', function () {
  return gulp.src(toLintFiles)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

/*
*
* `gulp build`
* Build the project
*
*/
gulp.task('build', (done) => {
  runSequence('clean', ['js', 'js-injected', 'static', 'css'], done);
});

/*
*
* `gulp`
* Watches on modifications
*
*/
gulp.task('default', (done) => {
  runSequence('clean', ['css', 'js', 'static'], () => {
    gulp.watch('./src/js/**/*.js', ['js']);
    gulp.watch('./src/css/**/*.css', ['css']);
    gulp.watch(staticFiles, ['static']);
    done();
  });
});
<commit_msg>:package: cssnano as a postcss plugin<commit_after>// Gulp & utils
import path from 'path';
import gulp from 'gulp';
import runSequence from 'run-sequence';
import del from 'del';
import plumber from 'gulp-plumber';
import notify from 'gulp-notify';

// JS
import browserify from 'browserify';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import eslint from 'gulp-eslint';
import uglify from 'gulp-uglify';
import sourcemaps from 'gulp-sourcemaps';
import gutil from 'gulp-util';

// CSS
import postcss from 'gulp-postcss';
import cssnext from 'postcss-cssnext';
import cssnano from 'cssnano';
import nested from 'postcss-nested';

const staticFiles = [
  'manifest.json',
  'icons/*.png'
].map((i) => path.resolve('src/', i));

const cssFiles = [
  'src/css/index.css'
];

const toLintFiles = [
  'src/js/**/*.js',
  '*.js'
];

const postCssPlugins = [
  cssnext,
  nested,
  cssnano
];

const maybeNotifyErrors = () => {
  return notify.onError({
    title: 'Compile Error',
    message: '<%= error.message %>'
  });
};

/*
*
* `gulp clean`
* Remove the build/ folder (used before build)
*
*/
gulp.task('clean', () => {
  return del(['dist/']);
});

/*
*
* `gulp static`
* Simply copy files like images/json to the build folder
*
*/
gulp.task('static', () => {
  return gulp.src(staticFiles, { base: './src' })
  .pipe(gulp.dest('./dist'));
});

/*
*
* `gulp js`
* Run babeljs + browserify on the js background.js/content.js files
*
*/
gulp.task('js-content', () => {
  return browserify({
    entries: 'src/js/content.js',
    debug: true
  })
  .transform('babelify')
  .transform('config-browserify')
  .bundle()
  .on('error', maybeNotifyErrors())
  .pipe(source('content.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({ loadMaps: true }))
  .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('./dist/js'));
});

gulp.task('js-injected', () => {
  return browserify({
    entries: 'src/js/inject.js',
    debug: true
  })
  .transform('babelify')
  .transform('config-browserify')
  .bundle()
  .on('error', maybeNotifyErrors())
  .pipe(source('inject.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({ loadMaps: true }))
  .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('./dist/js'));
});

gulp.task('js-background', () => {
  return browserify({
    entries: 'src/js/background.js',
    debug: true
  })
  .transform('babelify')
  .transform('config-browserify')
  .bundle()
  .on('error', maybeNotifyErrors())
  .pipe(source('background.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({ loadMaps: true }))
  .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('./dist/js'));
});

gulp.task('js', ['js-content', 'js-injected', 'js-background']);

/**
 * `gulp css`
 * Compile the css files using PostCSS + cssnext
 */
gulp.task('css', function () {
  return gulp.src(cssFiles)
    .pipe(postcss(postCssPlugins))
    .pipe(gutil.env.type === 'production' ? gutil.noop() : plumber())
    .pipe(gulp.dest('./dist/css'));
});

/**
 * `gulp lint`
 * Lint the JS files (Gulpfile as well)
 */
gulp.task('lint', function () {
  return gulp.src(toLintFiles)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

/*
*
* `gulp build`
* Build the project
*
*/
gulp.task('build', (done) => {
  runSequence('clean', ['js', 'js-injected', 'static', 'css'], done);
});

/*
*
* `gulp`
* Watches on modifications
*
*/
gulp.task('default', (done) => {
  runSequence('clean', ['css', 'js', 'static'], () => {
    gulp.watch('./src/js/**/*.js', ['js']);
    gulp.watch('./src/css/**/*.css', ['css']);
    gulp.watch(staticFiles, ['static']);
    done();
  });
});
<|endoftext|>


<commit_before>var command = {
  command: "test",
  description: "Run JavaScript and Solidity tests",
  builder: {
    "show-events": {
      describe: "Show all test logs",
      type: "boolean",
      default: false
    }
  },
  help: {
    usage:
      "truffle test [<test_file>] [--compile-all] [--network <name>] [--verbose-rpc] [--show-events]",
    options: [
      {
        option: "<test_file>",
        description:
          "Name of the test file to be run. Can include path information if the file " +
          "does not exist in the\n                    current directory."
      },
      {
        option: "--compile-all",
        description:
          "Compile all contracts instead of intelligently choosing which contracts need " +
          "to be compiled."
      },
      {
        option: "--network <name>",
        description:
          "Specify the network to use, using artifacts specific to that network. Network " +
          "name must exist\n                    in the configuration."
      },
      {
        option: "--verbose-rpc",
        description:
          "Log communication between Truffle and the Ethereum client."
      },
      {
        option: "--show-events",
        description: "Log all contract events."
      }
    ]
  },
  run: function(options, done) {
    const OS = require("os");
    const dir = require("node-dir");
    const temp = require("temp").track();
    const Config = require("truffle-config");
    const Artifactor = require("truffle-artifactor");
    const Develop = require("../develop");
    const Test = require("../test");
    const fs = require("fs");
    const { promisify } = require("util");
    const promisifiedCopy = promisify(require("../copy"));
    const Environment = require("../environment");

    var config = Config.detect(options);

    // if "development" exists, default to using that for testing
    if (!config.network && config.networks.development) {
      config.network = "development";
    }

    if (!config.network) {
      config.network = "test";
    }

    var ipcDisconnect;

    var files = [];

    if (options.file) {
      files = [options.file];
    } else if (options._.length > 0) {
      Array.prototype.push.apply(files, options._);
    }

    function getFiles(callback) {
      if (files.length !== 0) {
        return callback(null, files);
      }

      dir.files(config.test_directory, callback);
    }

    getFiles(function(err, files) {
      if (err) return done(err);

      files = files.filter(function(file) {
        return file.match(config.test_file_extension_regexp) != null;
      });

      temp.mkdir("test-", function(err, temporaryDirectory) {
        if (err) return done(err);

        function runCallback() {
          var args = arguments;
          // Ensure directory cleanup.
          done.apply(null, args);
          if (ipcDisconnect) {
            ipcDisconnect();
          }
        }

        function run() {
          // Set a new artifactor; don't rely on the one created by Environments.
          // TODO: Make the test artifactor configurable.
          config.artifactor = new Artifactor(temporaryDirectory);

          Test.run(
            config.with({
              test_files: files,
              contracts_build_directory: temporaryDirectory
            }),
            runCallback
          );
        }

        var environmentCallback = function(err) {
          if (err) return done(err);
          // Copy all the built files over to a temporary directory, because we
          // don't want to save any tests artifacts. Only do this if the build directory
          // exists.
          try {
            fs.statSync(config.contracts_build_directory);
          } catch (_error) {
            return run();
          }

          promisifiedCopy(config.contracts_build_directory, temporaryDirectory)
            .then(() => {
              config.logger.log(
                "Using network '" + config.network + "'." + OS.EOL
              );

              run();
            })
            .catch(error => {
              done(error);
            });
        };

        if (config.networks[config.network]) {
          Environment.detect(config)
            .then(() => {
              console.log("IN the then from detect!!!!!!");
              environmentCallback();
            })
            .catch(error => {
              environmentCallback(error);
            });
        } else {
          var ipcOptions = {
            network: "test"
          };

          var ganacheOptions = {
            host: "127.0.0.1",
            port: 7545,
            network_id: 4447,
            mnemonic:
              "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat",
            gasLimit: config.gas,
            noVMErrorsOnRPCResponse: true
          };
          console.log("about to run Develop.connectOrStart");
          Develop.connectOrStart(ipcOptions, ganacheOptions, function(
            started,
            disconnect
          ) {
            ipcDisconnect = disconnect;
            Environment.develop(config, ganacheOptions, environmentCallback);
          });
        }
      });
    });
  }
};

module.exports = command;
<commit_msg>Update packages/truffle-core/lib/commands/test.js<commit_after>var command = {
  command: "test",
  description: "Run JavaScript and Solidity tests",
  builder: {
    "show-events": {
      describe: "Show all test logs",
      type: "boolean",
      default: false
    }
  },
  help: {
    usage:
      "truffle test [<test_file>] [--compile-all] [--network <name>] [--verbose-rpc] [--show-events]",
    options: [
      {
        option: "<test_file>",
        description:
          "Name of the test file to be run. Can include path information if the file " +
          "does not exist in the\n                    current directory."
      },
      {
        option: "--compile-all",
        description:
          "Compile all contracts instead of intelligently choosing which contracts need " +
          "to be compiled."
      },
      {
        option: "--network <name>",
        description:
          "Specify the network to use, using artifacts specific to that network. Network " +
          "name must exist\n                    in the configuration."
      },
      {
        option: "--verbose-rpc",
        description:
          "Log communication between Truffle and the Ethereum client."
      },
      {
        option: "--show-events",
        description: "Log all contract events."
      }
    ]
  },
  run: function(options, done) {
    const OS = require("os");
    const dir = require("node-dir");
    const temp = require("temp").track();
    const Config = require("truffle-config");
    const Artifactor = require("truffle-artifactor");
    const Develop = require("../develop");
    const Test = require("../test");
    const fs = require("fs");
    const { promisify } = require("util");
    const promisifiedCopy = promisify(require("../copy"));
    const Environment = require("../environment");

    var config = Config.detect(options);

    // if "development" exists, default to using that for testing
    if (!config.network && config.networks.development) {
      config.network = "development";
    }

    if (!config.network) {
      config.network = "test";
    }

    var ipcDisconnect;

    var files = [];

    if (options.file) {
      files = [options.file];
    } else if (options._.length > 0) {
      Array.prototype.push.apply(files, options._);
    }

    function getFiles(callback) {
      if (files.length !== 0) {
        return callback(null, files);
      }

      dir.files(config.test_directory, callback);
    }

    getFiles(function(err, files) {
      if (err) return done(err);

      files = files.filter(function(file) {
        return file.match(config.test_file_extension_regexp) != null;
      });

      temp.mkdir("test-", function(err, temporaryDirectory) {
        if (err) return done(err);

        function runCallback() {
          var args = arguments;
          // Ensure directory cleanup.
          done.apply(null, args);
          if (ipcDisconnect) {
            ipcDisconnect();
          }
        }

        function run() {
          // Set a new artifactor; don't rely on the one created by Environments.
          // TODO: Make the test artifactor configurable.
          config.artifactor = new Artifactor(temporaryDirectory);

          Test.run(
            config.with({
              test_files: files,
              contracts_build_directory: temporaryDirectory
            }),
            runCallback
          );
        }

        var environmentCallback = function(err) {
          if (err) return done(err);
          // Copy all the built files over to a temporary directory, because we
          // don't want to save any tests artifacts. Only do this if the build directory
          // exists.
          try {
            fs.statSync(config.contracts_build_directory);
          } catch (_error) {
            return run();
          }

          promisifiedCopy(config.contracts_build_directory, temporaryDirectory)
            .then(() => {
              config.logger.log(
                "Using network '" + config.network + "'." + OS.EOL
              );

              run();
            })
            .catch(error => {
              done(error);
            });
        };

        if (config.networks[config.network]) {
          Environment.detect(config)
            .then(() => {
              environmentCallback();
            })
            .catch(error => {
              environmentCallback(error);
            });
        } else {
          var ipcOptions = {
            network: "test"
          };

          var ganacheOptions = {
            host: "127.0.0.1",
            port: 7545,
            network_id: 4447,
            mnemonic:
              "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat",
            gasLimit: config.gas,
            noVMErrorsOnRPCResponse: true
          };
          console.log("about to run Develop.connectOrStart");
          Develop.connectOrStart(ipcOptions, ganacheOptions, function(
            started,
            disconnect
          ) {
            ipcDisconnect = disconnect;
            Environment.develop(config, ganacheOptions, environmentCallback);
          });
        }
      });
    });
  }
};

module.exports = command;
<|endoftext|>


<commit_before>import gulp from 'gulp';
import path from 'path';
import fs   from 'fs-extra';

gulp.task('clean', (done) => {
    fs.remove(path.join(__dirname, 'postcss.js'), () => {
        fs.remove(path.join(__dirname, 'build'), done);
    });
});

// Build

gulp.task('build:lib', ['clean'], () => {
    let babel = require('gulp-babel');
    return gulp.src('lib/*.js')
        .pipe(babel())
        .pipe(gulp.dest('build/lib'));
});

gulp.task('build:docs', ['clean'], () => {
    let ignore = require('fs').readFileSync('.npmignore').toString()
        .trim().split(/\n+/)
        .concat(['.npmignore', 'index.js', 'package.json'])
        .map( i => '!' + i );
    return gulp.src(['*'].concat(ignore))
        .pipe(gulp.dest('build'));
});

gulp.task('build:package', ['clean'], () => {
    let editor = require('gulp-json-editor');
    gulp.src('./package.json')
        .pipe(editor( (p) => {
            p.main = 'lib/safe-parse';
            p.devDependencies['babel-core'] = p.dependencies['babel-core'];
            delete p.dependencies['babel-core'];
            return p;
        }))
        .pipe(gulp.dest('build'));
});

gulp.task('build', ['build:lib', 'build:docs', 'build:package']);

// Lint

gulp.task('lint', () => {
    let eslint = require('gulp-eslint');
    return gulp.src(['*.js', 'lib/*.js', 'test/*.js'])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

// Test

gulp.task('test', () => {
    require('./');
    let mocha = require('gulp-mocha');
    return gulp.src('test/*.js', { read: false }).pipe(mocha());
});

gulp.task('integration', (done) => {
    let real = require('postcss-parser-tests/real');
    let safe = require('./');
    real(safe, [['Browserhacks', 'http://browserhacks.com/']], done);
});

// Common

gulp.task('default', ['lint', 'test', 'integration']);
<commit_msg>Upate parser tests API<commit_after>import gulp from 'gulp';
import path from 'path';
import fs   from 'fs-extra';

gulp.task('clean', (done) => {
    fs.remove(path.join(__dirname, 'postcss.js'), () => {
        fs.remove(path.join(__dirname, 'build'), done);
    });
});

// Build

gulp.task('build:lib', ['clean'], () => {
    let babel = require('gulp-babel');
    return gulp.src('lib/*.js')
        .pipe(babel())
        .pipe(gulp.dest('build/lib'));
});

gulp.task('build:docs', ['clean'], () => {
    let ignore = require('fs').readFileSync('.npmignore').toString()
        .trim().split(/\n+/)
        .concat(['.npmignore', 'index.js', 'package.json'])
        .map( i => '!' + i );
    return gulp.src(['*'].concat(ignore))
        .pipe(gulp.dest('build'));
});

gulp.task('build:package', ['clean'], () => {
    let editor = require('gulp-json-editor');
    gulp.src('./package.json')
        .pipe(editor( (p) => {
            p.main = 'lib/safe-parse';
            p.devDependencies['babel-core'] = p.dependencies['babel-core'];
            delete p.dependencies['babel-core'];
            return p;
        }))
        .pipe(gulp.dest('build'));
});

gulp.task('build', ['build:lib', 'build:docs', 'build:package']);

// Lint

gulp.task('lint', () => {
    let eslint = require('gulp-eslint');
    return gulp.src(['*.js', 'lib/*.js', 'test/*.js'])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

// Test

gulp.task('test', () => {
    require('./');
    let mocha = require('gulp-mocha');
    return gulp.src('test/*.js', { read: false }).pipe(mocha());
});

gulp.task('integration', (done) => {
    let real = require('postcss-parser-tests/real');
    let safe = require('./');
    real(done, [['Browserhacks', 'http://browserhacks.com/']], (css) => {
        return safe(css).toResult({ map: { annotation: false } });
    });
});

// Common

gulp.task('default', ['lint', 'test', 'integration']);
<|endoftext|>