<commit_before>/*
 * RequireJS 'is' plugin
 *
 * Usage:
 *
 * is!myFeature?module
 * is!~myFeature?module (negation)
 *
 * Features can be set dynamically with
 * require('is', function(is) {
 *   is.enable('var');
 * });
 *
 * Or features can be set as startup config with
 * config: {
 *   is: {
 *     var: true
 *   }
 * }
 *
 * If none of the above applies, the feature is assumed to be a moduleId
 * that resolves to a boolean.
 *
 * Thus to write a dynamic feature, say iphone.js, just do:
 *
 * iphone.js:
 * define(function() {
 *   if (typeof navigator === 'undefined' || typeof navigator.userAgent === 'undefined')
 *     return false;
 *   return navigator.userAgent.match(/iPhone/i);
 * });
 *
 * Which can then be used with a require of the form: is!iphone?iphone-scripts.
 *
 *
 * Builds
 * The build environment features are computed in the same way as normally. Using path mappings
 * and the 'is' config, particular build environments can be configured.
 *
 * The build determines if the conditional modules should be written or not.
 *
 * It is still up to the environment detection to determine if the features apply or not.
 *
 * With careful config, this covers the use cases of specific device builds, as well as packaging
 * all variations into a single built file.
 *
 * Build layers corresponding to a particular feature variation can be created using a feature variation
 * build name.
 *
 * Basically, disable the feature and build the first modules that would be using it. Then create a separate
 * mobule which includes: [is!feature*]. This will then drop back all items of that feature into the build,
 * that were previously excluded.
 *
 * Example::
 *
 * name: 'main-build'
 * include: [all, my, stuff]
 *
 * name: 'feature-build'
 * include: [is!mobile*]
 * exclude: ['main-build']
 *
 * config: {
 *   is: {
 *     mobile: false
 *   }
 * }
 *
 *
 *
 * NB, runtime changes are not possible - config must be constant
 *
 */

define(['module', 'require'], function(module, require) {

  var is = {};

  is.features = module.config() || {};

  //check features
  for (var f in is.features)
    if (is.features[f] !== true && is.features[f] !== false)
      throw 'Feature ' + f + ' must be true or false in config.';

  is.used = {};

  //build tracking
  is.deps = {};
  is.writeFeatures = {};

  is.lookup = function(feature, isBuild, complete) {

    if (is.features[feature] !== undefined) {

      if (isBuild)
        //ensure we write in this feature detection
        //is.writeFeatures[feature] = is.features[feature];

      complete(is.features[feature]);
      return;
    }

    if (isBuild) {
      //add the feature detection to the build
      require([feature], function(){});
      //in build - return value isn't checked anyway
      complete();
      return;
    }

    require([feature], function(_feature) {
      if (_feature !== true && _feature !== false)
        throw 'Feature module ' + feature + ' must return true or false.';
      is.features[feature] = _feature;
      complete(_feature);
    });
  }

  /*
   * Breakdown 'is' call into an object:
   * {
   *   feature: 'featureId',
   *   type: 'load_if' / 'load_if_not' / 'check' / 'load_deps'
   *   moduleId: 'moduleId'
   * }
   */
  is.deconstruct = function(f) {
    //is![feature]
    if (f.substr(0, 1) == '[')
      return {
        feature: f.substr(1, f.length - 2),
        type: 'check'
      };

    //is!feature*
    if (f.substr(f.length - 1, 1) == '*')
      return {
        feature: f.substr(0, f.length - 1),
        type: 'load_deps'
      };

    var feature = f.substr(0, f.indexOf('?'));
    var moduleId = f.substr(feature.length + 1, f.length - feature.length - 1);

    //is!something
    if (feature == '')
      throw 'Not a valid is call: is!' + f;

    //is!feature?moduleId
    if (feature.substr(0, 1) == '~')
      return {
        feature: feature.substr(1, f.length - 1),
        type: 'load_if_not',
        moduleId: moduleId
      };
    //is!~feature?moduleId
    else
      return {
        feature: feature,
        type: 'load_if',
        moduleId: moduleId
      };
  }

  is.normalize = function(name, normalize) {
    var f = is.deconstruct(name);
    f.feature = normalize(f.feature);

    if (f.moduleId)
      f.moduleId = normalize(f.moduleId);

    //reconstruct
    if (f.type == 'check')
      return '[' + f.feature + ']';

    if (f.type == 'load_deps')
      return f.feature + '*';

    if (f.type == 'load_if_not')
      return '~' + f.feature + '?' + f.moduleId;

    if (f.type == 'load_if')
      return f.feature + '?' + f.moduleId;
  }

  is.set = function(feature) {
    if (is.used[feature] && is.features[feature] != true)
      throw 'is: Feature ' + feature + ' has already been used, can\'t change!';
    is.features[feature] = true;
  }

  is.unset = function(feature) {
    if (is.used[feature] && is.features[feature] == true)
      throw 'is: Feature ' + feature + ' has already been used, can\'t change!';
    is.features[feature] = false;
  }

  is.load = function(name, req, load, config) {
    var f = is.deconstruct(name);

    if (f.type == 'check') {
      is.lookup(f.feature, config.isBuild, load);
      return;
    }

    if (f.type == 'load_if' || f.type == 'load_if_not') {
      //track conditional loads for builds
      if (config.isBuild) {
        is.deps[f.feature] = is.deps[f.feature] || [];
        is.deps[f.feature].push(f.moduleId);
      }

      //check feature
      is.lookup(f.feature, config.isBuild, function(_feature) {

        if (config.isBuild) {
          if (config.isExclude && config.isExclude.indexOf(f.feature) != -1) {
            load(null);
            return;
          }
          //by default, build the module in
          req([f.moduleId], load);
          return;
        }

        if ((_feature && f.type == 'load_if') || (!_feature && f.type == 'load_if_not')) {
          //if doing a build, check if we are including the module or not
          req([f.moduleId], load);
        }
        else
          load(null);
      });
      return;
    }

    if (f.type == 'load_deps') {
      if (!config.isBuild)
        throw 'Can\'t form an "is" dependency load when not in build.';

      is.deps[f.feature] = is.deps[f.feature] || [];
      //by virtue of loading all the dependencies, they will get written into the layer
      req(is.deps[f.feature], function() {
        load(null);
      });
    }
  }

  /* is.write = function(pluginName, moduleName, write) {
    //write in the features
    for (var i = 0; i < is.writeFeatures.length; i++) {

    }
  } */

  return is;

});<commit_msg>by default allow the build environment to override the feature inclusion<commit_after>/*
 * RequireJS 'is' plugin
 *
 * Usage:
 *
 * is!myFeature?module
 * is!~myFeature?module (negation)
 *
 * Features can be set dynamically with
 * require('is', function(is) {
 *   is.enable('var');
 * });
 *
 * Or features can be set as startup config with
 * config: {
 *   is: {
 *     var: true
 *   }
 * }
 *
 * If none of the above applies, the feature is assumed to be a moduleId
 * that resolves to a boolean.
 *
 * Thus to write a dynamic feature, say iphone.js, just do:
 *
 * iphone.js:
 * define(function() {
 *   if (typeof navigator === 'undefined' || typeof navigator.userAgent === 'undefined')
 *     return false;
 *   return navigator.userAgent.match(/iPhone/i);
 * });
 *
 * Which can then be used with a require of the form: is!iphone?iphone-scripts.
 *
 *
 * Builds
 * The build environment features are computed in the same way as normally. Using path mappings
 * and the 'is' config, particular build environments can be configured.
 *
 * The build determines if the conditional modules should be written or not.
 *
 * It is still up to the environment detection to determine if the features apply or not.
 *
 * With careful config, this covers the use cases of specific device builds, as well as packaging
 * all variations into a single built file.
 *
 * Build layers corresponding to a particular feature variation can be created using a feature variation
 * build name.
 *
 * Basically, disable the feature and build the first modules that would be using it. Then create a separate
 * mobule which includes: [is!feature*]. This will then drop back all items of that feature into the build,
 * that were previously excluded.
 *
 * Example::
 *
 * name: 'main-build'
 * include: [all, my, stuff]
 *
 * name: 'feature-build'
 * include: [is!mobile*]
 * exclude: ['main-build']
 *
 * config: {
 *   is: {
 *     mobile: false
 *   }
 * }
 *
 *
 *
 * NB, runtime changes are not possible - config must be constant
 *
 */

define(['module', 'require'], function(module, require) {

  var is = {};

  is.features = module.config() || {};

  //check features
  for (var f in is.features)
    if (is.features[f] !== true && is.features[f] !== false)
      throw 'Feature ' + f + ' must be true or false in config.';

  is.used = {};

  //build tracking
  is.deps = {};
  is.writeFeatures = {};

  is.lookup = function(feature, isBuild, complete) {

    if (is.features[feature] !== undefined) {

      if (isBuild)
        //ensure we write in this feature detection
        //is.writeFeatures[feature] = is.features[feature];

      complete(is.features[feature]);
      return;
    }

    if (isBuild) {
      //add the feature detection to the build
      require([feature], function(){});
      //in build - return value isn't checked anyway
      complete();
      return;
    }

    require([feature], function(_feature) {
      if (_feature !== true && _feature !== false)
        throw 'Feature module ' + feature + ' must return true or false.';
      is.features[feature] = _feature;
      complete(_feature);
    });
  }

  /*
   * Breakdown 'is' call into an object:
   * {
   *   feature: 'featureId',
   *   type: 'load_if' / 'load_if_not' / 'check' / 'load_deps'
   *   moduleId: 'moduleId'
   * }
   */
  is.deconstruct = function(f) {
    //is![feature]
    if (f.substr(0, 1) == '[')
      return {
        feature: f.substr(1, f.length - 2),
        type: 'check'
      };

    //is!feature*
    if (f.substr(f.length - 1, 1) == '*')
      return {
        feature: f.substr(0, f.length - 1),
        type: 'load_deps'
      };

    var feature = f.substr(0, f.indexOf('?'));
    var moduleId = f.substr(feature.length + 1, f.length - feature.length - 1);

    //is!something
    if (feature == '')
      throw 'Not a valid is call: is!' + f;

    //is!feature?moduleId
    if (feature.substr(0, 1) == '~')
      return {
        feature: feature.substr(1, f.length - 1),
        type: 'load_if_not',
        moduleId: moduleId
      };
    //is!~feature?moduleId
    else
      return {
        feature: feature,
        type: 'load_if',
        moduleId: moduleId
      };
  }

  is.normalize = function(name, normalize) {
    var f = is.deconstruct(name);
    f.feature = normalize(f.feature);

    if (f.moduleId)
      f.moduleId = normalize(f.moduleId);

    //reconstruct
    if (f.type == 'check')
      return '[' + f.feature + ']';

    if (f.type == 'load_deps')
      return f.feature + '*';

    if (f.type == 'load_if_not')
      return '~' + f.feature + '?' + f.moduleId;

    if (f.type == 'load_if')
      return f.feature + '?' + f.moduleId;
  }

  is.set = function(feature) {
    if (is.used[feature] && is.features[feature] != true)
      throw 'is: Feature ' + feature + ' has already been used, can\'t change!';
    is.features[feature] = true;
  }

  is.unset = function(feature) {
    if (is.used[feature] && is.features[feature] == true)
      throw 'is: Feature ' + feature + ' has already been used, can\'t change!';
    is.features[feature] = false;
  }

  is.load = function(name, req, load, config) {
    var f = is.deconstruct(name);

    if (f.type == 'check') {
      is.lookup(f.feature, config.isBuild, load);
      return;
    }

    if (f.type == 'load_if' || f.type == 'load_if_not') {
      //track conditional loads for builds
      if (config.isBuild) {
        is.deps[f.feature] = is.deps[f.feature] || [];
        is.deps[f.feature].push(f.moduleId);
      }

      //check feature
      is.lookup(f.feature, config.isBuild, function(_feature) {

        if (config.isBuild) {
          if (_feature === false || (config.isExclude && config.isExclude.indexOf(f.feature) != -1)) {
            load(null);
            return;
          }
          //by default, build the module in, unless excluded by the config
          req([f.moduleId], load);
          return;
        }

        if ((_feature && f.type == 'load_if') || (!_feature && f.type == 'load_if_not')) {
          //if doing a build, check if we are including the module or not
          req([f.moduleId], load);
        }
        else
          load(null);
      });
      return;
    }

    if (f.type == 'load_deps') {
      if (!config.isBuild)
        throw 'Can\'t form an "is" dependency load when not in build.';

      is.deps[f.feature] = is.deps[f.feature] || [];
      //by virtue of loading all the dependencies, they will get written into the layer
      req(is.deps[f.feature], function() {
        load(null);
      });
    }
  }

  /* is.write = function(pluginName, moduleName, write) {
    //write in the features
    for (var i = 0; i < is.writeFeatures.length; i++) {

    }
  } */

  return is;

});<|endoftext|>


<commit_before>(function(root, ku) {
  if (typeof define === 'function' && define.amd) {
    define(['underscore'], function(_) {
      return ku(root, _);
    });
  } else if (typeof module !== 'undefined' && module.exports) {
    var _ = require('underscore');
    exports = module.exports = ku(root, _);
  } else {
    root.ku = ku(root, _);
  }
})(this, function(root, _) {
  'use strict';
  var curry = function(fn, expected) {
    if (expected == null) expected = fn.length;

    return function f() {
      var args = Array.prototype.slice.call(arguments, 0);

      if (args.length > expected) {
        var extra = args.splice(expected, args.length - expected),
            r = fn.apply(null, args);

        if (typeof r === 'function') {
          if (r.length === 0) {
            return r.apply(extra);
          } else {
            return curry(r).apply(extra);
          }
        } else {
          return r;
        }
      } else if (args.length === expected) {
        return fn.apply(this, args);
      } else {
        return function() {
          return f.apply(null, args.concat(
            Array.prototype.slice.call(arguments, 0)
          ));
        };
      }
    };
  };

  var op = function(op) {
    return curry(new Function('x,y', 'return x' + op +'y'), 2);
  };

  var w1 = function(exp) {
    return new Function('x', 'return ' + exp);
  };

  var w2 = function(exp) {
    return curry(new Function('x,y', 'return ' + exp), 2);
  };

  var ku = {
    add: op('+'),
    sub: op('-'),
    mul: op('*'),
    div: op('/'),
    mod: op('%'),
    cmod: w2('((x%y)+y)%y'),
    and: op('&&'),
    or: op('||'),
    eq: op('==='),

    map: 2,
    filter: 2,
    zip: 1,
    initial: 1,
    find: 2,
    findIndex: 2,
    zipObject: 2,
    pluck: 2,

    push: w2('y.concat([x])'),
    attr: w2('y[x]'),
    zero: w1('!!x'),
    not: w1('!x'),

    curry: curry,

    wrap: curry(function(attr, value) {
      var obj = {};
      obj[attr] = value;
      return obj;
    }),

    _: function(method) {
      method = _[method];

      if (typeof method === 'function') {
        if (method.length === 2) {
          return ku.compose(ku.flip, ku.curry)(method);
        } else {
          return method;
        }
      }
    },

    flip: curry(function(f, x, y) {
      return f(y, x);
    }),

    compose: curry(function(f, g, x) {
      return f(g(x));
    }),

    method: function(attr) {
      var args = Array.prototype.slice(arguments, 1);

      return function(obj) {
        return obj[attr] && obj[attr].apply(null, args)
      };
    }
  };

  for (var method in ku) {
    if (ku[method] === 1) {
      ku[method] = w1('_.' + method + '(x)');
    } else if(ku[method] === 2) {
      ku[method] = w2('_.' + method + '(y,x)');
    }
  }

  return ku;
});
<commit_msg>Made ku an multi-argument composition function<commit_after>(function(root, ku) {
  if (typeof define === 'function' && define.amd) {
    define(['underscore'], function(_) {
      return ku(root, _);
    });
  } else if (typeof module !== 'undefined' && module.exports) {
    var _ = require('underscore');
    exports = module.exports = ku(root, _);
  } else {
    root.ku = ku(root, _);
  }
})(this, function(root, _) {
  'use strict';
  var curry = function(fn, expected) {
    if (expected == null) expected = fn.length;

    return function f() {
      var args = Array.prototype.slice.call(arguments, 0);

      if (args.length > expected) {
        var extra = args.splice(expected, args.length - expected),
            r = fn.apply(null, args);

        if (typeof r === 'function') {
          if (r.length === 0) {
            return r.apply(extra);
          } else {
            return curry(r).apply(extra);
          }
        } else {
          return r;
        }
      } else if (args.length === expected) {
        return fn.apply(this, args);
      } else {
        return function() {
          return f.apply(null, args.concat(
            Array.prototype.slice.call(arguments, 0)
          ));
        };
      }
    };
  };

  var op = function(op) {
    return curry(new Function('x,y', 'return x' + op +'y'), 2);
  };

  var w1 = function(exp) {
    return new Function('x', 'return ' + exp);
  };

  var w2 = function(exp) {
    return curry(new Function('x,y', 'return ' + exp), 2);
  };

  var ku = _.extend(function() { // ku compose function
    var args = Array.prototype.slice(arguments, 0);

    return function(val) {
      for (var i = args.length - 1; i + 1; i--) {
        val = args[i](val);
      }

      return val;
    };
  }, {
    add: op('+'),
    sub: op('-'),
    mul: op('*'),
    div: op('/'),
    mod: op('%'),
    cmod: w2('((x%y)+y)%y'),
    and: op('&&'),
    or: op('||'),
    eq: op('==='),

    map: 2,
    filter: 2,
    zip: 1,
    initial: 1,
    find: 2,
    findIndex: 2,
    zipObject: 2,
    pluck: 2,

    push: w2('y.concat([x])'),
    attr: w2('y[x]'),
    zero: w1('!!x'),
    not: w1('!x'),

    curry: curry,

    wrap: curry(function(attr, value) {
      var obj = {};
      obj[attr] = value;
      return obj;
    }),

    _: function(method) {
      method = _[method];

      if (typeof method === 'function') {
        if (method.length === 2) {
          return ku.compose(ku.flip, ku.curry)(method);
        } else {
          return method;
        }
      }
    },

    flip: curry(function(f, x, y) {
      return f(y, x);
    }),

    compose: curry(function(f, g, x) {
      return f(g(x));
    }),

    method: function(attr) {
      var args = Array.prototype.slice(arguments, 1);

      return function(obj) {
        return obj[attr] && obj[attr].apply(null, args)
      };
    }
  });

  for (var method in ku) {
    if (ku[method] === 1) {
      ku[method] = w1('_.' + method + '(x)');
    } else if(ku[method] === 2) {
      ku[method] = w2('_.' + method + '(y,x)');
    }
  }

  return ku;
});
<|endoftext|>


<commit_before>/**
 * @copyright 2015, Robin Dietrich
 * @license MIT
 */
define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "language", "ext", "tabManager", "c9", "save",
        "settings", "preferences", "ui", "collab", "collab.connect",
        "error_handler", "dialog.error", "installer"
    ];
    main.provides = ["cpp"];
    return main;

    // returns true if file is handled by us (by extension)
    function is_c_cpp(filename) {
        // handled extensions, last used by capnproto ('-.-)
        var _extensions = ["c", "h", "cc", "cpp", "hpp", "cxx", "hxx", "h++", "c++"];

        // get extension
        var _extension = filename.split(".");
        if (_extension.length < 2)
            return false;

        _extension = _extension[_extension.length - 1];
        return (_extensions.indexOf(_extension) >= 0);
    }

    function main(options, imports, register) {
        // imports
        var _ = require("lodash");
        var language = imports.language;
        var ext = imports.ext;
        var Plugin = imports.Plugin;
        var plugin = new Plugin("Robin Dietrich", main.consumes);
        var tabManager = imports.tabManager;
        var c9 = imports.c9;
        var save = imports.save;
        var settings = imports.settings;
        var prefs = imports.preferences;
        var ui = imports.ui;
        var collab = imports.collab;
        var collabConnect = imports["collab.connect"];
        var errorHandler = imports.error_handler;
        var showError = imports["dialog.error"].show;
        var installer = imports.installer;
        var emit = plugin.getEmitter();

        // constants and services used in the plugin
        var basedir = c9.workspaceDir;  // Use this to get the full file path for clang_tool
        var clang_tool = null;          // Service side clang_tool component
        var worker = null;              // Language worker

        // for call throttling
        var pendingServerCall = null;
        var lastServerCall = Date.now();
        var callInterval = 1000;

        // make sure all deps are installed
        installer.createSession("c9.ide.language.cpp", require("./install"));

        // Calls a clang_remote function, uses rate limitting
        function callRemoteLimited(fcn, params) {
            var tries = 0;
            setupServerFcn();

            // Initiates a server call
            function setupServerFcn() {
                var waiting = lastServerCall + callInterval - Date.now();
                if (waiting > 0) {
                    // only set pending on first try
                    if (tries == 0)
                        pendingServerCall = setupServerFcn;

                    setTimeout(setupServerFcn, waiting, ++tries);
                } else {
                    //
                    if (pendingServerCall !== setupServerFcn && pendingServerCall != null) {
                    } else {
                        pendingServerCall = null; // reset our own fcn
                        lastServerCall = Date.now();
                        plugin.once("initServer", invokeServerFcn);
                    }
                }
            }

            // Invokes the actual server function
            function invokeServerFcn() {
                if (clang_tool)
                    clang_tool[fcn].apply(clang_tool, params);
            }
        }

        // Callback when a new document is opened
        //  - Adds new files to the index to enable faster completion
        function onDocumentOpened(event) {
            if (!is_c_cpp(event.data.path))
                return;

            if (clang_tool)
                clang_tool.indexTouch(basedir+event.data.path);
        }

        // Callback when a document is closed
        //  - Removed translation unit from the index
        function onDocumentClosed(event) {
            if (!is_c_cpp(event.data.path))
                return;

            if (clang_tool)
                clang_tool.indexClear(basedir+event.data.path);
        }

        // Callback when a document is saved
        function onDocumentSave(event) {
            if (!is_c_cpp(event.path))
                return;

            // add / update on index
            if (clang_tool)
                clang_tool.indexTouch(basedir+event.path);
        }

        // Code completion
        function workerCompletion(event) {
            var value = tabManager.focussedTab.document.value;
            var path = basedir+tabManager.focussedTab.path;

            if (!clang_tool)
                return worker.emit("_completionResult", {data: {id: event.data.id, results: []}});

            // add temporary data to index and do code completion
            callRemoteLimited("indexTouchUnsaved", [path, value, function () {
                clang_tool.cursorCandidatesAt(path, event.data.pos.row+1, event.data.pos.column+1, function(err, res) {
                    worker.emit("_completionResult", {data: {id: event.data.id, results: res}});
                })}
            ]);

            /*clang_tool.indexTouchUnsaved(path, value, function () {
                clang_tool.cursorCandidatesAt(path, event.data.pos.row+1, event.data.pos.column+1, function(err, res) {
                    worker.emit("_completionResult", {data: {id: event.data.id, results: res}});
                });
            });*/
        }

        // Code diagnosics
        function workerAnalysis(event) {
            var path = basedir+tabManager.focussedTab.path;

            if (!clang_tool)
                return worker.emit("_diagnoseResult", {data: {id: event.data.id, results: []}});

            callRemoteLimited("fileDiagnose", [path, function(err, res) {
                res = _.filter(res, function(r) {
                    return r.file == path;
                });

                worker.emit("_diagnoseResult", {data: {id: event.data.id, results: res, path: path}});
            }]);

            /*clang_tool.fileDiagnose(path, function(err, res) {
                res = _.filter(res, function(r) {
                    return r.file == path;
                });

                worker.emit("_diagnoseResult", {data: {id: event.data.id, results: res, path: path}});
            });*/
        }

        // AST to outline conversion
        function workerOutline(event) {
            var path = basedir+tabManager.focussedTab.path;

            if (!clang_tool)
                return worker.emit("_outlineResult", {data: {id: event.data.id, ast: []}});

            // generate outline
            clang_tool.fileAst(path, function(err, res) {
                worker.emit("_outlineResult", {data: {id: event.data.id, ast: res.children}});
            });
        }

        // Jump to definition/declaration
        function workerJumpToDefinition(event) {
            var path = basedir+tabManager.focussedTab.path;

            if (!clang_tool)
                return worker.emit("_jumpToDefResult", {data: {id: event.data.id, pos: {}}});

            var row = event.data.pos.row+1;
            var col = event.data.pos.column+1;

            // get definition/declaration
            clang_tool.cursorDefinitionAt(path, row, col, function(err, res) {
            	if (!res.file) {
            	    // no definition found, try declaration instead
                    clang_tool.cursorDeclarationAt(path, row, col, function(err, res) {
                        worker.emit("_jumpToDefResult", {data: {id: event.data.id, pos: res}});
                    });
            	} else {
            	    worker.emit("_jumpToDefResult", {data: {id: event.data.id, pos: res}});
            	}
            });
        }

        // Register our language handler
        var path = options.packagePath;
        path = path.substr(0, path.lastIndexOf("/") + 1) + "cpp_worker";

        language.registerLanguageHandler(path, function(err, worker_) {
            if (err) {
                errorHandler.reportError(err);
                return showError("Could not load cpp language worker: " + (err.message | err));
            }

            // Set worker object and register callback's
            worker = worker_;
            worker.on("documentOpened", onDocumentOpened);
            worker.on("documentClosed", onDocumentClosed);
            save.on("afterSave", onDocumentSave);

            //
            // Important:
            // Do not run indexTouch or indexTouchUnsaved for each and every worker action.
            // Certain actions may be interleaved, creating a indexTouch <-> indexTouchUnsaved chain
            // that takes forever to resolve.
            //
            // + Call indexTouchUnsaved in all worker functions that handle temp data
            // + Call indexTouch only on save events
            //

            worker.on("_completion", workerCompletion);
            worker.on("_diagnose", workerAnalysis);
            worker.on("_outline", workerOutline);
            worker.on("_jumpToDefinition", workerJumpToDefinition);
        });

        // Called on c9.connect
        function onOnline() {
            ext.loadRemotePlugin("clang_tool", {
                code: require("text!./cpp_server.js"),
                redefine: !clang_tool
            }, function(err, plugin) {
                if (err) {
                    errorHandler.reportError(err);
                    return showError("[c9.ide.language.cpp] Error initializing server: " + (err.message | err));
                }

                // connect clang
                clang_tool = plugin;
                clang_tool.load(function (err) {
                    if (err) {
                        errorHandler.reportError(err);
                        return showError("[c9.ide.language.cpp] Unable to load clang_tool: " + (err.message | err));
                    }

                    clang_tool.setArgs(settings.get("project/c_cpp/@compilerArguments").split("\n"));
                    emit.sticky("initServer");
                });
            });
        }

        // Called on c9.disconnect
        function onOffline() {
            if (clang_tool) {
                clang_tool.indexClear(function() {
                    clang_tool = null;
                });
            }
        }

        c9.on("connect", onOnline);
        c9.on("disconnect", onOffline);

        // Initialize the plugin
        plugin.on("load", function() {
            // Add project specific preferences
            prefs.add({
                "Project" : {
                    "C / C++" : {
                        position: 1000,
                        "Compiler Arguments" : {
                           type: "textarea",
                           width: 200,
                           height: 130,
                           rowheight: 155,
                           path: "project/c_cpp/@compilerArguments",
                           position: 5000
                        }
                    }
                }
            }, plugin);

            // Set default values
            settings.on("read", function(e) {
                settings.setDefaults("project/c_cpp", [
                    ["compilerArguments", "-I/usr/include\n-I/usr/local/include"]
                ]);
            }, plugin);

            // Listen to updates
            settings.on("project/c_cpp/@compilerArguments", function(value) {
                if (clang_tool)
                    clang_tool.setArgs(value.split(/\s+/));
            }, plugin);

            // Add css
            ui.insertCss(require("text!./icons.css"), false, plugin);
        });

        // Make sure the plugin is unloaded correctly so that cached translation units get purged
        plugin.on("unload", function(){
            if (clang_tool) {
                clang_tool.unload();
                clang_tool = null;
                worker = null;

                pendingServerCall = null;
                lastServerCall = 0;
            }
        });

        // Public api for the cpp plugin
        //  - Allow different cpp extensions to be added
        //  - Cache handling with indexStatus and indexClear
        //  - Recursive file ast parsing for tokenizers
        plugin.freezePublicAPI({});

        // Registers our plugin with C9
        register(null, { cpp: plugin });
    }
});
<commit_msg>Improve argument splitting (part 2)<commit_after>/**
 * @copyright 2015, Robin Dietrich
 * @license MIT
 */
define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "language", "ext", "tabManager", "c9", "save",
        "settings", "preferences", "ui", "collab", "collab.connect",
        "error_handler", "dialog.error", "installer"
    ];
    main.provides = ["cpp"];
    return main;

    // returns true if file is handled by us (by extension)
    function is_c_cpp(filename) {
        // handled extensions, last used by capnproto ('-.-)
        var _extensions = ["c", "h", "cc", "cpp", "hpp", "cxx", "hxx", "h++", "c++"];

        // get extension
        var _extension = filename.split(".");
        if (_extension.length < 2)
            return false;

        _extension = _extension[_extension.length - 1];
        return (_extensions.indexOf(_extension) >= 0);
    }

    function main(options, imports, register) {
        // imports
        var _ = require("lodash");
        var language = imports.language;
        var ext = imports.ext;
        var Plugin = imports.Plugin;
        var plugin = new Plugin("Robin Dietrich", main.consumes);
        var tabManager = imports.tabManager;
        var c9 = imports.c9;
        var save = imports.save;
        var settings = imports.settings;
        var prefs = imports.preferences;
        var ui = imports.ui;
        var collab = imports.collab;
        var collabConnect = imports["collab.connect"];
        var errorHandler = imports.error_handler;
        var showError = imports["dialog.error"].show;
        var installer = imports.installer;
        var emit = plugin.getEmitter();

        // constants and services used in the plugin
        var basedir = c9.workspaceDir;  // Use this to get the full file path for clang_tool
        var clang_tool = null;          // Service side clang_tool component
        var worker = null;              // Language worker

        // for call throttling
        var pendingServerCall = null;
        var lastServerCall = Date.now();
        var callInterval = 1000;

        // make sure all deps are installed
        installer.createSession("c9.ide.language.cpp", require("./install"));

        // Calls a clang_remote function, uses rate limitting
        function callRemoteLimited(fcn, params) {
            var tries = 0;
            setupServerFcn();

            // Initiates a server call
            function setupServerFcn() {
                var waiting = lastServerCall + callInterval - Date.now();
                if (waiting > 0) {
                    // only set pending on first try
                    if (tries == 0)
                        pendingServerCall = setupServerFcn;

                    setTimeout(setupServerFcn, waiting, ++tries);
                } else {
                    //
                    if (pendingServerCall !== setupServerFcn && pendingServerCall != null) {
                    } else {
                        pendingServerCall = null; // reset our own fcn
                        lastServerCall = Date.now();
                        plugin.once("initServer", invokeServerFcn);
                    }
                }
            }

            // Invokes the actual server function
            function invokeServerFcn() {
                if (clang_tool)
                    clang_tool[fcn].apply(clang_tool, params);
            }
        }

        // Callback when a new document is opened
        //  - Adds new files to the index to enable faster completion
        function onDocumentOpened(event) {
            if (!is_c_cpp(event.data.path))
                return;

            if (clang_tool)
                clang_tool.indexTouch(basedir+event.data.path);
        }

        // Callback when a document is closed
        //  - Removed translation unit from the index
        function onDocumentClosed(event) {
            if (!is_c_cpp(event.data.path))
                return;

            if (clang_tool)
                clang_tool.indexClear(basedir+event.data.path);
        }

        // Callback when a document is saved
        function onDocumentSave(event) {
            if (!is_c_cpp(event.path))
                return;

            // add / update on index
            if (clang_tool)
                clang_tool.indexTouch(basedir+event.path);
        }

        // Code completion
        function workerCompletion(event) {
            var value = tabManager.focussedTab.document.value;
            var path = basedir+tabManager.focussedTab.path;

            if (!clang_tool)
                return worker.emit("_completionResult", {data: {id: event.data.id, results: []}});

            // add temporary data to index and do code completion
            callRemoteLimited("indexTouchUnsaved", [path, value, function () {
                clang_tool.cursorCandidatesAt(path, event.data.pos.row+1, event.data.pos.column+1, function(err, res) {
                    worker.emit("_completionResult", {data: {id: event.data.id, results: res}});
                })}
            ]);

            /*clang_tool.indexTouchUnsaved(path, value, function () {
                clang_tool.cursorCandidatesAt(path, event.data.pos.row+1, event.data.pos.column+1, function(err, res) {
                    worker.emit("_completionResult", {data: {id: event.data.id, results: res}});
                });
            });*/
        }

        // Code diagnosics
        function workerAnalysis(event) {
            var path = basedir+tabManager.focussedTab.path;

            if (!clang_tool)
                return worker.emit("_diagnoseResult", {data: {id: event.data.id, results: []}});

            callRemoteLimited("fileDiagnose", [path, function(err, res) {
                res = _.filter(res, function(r) {
                    return r.file == path;
                });

                worker.emit("_diagnoseResult", {data: {id: event.data.id, results: res, path: path}});
            }]);

            /*clang_tool.fileDiagnose(path, function(err, res) {
                res = _.filter(res, function(r) {
                    return r.file == path;
                });

                worker.emit("_diagnoseResult", {data: {id: event.data.id, results: res, path: path}});
            });*/
        }

        // AST to outline conversion
        function workerOutline(event) {
            var path = basedir+tabManager.focussedTab.path;

            if (!clang_tool)
                return worker.emit("_outlineResult", {data: {id: event.data.id, ast: []}});

            // generate outline
            clang_tool.fileAst(path, function(err, res) {
                worker.emit("_outlineResult", {data: {id: event.data.id, ast: res.children}});
            });
        }

        // Jump to definition/declaration
        function workerJumpToDefinition(event) {
            var path = basedir+tabManager.focussedTab.path;

            if (!clang_tool)
                return worker.emit("_jumpToDefResult", {data: {id: event.data.id, pos: {}}});

            var row = event.data.pos.row+1;
            var col = event.data.pos.column+1;

            // get definition/declaration
            clang_tool.cursorDefinitionAt(path, row, col, function(err, res) {
            	if (!res.file) {
            	    // no definition found, try declaration instead
                    clang_tool.cursorDeclarationAt(path, row, col, function(err, res) {
                        worker.emit("_jumpToDefResult", {data: {id: event.data.id, pos: res}});
                    });
            	} else {
            	    worker.emit("_jumpToDefResult", {data: {id: event.data.id, pos: res}});
            	}
            });
        }

        // Register our language handler
        var path = options.packagePath;
        path = path.substr(0, path.lastIndexOf("/") + 1) + "cpp_worker";

        language.registerLanguageHandler(path, function(err, worker_) {
            if (err) {
                errorHandler.reportError(err);
                return showError("Could not load cpp language worker: " + (err.message | err));
            }

            // Set worker object and register callback's
            worker = worker_;
            worker.on("documentOpened", onDocumentOpened);
            worker.on("documentClosed", onDocumentClosed);
            save.on("afterSave", onDocumentSave);

            //
            // Important:
            // Do not run indexTouch or indexTouchUnsaved for each and every worker action.
            // Certain actions may be interleaved, creating a indexTouch <-> indexTouchUnsaved chain
            // that takes forever to resolve.
            //
            // + Call indexTouchUnsaved in all worker functions that handle temp data
            // + Call indexTouch only on save events
            //

            worker.on("_completion", workerCompletion);
            worker.on("_diagnose", workerAnalysis);
            worker.on("_outline", workerOutline);
            worker.on("_jumpToDefinition", workerJumpToDefinition);
        });

        // Called on c9.connect
        function onOnline() {
            ext.loadRemotePlugin("clang_tool", {
                code: require("text!./cpp_server.js"),
                redefine: !clang_tool
            }, function(err, plugin) {
                if (err) {
                    errorHandler.reportError(err);
                    return showError("[c9.ide.language.cpp] Error initializing server: " + (err.message | err));
                }

                // connect clang
                clang_tool = plugin;
                clang_tool.load(function (err) {
                    if (err) {
                        errorHandler.reportError(err);
                        return showError("[c9.ide.language.cpp] Unable to load clang_tool: " + (err.message | err));
                    }

                    clang_tool.setArgs(settings.get("project/c_cpp/@compilerArguments").split(/\s+/));
                    emit.sticky("initServer");
                });
            });
        }

        // Called on c9.disconnect
        function onOffline() {
            if (clang_tool) {
                clang_tool.indexClear(function() {
                    clang_tool = null;
                });
            }
        }

        c9.on("connect", onOnline);
        c9.on("disconnect", onOffline);

        // Initialize the plugin
        plugin.on("load", function() {
            // Add project specific preferences
            prefs.add({
                "Project" : {
                    "C / C++" : {
                        position: 1000,
                        "Compiler Arguments" : {
                           type: "textarea",
                           width: 200,
                           height: 130,
                           rowheight: 155,
                           path: "project/c_cpp/@compilerArguments",
                           position: 5000
                        }
                    }
                }
            }, plugin);

            // Set default values
            settings.on("read", function(e) {
                settings.setDefaults("project/c_cpp", [
                    ["compilerArguments", "-I/usr/include\n-I/usr/local/include"]
                ]);
            }, plugin);

            // Listen to updates
            settings.on("project/c_cpp/@compilerArguments", function(value) {
                if (clang_tool)
                    clang_tool.setArgs(value.split(/\s+/));
            }, plugin);

            // Add css
            ui.insertCss(require("text!./icons.css"), false, plugin);
        });

        // Make sure the plugin is unloaded correctly so that cached translation units get purged
        plugin.on("unload", function(){
            if (clang_tool) {
                clang_tool.unload();
                clang_tool = null;
                worker = null;

                pendingServerCall = null;
                lastServerCall = 0;
            }
        });

        // Public api for the cpp plugin
        //  - Allow different cpp extensions to be added
        //  - Cache handling with indexStatus and indexClear
        //  - Recursive file ast parsing for tokenizers
        plugin.freezePublicAPI({});

        // Registers our plugin with C9
        register(null, { cpp: plugin });
    }
});
<|endoftext|>


<commit_before>/**
 *  Routes
 *  ======
 *
 *  Matching request/URL routes.
 *
 *  allows to define customRoutes & default (which will be called in initalization !)
 *
 * // setting up routes - optional setting, can provide a dictionary for custom routes + default route
 *  ToDo:
 *
 *  - add History API support (see server side support)
 *
 *  - improve param splitting + channel / game recognition
 *
 *
 *  as of v2 using functions, easier as mostly the application itself will just need on hook,
 *  and not multiple (see demonstration, || there can be different routes, but else simpler !)
 *
 *  Example:
 *
 *    pg.routes(
 *
 *      // channel,
 *
 *      // game
 *    ) // 2 simple - or one objct for cunfiguraiton !
 *
 *		pg.routes({
 *
 *
 *		})
 */

var channelRoutes   = {},               // collection of the channel routes
    gameRoutes      = {},               // collection of the game  routes
    LAST_ROUTE      = null,
    DEFAULT_ROUTE   = '/lobby/';

pg.routes = function ( customRoutes, defaultRoute ) {

  if ( !defaultRoute && typeof customRoutes === 'string' ) { // less then 2 arguments

    defaultRoute = customRoutes;
    customRoutes = null;
  }

  if ( customRoutes ) defineCustomRoutes( customRoutes );
  if ( defaultRoute ) DEFAULT_ROUTE = defaultRoute;

  return [ channelRoutes, gameRoutes, DEFAULT_ROUTE ];
};

// var CHANNEL_PATTERN = /\/(.*?)\//g,
//     ARGS_PATTERN    = /(\?)?:\w+/g;

function defineCustomRoutes ( customRoutes ) {

  channelRoutes = {};
  gameRoutes = {};
}

// extract params
function checkRoute() {

  var path    = win.location.hash.substr(3),
      args    = path.split('/');

  INFO.room = SESSION.currentRoute = path;

  if ( args.length < 1 ) return;

  // if ( Object.keys( CUSTOM_PATTERNS ).length ) extractRoute();

  matchRoute( args );
}

// execute wrapped function, cann be a channel or game
function matchRoute ( args ) {

  var room = args.shift();

  if ( !room ) { // re-routing

    win.location.hash = '!/' + DEFAULT_ROUTE.substr(1);

    return;
  }

  // room match -> arguments, defined as a channel or game
  var match = !args[0].length ? channels[ room ] || channels[ '*' ]  :
                                   games[ room ] ||    games[ '*' ]  ;

  // TODO: parse for custom routes
  var params = args;

  // prevent re-join the current room...
  if ( LAST_ROUTE === INFO.room ) return;

  if ( match ) {

    match.call( match, params );

    if ( LAST_ROUTE  ) {

      // TODO: close all peerconnections else ! (see manager)
      socket.send({ action: 'change', data: LAST_ROUTE });
    }

    LAST_ROUTE = INFO.room;

  } else {

    throw new Error('Missing channel/game handler !');
  }
}

// customRoute with specifc params
// function extractRoute() {

//   console.log('[ToDo] Extract Params');
// }

function leaveSite ( e ) {

  // prevent initial triggering
  if ( chrome ) { chrome = !chrome; return; }

  // if ( !history.state ) {
  // console.log(LAST_ROUTE);

  // return window.history.back();
  // }
}

/** attach listener **/
win.addEventListener( 'hashchange', checkRoute ); // join
win.addEventListener( 'popstate', leaveSite );    // history navigation
<commit_msg>fix disconnect<commit_after>/**
 *  Routes
 *  ======
 *
 *  Matching request/URL routes.
 *
 *  allows to define customRoutes & default (which will be called in initalization !)
 *
 * // setting up routes - optional setting, can provide a dictionary for custom routes + default route
 *  ToDo:
 *
 *  - add History API support (see server side support)
 *
 *  - improve param splitting + channel / game recognition
 *
 *
 *  as of v2 using functions, easier as mostly the application itself will just need on hook,
 *  and not multiple (see demonstration, || there can be different routes, but else simpler !)
 *
 *  Example:
 *
 *    pg.routes(
 *
 *      // channel,
 *
 *      // game
 *    ) // 2 simple - or one objct for cunfiguraiton !
 *
 *		pg.routes({
 *
 *
 *		})
 */

var channelRoutes   = {},               // collection of the channel routes
    gameRoutes      = {},               // collection of the game  routes
    LAST_ROUTE      = null,
    DEFAULT_ROUTE   = '/lobby/';

pg.routes = function ( customRoutes, defaultRoute ) {

  if ( !defaultRoute && typeof customRoutes === 'string' ) { // less then 2 arguments

    defaultRoute = customRoutes;
    customRoutes = null;
  }

  if ( customRoutes ) defineCustomRoutes( customRoutes );
  if ( defaultRoute ) DEFAULT_ROUTE = defaultRoute;

  return [ channelRoutes, gameRoutes, DEFAULT_ROUTE ];
};

// var CHANNEL_PATTERN = /\/(.*?)\//g,
//     ARGS_PATTERN    = /(\?)?:\w+/g;

function defineCustomRoutes ( customRoutes ) {

  channelRoutes = {};
  gameRoutes = {};
}

// extract params
function checkRoute() {

  var path    = win.location.hash.substr(3),
      args    = path.split('/');

  INFO.room = SESSION.currentRoute = path;

  if ( args.length < 1 ) return;

  // if ( Object.keys( CUSTOM_PATTERNS ).length ) extractRoute();

  matchRoute( args );
}

// execute wrapped function, cann be a channel or game
function matchRoute ( args ) {

  var room = args.shift();

  if ( !room ) { // re-routing

    win.location.hash = '!/' + DEFAULT_ROUTE.substr(1);

    return;
  }

  // room match -> arguments, defined as a channel or game
  var match = !args[0].length ? channels[ room ] || channels[ '*' ]  :
                                   games[ room ] ||    games[ '*' ]  ;

  // TODO: parse for custom routes
  var params = args;

  // prevent re-join the current room...
  if ( LAST_ROUTE === INFO.room ) return;

  if ( match ) {

    match.call( match, params );

    if ( LAST_ROUTE  ) {

      var keys = Object.keys( CONNECTIONS );

      for ( var i = 0, l = keys.length; i < l; i++ ) Manager.disconnect( keys[i] );

      socket.send({ action: 'change', data: LAST_ROUTE });
    }

    LAST_ROUTE = INFO.room;

  } else {

    throw new Error('Missing channel/game handler !');
  }
}

// customRoute with specifc params
// function extractRoute() {

//   console.log('[ToDo] Extract Params');
// }

function leaveSite ( e ) {

  // prevent initial triggering
  if ( chrome ) { chrome = !chrome; return; }

  // if ( !history.state ) {
  // console.log(LAST_ROUTE);

  // return window.history.back();
  // }
}

/** attach listener **/
win.addEventListener( 'hashchange', checkRoute ); // join
win.addEventListener( 'popstate', leaveSite );    // history navigation
<|endoftext|>


<commit_before>define([
	"intern!object",
	"intern/chai!assert",
	"dojo/dom-geometry",
	"dojo/dom-class",
	"delite/register",
	"deliteful/SidePane"
], function (registerSuite, assert, domGeom, domClass, register, SidePane) {
	var container, node;

	registerSuite({
		name: "SidePane Overlay",
		setup: function () {
			node = new SidePane();
			document.body.appendChild(node);
			register.parse();
			node.show();
		},
		"Default values" : function () {
			assert.deepEqual(node.mode, "push");
			assert.deepEqual(node.position, "start");
			assert.deepEqual(node.animate, true);
			assert.deepEqual(node.swipeClosing, true);
		},
		"Size Computation" : function () {
			var box = domGeom.getMarginBox(node);
			assert.isTrue(box.w > 0);
			assert.isTrue(box.h > 0);
		},
		"CSS Classes: Push Start (Default)" : function () {
			assert.isTrue(domClass.contains(node, "d-side-pane"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-push"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-start"));
		},
		"CSS Classes: Push End" : function () {
			node.mode = "push";
			node.position = "end";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-push"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-end"));
		},
		"CSS Classes: Overlay Start" : function () {
			node.mode = "overlay";
			node.position = "start";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-overlay"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-start"));
		},
		"CSS Classes: Overlay End" : function () {
			node.mode = "overlay";
			node.position = "end";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-overlay"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-end"));
		},
		"CSS Classes: Reveal Start" : function () {
			node.mode = "reveal";
			node.position = "start";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-reveal"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-start"));
		},
		"CSS Classes: Reveal End" : function () {
			node.mode = "reveal";
			node.position = "end";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-reveal"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-end"));
		},
		teardown: function () {
			node.parentNode.removeChild(node);
		}
	});
});
<commit_msg>jshint fix<commit_after>define([
	"intern!object",
	"intern/chai!assert",
	"dojo/dom-geometry",
	"dojo/dom-class",
	"delite/register",
	"deliteful/SidePane"
], function (registerSuite, assert, domGeom, domClass, register, SidePane) {
	var node;

	registerSuite({
		name: "SidePane Overlay",
		setup: function () {
			node = new SidePane();
			document.body.appendChild(node);
			register.parse();
			node.show();
		},
		"Default values" : function () {
			assert.deepEqual(node.mode, "push");
			assert.deepEqual(node.position, "start");
			assert.deepEqual(node.animate, true);
			assert.deepEqual(node.swipeClosing, true);
		},
		"Size Computation" : function () {
			var box = domGeom.getMarginBox(node);
			assert.isTrue(box.w > 0);
			assert.isTrue(box.h > 0);
		},
		"CSS Classes: Push Start (Default)" : function () {
			assert.isTrue(domClass.contains(node, "d-side-pane"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-push"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-start"));
		},
		"CSS Classes: Push End" : function () {
			node.mode = "push";
			node.position = "end";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-push"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-end"));
		},
		"CSS Classes: Overlay Start" : function () {
			node.mode = "overlay";
			node.position = "start";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-overlay"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-start"));
		},
		"CSS Classes: Overlay End" : function () {
			node.mode = "overlay";
			node.position = "end";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-overlay"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-end"));
		},
		"CSS Classes: Reveal Start" : function () {
			node.mode = "reveal";
			node.position = "start";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-reveal"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-start"));
		},
		"CSS Classes: Reveal End" : function () {
			node.mode = "reveal";
			node.position = "end";
			node.deliver();
			assert.isTrue(domClass.contains(node, "-d-side-pane-reveal"));
			assert.isTrue(domClass.contains(node, "-d-side-pane-end"));
		},
		teardown: function () {
			node.parentNode.removeChild(node);
		}
	});
});
<|endoftext|>


<commit_before>define([
	"intern!object",
	"intern/chai!assert",
	"delite/register",
	"decor/Stateful",
	"requirejs-domready/domReady!"
], function (registerSuite, assert, register, Stateful) {

	// The
 node where we will put all our DOM nodes
	var container;

	var Mixin, TestWidget, TestButtonWidget, TestExtendedWidget, TestExtendedButtonWidget;

	var nativeButton = document.createElement("button");

	registerSuite({
		name: "register",

		setup: function () {
			container = document.createElement("div");
			document.body.appendChild(container);
		},

		// Test the parser doesn't fail when no widgets are registered.  It just shouldn't do anything.
		// Unfortunately, since Intern doesn't have sandboxing, usually when this runs there are already
		// widgets registered, so it's not actually testing anything yet.
		"no widgets registered parse": function () {
			container.innerHTML = "
" +
				"<button is='test-extended-button-widget' id=ebw2>hello</button>" +
				"random node" +
				"<test-parser-widget id=pw></test-parser-widget>" +
				"
";

			register.parse(container);
		},

		// Declare and instantiate a simple widget
		simple: function () {
			TestWidget = register("test-simple-widget", [HTMLElement], {
				foo: 3,
				createdCallback: function () {
					this._createdCallbackCalled = true;
				},
				attachedCallback: function () {
					this._attachedCallbackCalled = true;
				},
				fooFunc: function () {
					this._fooCalled = true;
				},

				barFunc: function () {
					this._barCalled = true;
				}
			});
			assert.ok(TestWidget, "TestWidget created");

			container.innerHTML += "<test-simple-widget id=tsw></test-simple-widget>";
			var tsw = document.getElementById("tsw");
			register.upgrade(tsw);

			// lifecycle methods
			assert.ok(tsw._createdCallbackCalled, "createdCallback called");
			assert.ok(tsw._attachedCallbackCalled, "attachedCallback called");

			// property exists
			assert.ok(tsw.foo, "foo");

			// function from mixin exists
			tsw.fooFunc();
			assert.ok(tsw._fooCalled, "_fooCalled");

			// properties are enumerable
			var sawFoo;
			for (var key in tsw) {
				if (key === "foo") {
					sawFoo = true;
					break;
				}
			}
			assert.ok(sawFoo, "foo enumerable");
		},

		// Declare and instantiate a widget from a mixin that extends Stateful
		stateful: function () {
			// Create a mixin for testing purposes.
			// register() should call this.introspect() if it's defined, because it isn't called naturally.
			Mixin = register.dcl(Stateful, {
				foo: 3,
				fooFunc: function () {
					this._fooCalled = true;
				},

				cs1: 3,
				_setCs1Attr: function (val) {
					this._set("cs1", val + 1);
				},

				// Need to redefine Stateful.getProps() because on FF and IE, we get exceptions when accessing props
				// like HTMLElement.title.  We are accessing them in the HTMLElement prototype rather than an object
				// created from the document.createElement() factory.
				getProps: function () {
					var hash = {};
					for (var prop in this) {
						if (!(prop in nativeButton)) {
							hash[prop] = true;
						}
					}
					return hash;
				}
			});
			assert.ok(Mixin, "Mixin created");

			TestWidget = register("test-widget", [HTMLElement, Mixin], {
				barFunc: function () {
					this._barCalled = true;
				},

				cs2: 3,
				_setCs2Attr: function (val) {
					this._set("cs2", val + 1);
				}
			});
			assert.ok(TestWidget, "TestWidget created");

			container.innerHTML += "<test-widget id=tw></test-widget>";
			var tw = document.getElementById("tw");
			register.upgrade(tw);

			// property from mixin exists
			assert.ok(tw.foo, "foo");

			// function from mixin exists
			tw.fooFunc();
			assert.ok(tw._fooCalled, "_fooCalled");

			// function from register() call exists
			tw.barFunc();
			assert.ok(tw._barCalled, "_barCalled");

			// check that custom setters are working
			assert.strictEqual(tw.cs1, 3, "tw.cs1");
			tw.cs1 = 4;			// actually sets cs1 to 5, due to custom setter
			assert.strictEqual(tw.cs1, 5, "tw.cs1 after set");

			assert.strictEqual(tw.cs2, 3, "tw.cs2");
			tw.cs2 = 4;			// actually sets cs2 to 5, due to custom setter
			assert.strictEqual(tw.cs1, 5, "tw.cs2 after set");

		},

		extended: function () {
			// Create extension of another widget
			TestExtendedWidget = register("test-extended-widget", [TestWidget], {
				extFunc: function () {
					this._extCalled = true;
				}
			});
			assert.ok(TestExtendedWidget, "TestExtendedWidget created");

			container.innerHTML += "<test-extended-widget id=tew></test-extended-widget>";
			var tew = document.getElementById("tew");
			register.upgrade(tew);
			assert.ok(tew.foo, "foo");
			tew.fooFunc();
			assert.ok(tew._fooCalled, "_fooCalled");
			tew.barFunc();
			assert.ok(tew._barCalled, "_barCalled");
			tew.extFunc();
			assert.ok(tew._extCalled, "_extCalled");

			// properties are enumerable
			var sawExt;
			for (var key in tew) {
				if (key === "extFunc") {
					sawExt = true;
					break;
				}
			}
			assert.ok(sawExt, "ext enumerable");
		},

		button: function () {
			// Create a simple widget extending something other than HTMLElement.
			TestButtonWidget = register("test-button-widget", [HTMLButtonElement, Mixin], {
				label: "my label"
			});
			assert.ok(TestButtonWidget, "TestButtonWidget created");

			container.innerHTML += "<button is='test-button-widget' id=tbw></button>";
			var tbw = document.getElementById("tbw");
			register.upgrade(tbw);

			assert.ok(tbw.foo, "foo");
			assert.ok(tbw.label, "label");
		},

		"extended button": function () {
			// Create extension of another widget.
			TestExtendedButtonWidget = register("test-extended-button-widget", [TestButtonWidget], {
				extFunc: function () {
					this._extCalled = true;
				}
			});
			assert.ok(TestExtendedButtonWidget, "TestExtendedButtonWidget created");

			container.innerHTML += "<button is='test-extended-button-widget' id=tebw></button>";
			var tebw = document.getElementById("tebw");
			register.upgrade(tebw);

			assert.ok(tebw.foo, "foo");
			assert.ok(tebw.label, "label");
			tebw.extFunc();
			assert.ok(tebw._extCalled, "_extCalled");
		},

		// Create element is like upgrade() but it also creates the element for you.
		createElement: function () {
			var tw = register.createElement("test-widget");
			assert.ok(tw.foo, "TestWidget.foo");

			// Test also that we can create plain elements that are not registered as widgets
			var div = register.createElement("div");
			assert.strictEqual("div", div.nodeName.toLowerCase(), "nodeName of div");
		},

		// Test the new MyWidget() syntactic sugar
		"new": function () {
			var tw = new TestWidget({});
			assert.ok(tw.foo, "TestWidget.foo");
			assert.strictEqual("test-widget", tw.nodeName.toLowerCase(), "nodeName of TestWidget");
		},

		// Test the parser, which scans the DOM for registered widgets and upgrades them
		parse: function () {
			register("test-parser-widget", [HTMLElement, Mixin], {
				createdCalls: 0,
				createdCallback: function () {
					this.createdCalls++;
				},

				attachedCalls: 0,
				attachedCallback: function () {
					this.attachedCalls++;
				}
			});

			container.innerHTML += "
" +
				"<button is='test-extended-button-widget' id=ebw2>hello</button>" +
				"random node" +
				"<test-parser-widget id=pw></test-parser-widget>" +
				"
";

			register.parse(container);
			assert.strictEqual("my label", document.getElementById("ebw2").label, "ebw2.label");
			assert.strictEqual(1, document.getElementById("pw").createdCalls, "pw.createdCalls");
			assert.strictEqual(1, document.getElementById("pw").attachedCalls, "pw.attachedCalls");

			// Call parse again to make sure that we don't repeat
			register.parse(container);
			assert.strictEqual(1, document.getElementById("pw").createdCalls, "pw.createdCalls");
			assert.strictEqual(1, document.getElementById("pw").attachedCalls, "pw.attachedCalls");
		},

		// Test error conditions
		errors: function () {
			var threw;

			try {
				register("test-bad-inheritance", [Stateful], { });
			} catch (err) {
				assert(/must have HTMLElement in prototype chain/.test(err.toString()),
					"err not extending HTMLElement");
				threw = true;
			}
			assert(threw, "threw error when not extending HTMLElement");

			register("test-repeated-tag", [HTMLElement, Mixin], { });
			threw = false;
			try {
				register("test-repeated-tag", [HTMLElement], { });
			} catch (err) {
				assert(/A widget is already registered with tag/.test(err.toString()), "err repeating tag");
				threw = true;
			}
			assert(threw, "threw error when redeclaring same tag");
		},

		teardown: function () {
			container.parentNode.removeChild(container);
		}
	});
});
<commit_msg>skip test that fails on latest safari and ios due to https://github.com/uhop/dcl/issues/15<commit_after>define([
	"intern!object",
	"intern/chai!assert",
	"decor/sniff",
	"delite/register",
	"decor/Stateful",
	"requirejs-domready/domReady!"
], function (registerSuite, assert, has, register, Stateful) {

	// The
 node where we will put all our DOM nodes
	var container;

	var Mixin, TestWidget, TestButtonWidget, TestExtendedWidget, TestExtendedButtonWidget;

	var nativeButton = document.createElement("button");

	registerSuite({
		name: "register",

		setup: function () {
			container = document.createElement("div");
			document.body.appendChild(container);
		},

		// Test the parser doesn't fail when no widgets are registered.  It just shouldn't do anything.
		// Unfortunately, since Intern doesn't have sandboxing, usually when this runs there are already
		// widgets registered, so it's not actually testing anything yet.
		"no widgets registered parse": function () {
			container.innerHTML = "
" +
				"<button is='test-extended-button-widget' id=ebw2>hello</button>" +
				"random node" +
				"<test-parser-widget id=pw></test-parser-widget>" +
				"
";

			register.parse(container);
		},

		// Declare and instantiate a simple widget
		simple: function () {
			if (has("ios") >= 8 || has("safari") >= 8) {
				return this.skip("fails on safari and ios due to https://github.com/uhop/dcl/issues/15");
			}
			TestWidget = register("test-simple-widget", [HTMLElement], {
				foo: 3,
				createdCallback: function () {
					this._createdCallbackCalled = true;
				},
				attachedCallback: function () {
					this._attachedCallbackCalled = true;
				},
				fooFunc: function () {
					this._fooCalled = true;
				},

				barFunc: function () {
					this._barCalled = true;
				}
			});
			assert.ok(TestWidget, "TestWidget created");

			container.innerHTML += "<test-simple-widget id=tsw></test-simple-widget>";
			var tsw = document.getElementById("tsw");
			register.upgrade(tsw);

			// lifecycle methods
			assert.ok(tsw._createdCallbackCalled, "createdCallback called");
			assert.ok(tsw._attachedCallbackCalled, "attachedCallback called");

			// property exists
			assert.ok(tsw.foo, "foo");

			// function from mixin exists
			tsw.fooFunc();
			assert.ok(tsw._fooCalled, "_fooCalled");

			// properties are enumerable
			var sawFoo;
			for (var key in tsw) {
				if (key === "foo") {
					sawFoo = true;
					break;
				}
			}
			assert.ok(sawFoo, "foo enumerable");
		},

		// Declare and instantiate a widget from a mixin that extends Stateful
		stateful: function () {
			// Create a mixin for testing purposes.
			// register() should call this.introspect() if it's defined, because it isn't called naturally.
			Mixin = register.dcl(Stateful, {
				foo: 3,
				fooFunc: function () {
					this._fooCalled = true;
				},

				cs1: 3,
				_setCs1Attr: function (val) {
					this._set("cs1", val + 1);
				},

				// Need to redefine Stateful.getProps() because on FF and IE, we get exceptions when accessing props
				// like HTMLElement.title.  We are accessing them in the HTMLElement prototype rather than an object
				// created from the document.createElement() factory.
				getProps: function () {
					var hash = {};
					for (var prop in this) {
						if (!(prop in nativeButton)) {
							hash[prop] = true;
						}
					}
					return hash;
				}
			});
			assert.ok(Mixin, "Mixin created");

			TestWidget = register("test-widget", [HTMLElement, Mixin], {
				barFunc: function () {
					this._barCalled = true;
				},

				cs2: 3,
				_setCs2Attr: function (val) {
					this._set("cs2", val + 1);
				}
			});
			assert.ok(TestWidget, "TestWidget created");

			container.innerHTML += "<test-widget id=tw></test-widget>";
			var tw = document.getElementById("tw");
			register.upgrade(tw);

			// property from mixin exists
			assert.ok(tw.foo, "foo");

			// function from mixin exists
			tw.fooFunc();
			assert.ok(tw._fooCalled, "_fooCalled");

			// function from register() call exists
			tw.barFunc();
			assert.ok(tw._barCalled, "_barCalled");

			// check that custom setters are working
			assert.strictEqual(tw.cs1, 3, "tw.cs1");
			tw.cs1 = 4;			// actually sets cs1 to 5, due to custom setter
			assert.strictEqual(tw.cs1, 5, "tw.cs1 after set");

			assert.strictEqual(tw.cs2, 3, "tw.cs2");
			tw.cs2 = 4;			// actually sets cs2 to 5, due to custom setter
			assert.strictEqual(tw.cs1, 5, "tw.cs2 after set");

		},

		extended: function () {
			// Create extension of another widget
			TestExtendedWidget = register("test-extended-widget", [TestWidget], {
				extFunc: function () {
					this._extCalled = true;
				}
			});
			assert.ok(TestExtendedWidget, "TestExtendedWidget created");

			container.innerHTML += "<test-extended-widget id=tew></test-extended-widget>";
			var tew = document.getElementById("tew");
			register.upgrade(tew);
			assert.ok(tew.foo, "foo");
			tew.fooFunc();
			assert.ok(tew._fooCalled, "_fooCalled");
			tew.barFunc();
			assert.ok(tew._barCalled, "_barCalled");
			tew.extFunc();
			assert.ok(tew._extCalled, "_extCalled");

			// properties are enumerable
			var sawExt;
			for (var key in tew) {
				if (key === "extFunc") {
					sawExt = true;
					break;
				}
			}
			assert.ok(sawExt, "ext enumerable");
		},

		button: function () {
			// Create a simple widget extending something other than HTMLElement.
			TestButtonWidget = register("test-button-widget", [HTMLButtonElement, Mixin], {
				label: "my label"
			});
			assert.ok(TestButtonWidget, "TestButtonWidget created");

			container.innerHTML += "<button is='test-button-widget' id=tbw></button>";
			var tbw = document.getElementById("tbw");
			register.upgrade(tbw);

			assert.ok(tbw.foo, "foo");
			assert.ok(tbw.label, "label");
		},

		"extended button": function () {
			// Create extension of another widget.
			TestExtendedButtonWidget = register("test-extended-button-widget", [TestButtonWidget], {
				extFunc: function () {
					this._extCalled = true;
				}
			});
			assert.ok(TestExtendedButtonWidget, "TestExtendedButtonWidget created");

			container.innerHTML += "<button is='test-extended-button-widget' id=tebw></button>";
			var tebw = document.getElementById("tebw");
			register.upgrade(tebw);

			assert.ok(tebw.foo, "foo");
			assert.ok(tebw.label, "label");
			tebw.extFunc();
			assert.ok(tebw._extCalled, "_extCalled");
		},

		// Create element is like upgrade() but it also creates the element for you.
		createElement: function () {
			var tw = register.createElement("test-widget");
			assert.ok(tw.foo, "TestWidget.foo");

			// Test also that we can create plain elements that are not registered as widgets
			var div = register.createElement("div");
			assert.strictEqual("div", div.nodeName.toLowerCase(), "nodeName of div");
		},

		// Test the new MyWidget() syntactic sugar
		"new": function () {
			var tw = new TestWidget({});
			assert.ok(tw.foo, "TestWidget.foo");
			assert.strictEqual("test-widget", tw.nodeName.toLowerCase(), "nodeName of TestWidget");
		},

		// Test the parser, which scans the DOM for registered widgets and upgrades them
		parse: function () {
			register("test-parser-widget", [HTMLElement, Mixin], {
				createdCalls: 0,
				createdCallback: function () {
					this.createdCalls++;
				},

				attachedCalls: 0,
				attachedCallback: function () {
					this.attachedCalls++;
				}
			});

			container.innerHTML += "
" +
				"<button is='test-extended-button-widget' id=ebw2>hello</button>" +
				"random node" +
				"<test-parser-widget id=pw></test-parser-widget>" +
				"
";

			register.parse(container);
			assert.strictEqual("my label", document.getElementById("ebw2").label, "ebw2.label");
			assert.strictEqual(1, document.getElementById("pw").createdCalls, "pw.createdCalls");
			assert.strictEqual(1, document.getElementById("pw").attachedCalls, "pw.attachedCalls");

			// Call parse again to make sure that we don't repeat
			register.parse(container);
			assert.strictEqual(1, document.getElementById("pw").createdCalls, "pw.createdCalls");
			assert.strictEqual(1, document.getElementById("pw").attachedCalls, "pw.attachedCalls");
		},

		// Test error conditions
		errors: function () {
			var threw;

			try {
				register("test-bad-inheritance", [Stateful], { });
			} catch (err) {
				assert(/must have HTMLElement in prototype chain/.test(err.toString()),
					"err not extending HTMLElement");
				threw = true;
			}
			assert(threw, "threw error when not extending HTMLElement");

			register("test-repeated-tag", [HTMLElement, Mixin], { });
			threw = false;
			try {
				register("test-repeated-tag", [HTMLElement], { });
			} catch (err) {
				assert(/A widget is already registered with tag/.test(err.toString()), "err repeating tag");
				threw = true;
			}
			assert(threw, "threw error when redeclaring same tag");
		},

		teardown: function () {
			container.parentNode.removeChild(container);
		}
	});
});
<|endoftext|>


<commit_before>(function(ns) {
	"use strict";

	var mixin = ns.mixin || (ns.mixin = {});

	function getEvents(object) {
		return object.events ?
			object.events :
			Object.defineProperty(object, 'events', {
				value: {}
			}).events ;
	}

	mixin.events = {
		// Events
		on: function(types, fn) {
			var type, events, args;

			if (!fn) { return this; }

			types = types.split(/\s+/);
			events = getEvents(this);
			args = Array.prototype.slice.call(arguments, 2);

			while (type = types.shift()) {
				if (events[type]) {
					events[type].push([fn, args]);
				}
				else {
					events[type] = [[fn, args]];
				}
			}

			return this;
		},

		// Remove one or many callbacks. If `context` is null, removes all callbacks
		// with that function. If `callback` is null, removes all callbacks for the
		// event. If `events` is null, removes all bound callbacks for all events.
		off: function(types, fn) {
			var type, calls, list, i;

			// No events, or removing *all* events.
			if (!this.events) { return this; }

			if (!(types || fn)) {
				for (type in this.events) {
					this.events[type].length = 0;
				}

				delete this.events;
				return this;
			}

			types = types ?
				types.split(/\s+/) :
				Object.keys(this.events) ;

			while (type = types.shift()) {
				listeners = this.events[type];

				if (!listeners) {
					continue;
				}

				if (!fn) {
					delete this.events[type];
					continue;
				}

				listeners.forEach(function(v, i) {
					if (v[0] === fn) {
						listeners.splice(i, i+1);
					}
				});
			}

			return this;
		},

		trigger: function(type) {
			var listeners, i, l, args, params;

			if (!this.events || !this.events[type]) { return this; }

			// Use a copy of the event list in case it gets mutated while we're
			// triggering the callbacks.
			listeners = this.events[type].slice();

			// Execute event callbacks.
			i = -1;
			l = listeners.length;

			args = arguments.length > 1 ?
				Array.prototype.slice.call(arguments, 1) :
				[] ;

			while (++i < l) {
				params = args.concat(listeners[i][1]);
				listeners[i][0].apply(this, params);
			}

			return this;
		}
	};
})(this);<commit_msg>Debugs mixin.events<commit_after>(function(ns) {
	"use strict";

	var mixin = ns.mixin || (ns.mixin = {});

	function getEvents(object) {
		return object.events ?
			object.events :
			Object.defineProperty(object, 'events', {
				value: {}
			}).events ;
	}

	mixin.events = {
		// Events
		on: function(types, fn) {
			var type, events, args;

			if (!fn) { return this; }

			types = types.split(/\s+/);
			events = getEvents(this);
			args = Array.prototype.slice.call(arguments, 2);

			while (type = types.shift()) {
				if (events[type]) {
					events[type].push([fn, args]);
				}
				else {
					events[type] = [[fn, args]];
				}
			}

			return this;
		},

		// Remove one or many callbacks. If `context` is null, removes all callbacks
		// with that function. If `callback` is null, removes all callbacks for the
		// event. If `events` is null, removes all bound callbacks for all events.
		off: function(types, fn) {
			var type, calls, list, i;

			// No events.
			if (!this.events) { return this; }

			// Remove all events.
			if (!(types || fn)) {
				for (type in this.events) {
					this.events[type].length = 0;
					delete this.events[type];
				}

				return this;
			}

			types = types ?
				types.split(/\s+/) :
				Object.keys(this.events) ;

			while (type = types.shift()) {
				listeners = this.events[type];

				if (!listeners) {
					continue;
				}

				if (!fn) {
					delete this.events[type];
					continue;
				}

				listeners.forEach(function(v, i) {
					if (v[0] === fn) {
						listeners.splice(i, i+1);
					}
				});
			}

			return this;
		},

		trigger: function(type) {
			var listeners, i, l, args, params;

			if (!this.events || !this.events[type]) { return this; }

			// Use a copy of the event list in case it gets mutated while we're
			// triggering the callbacks.
			listeners = this.events[type].slice();

			// Execute event callbacks.
			i = -1;
			l = listeners.length;

			args = arguments.length > 1 ?
				Array.prototype.slice.call(arguments, 1) :
				[] ;

			while (++i < l) {
				params = args.concat(listeners[i][1]);
				listeners[i][0].apply(this, params);
			}

			return this;
		}
	};
})(this);<|endoftext|>


<commit_before>import getScrollBarWidth from '../_core/_utils/getScrollBarWidth.js'

export default {
  props: {
    backdrop: {type: Boolean, default: true},
    callback: {type: Function, default: null},
    cancelText: {type: String, default: 'Close'},
    effect: {type: String, default: null},
    large: {type: Boolean, default: false},
    okText: {type: String, default: 'Save changes'},
    small: {type: Boolean, default: false},
    title: {type: String, default: ''},
    value: {type: Boolean, required: true},
    width: {default: null},
    subModal: {type: Boolean, default: false}
  },
  data () {
    return {
      transition: false,
      val: null
    }
  },
  computed: {
    optionalWidth () {
      if (this.width === null) {
        return null
      } else if (Number.isInteger(this.width)) {
        return this.width + 'px'
      }
      return this.width
    }
  },
  watch: {
    transition (val, old) {
      if (val === old) { return }
      const el = this.$el
      const body = document.body
      if (val) {
        if (this.val) {
          el.querySelector('.modal-content').focus()
          el.style.display = 'block'
          setTimeout(() => el.classList.add('in'), 0)
          body.classList.add('modal-open')
          if (getScrollBarWidth() !== 0) {
            body.style.paddingRight = getScrollBarWidth() + 'px'
          }
        } else {
          el.classList.remove('in')
        }
      } else {
        this.$emit(this.val ? 'opened' : 'closed')
        if (!this.val) {
          el.style.display = 'none'
          body.style.paddingRight = null
          if (!this.subModal) {
            body.classList.remove('modal-open')
          }
        }
      }
    },
    val (val, old) {
      this.$emit('input', val)
      if (old === null ? val === true : val !== old) this.transition = true
    },
    value (val, old) {
      if (val !== old) this.val = val
    }
  },
  methods: {
    action (val, p) {
      if (val === null) { return }
      if (val && this.callback instanceof Function) this.callback()
      this.$emit(val ? 'ok' : 'cancel', p)
      this.val = val || false
    }
  },
  mounted () {
    this.val = this.value
  }
}
<commit_msg>created semaphore<commit_after>import getScrollBarWidth from '../_core/_utils/getScrollBarWidth.js'

export default {
  props: {
    backdrop: {type: Boolean, default: true},
    callback: {type: Function, default: null},
    cancelText: {type: String, default: 'Close'},
    effect: {type: String, default: null},
    large: {type: Boolean, default: false},
    okText: {type: String, default: 'Save changes'},
    small: {type: Boolean, default: false},
    title: {type: String, default: ''},
    value: {type: Boolean, required: true},
    width: {default: null},
    subModal: {type: Boolean, default: false}
  },
  data () {
    return {
      transition: false,
      val: null,
      sem: true
    }
  },
  computed: {
    optionalWidth () {
      if (this.width === null) {
        return null
      } else if (Number.isInteger(this.width)) {
        return this.width + 'px'
      }
      return this.width
    }
  },
  watch: {
    transition (val, old) {
      if (val === old) { return }
      const el = this.$el
      const body = document.body
      if (val) {
        if (this.val) {
          el.querySelector('.modal-content').focus()
          el.style.display = 'block'
          setTimeout(() => el.classList.add('in'), 0)
          body.classList.add('modal-open')
          if (getScrollBarWidth() !== 0) {
            body.style.paddingRight = getScrollBarWidth() + 'px'
          }
        } else {
          el.classList.remove('in')
        }
      } else {
        this.$emit(this.val ? 'opened' : 'closed')
        if (!this.val) {
          el.style.display = 'none'
          body.style.paddingRight = null
          if (!this.subModal) {
            body.classList.remove('modal-open')
          }
        }
      }
    },
    val (val, old) {
      this.$emit('input', val)
      if (old === null ? val === true : val !== old) this.transition = true
    },
    value (val, old) {
      if (val !== old) this.val = val
    }
  },
  methods: {
    action (val, p) {
      if (this.sem) {
        this.sem = false
        if (val === null) { return }
        if (val && this.callback instanceof Function) this.callback()
        this.$emit(val ? 'ok' : 'cancel', p)
        this.val = val || false

        setTimeout(() => this.sem = true, 900)
      }
    }
  },
  mounted () {
    this.val = this.value
  }
}
<|endoftext|>


<commit_before>
(function (cyto_chr, d3) {

  var defaultDataURLs = {
    "400" : "ideogram_9606_GCF_000001305.14_400_V1",
    "550" : "ideogram_9606_GCF_000001305.14_550_V1",
    "850" : "ideogram_9606_GCF_000001305.14_850_V1",
    "1200" : "ideogram_9606_GCF_000001305.13_1200_v1"
  };

  var baseDir = 'data/';

  var dataCache = {
    "400" : [],
    "550" : [],
    "850" : [],
    "1200" : []
  };

  var loaded = false;

  var callQueue = [];

  function loadData(file, res, cb) {
//TODO fix caching for multiple resolution
    if (dataCache[res].length === 0) {
      if (loaded) {
        callQueue.push(cb);
        return;
      }

      loaded = true;
      //console.log('network')
      d3.tsv(file, function(d) {
        dataCache[res] = d;
        loaded = true;
        cb(d);

        while(callQueue.length > 0) {
          var cbq = callQueue.shift();
          cbq(d);
        }

      });

    } else {
      cb(dataCache[res]);
    }
  }

  function getChromosomeData(chr, resolution, cb) {

    var fileName = defaultDataURLs[resolution];

    loadData(baseDir + fileName, resolution, function (d) {
      var filteredResults = filterByChromosome(d, chr);
      cb(filteredResults);
    });
  }

  function filterByChromosome(data, chr) {
    var newAry = [];
    for(var i = 0; i < data.length; i++) {
      if (data[i]['#chromosome'] === chr) {
        newAry.push(data[i]);
      }
    }
    return newAry;
  }

  cyto_chr.modelLoader = {
    load: getChromosomeData,
    setBaseDir: function(d) {baseDir = d;}
  };

})(window.cyto_chr = window.cyto_chr || {}, d3);<commit_msg>dynamic resource loading for multiple resolutions<commit_after>
(function (cyto_chr, d3) {

  var defaultDataURLs = {
    "400" : "ideogram_9606_GCF_000001305.14_400_V1",
    "550" : "ideogram_9606_GCF_000001305.14_550_V1",
    "850" : "ideogram_9606_GCF_000001305.14_850_V1",
    "1200" : "ideogram_9606_GCF_000001305.13_1200_v1"
  };

  var baseDir = 'data/';

  function CacheInstance() {
    this.status = "notloaded";
    this.cache = [];
  }

  var dataCache = {
    "400" : new CacheInstance,
    "550" : new CacheInstance,
    "850" : new CacheInstance,
    "1200" : new CacheInstance
  };

  var callQueue = [];

  function loadData(file, res, cb) {

    var c = dataCache[res];
    if (c.cache.length === 0) {
      if (c.status === "loading") {
        callQueue.push({
          res: res,
          cb: cb
        });

        return;
      } else if (c.status === "notloaded") {
        console.log("network for ", res)
        c.status = "loading";
        d3.tsv(file, function(d) {
          c.cache = d;
          c.status = "loaded";
          cb(d);

          while(callQueue.length > 0) {
            var cbq = callQueue.shift();
            cbq.cb(d);
          }

        });
      }
    } else {
      cb(c.cache);
    }
  }

  function getChromosomeData(chr, resolution, cb) {

    var fileName = defaultDataURLs[resolution];

    loadData(baseDir + fileName, resolution, function (d) {
      var filteredResults = filterByChromosome(d, chr);
      cb(filteredResults);
    });
  }

  function filterByChromosome(data, chr) {
    var newAry = [];
    for(var i = 0; i < data.length; i++) {
      if (data[i]['#chromosome'] === chr) {
        newAry.push(data[i]);
      }
    }
    return newAry;
  }

  cyto_chr.modelLoader = {
    load: getChromosomeData,
    setBaseDir: function(d) {baseDir = d;}
  };

})(window.cyto_chr = window.cyto_chr || {}, d3);<|endoftext|>


<commit_before>describe('login', function () {
  beforeEach(function () {
    browser.addMockModule('httpBackendMock', function () {
      angular.module('httpBackendMock', ['ngMockE2E'])
        .run(function ($httpBackend) {
          $httpBackend.whenPOST('login').respond(function (method, url, data) {
            var creds = angular.fromJson(data);
            if (creds.username === 'jooseppi') {
              if (creds.password !== 'oikee') {
                return [401, { error: 'wrong password' }];
              }
              return [200, { id: 1, username: 'jooseppi' }];
            }
            return [401, { error: 'invalid username' }];
          });
        });
    });
  });

  it('should fail with invalid user', function () {
    browser.get('#/login');

    element(by.model('login.username')).sendKeys('hax0r');
    element(by.model('login.password')).sendKeys('1337');
    element(by.buttonText('Login')).click();

    expect(element(by.className('error')).getText()).toBe('invalid username');
  });

  it('should fail with wrong password', function () {
    browser.get('#/login');

    element(by.model('login.username')).sendKeys('jooseppi');
    element(by.model('login.password')).sendKeys('eioo');
    element(by.buttonText('Login')).click();

    expect(element(by.className('error')).getText()).toBe('wrong password');
  });

  it('should redirect to /home with no history', function () {
    browser.get('#/login');

    element(by.model('login.username')).sendKeys('jooseppi');
    element(by.model('login.password')).sendKeys('oikee');
    element(by.buttonText('Login')).click();

    expect(browser.getLocationAbsUrl()).toMatch('/home');
  });

  it('should redirect back /home', function () {
    browser.get('#/home');
    element(by.linkText('Login')).click();

    element(by.model('login.username')).sendKeys('jooseppi');
    element(by.model('login.password')).sendKeys('oikee');
    element(by.buttonText('Login')).click();

    expect(browser.getLocationAbsUrl()).toMatch('/home');
  });

  it('should redirect back to protected route', function () {
    browser.get('#/home');
    element(by.linkText('Show statistics screen')).click();

    expect(browser.getLocationAbsUrl()).toMatch('/login');
    element(by.model('login.username')).sendKeys('jooseppi');
    element(by.model('login.password')).sendKeys('oikee');
    element(by.buttonText('Login')).click();

    expect(browser.getLocationAbsUrl()).toMatch('/stats');
  });
});
<commit_msg>Fix Protractor tests by moving mouse on navbar element<commit_after>describe('login', function () {
  beforeEach(function () {
    browser.addMockModule('httpBackendMock', function () {
      angular.module('httpBackendMock', ['ngMockE2E'])
        .run(function ($httpBackend) {
          $httpBackend.whenPOST('login').respond(function (method, url, data) {
            var creds = angular.fromJson(data);
            if (creds.username === 'jooseppi') {
              if (creds.password !== 'oikee') {
                return [401, { error: 'wrong password' }];
              }
              return [200, { id: 1, username: 'jooseppi' }];
            }
            return [401, { error: 'invalid username' }];
          });
        });
    });
  });

  it('should fail with invalid user', function () {
    browser.get('#/login');

    element(by.model('login.username')).sendKeys('hax0r');
    element(by.model('login.password')).sendKeys('1337');
    element(by.buttonText('Login')).click();

    expect(element(by.className('error')).getText()).toBe('invalid username');
  });

  it('should fail with wrong password', function () {
    browser.get('#/login');

    element(by.model('login.username')).sendKeys('jooseppi');
    element(by.model('login.password')).sendKeys('eioo');
    element(by.buttonText('Login')).click();

    expect(element(by.className('error')).getText()).toBe('wrong password');
  });

  it('should redirect to /home with no history', function () {
    browser.get('#/login');

    element(by.model('login.username')).sendKeys('jooseppi');
    element(by.model('login.password')).sendKeys('oikee');
    element(by.buttonText('Login')).click();

    expect(browser.getLocationAbsUrl()).toMatch('/home');
  });

  it('should redirect back /home', function () {
    browser.get('#/home');
    browser.actions().mouseMove(element(by.className('navbar'))).perform();
    element(by.className('navbar')).element(by.linkText('Login')).click();

    element(by.model('login.username')).sendKeys('jooseppi');
    element(by.model('login.password')).sendKeys('oikee');
    element(by.buttonText('Login')).click();

    expect(browser.getLocationAbsUrl()).toMatch('/home');
  });

  it('should redirect back to protected route', function () {
    browser.get('#/home');
    browser.actions().mouseMove(element(by.className('navbar'))).perform();
    element(by.className('navbar')).element(by.linkText('Show statistics screen')).click();

    expect(browser.getLocationAbsUrl()).toMatch('/login');
    element(by.model('login.username')).sendKeys('jooseppi');
    element(by.model('login.password')).sendKeys('oikee');
    element(by.buttonText('Login')).click();

    expect(browser.getLocationAbsUrl()).toMatch('/stats');
  });
});
<|endoftext|>