<commit_before>//External modules
var path = require('path');
var util = require("util");

// Module Compile
exports.init = function (grunt) {
    'use strict';

    var module = require(path.join(path.dirname(__dirname), "default")).init(grunt);
    var deps = require("./include/depsAdder").init(grunt);

    var configuration = {};
    var moduleIncludes = {};

    module.registerTask("addDependencies", "Adding dependencies to files", function () {
        var depsPath = path.resolve(process.cwd(), configuration.default.options.baseUrl);
        // Get Modules with dependencies
        deps.addFoundDependenciesToFiles(depsPath);
    });

    module.registerTask("replaceDependencies", "Replacing dependencies to files", function () {
        // Load library
        var deps = require("./include/depsReplacer").init(grunt);
        var depsPath = path.resolve(process.cwd(), configuration.default.options.baseUrl);
        // Get Modules with dependencies
        deps.replaceDependencies();
    });

    util._extend(module, {
        name: path.basename(__dirname),
        run: function () {
            this.getConfiguration();

            // Load library
            deps.findDependencies(module.environment);
            moduleIncludes = deps.getIncludes(this.lastConfigurations.compile.default.sourcePath);

            this.runTask("addDependencies", {default: {}}, []);

            if (this.isNotEmptyObject(this.environment.libraries)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseLibraries(this.environment.libraries));
            }

            if (this.isNotEmptyObject(this.environment.reqModules) || this.isNotEmptyObject(this.lastConfigurations.compile.default.jsMapping)) {
                this.smartMerge(configuration.default.options, this.parseRequireModules(this.environment.reqModules, this.lastConfigurations.compile.default.jsMapping));
            }

            if (this.isNotEmptyObject(this.environment.packages)) {
                this.parsePackages(this.environment.packages, configuration.default.options.packages);
            }

            if (this.isNotEmptyObject(this.environment.base)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseBaseLibs(this.environment.base));
            }

            if (this.isNotEmptyObject(this.environment.shim)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseShim(this.environment.shim));
            }

            if (typeof configuration.default != "undefined" && typeof configuration.default.options.dir != "undefined") {
                this.makeClear(configuration.default.options.dir);
            }

            // Set SourcePath
            configuration.default.options.sourcePath = this.lastConfigurations.compile.default.sourcePath;

            // For Debug ->
            grunt.log.debug(JSON.stringify(configuration));

            // Make bundles
            configuration.default.options.done = function (done, output) {
                var bundles = require('rjs-build-analysis').parse(output);

                var output = {};
                if (bundles.hasOwnProperty("bundles") && grunt.util.kindOf(bundles.bundles) == "array") {

                    var reqModules = [];
                    for (var reqMod in module.environment.reqModules) {
                        reqModules.push(
                            module.environment.reqModules[reqMod].replace("{path.fromRoot}", process.cwd().replace(/\\/g, "/"))
                        );
                    }

                    bundles.bundles.forEach(function (bundle) {
                        var parent = path.relative(
                            path.resolve(process.cwd(), configuration.default.options.dir),
                            bundle.parent.substr(0, bundle.parent.lastIndexOf('/main')) || bundle.parent
                        );

                        output[parent] = bundle.children.map(function (bnd) {
                            if (/^[\w]+!/.test(bnd)) {
                                return bnd;
                            } else {
                                if (reqModules.indexOf((bnd.substr(0, bnd.lastIndexOf('.')) || bnd).replace(/\\/g, "/")) > -1) {
                                    return false;
                                }

                                return path.relative(
                                    path.resolve(process.cwd(), configuration.default.options.baseUrl),
                                    (bnd.substr(0, bnd.lastIndexOf('.')) || bnd).replace(/\\/g, "/")
                                ).replace(/\\/g, "/");
                            }
                        });
                    });
                }
                module.configuration.bundles = module.mergeObjects(module.configuration.bundles || {}, output);
                done();
            };

            var newConfig = grunt.util._.clone(configuration);
            if (grunt.util.kindOf(configuration.default.options.modules) == "array" && configuration.default.options.modules.length > 0) {
                for (var i = 0; i < configuration.default.options.modules.length; i++) {
                    var optModule = grunt.util._.clone(configuration.default.options.modules[i], true);
                    newConfig[optModule.name] = grunt.util._.clone(configuration.default, true);

                    var excludes = [];
                    if (optModule.exclude && optModule.exclude.length > 0) {
                        optModule.exclude.forEach(function (mdl) {
                            newConfig[optModule.name].options.paths[mdl] = "empty:";
                        });
                    }

                    for(var mInc in moduleIncludes){
                        if(optModule.include.indexOf(mInc) > -1){
                            optModule.include = optModule.include.concat(moduleIncludes[mInc]);
                        }
                    }

                    this.smartMerge(newConfig[optModule.name].options, {
                        name: optModule.name,
                        include: optModule.include,
                        exclude: excludes,
                        out: path.resolve(newConfig[optModule.name].options.dir, optModule.name, "main.js"),
                        requireDeps: optModule.insertRequire,
                        create: true
                    });

                    this.parseConfigs(newConfig[optModule.name]);

                    grunt.file.mkdir(
                        path.resolve(newConfig[optModule.name].options.dir, optModule.name)
                    );

                    delete newConfig[optModule.name].options.modules;
                    delete newConfig[optModule.name].options.dir;
                }
                delete newConfig["default"].options.modules;
            }

            this.configuration = configuration;

            // Setting configuration
            this.loadPlugin("grunt-contrib-requirejs");

            if (Object.keys(newConfig).length > 1) {
                var tasks = this.runTask("requirejs", newConfig, Object.keys(newConfig));
                this.runTask("replaceDependencies", newConfig, Object.keys(newConfig));
                return tasks;
            }

            return this.runTask("requirejs", newConfig);
        },
        getConfiguration: function () {
            // Load default configuration
            var configFile = path.resolve(__dirname, "config/default.json");
            if (grunt.file.exists(configFile)) {
                try {
                    configuration = grunt.file.readJSON(configFile);
                    grunt.log.debug(this.name + " plugin default configuration is loaded!");
                } catch (ex) {
                    grunt.log.error("[ERROR] " + this.name + " plugin default configuration has error!");
                    configuration = {};
                }
            }

            // Load user created configuration
            var userFile = grunt.config.get("kelper");
            if (userFile && userFile[this.name] && typeof userFile[this.name] == "function") {
                var config = (userFile[this.name])();
                //Parsing configuration
                configuration = this.mergeObjects(configuration, this.parse(config));
            } else {
                grunt.log.debug(this.name + " user configuration not found, continue");
            }

            return configuration;
        },
        parse: function (configuration) {
            var parsed = {};

            // Parsing
            if (configuration.hasOwnProperty("source")) {
                parsed.baseUrl = path.resolve(process.cwd(), configuration.source);
            }

            if (configuration.hasOwnProperty("target")) {
                parsed.dir = path.resolve(process.cwd(), configuration.target);
            }

            // Fix for RequireJS
            return {
                default: {
                    options: parsed
                }
            };
        },
        parseLibraries: function (source) {
            var parsed = {
                modules: [],
                packages: [],
                paths: {}
            };

            var skipPaths = {};
            for (var libraryName in source) {
                var library = source[libraryName];

                // Check each library and library name
                if (library) {
                    var includes = [];
                    var excludes = [];
                    var includeRequire = [];

                    // Check packages
                    if (this.isNotEmptyObject(library.packages)) {
                        for (var packageName in library.packages) {
                            var pkg = library.packages[packageName];

                            if (typeof pkg == "boolean") {
                                excludes.push(packageName);
                            } else {
                                if (pkg.skip) {
                                    skipPaths[packageName] = 'empty:';
                                }
                                includes.push(packageName);

                                if (!pkg.skipRequire) {
                                    includeRequire.push(
                                        pkg.requireName ? pkg.requireName : packageName
                                    );
                                }

                                if (pkg.replace) {
                                    parsed.paths = this.mergeObjects(parsed.paths, pkg.replace);
                                }
                            }
                        }
                    }

                    parsed.modules.push({
                        name: libraryName,
                        include: includes,
                        exclude: excludes,
                        insertRequire: includeRequire,
                        create: true
                    });

                    parsed.packages.push(libraryName);
                }

                parsed.packages = parsed.packages.concat(includes);
            }

            return parsed;
        },
        parseBaseLibs: function (libs) {
            var paths = {};
            for (var lib in libs) {
                paths[lib] = "empty:";
            }
            return {
                paths: paths
            };
        },
        parsePackages: function (packages, confPackages) {
            var parsed = confPackages || [];

            for (var packageName in packages) {
                var pkg = packages[packageName];

                if (pkg) {
                    parsed.push(packageName);
                    if (pkg.replace) {
                        parsed.paths = this.mergeObjects(parsed.paths, pkg.replace);
                    }
                }
            }

            confPackages = parsed;
        },
        parseRequireModules: function (reqModules, jsMapping) {
            var paths = {};
            var srcPath = path.resolve(process.cwd(), this.lastConfigurations.compile.default.sourcePath) + path.sep;

            if (this.isNotEmptyObject(reqModules)) {
                for (var lib in reqModules) {
                    var reqModulePath = reqModules[lib]
                        .replace("{path.fromKelper}", this.modulePath)
                        .replace("{path.fromSource}", path.resolve(process.cwd(), this.lastConfigurations.compile.default.sourcePath))
                        .replace("{path.fromRoot}", process.cwd());
                    paths[lib] = path.normalize(reqModulePath);
                }
            }

            var ret = grunt.util._.clone(paths);
            if (this.isNotEmptyObject(jsMapping)) {
                if (jsMapping.files && jsMapping.files.length > 0) {
                    jsMapping.files.forEach(function (map) {
                        var files = grunt.file.expand(path.resolve(srcPath, map));
                        files.forEach(function (file) {
                            var fileMap = path.relative(
                                srcPath,
                                file.replace(/\.js$/i, "")
                            ).replace(/\\/g, "/");
                            paths[fileMap] = path.resolve(srcPath, fileMap).replace(/\\/g, "/");
                        });
                    });
                }
            }

            return {
                paths: paths,
                stubModules: Object.keys(ret),
                sourceDir: srcPath
            }
        },
        parseShim: function (shims) {
            return {
                shim: shims
            }
        },
        parseConfigs: function (config) {
            var paths = config.options.paths || {};
            var excludePaths = [];

            // Filter excluded paths
            for (var path in paths) {
                if (paths[path] == "empty:") {
                    excludePaths.push(path);
                }
            }

            // Get paths to remove
            for (var path in paths) {
                if (paths[path] !== "empty:") {
                    excludePaths.forEach(function (exclPath) {
                        var regEx = new RegExp("^" + exclPath, "i");
                        if (regEx.test(path)) {
                            delete paths[path];
                        }
                    });
                }
            }

            return paths;
        },
        createModule: function (fileName, dest, modules) {
            var fileText = 'define("' + dest + '", ["' + modules.join('","') + '"], function(){});';
            grunt.file.write(fileName, fileText);
        }
    });

    return module;
};
<commit_msg>optimization: skipPaths fixed<commit_after>//External modules
var path = require('path');
var util = require("util");

// Module Compile
exports.init = function (grunt) {
    'use strict';

    var module = require(path.join(path.dirname(__dirname), "default")).init(grunt);
    var deps = require("./include/depsAdder").init(grunt);

    var configuration = {};
    var moduleIncludes = {};

    module.registerTask("addDependencies", "Adding dependencies to files", function () {
        var depsPath = path.resolve(process.cwd(), configuration.default.options.baseUrl);
        // Get Modules with dependencies
        deps.addFoundDependenciesToFiles(depsPath);
    });

    module.registerTask("replaceDependencies", "Replacing dependencies to files", function () {
        // Load library
        var deps = require("./include/depsReplacer").init(grunt);
        var depsPath = path.resolve(process.cwd(), configuration.default.options.baseUrl);
        // Get Modules with dependencies
        deps.replaceDependencies();
    });

    util._extend(module, {
        name: path.basename(__dirname),
        run: function () {
            this.getConfiguration();

            // Load library
            deps.findDependencies(module.environment);
            moduleIncludes = deps.getIncludes(this.lastConfigurations.compile.default.sourcePath);

            this.runTask("addDependencies", {default: {}}, []);

            if (this.isNotEmptyObject(this.environment.libraries)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseLibraries(this.environment.libraries));
            }

            if (this.isNotEmptyObject(this.environment.reqModules) || this.isNotEmptyObject(this.lastConfigurations.compile.default.jsMapping)) {
                this.smartMerge(configuration.default.options, this.parseRequireModules(this.environment.reqModules, this.lastConfigurations.compile.default.jsMapping));
            }

            if (this.isNotEmptyObject(this.environment.packages)) {
                this.parsePackages(this.environment.packages, configuration.default.options.packages);
            }

            if (this.isNotEmptyObject(this.environment.base)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseBaseLibs(this.environment.base));
            }

            if (this.isNotEmptyObject(this.environment.shim)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseShim(this.environment.shim));
            }

            if (typeof configuration.default != "undefined" && typeof configuration.default.options.dir != "undefined") {
                this.makeClear(configuration.default.options.dir);
            }

            // Set SourcePath
            configuration.default.options.sourcePath = this.lastConfigurations.compile.default.sourcePath;

            // For Debug ->
            grunt.log.debug(JSON.stringify(configuration));

            // Make bundles
            configuration.default.options.done = function (done, output) {
                var bundles = require('rjs-build-analysis').parse(output);

                var output = {};
                if (bundles.hasOwnProperty("bundles") && grunt.util.kindOf(bundles.bundles) == "array") {

                    var reqModules = [];
                    for (var reqMod in module.environment.reqModules) {
                        reqModules.push(
                            module.environment.reqModules[reqMod].replace("{path.fromRoot}", process.cwd().replace(/\\/g, "/"))
                        );
                    }

                    bundles.bundles.forEach(function (bundle) {
                        var parent = path.relative(
                            path.resolve(process.cwd(), configuration.default.options.dir),
                            bundle.parent.substr(0, bundle.parent.lastIndexOf('/main')) || bundle.parent
                        );

                        output[parent] = bundle.children.map(function (bnd) {
                            if (/^[\w]+!/.test(bnd)) {
                                return bnd;
                            } else {
                                if (reqModules.indexOf((bnd.substr(0, bnd.lastIndexOf('.')) || bnd).replace(/\\/g, "/")) > -1) {
                                    return false;
                                }

                                return path.relative(
                                    path.resolve(process.cwd(), configuration.default.options.baseUrl),
                                    (bnd.substr(0, bnd.lastIndexOf('.')) || bnd).replace(/\\/g, "/")
                                ).replace(/\\/g, "/");
                            }
                        });
                    });
                }
                module.configuration.bundles = module.mergeObjects(module.configuration.bundles || {}, output);
                done();
            };

            var newConfig = grunt.util._.clone(configuration);
            if (grunt.util.kindOf(configuration.default.options.modules) == "array" && configuration.default.options.modules.length > 0) {
                for (var i = 0; i < configuration.default.options.modules.length; i++) {
                    var optModule = grunt.util._.clone(configuration.default.options.modules[i], true);
                    newConfig[optModule.name] = grunt.util._.clone(configuration.default, true);

                    var excludes = [];
                    if (optModule.exclude && optModule.exclude.length > 0) {
                        optModule.exclude.forEach(function (mdl) {
                            newConfig[optModule.name].options.paths[mdl] = "empty:";
                        });
                    }

                    for(var mInc in moduleIncludes){
                        if(optModule.include.indexOf(mInc) > -1){
                            optModule.include = optModule.include.concat(moduleIncludes[mInc]);
                        }
                    }

                    this.smartMerge(newConfig[optModule.name].options, {
                        name: optModule.name,
                        include: optModule.include,
                        exclude: excludes,
                        out: path.resolve(newConfig[optModule.name].options.dir, optModule.name, "main.js"),
                        requireDeps: optModule.insertRequire,
                        create: true
                    });

                    this.parseConfigs(newConfig[optModule.name]);

                    grunt.file.mkdir(
                        path.resolve(newConfig[optModule.name].options.dir, optModule.name)
                    );

                    delete newConfig[optModule.name].options.modules;
                    delete newConfig[optModule.name].options.dir;
                }
                delete newConfig["default"].options.modules;
            }

            this.configuration = configuration;

            // Setting configuration
            this.loadPlugin("grunt-contrib-requirejs");

            if (Object.keys(newConfig).length > 1) {
                var tasks = this.runTask("requirejs", newConfig, Object.keys(newConfig));
                this.runTask("replaceDependencies", newConfig, Object.keys(newConfig));
                return tasks;
            }

            return this.runTask("requirejs", newConfig);
        },
        getConfiguration: function () {
            // Load default configuration
            var configFile = path.resolve(__dirname, "config/default.json");
            if (grunt.file.exists(configFile)) {
                try {
                    configuration = grunt.file.readJSON(configFile);
                    grunt.log.debug(this.name + " plugin default configuration is loaded!");
                } catch (ex) {
                    grunt.log.error("[ERROR] " + this.name + " plugin default configuration has error!");
                    configuration = {};
                }
            }

            // Load user created configuration
            var userFile = grunt.config.get("kelper");
            if (userFile && userFile[this.name] && typeof userFile[this.name] == "function") {
                var config = (userFile[this.name])();
                //Parsing configuration
                configuration = this.mergeObjects(configuration, this.parse(config));
            } else {
                grunt.log.debug(this.name + " user configuration not found, continue");
            }

            return configuration;
        },
        parse: function (configuration) {
            var parsed = {};

            // Parsing
            if (configuration.hasOwnProperty("source")) {
                parsed.baseUrl = path.resolve(process.cwd(), configuration.source);
            }

            if (configuration.hasOwnProperty("target")) {
                parsed.dir = path.resolve(process.cwd(), configuration.target);
            }

            // Fix for RequireJS
            return {
                default: {
                    options: parsed
                }
            };
        },
        parseLibraries: function (source) {
            var parsed = {
                modules: [],
                packages: [],
                paths: {}
            };

            var skipPaths = {};
            for (var libraryName in source) {
                var library = source[libraryName];

                // Check each library and library name
                if (library) {
                    var includes = [];
                    var excludes = [];
                    var includeRequire = [];

                    // Check packages
                    if (this.isNotEmptyObject(library.packages)) {
                        for (var packageName in library.packages) {
                            var pkg = library.packages[packageName];

                            if (typeof pkg == "boolean") {
                                excludes.push(packageName);
                            } else {
                                if (pkg.skip) {
                                    skipPaths[packageName] = 'empty:';
                                }
                                includes.push(packageName);

                                if (!pkg.skipRequire) {
                                    includeRequire.push(
                                        pkg.requireName ? pkg.requireName : packageName
                                    );
                                }

                                if (pkg.replace) {
                                    parsed.paths = this.mergeObjects(parsed.paths, pkg.replace);
                                }
                            }
                        }
                    }

                    parsed.modules.push({
                        name: libraryName,
                        include: includes,
                        exclude: excludes,
                        insertRequire: includeRequire,
                        create: true
                    });

                    parsed.packages.push(libraryName);
                }

                parsed.packages = parsed.packages.concat(includes);
            }

            parsed.paths = this.mergeObjects(parsed.paths, skipPaths);

            return parsed;
        },
        parseBaseLibs: function (libs) {
            var paths = {};
            for (var lib in libs) {
                paths[lib] = "empty:";
            }
            return {
                paths: paths
            };
        },
        parsePackages: function (packages, confPackages) {
            var parsed = confPackages || [];

            for (var packageName in packages) {
                var pkg = packages[packageName];

                if (pkg) {
                    parsed.push(packageName);
                    if (pkg.replace) {
                        parsed.paths = this.mergeObjects(parsed.paths, pkg.replace);
                    }
                }
            }

            confPackages = parsed;
        },
        parseRequireModules: function (reqModules, jsMapping) {
            var paths = {};
            var srcPath = path.resolve(process.cwd(), this.lastConfigurations.compile.default.sourcePath) + path.sep;

            if (this.isNotEmptyObject(reqModules)) {
                for (var lib in reqModules) {
                    var reqModulePath = reqModules[lib]
                        .replace("{path.fromKelper}", this.modulePath)
                        .replace("{path.fromSource}", path.resolve(process.cwd(), this.lastConfigurations.compile.default.sourcePath))
                        .replace("{path.fromRoot}", process.cwd());
                    paths[lib] = path.normalize(reqModulePath);
                }
            }

            var ret = grunt.util._.clone(paths);
            if (this.isNotEmptyObject(jsMapping)) {
                if (jsMapping.files && jsMapping.files.length > 0) {
                    jsMapping.files.forEach(function (map) {
                        var files = grunt.file.expand(path.resolve(srcPath, map));
                        files.forEach(function (file) {
                            var fileMap = path.relative(
                                srcPath,
                                file.replace(/\.js$/i, "")
                            ).replace(/\\/g, "/");
                            paths[fileMap] = path.resolve(srcPath, fileMap).replace(/\\/g, "/");
                        });
                    });
                }
            }

            return {
                paths: paths,
                stubModules: Object.keys(ret),
                sourceDir: srcPath
            }
        },
        parseShim: function (shims) {
            return {
                shim: shims
            }
        },
        parseConfigs: function (config) {
            var paths = config.options.paths || {};
            var excludePaths = [];

            // Filter excluded paths
            for (var path in paths) {
                if (paths[path] == "empty:") {
                    excludePaths.push(path);
                }
            }

            // Get paths to remove
            for (var path in paths) {
                if (paths[path] !== "empty:") {
                    excludePaths.forEach(function (exclPath) {
                        var regEx = new RegExp("^" + exclPath, "i");
                        if (regEx.test(path)) {
                            delete paths[path];
                        }
                    });
                }
            }

            return paths;
        },
        createModule: function (fileName, dest, modules) {
            var fileText = 'define("' + dest + '", ["' + modules.join('","') + '"], function(){});';
            grunt.file.write(fileName, fileText);
        }
    });

    return module;
};
<|endoftext|>


<commit_before>dc.ui.ProjectDialog = dc.ui.Dialog.extend({

  id : 'project_dialog',

  events : {
    'click .ok'                     : 'confirm',
    'click .cancel'                 : 'close',
    'click .delete'                 : '_deleteProject',
    'click .add_collaborator'       : '_showEnterEmail',
    'click .minibutton.add'         : '_addCollaborator',
    'keypress #collaborator_email'  : '_maybeAddCollaborator',
    'click .remove'                 : '_removeCollaborator'
  },

  constructor : function(options) {
    this.model = options.model;
    dc.ui.Dialog.call(this, {
      mode        : 'custom',
      title       : _.t('edit_x', this.model.get('title') )
    });
  },

  render : function(noHide) {
    if (!noHide) $(this.el).hide();
    dc.ui.Dialog.prototype.render.call(this, {editor : true, information : this.model.statistics()});
    this.$('.custom').html(JST['organizer/project_dialog']({model : this.model}));
    this.$('#project_title').val(this.model.get('title'));
    this.$('#project_description').val(this.model.get('description') || '');
    if (!this.model.get('owner')) this.$('.minibutton.delete').text("Remove");
    if (this.model.collaborators.length) {
      var views = this.model.collaborators.map(_.bind(function(account) {
        return (new dc.ui.AccountView({model : account, kind : 'collaborator'})).render(null, {project : this.model}).el;
      }, this));
      this.$('.collaborator_list tbody').append(views);
      this.$('.collaborators').show();
    }
    $(this.el).show();
    this.center();
    this._setPlaceholders();
    return this;
  },

  confirm : function() {
    var project     = this.model;
    var title       = this.$('#project_title').val();
    var description = this.$('#project_description').val();
    var already = Projects.any(function(other) {
      return (other !== project) && (other.get('title') == title);
    });
    if (!title)  return this.error("Please specify a project title.");
    if (already) return this.error("There is already a project with that title.");
    this.model.save({
      title       : title,
      description : description
    });
    this.close();
  },

  _setPlaceholders : function() {
    this.$('#project_title, #project_description').placeholder();
  },

  // If we don't own it, a request to remove the project is a request to remove
  // ourselves as a collaborator.
  _deleteProject : function() {
    var wasOpen = Projects.selected()[0] == this.model;
    if (!this.model.get('owner')) {
      Projects.remove(this.model);
      var me = Accounts.current().clone();
      me.collection = this.model.collaborators;
      me.destroy();
    } else {
      this.model.destroy();
    }
    this.close();
    if (wasOpen && !dc.app.searcher.flags.outstandingSearch) {
      dc.app.searcher.loadDefault({clear : true});
    }
  },

  _maybeAddCollaborator : function(e) {
    if (e.which == 13) this._addCollaborator();
  },

  _addCollaborator : function() {
    var email = this.$('#collaborator_email').val();
    if (!email) return this.error('Please enter an email address.');
    this.showSpinner();
    this.model.collaborators.create({email : email}, {
      wait: true,
      success : _.bind(function(acc, resp) {
        this.model.change();
        this.render(true);
      }, this),
      error   : _.bind(function(acc, resp) {
        errorResp = JSON.parse(resp.responseText);
        if (errorResp.errors) {
          this.error(errorResp.errors[0]);
        } else {
          this.error('No DocumentCloud account was found with that email.');
        }
        this.hideSpinner();
      }, this)
    });
  },

  _removeCollaborator : function(e) {
    this.showSpinner();
    var collab = this.model.collaborators.get(parseInt($(e.target).attr('data-id'), 10));
    collab.destroy({
      success : _.bind(function(){
        this.model.change();
        this.render(true);
      }, this)
    });
  },

  _showEnterEmail : function() {
    this.$('.add_collaborator').hide();
    this.$('.enter_email').show();
    this.$('#collaborator_email').focus();
  }

});
<commit_msg>Comment out deprecated api usage.<commit_after>dc.ui.ProjectDialog = dc.ui.Dialog.extend({

  id : 'project_dialog',

  events : {
    'click .ok'                     : 'confirm',
    'click .cancel'                 : 'close',
    'click .delete'                 : '_deleteProject',
    'click .add_collaborator'       : '_showEnterEmail',
    'click .minibutton.add'         : '_addCollaborator',
    'keypress #collaborator_email'  : '_maybeAddCollaborator',
    'click .remove'                 : '_removeCollaborator'
  },

  constructor : function(options) {
    this.model = options.model;
    dc.ui.Dialog.call(this, {
      mode        : 'custom',
      title       : _.t('edit_x', this.model.get('title') )
    });
  },

  render : function(noHide) {
    if (!noHide) $(this.el).hide();
    dc.ui.Dialog.prototype.render.call(this, {editor : true, information : this.model.statistics()});
    this.$('.custom').html(JST['organizer/project_dialog']({model : this.model}));
    this.$('#project_title').val(this.model.get('title'));
    this.$('#project_description').val(this.model.get('description') || '');
    if (!this.model.get('owner')) this.$('.minibutton.delete').text("Remove");
    if (this.model.collaborators.length) {
      var views = this.model.collaborators.map(_.bind(function(account) {
        return (new dc.ui.AccountView({model : account, kind : 'collaborator'})).render(null, {project : this.model}).el;
      }, this));
      this.$('.collaborator_list tbody').append(views);
      this.$('.collaborators').show();
    }
    $(this.el).show();
    this.center();
    this._setPlaceholders();
    return this;
  },

  confirm : function() {
    var project     = this.model;
    var title       = this.$('#project_title').val();
    var description = this.$('#project_description').val();
    var already = Projects.any(function(other) {
      return (other !== project) && (other.get('title') == title);
    });
    if (!title)  return this.error("Please specify a project title.");
    if (already) return this.error("There is already a project with that title.");
    this.model.save({
      title       : title,
      description : description
    });
    this.close();
  },

  _setPlaceholders : function() {
    this.$('#project_title, #project_description').placeholder();
  },

  // If we don't own it, a request to remove the project is a request to remove
  // ourselves as a collaborator.
  _deleteProject : function() {
    var wasOpen = Projects.selected()[0] == this.model;
    if (!this.model.get('owner')) {
      Projects.remove(this.model);
      var me = Accounts.current().clone();
      me.collection = this.model.collaborators;
      me.destroy();
    } else {
      this.model.destroy();
    }
    this.close();
    if (wasOpen && !dc.app.searcher.flags.outstandingSearch) {
      dc.app.searcher.loadDefault({clear : true});
    }
  },

  _maybeAddCollaborator : function(e) {
    if (e.which == 13) this._addCollaborator();
  },

  _addCollaborator : function() {
    var email = this.$('#collaborator_email').val();
    if (!email) return this.error('Please enter an email address.');
    this.showSpinner();
    this.model.collaborators.create({email : email}, {
      wait: true,
      success : _.bind(function(acc, resp) {
        //this.model.change();
        this.render(true);
      }, this),
      error   : _.bind(function(acc, resp) {
        errorResp = JSON.parse(resp.responseText);
        if (errorResp.errors) {
          this.error(errorResp.errors[0]);
        } else {
          this.error('No DocumentCloud account was found with that email.');
        }
        this.hideSpinner();
      }, this)
    });
  },

  _removeCollaborator : function(e) {
    this.showSpinner();
    var collab = this.model.collaborators.get(parseInt($(e.target).attr('data-id'), 10));
    collab.destroy({
      success : _.bind(function(){
        //this.model.change();
        this.render(true);
      }, this)
    });
  },

  _showEnterEmail : function() {
    this.$('.add_collaborator').hide();
    this.$('.enter_email').show();
    this.$('#collaborator_email').focus();
  }

});
<|endoftext|>


<commit_before>var
    _ = require('underscore'),
    argv = require('./argv.js'),
    fileExists = require('file-exists'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    concat = require('gulp-concat-util'),
    plumber = require('gulp-plumber'),
    fs = require('fs'),
    gulpWebpack = require('webpack-stream'),
    path = require('path'),

    sTenantName = argv.getParameter('--tenant'),
    sOutputName = argv.getParameter('--output'), /* app, app-mobile, app-message-newtab, app-adminpanel, app-files-pub, app-calendar-pub, app-helpdesk*/
    aModulesNames = argv.getModules(),
    // aModulesWatchPaths = [],
    sPath = sTenantName ? './tenants/' + sTenantName + '/static/js/' : './static/js/',
    crlf = '\n'
;

// aModulesNames.forEach(function (sModuleName) {
    // if (fileExists('./modules/' + sModuleName + '/js/*.js')) {
        // aModulesWatchPaths.push('./modules/' + sModuleName + '/js/**/*.js');
    // }
// });

function GetModuleName(sFilePath) {
    return sFilePath.replace(/.*modules[\\/](.*?)[\\/]js.*/, "$1");
}

var
	aModules = _.map(aModulesNames, function (sModuleName) {
		var
			sFilePath = './modules/' + sModuleName + '/js/manager.js',
			sTenantFilePath = './tenants/' + sTenantName + '/modules/' + sModuleName + '/js/manager.js',
			sFoundedFilePath = ''
		;

		if (fileExists(sTenantFilePath)) {
			sFoundedFilePath = sTenantFilePath;
		} else if (fileExists(sFilePath)) {
			sFoundedFilePath = sFilePath;
		}

		return sFoundedFilePath;
	}),
	oWebPackConfig = {
		resolveLoader: {
			alias: {
				"replace-module-names-loader": path.join(__dirname, "replace-module-names-loader.js")
			}
		},
		resolve: {
			root: [
				path.resolve('./')
			]
		},
		module: {
			loaders: [
				{
					test: /[\\\/]modernizr\.js$/,
					loader: "imports?this=>window!exports?window.Modernizr"
				},
				{
					test: /\.js$/,
					loader: 'replace-module-names-loader'
				}
			]
		}
	},
	compileCallback = function (sName, err, stats) {
		if (err) {
			throw new gutil.PluginError(sName, err);
		}
		gutil.log(sName, stats.toString({
			colors: true,
			//context: true,
			hash: false,
			version: false,
			timings: true,
			assets: false,
			chunks: false,
			chunkModules: false,
			modules: false,
			children: false,
			cached: false,
			reasons: false,
			source: false,
			errorDetails: false,
			chunkOrigins: false
		}));
	}
;

function jsTask(sTaskName, sName, oWebPackConfig) {

    gulp.src(aModules)
		.pipe(plumber({
            errorHandler: function (err) {
                console.log(err.toString());
                gutil.beep();
                this.emit('end');
            }
        }))
        .pipe(concat('_' + sName + '-entry.js', {
            sep: ',' + crlf,
            process: function (sSrc, sFilePath) {
                var sModuleName = GetModuleName(sFilePath);
                return "\t\t\t'" + sModuleName + "': " + "require(" + "'" + 'modules/' + sModuleName + '/js/manager.js' + "')";
            }
        }))
        .pipe(concat.header("'use strict';" + crlf +
            "var $ = require('jquery');" + crlf +
            "$('body').ready(function () {" + crlf +
            "\t" + "//for " + sTaskName + crlf +
            "\t" + "var" + crlf +
            "\t\t" + "oAvaliableModules = {" + crlf
        ))
        .pipe(concat.footer(crlf + "\t\t}," + crlf +
            "\t\t" + "ModulesManager = require('modules/CoreWebclient/js/ModulesManager.js')," + crlf +
            "\t\t" + "App = require('modules/CoreWebclient/js/App.js')," + crlf +
            "\t\t" + "bSwitchingToMobile = App.checkMobile()" + crlf +
            "\t" + ";" + crlf +
            "\t" + "if (!bSwitchingToMobile)" + crlf +
            "\t" + "{" + crlf +
            "\t\t" + "ModulesManager.init(oAvaliableModules, App.getUserRole(), App.isPublic());" + crlf +
            "\t\t" + "App.init();" + crlf +
            "\t" + "}" + crlf +
            "});" + crlf
        ))
		.pipe(gulp.dest(sPath))
		.pipe(gulpWebpack(oWebPackConfig, null, function (err, stats) {
			compileCallback.call(null, sTaskName, err, stats);
		}))
		// .pipe(concat(oData.name)) //break file saving in watch mode
		.pipe(plumber.stop())
        .pipe(gulp.dest(sPath))
	;
}

gulp.task('js1:build', function () {
	jsTask('js1:build', sOutputName, _.defaults({
		'output':  {
			'filename': sOutputName + '.js'
		}
	}, oWebPackConfig));
});

gulp.task('js1:watch', function () {
	jsTask('js1:watch', sOutputName, _.defaults({
		'watch': true,
		'aggregateTimeout': 300,
		'poll': true,
		'output':  {
			'filename': sOutputName + '.js'
		}
	}, oWebPackConfig));
});

gulp.task('js1:min', function () {
	jsTask('js1:min', sOutputName, _.defaults({
		'plugins': [
			new webpack.optimize.UglifyJsPlugin({
				compress: {
					warnings: false,
					drop_console: true,
					unsafe: true
				}
			})
		],
		'output':  {
			'filename': sOutputName + '.min.js'
		}
	}, oWebPackConfig));
});

module.exports = {};
<commit_msg>System - use manager.js files instead of manager-smth.js<commit_after>var
    _ = require('underscore'),
    argv = require('./argv.js'),
    fileExists = require('file-exists'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    concat = require('gulp-concat-util'),
    plumber = require('gulp-plumber'),
    fs = require('fs'),
    gulpWebpack = require('webpack-stream'),
    path = require('path'),

    sTenantName = argv.getParameter('--tenant'),
    sOutputName = argv.getParameter('--output'), /* app, app-mobile, app-message-newtab, app-adminpanel, app-files-pub, app-calendar-pub, app-helpdesk*/
    aModulesNames = argv.getModules(),
    // aModulesWatchPaths = [],
    sPath = sTenantName ? './tenants/' + sTenantName + '/static/js/' : './static/js/',
    crlf = '\n'
;

// aModulesNames.forEach(function (sModuleName) {
    // if (fileExists('./modules/' + sModuleName + '/js/*.js')) {
        // aModulesWatchPaths.push('./modules/' + sModuleName + '/js/**/*.js');
    // }
// });

function GetModuleName(sFilePath) {
    return sFilePath.replace(/.*modules[\\/](.*?)[\\/]js.*/, "$1");
}

var
	aModules = _.map(aModulesNames, function (sModuleName) {
		var
			sFilePath = './modules/' + sModuleName + '/js/manager.js',
			sTenantFilePath = './tenants/' + sTenantName + '/modules/' + sModuleName + '/js/manager.js',
			sFoundedFilePath = ''
		;

		if (fileExists(sTenantFilePath)) {
			sFoundedFilePath = sTenantFilePath;
		} else if (fileExists(sFilePath)) {
			sFoundedFilePath = sFilePath;
		}

		return sFoundedFilePath;
	}),
	oWebPackConfig = {
		resolveLoader: {
			alias: {
				"replace-module-names-loader": path.join(__dirname, "replace-module-names-loader.js")
			}
		},
		resolve: {
			root: [
				path.resolve('./')
			]
		},
		module: {
			loaders: [
				{
					test: /[\\\/]modernizr\.js$/,
					loader: "imports?this=>window!exports?window.Modernizr"
				},
				{
					test: /\.js$/,
					loader: 'replace-module-names-loader'
				}
			]
		}
	},
	compileCallback = function (sName, err, stats) {
		if (err) {
			throw new gutil.PluginError(sName, err);
		}
		gutil.log(sName, stats.toString({
			colors: true,
			//context: true,
			hash: false,
			version: false,
			timings: true,
			assets: false,
			chunks: false,
			chunkModules: false,
			modules: false,
			children: false,
			cached: false,
			reasons: false,
			source: false,
			errorDetails: false,
			chunkOrigins: false
		}));
	}
;

function jsTask(sTaskName, sName, oWebPackConfig) {

    gulp.src(aModules)
		.pipe(plumber({
            errorHandler: function (err) {
                console.log(err.toString());
                gutil.beep();
                this.emit('end');
            }
        }))
        .pipe(concat('_' + sName + '-entry.js', {
            sep: ',' + crlf,
            process: function (sSrc, sFilePath) {
                var sModuleName = GetModuleName(sFilePath);
                return "\t\t\t'" + sModuleName + "': " + "require(" + "'" + 'modules/' + sModuleName + '/js/manager.js' + "')";
            }
        }))
        .pipe(concat.header("'use strict';" + crlf +
            "var $ = require('jquery');" + crlf +
            "$('body').ready(function () {" + crlf +
            "\t" + "//for " + sTaskName + crlf +
            "\t" + "var" + crlf +
            "\t\t" + "oAvaliableModules = {" + crlf
        ))
        .pipe(concat.footer(crlf + "\t\t}," + crlf +
            "\t\t" + "ModulesManager = require('modules/CoreWebclient/js/ModulesManager.js')," + crlf +
            "\t\t" + "App = require('modules/CoreWebclient/js/App.js')," + crlf +
            "\t\t" + "bSwitchingToMobile = App.checkMobile()" + crlf +
            "\t" + ";" + crlf +
            "\t" + "if (!bSwitchingToMobile)" + crlf +
            "\t" + "{" + crlf +
            "\t\t" + "ModulesManager.init(oAvaliableModules);" + crlf +
            "\t\t" + "App.init();" + crlf +
            "\t" + "}" + crlf +
            "});" + crlf
        ))
		.pipe(gulp.dest(sPath))
		.pipe(gulpWebpack(oWebPackConfig, null, function (err, stats) {
			compileCallback.call(null, sTaskName, err, stats);
		}))
		// .pipe(concat(oData.name)) //break file saving in watch mode
		.pipe(plumber.stop())
        .pipe(gulp.dest(sPath))
	;
}

gulp.task('js1:build', function () {
	jsTask('js1:build', sOutputName, _.defaults({
		'output':  {
			'filename': sOutputName + '.js'
		}
	}, oWebPackConfig));
});

gulp.task('js1:watch', function () {
	jsTask('js1:watch', sOutputName, _.defaults({
		'watch': true,
		'aggregateTimeout': 300,
		'poll': true,
		'output':  {
			'filename': sOutputName + '.js'
		}
	}, oWebPackConfig));
});

gulp.task('js1:min', function () {
	jsTask('js1:min', sOutputName, _.defaults({
		'plugins': [
			new webpack.optimize.UglifyJsPlugin({
				compress: {
					warnings: false,
					drop_console: true,
					unsafe: true
				}
			})
		],
		'output':  {
			'filename': sOutputName + '.min.js'
		}
	}, oWebPackConfig));
});

module.exports = {};
<|endoftext|>


<commit_before>/* Based on aqtree3clickable from http://www.kryogenix.org/code/browser/aqlists/
Modifications by Jeremy Evans (code@jeremyevans.net) */

addEvent(window, "load", makeTreesC);

function makeTreesC() {
    if (!document.createElement)
        return;
    uls = document.getElementsByTagName("ul");
    for (uli=0;uli<uls.length;uli++) {
        ul = uls[uli];
        if (ul.nodeName == "UL" && ul.className == "scaffold_associations_tree") {
            processULELC(ul);
        }
    }
}

function processULELC(ul) {
    if (!ul.childNodes || ul.childNodes.length == 0)
        return;
    for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
        var item = ul.childNodes[itemi];
        if (item.nodeName == "LI") {
            var subul;
            subul = "";
            for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
                if (item.childNodes[sitemi].nodeName == "UL") {
                    subul = item.childNodes[sitemi];
                    processULELC(subul);
                }
            }
            if (subul) {
                item.className = 'sat_closed'
                item.innerHTML = '' + item.innerHTML
            } else {
                item.className = "sat_bullet";
                item.innerHTML = '' + item.innerHTML
            }
        }
    }
}

/*              Utility functions                    */

function addEvent(obj, evType, fn){
    /* adds an eventListener for browsers which support it
       Written by Scott Andrew: nice one, Scott */
    if (obj.addEventListener){
        obj.addEventListener(evType, fn, false);
        return true;
    } else if (obj.attachEvent){
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    } else {
        return false;
    }
}
<commit_msg>Make scaffold_associations_tree.js work with multiple class names on ul tags<commit_after>/* Based on aqtree3clickable from http://www.kryogenix.org/code/browser/aqlists/
Modifications by Jeremy Evans (code@jeremyevans.net) */

addEvent(window, "load", makeTreesC);

function makeTreesC() {
    if (!document.createElement)
        return;
    uls = document.getElementsByTagName("ul");
    for (uli=0;uli<uls.length;uli++) {
        ul = uls[uli];
        if (ul.nodeName == "UL" && ul.className.split(" ").indexOf("scaffold_associations_tree") != -1) {
            processULELC(ul);
        }
    }
}

function processULELC(ul) {
    if (!ul.childNodes || ul.childNodes.length == 0)
        return;
    for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
        var item = ul.childNodes[itemi];
        if (item.nodeName == "LI") {
            var subul;
            subul = "";
            for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
                if (item.childNodes[sitemi].nodeName == "UL") {
                    subul = item.childNodes[sitemi];
                    processULELC(subul);
                }
            }
            if (subul) {
                item.className = 'sat_closed'
                item.innerHTML = '' + item.innerHTML
            } else {
                item.className = "sat_bullet";
                item.innerHTML = '' + item.innerHTML
            }
        }
    }
}

/*              Utility functions                    */

function addEvent(obj, evType, fn){
    /* adds an eventListener for browsers which support it
       Written by Scott Andrew: nice one, Scott */
    if (obj.addEventListener){
        obj.addEventListener(evType, fn, false);
        return true;
    } else if (obj.attachEvent){
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    } else {
        return false;
    }
}
<|endoftext|>


<commit_before>module.exports = function (config) {

    config.set({
        basePath: '../../../',
        files: [
            // libs
            'build/www/lib/js/ionic.bundle.js',
            'build/www/lib/js/angular/angular-mocks.js',

            // app
            'build/www/js/**/*Module.js',
            'build/www/js/**/*.js',

            // tests
            'app/src/js/**/*.spec.js'
        ],
        frameworks: ['jasmine'],
        reporters: ['dots'],
        browsers: ['Chrome'],
        autoWatch: false,
        singleRun: true,
        colors: true
    });

};
<commit_msg>fixed karma.conf.js<commit_after>module.exports = function (config) {

    config.set({
        basePath: '../../../',
        files: [
            // libs
            'build/www/lib/js/ionic.bundle.js',
            'build/www/lib/js/angular/angular-mocks.js',

            // app
            'build/www/app.js',

            // tests
            'app/src/js/**/*.spec.js'
        ],
        frameworks: ['jasmine'],
        reporters: ['dots'],
        browsers: ['Chrome'],
        autoWatch: false,
        singleRun: true,
        colors: true
    });

};
<|endoftext|>


<commit_before>const Spawn = require('../lib/spawn.js')
const t = require('../')
const Test = t.Test
const Parser = require('tap-parser')
const node = process.execPath
const file = __filename

process.env.TAP_BAIL = ''
process.env.TAP_BUFFER = ''

const clean = require('./clean-stacks.js')

const main = () => {
  t.test('basic child process', t =>
    t.spawn(node, [ file, 'ok' ]))

  t.test('using a plan', t =>
    t.spawn(node, [ file, 'plan-ok' ]))

  t.test('hard quit', t =>
    t.spawn(node, [ file, 'sigself' ],
      { expectFail: true }))

  t.test('failing process', t =>
    t.spawn(node, [ file, 'not-ok' ],
            { expectFail: true }))

  t.test('timeout', t =>
    t.spawn(node, [ file, 'timeout' ], {
      expectFail: true,
      timeout: 1
    }))

  t.test('timeout KILL', t => {
    const s = new Spawn({
      command: node,
      args: [ file, 'catch-term' ],
      timeout: 500,
      buffered: true,
      name: 'killa'
    })
    s.main(() => {
      t.matchSnapshot(clean(s.output))
      t.end()
    })
  })

  t.test('skip stuff', t => {
    const tt = new Test({ buffered: true, bail: false })
    tt.spawn(node, [ file, 'skip' ], {
      bail: true,
      buffered: true
    }, 'skipper')
    tt.spawn(node, [ file, 'skip-reason' ])
    tt.test('check it', ttt => {
      t.matchSnapshot(clean(tt.output))
      t.end()
      tt.end()
      ttt.end()
    })
  })

  t.test('timeout before spawn is no-op', t => {
    const s = new Spawn({
      command: node,
      args: [ file, 'timeout' ]
    })
    s.timeout()
    t.end()
  })

  t.test('using spawn event', t => {
    t.on('spawn', t =>
      t.proc.stdin.end('TAP version 13\nok\n1..1\n'))
    t.spawn('cat', [], { stdio: [ 'pipe', 'pipe', 'ignore' ] })
    t.end()
  })

  t.test('using proc event', t => {
    const s = new Spawn({
      command: 'cat',
      args: [],
      buffered: true,
      bail: false,
      stdio: [ 'pipe', 'ignore', 'ignore' ]
    })
    s.on('process', p =>
      p.stdin.end('TAP version 13\nok\n1..1\n'))

    t.plan(1)
    s.main(() => t.matchSnapshot(clean(s.output)))
  })

  t.test('failure to spawn', t => {
    const s = new Spawn({
      command: 'something that does not exist',
      args: [],
      buffered: true,
      bail: false,
      stdio: [0, 1, 2]
    })
    t.plan(1)
    s.main(() => t.matchSnapshot(clean(s.output)))
  })

  t.test('failure to spawn even harder', t => {
    const cp = require('child_process')
    const spawn = cp.spawn
    const poop = new Error('poop error')
    cp.spawn = () => { throw poop }
    t.teardown(_ => cp.spawn = spawn)
    const s = new Spawn({
      command: 'poop',
      args: [],
      buffered: true,
      bail: false,
      stdio: 'inherit'
    })
    s.main(_ => {
      t.match(s.output, 'not ok 1 - poop error\n')
      t.match(s.output, 'command: poop\n')
      t.end()
    })
  })

  t.throws(_ => new Spawn(),
           new TypeError('no command provided'))

  t.test('endAll called', t => {
    t.test('call proc', t => {
      const s = new Spawn({
        command: node,
        args: [ file, 'timeout' ],
        bail: false,
        buffered: true
      })
      s.main(_ => {
        t.match(s.output, 'not ok 1 - test unfinished')
        t.end()
      })
      setTimeout(_ => s.endAll())
    })

    t.test('pre-call', t => {
      const s = new Spawn({
        command: node,
        args: [ file, 'timeout' ],
        bail: false,
        buffered: true
      })
      s.endAll()
      t.match(s.output, 'not ok 1 - test unfinished')
      t.end()
    })
    t.end()
  })
}

// Ignore this because a lot of these cases involve
// using a SIGKILL before nyc can write coverage
/* istanbul ignore next */
switch (process.argv[2]) {
  case 'ok':
    t.pass('this is fine')
    break

  case 'plan-ok':
    t.plan(1)
    t.pass('this is fine')
    setTimeout(_ => _, 200)
    break

  case 'sigself':
    setTimeout(_ =>
      process.kill(process.pid, 'SIGQUIT'), 300)
    break

  case 'not-ok':
    process.exit(1)
    break

  case 'skip':
    t.plan(0)
    break

  case 'skip-reason':
    t.plan(0, 'for no raisins')
    break

  case 'catch-term':
    process.on('SIGTERM', _ => console.log('SIGTERM'))
  case 'timeout':
    setTimeout(_ => _, 5000)
    break

  default:
    main()
}
<commit_msg>give sigterm catching MUCH longer on CI<commit_after>const Spawn = require('../lib/spawn.js')
const t = require('../')
const Test = t.Test
const Parser = require('tap-parser')
const node = process.execPath
const file = __filename

process.env.TAP_BAIL = ''
process.env.TAP_BUFFER = ''

const clean = require('./clean-stacks.js')

const main = () => {
  t.test('basic child process', t =>
    t.spawn(node, [ file, 'ok' ]))

  t.test('using a plan', t =>
    t.spawn(node, [ file, 'plan-ok' ]))

  t.test('hard quit', t =>
    t.spawn(node, [ file, 'sigself' ],
      { expectFail: true }))

  t.test('failing process', t =>
    t.spawn(node, [ file, 'not-ok' ],
            { expectFail: true }))

  t.test('timeout', t =>
    t.spawn(node, [ file, 'timeout' ], {
      expectFail: true,
      timeout: 1
    }))

  t.test('timeout KILL', t => {
    const s = new Spawn({
      command: node,
      args: [ file, 'catch-term' ],
      timeout: process.env.CI ? 2000 : 500,
      buffered: true,
      name: 'killa'
    })
    s.main(() => {
      t.matchSnapshot(clean(s.output))
      t.end()
    })
  })

  t.test('skip stuff', t => {
    const tt = new Test({ buffered: true, bail: false })
    tt.spawn(node, [ file, 'skip' ], {
      bail: true,
      buffered: true
    }, 'skipper')
    tt.spawn(node, [ file, 'skip-reason' ])
    tt.test('check it', ttt => {
      t.matchSnapshot(clean(tt.output))
      t.end()
      tt.end()
      ttt.end()
    })
  })

  t.test('timeout before spawn is no-op', t => {
    const s = new Spawn({
      command: node,
      args: [ file, 'timeout' ]
    })
    s.timeout()
    t.end()
  })

  t.test('using spawn event', t => {
    t.on('spawn', t =>
      t.proc.stdin.end('TAP version 13\nok\n1..1\n'))
    t.spawn('cat', [], { stdio: [ 'pipe', 'pipe', 'ignore' ] })
    t.end()
  })

  t.test('using proc event', t => {
    const s = new Spawn({
      command: 'cat',
      args: [],
      buffered: true,
      bail: false,
      stdio: [ 'pipe', 'ignore', 'ignore' ]
    })
    s.on('process', p =>
      p.stdin.end('TAP version 13\nok\n1..1\n'))

    t.plan(1)
    s.main(() => t.matchSnapshot(clean(s.output)))
  })

  t.test('failure to spawn', t => {
    const s = new Spawn({
      command: 'something that does not exist',
      args: [],
      buffered: true,
      bail: false,
      stdio: [0, 1, 2]
    })
    t.plan(1)
    s.main(() => t.matchSnapshot(clean(s.output)))
  })

  t.test('failure to spawn even harder', t => {
    const cp = require('child_process')
    const spawn = cp.spawn
    const poop = new Error('poop error')
    cp.spawn = () => { throw poop }
    t.teardown(_ => cp.spawn = spawn)
    const s = new Spawn({
      command: 'poop',
      args: [],
      buffered: true,
      bail: false,
      stdio: 'inherit'
    })
    s.main(_ => {
      t.match(s.output, 'not ok 1 - poop error\n')
      t.match(s.output, 'command: poop\n')
      t.end()
    })
  })

  t.throws(_ => new Spawn(),
           new TypeError('no command provided'))

  t.test('endAll called', t => {
    t.test('call proc', t => {
      const s = new Spawn({
        command: node,
        args: [ file, 'timeout' ],
        bail: false,
        buffered: true
      })
      s.main(_ => {
        t.match(s.output, 'not ok 1 - test unfinished')
        t.end()
      })
      setTimeout(_ => s.endAll())
    })

    t.test('pre-call', t => {
      const s = new Spawn({
        command: node,
        args: [ file, 'timeout' ],
        bail: false,
        buffered: true
      })
      s.endAll()
      t.match(s.output, 'not ok 1 - test unfinished')
      t.end()
    })
    t.end()
  })
}

// Ignore this because a lot of these cases involve
// using a SIGKILL before nyc can write coverage
/* istanbul ignore next */
switch (process.argv[2]) {
  case 'ok':
    t.pass('this is fine')
    break

  case 'plan-ok':
    t.plan(1)
    t.pass('this is fine')
    setTimeout(_ => _, 200)
    break

  case 'sigself':
    setTimeout(_ =>
      process.kill(process.pid, 'SIGQUIT'), 300)
    break

  case 'not-ok':
    process.exit(1)
    break

  case 'skip':
    t.plan(0)
    break

  case 'skip-reason':
    t.plan(0, 'for no raisins')
    break

  case 'catch-term':
    process.on('SIGTERM', _ => console.log('SIGTERM'))
  case 'timeout':
    setTimeout(_ => _, process.env.CI ? 50000 : 5000)
    break

  default:
    main()
}
<|endoftext|>


<commit_before>// @flow

declare var API_WS: string;
/* global process */

import WebSocket from 'reconnecting-websocket';
import type { Store } from 'redux';

import history from '../history';
import { setStream, setAfk } from '.';

let socket;
export let emit; // eslint-disable-line one-var

// the types of payloads we can expect from the server
export const actions = [
  'AFK_SET',
  'ERR',
  'RUSTLERS_SET',
  'STREAM_SET',
  'STREAMS_SET',
  'STREAM_GET',
  'STREAM_BANNED',
].reduce((acc, curr) => {
  acc[curr] = Symbol(curr);
  return acc;
}, {});

// thunks for these payloads
const thunks = {
  RUSTLERS_SET: payload => (dispatch, getState) => {
    const state = getState();
    const [ id ] = payload;
    if (!state.streams[id]) {
      emit('getStream', id);
    }
    else {
      dispatch({
        type: actions.RUSTLERS_SET,
        payload,
      });
    }
  },
  STREAM_BANNED: () => (dispatch) => {
    history.push('/beand');
    dispatch({
      type: actions.STREAM_BANNED,
      payload: null,
    });
  },
  STREAM_SET: (payload) => (dispatch, getState) => {
    dispatch({
      type: actions.STREAM_SET,
      payload,
    });
    if (getState().isAfk) {
      dispatch(setAfk(true));
    }
  },
};

export const init = (store: Store<*, *, *>) => {
  console.log(API_WS);
  socket = new WebSocket(API_WS || `ws://${location.host}`, [], {minReconnectionDelay: 1});
  let messageQueue = [];
  let wasReconnect = false;
  emit = (...args) => {
    if (socket.readyState !== 1) {
      messageQueue.push(args);
    }
    else {
      socket.send(JSON.stringify(args));
    }
  };

  const ping = () => socket.send('');
  let pingInterval;

  socket.onopen = function onopen() {
    pingInterval = setInterval(ping, 20000);
    messageQueue.forEach(args => emit(...args));
    messageQueue = [];
    if (wasReconnect) {
      // resend setStream on reconnect if we're watching one
      const state = store.getState();
      const stream = state.streams[state.stream];
      if (stream) {
        if (stream.overrustle_id) {
          store.dispatch(setStream(stream.overrustle_id));
        }
        else {
          store.dispatch(setStream(stream.channel, stream.service));
        }
      }
    }
    wasReconnect = true;
  };

  socket.onclose = function onclose() {
    clearInterval(pingInterval);
  };

  socket.onmessage = function onmessage(event) {
    if (process.env.NODE_ENV !== 'production') {
      // eslint-disable-next-line no-console
      console.log('socket message', event);
    }

    const { data } = event;
    try {
      const [ ws_action, ...args ] = JSON.parse(data);
      const action = actions[ws_action];
      // make sure we know what to do with this action
      if (!action) {
        throw new TypeError(`Invalid action "${ws_action}"`);
      }
      // call any 'hook' thunks if they exist
      if (thunks[ws_action]) {
        store.dispatch(thunks[ws_action](args));
      }
      // just dispatch the action if no hooks exist
      else {
        store.dispatch({
          type: action,
          payload: args,
        });
      }
    }
    catch (err) {
      /* eslint-disable-next-line no-console */
      console.error(`Failed to handle incoming websocket action\n${data}\n`, err);
    }
  };
};

// expose this for testing
window.__emit__ = emit;
<commit_msg>remove console.log<commit_after>// @flow

declare var API_WS: string;
/* global process */

import WebSocket from 'reconnecting-websocket';
import type { Store } from 'redux';

import history from '../history';
import { setStream, setAfk } from '.';

let socket;
export let emit; // eslint-disable-line one-var

// the types of payloads we can expect from the server
export const actions = [
  'AFK_SET',
  'ERR',
  'RUSTLERS_SET',
  'STREAM_SET',
  'STREAMS_SET',
  'STREAM_GET',
  'STREAM_BANNED',
].reduce((acc, curr) => {
  acc[curr] = Symbol(curr);
  return acc;
}, {});

// thunks for these payloads
const thunks = {
  RUSTLERS_SET: payload => (dispatch, getState) => {
    const state = getState();
    const [ id ] = payload;
    if (!state.streams[id]) {
      emit('getStream', id);
    }
    else {
      dispatch({
        type: actions.RUSTLERS_SET,
        payload,
      });
    }
  },
  STREAM_BANNED: () => (dispatch) => {
    history.push('/beand');
    dispatch({
      type: actions.STREAM_BANNED,
      payload: null,
    });
  },
  STREAM_SET: (payload) => (dispatch, getState) => {
    dispatch({
      type: actions.STREAM_SET,
      payload,
    });
    if (getState().isAfk) {
      dispatch(setAfk(true));
    }
  },
};

export const init = (store: Store<*, *, *>) => {
  socket = new WebSocket(API_WS || `ws://${location.host}`, [], {minReconnectionDelay: 1});
  let messageQueue = [];
  let wasReconnect = false;
  emit = (...args) => {
    if (socket.readyState !== 1) {
      messageQueue.push(args);
    }
    else {
      socket.send(JSON.stringify(args));
    }
  };

  const ping = () => socket.send('');
  let pingInterval;

  socket.onopen = function onopen() {
    pingInterval = setInterval(ping, 20000);
    messageQueue.forEach(args => emit(...args));
    messageQueue = [];
    if (wasReconnect) {
      // resend setStream on reconnect if we're watching one
      const state = store.getState();
      const stream = state.streams[state.stream];
      if (stream) {
        if (stream.overrustle_id) {
          store.dispatch(setStream(stream.overrustle_id));
        }
        else {
          store.dispatch(setStream(stream.channel, stream.service));
        }
      }
    }
    wasReconnect = true;
  };

  socket.onclose = function onclose() {
    clearInterval(pingInterval);
  };

  socket.onmessage = function onmessage(event) {
    if (process.env.NODE_ENV !== 'production') {
      // eslint-disable-next-line no-console
      console.log('socket message', event);
    }

    const { data } = event;
    try {
      const [ ws_action, ...args ] = JSON.parse(data);
      const action = actions[ws_action];
      // make sure we know what to do with this action
      if (!action) {
        throw new TypeError(`Invalid action "${ws_action}"`);
      }
      // call any 'hook' thunks if they exist
      if (thunks[ws_action]) {
        store.dispatch(thunks[ws_action](args));
      }
      // just dispatch the action if no hooks exist
      else {
        store.dispatch({
          type: action,
          payload: args,
        });
      }
    }
    catch (err) {
      /* eslint-disable-next-line no-console */
      console.error(`Failed to handle incoming websocket action\n${data}\n`, err);
    }
  };
};

// expose this for testing
window.__emit__ = emit;
<|endoftext|>


<commit_before>(function() {
	//CKEDITOR
	CKEDITOR.plugins.add( 'hubzerohighlight', {
		init: function( editor ) {
			var $      = jq,
				mode   = '',
				plugin = this;

			// dont highlight for ie8
			if ($('html').hasClass('ie8'))
			{
				return;
			}

			editor.on('mode', function(event) {
				plugin.highlight(editor);

				// add css for mark elements
				if (editor.mode != 'source')
				{
					this.document.appendStyleSheet('/media/editors/ckeditor/plugins/hubzerohighlight/plugin.css');
				}
			});

			editor.on('blur', function(event) {
				plugin.highlight(editor);

				// add css for mark elements
				if (editor.mode != 'source')
				{
					this.document.appendStyleSheet('/media/editors/ckeditor/plugins/hubzerohighlight/plugin.css');
				}
			});

			var form = $(editor.element.$.form);
			form.submit(function(event) {
				var data  = editor.getData();

				// remove old mark tags
				data = data.replace(//g, '');
				data = data.replace(/<\/mark>/g, '');
				data = data.replace(//g, '');
				data = data.replace(/<\/mark>/g, '');
				data = data.replace(//g, '');
				data = data.replace(/<\/mark>/g, '');

				// set new data
				editor.setData(data);
			});
		},

		highlight: function( editor )
		{
			console.log('highlight');

			// get current data
			var data  = editor.getData();

			// remove old mark tags
			data = data.replace(//g, '');
			data = data.replace(/<\/mark>/g, '');
			data = data.replace(//g, '');
			data = data.replace(/<\/mark>/g, '');
			data = data.replace(//g, '');
			data = data.replace(/<\/mark>/g, '');

			// add new mark tags
			if (editor.mode == 'wysiwyg')
			{
				data = data.replace(/(\[\[[^\]]*]])/g, '$1');
				data = data.replace(/(<group:include[^>]*>)/g, '$1');
				data = data.replace(/({xhub:[^}]*})/g, '$1');
			}

			// set new data
			editor.setData(data);
		}
	});
})();<commit_msg>[PLG_EDITORS_CKEDITOR] Fixed hubzero highlight plugin to not break if "jq" is not defined.<commit_after>(function() {
	//CKEDITOR
	CKEDITOR.plugins.add( 'hubzerohighlight', {
		init: function( editor ) {
			var $      = (typeof(jq) !== "undefined" ? jq : jQuery),
				mode   = '',
				plugin = this;

			// dont highlight for ie8
			if ($('html').hasClass('ie8'))
			{
				return;
			}

			editor.on('mode', function(event) {
				plugin.highlight(editor);

				// add css for mark elements
				if (editor.mode != 'source')
				{
					this.document.appendStyleSheet('/media/editors/ckeditor/plugins/hubzerohighlight/plugin.css');
				}
			});

			editor.on('blur', function(event) {
				plugin.highlight(editor);

				// add css for mark elements
				if (editor.mode != 'source')
				{
					this.document.appendStyleSheet('/media/editors/ckeditor/plugins/hubzerohighlight/plugin.css');
				}
			});

			var form = $(editor.element.$.form);
			form.submit(function(event) {
				var data  = editor.getData();

				// remove old mark tags
				data = data.replace(//g, '');
				data = data.replace(/<\/mark>/g, '');
				data = data.replace(//g, '');
				data = data.replace(/<\/mark>/g, '');
				data = data.replace(//g, '');
				data = data.replace(/<\/mark>/g, '');

				// set new data
				editor.setData(data);
			});
		},

		highlight: function( editor )
		{
			// get current data
			var data  = editor.getData();

			// remove old mark tags
			data = data.replace(//g, '');
			data = data.replace(/<\/mark>/g, '');
			data = data.replace(//g, '');
			data = data.replace(/<\/mark>/g, '');
			data = data.replace(//g, '');
			data = data.replace(/<\/mark>/g, '');

			// add new mark tags
			if (editor.mode == 'wysiwyg')
			{
				data = data.replace(/(\[\[[^\]]*]])/g, '$1');
				data = data.replace(/(<group:include[^>]*>)/g, '$1');
				data = data.replace(/({xhub:[^}]*})/g, '$1');
			}

			// set new data
			editor.setData(data);
		}
	});
})();<|endoftext|>


<commit_before>(function() {
  "use strict";
  App.ui.interfaces.std.validate = {
    methods: {
      _formatForEmpty: function() {
        return null;
      },
      _valueIsEmpty: function(value) {
        if (value === undefined || value === null || String(value).trim().length < 1) {
          return true;
        } else {
          return false;
        }
      },
      _formatForUrl: function() {
        return "http://example.com";
      },
      _valueIsUrl: function(url) {
        var r = /^((http|https):\/\/)?[\w-]+(\.[\w-]{2,})+(\/[\w-]*)*(\?([\w-%]+=[\w-%]+)(&([\w-%]+=[\w-%]+))*)?$/i;
        if (r.test(url)) {
          return true;
        } else {
          return false;
        }
      },
      _formatForDate: function() {
        return 'MM/DD/YYYY';
      },
      _valueIsDate: function(date) {
        if (date && date instanceOf Date) {
          return true;
        }
        var r = /^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/\d\d\d\d$/;
        if (r.test(date)) {
          return true;
        } else {
          return false;
        }
      },
      _formatForEmail: function() {
        return 'user@domain.com';
      },
      _valueIsEmail: function(email) {
        var r = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
        if (r.test(email)) {
          return true;
        } else {
          return false;
        }
      },
      _formatForPhone: function() {
        return '+X (XXX) XXX-XXXX';
      },
      _valueIsPhone: function(phone) {
        var r = /^(?:(\+?(?:(\d{1,2}))\s?)?(\(?(?:(\d{3}))\)?(\s|-|\.)?)((?:(\d{3}))(\s|-|\.)?)((?:(\d{4}))))$/i;
        if (r.test(phone)) {
          return true;
        } else {
          return false;
        }
      }
    }
  };
})();
<commit_msg>Create validate.js<commit_after>(function() {
  "use strict";
  App.ui.interfaces.std.validate = {
    methods: {
      _formatForEmpty: function() {
        return null;
      },
      _valueIsEmpty: function(value) {
        if (value === undefined || value === null || String(value).trim().length < 1) {
          return true;
        } else {
          return false;
        }
      },
      _formatForUrl: function() {
        return "http://example.com";
      },
      _valueIsUrl: function(url) {
        var r = /^((http|https):\/\/)?[\w-]+(\.[\w-]{2,})+(\/[\w-]*)*(\?([\w-%]+=[\w-%]+)(&([\w-%]+=[\w-%]+))*)?$/i;
        if (r.test(url)) {
          return true;
        } else {
          return false;
        }
      },
      _formatForDate: function() {
        return 'MM/DD/YYYY';
      },
      _valueIsDate: function(date) {
        if (date && date instanceof Date) {
          return true;
        }
        var r = /^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/\d\d\d\d$/;
        if (r.test(date)) {
          return true;
        } else {
          return false;
        }
      },
      _formatForEmail: function() {
        return 'user@domain.com';
      },
      _valueIsEmail: function(email) {
        var r = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
        if (r.test(email)) {
          return true;
        } else {
          return false;
        }
      },
      _formatForPhone: function() {
        return '+X (XXX) XXX-XXXX';
      },
      _valueIsPhone: function(phone) {
        var r = /^(?:(\+?(?:(\d{1,2}))\s?)?(\(?(?:(\d{3}))\)?(\s|-|\.)?)((?:(\d{3}))(\s|-|\.)?)((?:(\d{4}))))$/i;
        if (r.test(phone)) {
          return true;
        } else {
          return false;
        }
      }
    }
  };
})();
<|endoftext|>


<commit_before>'use babel'

import { client } from '../connection'
import { views } from '../ui'

const { webview } = views.tags

function consoleLog (e) {
  let log
  if (e.level === 0) {
    log = console.log
  } else if (e.level === 1) {
    log = console.warn
  } else if (e.level === 2) {
    log = console.error
  }
  log(e.message, `\nat ${e.sourceID}:${e.line}`)
}

export default {
  activate () {
    client.handle({
      plot: x => this.show(x),
      plotsize: () => this.plotSize(),
      ploturl: url => this.ploturl(url),
      jlpane: (id, opts) => this.jlpane(id, opts)
    })
    this.create()

    atom.config.observe('julia-client.uiOptions.usePlotPane', enabled => {
      if (enabled) {
        return this.pane.setTitle('Plots')
      } else {
        return this.pane.setTitle('Plots (disabled)')
      }
    })

    return atom.config.observe('julia-client.uiOptions.layouts.plotPane.defaultLocation', defaultLocation => {
      this.pane.setDefaultLocation(defaultLocation)
    })
  },

  create () {
    return this.pane = this.ink.PlotPane.fromId('default')
  },

  open () {
    return this.pane.open({
      split: atom.config.get('julia-client.uiOptions.layouts.plotPane.split')})
  },

  ensureVisible () {
    return this.pane.ensureVisible({ split: atom.config.get('julia-client.uiOptions.layouts.plotPane.split') })
  },

  close () {
    return this.pane.close()
  },

  show (view) {
    this.ensureVisible()
    const v = views.render(view)
    this.pane.show(new this.ink.Pannable(v))
    return v
  },

  plotSize () {
    return this.ensureVisible().then(() => {
      return this.pane.size().map(x => x*window.devicePixelRatio)
    })
  },

  webview (url) {
    const v = views.render(webview({
      class: 'blinkjl',
      src: url,
      style: 'width: 100% height: 100%'
    })
    )
    v.classList.add('native-key-bindings')
    v.addEventListener('console-message', e => consoleLog(e))
    return v
  },

  ploturl (url) {
    const v = this.webview(url)
    this.ensureVisible()
    return this.pane.show(v)
  },

  jlpane (id, opts) {
    if (opts == null) { opts = {} }
    let v = undefined
    if (opts.url) {
      v = this.webview(opts.url)
      if (opts.devtools) {
        v.addEventListener('dom-ready', () => {
          return v.openDevTools()
        })
      }
    }

    const pane = this.ink.HTMLPane.fromId(id)

    if (opts.close) {
      return pane.close()
    } else if (opts.destroy) {
      if (pane.closeAndDestroy) {
        return pane.closeAndDestroy()
      }
    } else {
      pane.show({
        item: v,
        icon: opts.icon,
        title: opts.title
      })

      return pane.ensureVisible({
        split: opts.split || atom.config.get('julia-client.uiOptions.layouts.plotPane.split')
      })
    }
  }
}
<commit_msg>plotsize gives info about devicePixelRatio<commit_after>'use babel'

import { client } from '../connection'
import { views } from '../ui'

const { webview } = views.tags

function consoleLog (e) {
  let log
  if (e.level === 0) {
    log = console.log
  } else if (e.level === 1) {
    log = console.warn
  } else if (e.level === 2) {
    log = console.error
  }
  log(e.message, `\nat ${e.sourceID}:${e.line}`)
}

export default {
  activate () {
    client.handle({
      plot: x => this.show(x),
      plotsize: () => this.plotSize(),
      ploturl: url => this.ploturl(url),
      jlpane: (id, opts) => this.jlpane(id, opts)
    })
    this.create()

    atom.config.observe('julia-client.uiOptions.usePlotPane', enabled => {
      if (enabled) {
        return this.pane.setTitle('Plots')
      } else {
        return this.pane.setTitle('Plots (disabled)')
      }
    })

    return atom.config.observe('julia-client.uiOptions.layouts.plotPane.defaultLocation', defaultLocation => {
      this.pane.setDefaultLocation(defaultLocation)
    })
  },

  create () {
    return this.pane = this.ink.PlotPane.fromId('default')
  },

  open () {
    return this.pane.open({
      split: atom.config.get('julia-client.uiOptions.layouts.plotPane.split')})
  },

  ensureVisible () {
    return this.pane.ensureVisible({ split: atom.config.get('julia-client.uiOptions.layouts.plotPane.split') })
  },

  close () {
    return this.pane.close()
  },

  show (view) {
    this.ensureVisible()
    const v = views.render(view)
    this.pane.show(new this.ink.Pannable(v))
    return v
  },

  plotSize () {
    return this.ensureVisible().then(() => {
      return {
        size: this.pane.size(),
        ratio: window.devicePixelRatio
      }
    })
  },

  webview (url) {
    const v = views.render(webview({
      class: 'blinkjl',
      src: url,
      style: 'width: 100% height: 100%'
    })
    )
    v.classList.add('native-key-bindings')
    v.addEventListener('console-message', e => consoleLog(e))
    return v
  },

  ploturl (url) {
    const v = this.webview(url)
    this.ensureVisible()
    return this.pane.show(v)
  },

  jlpane (id, opts) {
    if (opts == null) { opts = {} }
    let v = undefined
    if (opts.url) {
      v = this.webview(opts.url)
      if (opts.devtools) {
        v.addEventListener('dom-ready', () => {
          return v.openDevTools()
        })
      }
    }

    const pane = this.ink.HTMLPane.fromId(id)

    if (opts.close) {
      return pane.close()
    } else if (opts.destroy) {
      if (pane.closeAndDestroy) {
        return pane.closeAndDestroy()
      }
    } else {
      pane.show({
        item: v,
        icon: opts.icon,
        title: opts.title
      })

      return pane.ensureVisible({
        split: opts.split || atom.config.get('julia-client.uiOptions.layouts.plotPane.split')
      })
    }
  }
}
<|endoftext|>


<commit_before>// @flow
// @jsx createElement

import '../../../../css/popup/bookmark-tree.css'

import {PureComponent, createElement} from 'react'
import List from 'react-virtualized/dist/es/List'

import * as CST from '../../constants'
import type {BookmarkInfo, BookmarkTree as BookmarkTreeType} from '../../types'
import Mask from '../Mask'
import BookmarkRow from './BookmarkRow'
import TreeHeader from './TreeHeader'

type Props = {|
  focusId: string,
  iconSize: number,
  isShowCover: boolean,
  isShowHeader: boolean,
  listItemWidth: number,
  onCloseButtonClick: () => void,
  onCoverClick: () => void,
  onRowAuxClick: (string) => (MouseEvent) => void,
  onRowClick: (string) => (SyntheticMouseEvent<HTMLElement>) => void,
  onRowMouseEnter: (BookmarkInfo) => () => void,
  onRowMouseLeave: () => void,
  rowHeight: number,
  scrollToIndex: number,
  treeInfo: BookmarkTreeType
|}
type State = {|
  listHeight: number
|}
class BookmarkTree extends PureComponent<Props, State> {
  state = {
    listHeight: 0
  }

  componentDidMount() {
    this.setHeight()
  }

  componentDidUpdate(prevProps: Props) {
    if (prevProps.treeInfo !== this.props.treeInfo) {
      // force recalculate all row heights as it doesn't recalculate
      this.props.treeInfo.children.forEach((x, index) => {
        if (this.list) this.list.recomputeRowHeights(index)
      })

      this.setHeight()
    }
  }

  getRowHeight = (payload: {| index: number |}) => {
    let rowHeight = this.props.rowHeight

    const bookmarkInfo = this.props.treeInfo.children[payload.index]
    if (bookmarkInfo.type === CST.TYPE_SEPARATOR) {
      rowHeight /= 2
    }

    // for the indicator show the end of folder
    if (payload.index === this.props.treeInfo.children.length - 1) {
      rowHeight += CST.GOLDEN_GAP * 2
    }

    return rowHeight
  }

  setHeight = () => {
    if (!this.list) return

    // search-box and tree-header-box height
    const listContainerElOffsetTop = this.list.Grid._scrollingContainer.getBoundingClientRect().top

    const totalRowHeight = this.props.treeInfo.children.reduce(
      (acc, x, index) => acc + this.getRowHeight({index}),
      0
    )

    const maxListHeight = CST.MAX_HEIGHT - listContainerElOffsetTop

    this.setState({
      listHeight: Math.min(maxListHeight, totalRowHeight)
    })
  }

  list: ?Object
  render = () => (

      {this.props.isShowHeader && (
        <TreeHeader
          title={this.props.treeInfo.parent.title}
          onClose={this.props.onCloseButtonClick}
        />
      )}

      <List
        ref={(ref) => {
          this.list = ref
        }}
        height={this.state.listHeight}
        // onScroll={this.props.onScroll}
        rowCount={this.props.treeInfo.children.length}
        rowHeight={this.getRowHeight}
        rowRenderer={(rendererProps: {| index: number, key: string, style: Object |}) => {
          const bookmarkInfo = this.props.treeInfo.children[rendererProps.index]
          return (

              <BookmarkRow
                key={bookmarkInfo.id}
                bookmarkInfo={bookmarkInfo}
                iconSize={this.props.iconSize}
                isFocused={this.props.focusId === bookmarkInfo.id}
                onAuxClick={this.props.onRowAuxClick}
                onClick={this.props.onRowClick}
                onMouseEnter={this.props.onRowMouseEnter}
                onMouseLeave={this.props.onRowMouseLeave}
              />

          )
        }}
        scrollToIndex={this.props.scrollToIndex >= 0 ? this.props.scrollToIndex : undefined}
        // scrollTop={this.props.lastScrollTop}
        tabIndex={-1}
        width={this.props.listItemWidth}
      />

      {this.props.isShowCover && (
        <Mask backgroundColor='#000' opacity={0.16} onClick={this.props.onCoverClick} />
      )}

  )
}

export default BookmarkTree
<commit_msg>style: remove unused code<commit_after>// @flow
// @jsx createElement

import '../../../../css/popup/bookmark-tree.css'

import {PureComponent, createElement} from 'react'
import List from 'react-virtualized/dist/es/List'

import * as CST from '../../constants'
import type {BookmarkInfo, BookmarkTree as BookmarkTreeType} from '../../types'
import Mask from '../Mask'
import BookmarkRow from './BookmarkRow'
import TreeHeader from './TreeHeader'

type Props = {|
  focusId: string,
  iconSize: number,
  isShowCover: boolean,
  isShowHeader: boolean,
  listItemWidth: number,
  onCloseButtonClick: () => void,
  onCoverClick: () => void,
  onRowAuxClick: (string) => (MouseEvent) => void,
  onRowClick: (string) => (SyntheticMouseEvent<HTMLElement>) => void,
  onRowMouseEnter: (BookmarkInfo) => () => void,
  onRowMouseLeave: () => void,
  rowHeight: number,
  scrollToIndex: number,
  treeInfo: BookmarkTreeType
|}
type State = {|
  listHeight: number
|}
class BookmarkTree extends PureComponent<Props, State> {
  state = {
    listHeight: 0
  }

  componentDidMount() {
    this.setHeight()
  }

  componentDidUpdate(prevProps: Props) {
    if (prevProps.treeInfo !== this.props.treeInfo) {
      // force recalculate all row heights as it doesn't recalculate
      this.props.treeInfo.children.forEach((x, index) => {
        if (this.list) this.list.recomputeRowHeights(index)
      })

      this.setHeight()
    }
  }

  getRowHeight = (payload: {| index: number |}) => {
    let rowHeight = this.props.rowHeight

    const bookmarkInfo = this.props.treeInfo.children[payload.index]
    if (bookmarkInfo.type === CST.TYPE_SEPARATOR) {
      rowHeight /= 2
    }

    // for the indicator show the end of folder
    if (payload.index === this.props.treeInfo.children.length - 1) {
      rowHeight += CST.GOLDEN_GAP * 2
    }

    return rowHeight
  }

  setHeight = () => {
    if (!this.list) return

    // search-box and tree-header-box height
    const listContainerElOffsetTop = this.list.Grid._scrollingContainer.getBoundingClientRect().top

    const totalRowHeight = this.props.treeInfo.children.reduce(
      (acc, x, index) => acc + this.getRowHeight({index}),
      0
    )

    const maxListHeight = CST.MAX_HEIGHT - listContainerElOffsetTop

    this.setState({
      listHeight: Math.min(maxListHeight, totalRowHeight)
    })
  }

  list: ?Object
  render = () => (

      {this.props.isShowHeader && (
        <TreeHeader
          title={this.props.treeInfo.parent.title}
          onClose={this.props.onCloseButtonClick}
        />
      )}

      <List
        ref={(ref) => {
          this.list = ref
        }}
        height={this.state.listHeight}
        // onScroll={this.props.onScroll}
        rowCount={this.props.treeInfo.children.length}
        rowHeight={this.getRowHeight}
        rowRenderer={(rendererProps: {| index: number, key: string, style: Object |}) => {
          const bookmarkInfo = this.props.treeInfo.children[rendererProps.index]
          return (

              <BookmarkRow
                bookmarkInfo={bookmarkInfo}
                iconSize={this.props.iconSize}
                isFocused={this.props.focusId === bookmarkInfo.id}
                onAuxClick={this.props.onRowAuxClick}
                onClick={this.props.onRowClick}
                onMouseEnter={this.props.onRowMouseEnter}
                onMouseLeave={this.props.onRowMouseLeave}
              />

          )
        }}
        scrollToIndex={this.props.scrollToIndex >= 0 ? this.props.scrollToIndex : undefined}
        // scrollTop={this.props.lastScrollTop}
        tabIndex={-1}
        width={this.props.listItemWidth}
      />

      {this.props.isShowCover && (
        <Mask backgroundColor='#000' opacity={0.16} onClick={this.props.onCoverClick} />
      )}

  )
}

export default BookmarkTree
<|endoftext|>