<commit_before>// The main search module that allows users to view the Preference Terms Dictionary

(function ($) {
    "use strict";
    var search    = fluid.registerNamespace("ctr.components.search");
    var templates = fluid.registerNamespace("ctr.components.templates");

    // TODO:  Create session-scoped variables for query, status, record type, and language, and use if no data is provided.

    search.clear = function(that) {
        var queryInput = that.locate("input");
        queryInput.val(null);
        search.queryChanged(that,null);
    };

    search.showClearButton = function (that, show) {
        // Wire in support for clearing the search easily
        var clearButton = that.locate("clear");
        if (show) {
            clearButton.attr("tabIndex",0);
            clearButton.show();
        }
        else {
            clearButton.attr("tabIndex",-1);
            clearButton.hide();
        }
    };

    // This function is meant to be called on an individual alias entry toggle
    search.toggleAliasRecord = function () {
        $(this).html($(this).html() === "less" ? "more": "less");
        $(this).parent().parent().parent().find(".alias-details").toggle();
    };

    // Update the results displayed whenever we have new search data
    search.queryChanged = function(that, queryInput) {
        var emptyQuery = (!queryInput || queryInput === "");
        if (that.showClearButton) {
            that.showClearButton(!emptyQuery);
        }

        // TODO: Figure out why the hell this is happening...
        if (!that.displayResults) {
            console.log("queryChanged was called before invokers were in place.  Bailing out...");
            return;
        }

        var settings = {
            url:     that.options.baseUrl,
            success: that.displayResults,
            error:   that.displayError
        };

        // Wire in sorting and filtering to both types of requests
        // TODO: Break out this AJAX assembly and launch function into its own function
        var baseUrl = that.options.baseUrl;
        if (emptyQuery) {
            settings.url += "/records?children=true";
        }
        else {
            settings.url += "/search";
            settings.data = { q: queryInput};
        }

        // TODO:  Wire in support for status controls

        // TODO:  Wire in support for record type controls

        $.ajax(settings);
    };

    search.displayError = function(that, jqXHR, textStatus, errorThrown) {
        templates.prependTo(that.locate("viewport"),"error",{message: errorThrown});
    };

    search.displayResults = function(that, data, textStatus, jqXHR) {
        var viewport = that.locate("viewport");
        if (data && data.records && data.records.length > 0) {
            viewport.html("");

            // TODO:  Come up with a meaningful list of untranslated records
            var localEnd = data.offset + data.limit;
            var navData = {
                count: data.total_rows,
                start: data.offset + 1,
                end: data.total_rows < localEnd ? data.total_rows : localEnd,
                untranslated: 0
            };

            // prepend the control title bar
            templates.appendTo(viewport, "navigation", navData);

            // display each record in the results area
            data.records.forEach(function(record) {
                templates.appendTo(viewport, "search-record", { record: record, user: that.data.model.user });
            });
        }
        else {
            templates.replaceWith(viewport, "norecord");
        }

        // Wire up the alias show/hide controls
        $(viewport).find(".alias-toggle").bind('click',search.toggleAliasRecord);

        // TODO: add support for pagination or infinite scrolling
    };

    // We have to do this because templates need to be loaded before we initialize our own code.
    search.init = function(that) {
        templates.loadTemplates(function() { search.queryChanged(that); });
    };

    // TODO:  Figure out why this couldn't address {data}.model.record and make the general library work for both the search and the details page.
    ctr.components.applyBinding = function (that) {
        var bindings = that.options.bindings;
        fluid.each(bindings, function (binding) {
            var element = that.locate(binding.selector);
            // in time, break out different ways of accessing the DOM into dedicated functions,
            // index by the "elementType" field we will add to "bindings"
            element.change(function () {
                var value = element.val();
                that.applier.change(binding.path, value);
            });
            that.applier.modelChanged.addListener(binding.path, function (change) {
                element.val(change);
            });
        });
    };

    fluid.defaults("ctr.components.search", {
        gradeNames: ["fluid.viewRelayComponent", "autoInit"],
        baseUrl: "/api",
        selectors: {
            "input":    ".ptd-search-input",
            "go":       ".ptd-search-button",
            "clear":    ".ptd-clear-button",
            "viewport": ".ptd-viewport"
        },
        bindings: [{
            selector:    "input",
            path:        "input",
            elementType: "encode different ways of accessing values here"
        }],
        components: {
            data:    {
                type: "ctr.components.data"
            },
            controls:    {
                type: "ctr.components.userControls",
                container: ".user-container",
                options: {
                    components: {
                        data: "{ctr.components.search}.data"
                    },
                    listeners: {
                        afterLogout:
                        {
                            func: "{ctr.components.search}.events.refresh.fire"
                        }
                    }
                }
            }
        },
        events: {
            "refresh":   "preventable",
            "clear":     "preventable"
        },
        invokers: {
            "clear": {
                funcName: "ctr.components.search.clear",
                args: [ "{that}"]
            },
            "init": {
                funcName: "ctr.components.search.init",
                args: ["{that}"]
            },
            "displayError": {
                funcName: "ctr.components.search.displayError",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
            },
            "displayResults": {
                funcName: "ctr.components.search.displayResults",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
            },
            "showClearButton": {
                funcName: "ctr.components.search.showClearButton",
                args: ["{that}", "{arguments}.0"]
            }
        },
        modelListeners: {
            "input": {
                funcName: "ctr.components.search.queryChanged",
                excludeSource: "init",
                args: ["{that}", "{change}.value"]
            }
        },
        listeners: {
            onCreate: [
                {
                    "this": "{that}.dom.clear",
                    method: "click",
                    args:   "{that}.clear"
                },
                {
                    "this": "{that}.dom.clear",
                    method: "keypress",
                    args:   "{that}.clear"
                },
                {
                    "funcName": "ctr.components.applyBinding",
                    "args":     "{that}"
                },
                {
                    "funcName": "ctr.components.search.init",
                    "args":     "{that}"
                }
            ],
            "refresh": {
                func: "ctr.components.search.queryChanged",
                args: [ "{that}"]
            }
        }
    });
})(jQuery);<commit_msg>Fixed display of aliases on search page.<commit_after>// The main search module that allows users to view the Preference Terms Dictionary

(function ($) {
    "use strict";
    var search    = fluid.registerNamespace("ctr.components.search");
    var templates = fluid.registerNamespace("ctr.components.templates");

    // TODO:  Create session-scoped variables for query, status, record type, and language, and use if no data is provided.

    search.clear = function(that) {
        var queryInput = that.locate("input");
        queryInput.val(null);
        search.queryChanged(that,null);
    };

    search.showClearButton = function (that, show) {
        // Wire in support for clearing the search easily
        var clearButton = that.locate("clear");
        if (show) {
            clearButton.attr("tabIndex",0);
            clearButton.show();
        }
        else {
            clearButton.attr("tabIndex",-1);
            clearButton.hide();
        }
    };

    // This function is meant to be called on an individual alias entry toggle
    search.toggleAliasRecord = function () {
        $(this).html($(this).html() === "less" ? "more": "less");
        $(this).parent().parent().parent().find(".alias-details").toggle();
    };

    // Update the results displayed whenever we have new search data
    search.queryChanged = function(that, queryInput) {
        var emptyQuery = (!queryInput || queryInput === "");
        if (that.showClearButton) {
            that.showClearButton(!emptyQuery);
        }

        // TODO: Figure out why the hell this is happening...
        if (!that.displayResults) {
            console.log("queryChanged was called before invokers were in place.  Bailing out...");
            return;
        }

        var settings = {
            url:     that.options.baseUrl,
            success: that.displayResults,
            error:   that.displayError
        };

        // Wire in sorting and filtering to both types of requests
        // TODO: Break out this AJAX assembly and launch function into its own function
        var baseUrl = that.options.baseUrl;
        if (emptyQuery) {
            settings.url += "/terms?children=true";
        }
        else {
            settings.url += "/search";
            settings.data = { q: queryInput};
        }

        // TODO:  Wire in support for status controls

        // TODO:  Wire in support for record type controls

        $.ajax(settings);
    };

    search.displayError = function(that, jqXHR, textStatus, errorThrown) {
        templates.prependTo(that.locate("viewport"),"error",{message: errorThrown});
    };

    search.displayResults = function(that, data, textStatus, jqXHR) {
        var viewport = that.locate("viewport");
        if (data && data.records && data.records.length > 0) {
            viewport.html("");

            // TODO:  Come up with a meaningful list of untranslated records
            var localEnd = data.offset + data.limit;
            var navData = {
                count: data.total_rows,
                start: data.offset + 1,
                end: data.total_rows < localEnd ? data.total_rows : localEnd,
                untranslated: 0
            };

            // prepend the control title bar
            templates.appendTo(viewport, "navigation", navData);

            // display each record in the results area
            data.records.forEach(function(record) {
                templates.appendTo(viewport, "search-record", { record: record, user: that.data.model.user });
            });
        }
        else {
            templates.replaceWith(viewport, "norecord");
        }

        // Wire up the alias show/hide controls
        $(viewport).find(".alias-toggle").bind('click',search.toggleAliasRecord);

        // TODO: add support for pagination or infinite scrolling
    };

    // We have to do this because templates need to be loaded before we initialize our own code.
    search.init = function(that) {
        templates.loadTemplates(function() { search.queryChanged(that); });
    };

    // TODO:  Figure out why this couldn't address {data}.model.record and make the general library work for both the search and the details page.
    ctr.components.applyBinding = function (that) {
        var bindings = that.options.bindings;
        fluid.each(bindings, function (binding) {
            var element = that.locate(binding.selector);
            // in time, break out different ways of accessing the DOM into dedicated functions,
            // index by the "elementType" field we will add to "bindings"
            element.change(function () {
                var value = element.val();
                that.applier.change(binding.path, value);
            });
            that.applier.modelChanged.addListener(binding.path, function (change) {
                element.val(change);
            });
        });
    };

    fluid.defaults("ctr.components.search", {
        gradeNames: ["fluid.viewRelayComponent", "autoInit"],
        baseUrl: "/api",
        selectors: {
            "input":    ".ptd-search-input",
            "go":       ".ptd-search-button",
            "clear":    ".ptd-clear-button",
            "viewport": ".ptd-viewport"
        },
        bindings: [{
            selector:    "input",
            path:        "input",
            elementType: "encode different ways of accessing values here"
        }],
        components: {
            data:    {
                type: "ctr.components.data"
            },
            controls:    {
                type: "ctr.components.userControls",
                container: ".user-container",
                options: {
                    components: {
                        data: "{ctr.components.search}.data"
                    },
                    listeners: {
                        afterLogout:
                        {
                            func: "{ctr.components.search}.events.refresh.fire"
                        }
                    }
                }
            }
        },
        events: {
            "refresh":   "preventable",
            "clear":     "preventable"
        },
        invokers: {
            "clear": {
                funcName: "ctr.components.search.clear",
                args: [ "{that}"]
            },
            "init": {
                funcName: "ctr.components.search.init",
                args: ["{that}"]
            },
            "displayError": {
                funcName: "ctr.components.search.displayError",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
            },
            "displayResults": {
                funcName: "ctr.components.search.displayResults",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
            },
            "showClearButton": {
                funcName: "ctr.components.search.showClearButton",
                args: ["{that}", "{arguments}.0"]
            }
        },
        modelListeners: {
            "input": {
                funcName: "ctr.components.search.queryChanged",
                excludeSource: "init",
                args: ["{that}", "{change}.value"]
            }
        },
        listeners: {
            onCreate: [
                {
                    "this": "{that}.dom.clear",
                    method: "click",
                    args:   "{that}.clear"
                },
                {
                    "this": "{that}.dom.clear",
                    method: "keypress",
                    args:   "{that}.clear"
                },
                {
                    "funcName": "ctr.components.applyBinding",
                    "args":     "{that}"
                },
                {
                    "funcName": "ctr.components.search.init",
                    "args":     "{that}"
                }
            ],
            "refresh": {
                func: "ctr.components.search.queryChanged",
                args: [ "{that}"]
            }
        }
    });
})(jQuery);<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var _ = require('lodash');

var config = require('./_config.js');
var paths = config.paths;

var karma = require('karma').server;

var browserSync = require('browser-sync');
var pagespeed = require('psi');
var ngrok = require('ngrok');

var karmaConf = {
  browsers: ['PhantomJS'],
  frameworks: ['mocha'],
  preprocessors: {},
  files: [
    paths.tmp + "/js/main.js",
    './node_modules/should/should.min.js',
    paths.test + '/**/*.spec.js'
  ],
  reporters: ['mocha', 'osx', 'coverage'],
  coverageReporter: {
    type : 'lcov',
    dir : 'coverage/',
    subdir: function (browser) {
      return browser.toLowerCase().split(/[ /-]/)[0];
    }
  }
};

karmaConf.preprocessors[paths.tmp + '/js/main.js'] = ['coverage'];

gulp.task('test', function (done) {
  karma.start(karmaConf, done);
});

gulp.task('test:once', ['build'], function () {
  karma.start(_.assign({}, karmaConf, { singleRun: true }));
});

gulp.task('pagespeed', ['build:dist'], function () {
  browserSync({
    server: {
      baseDir: paths.dist
    },
    open: false
  }, function (err, bs) {
    if (err) {
      console.log(err);
      process.exit(0);
    }

    ngrok.connect(bs.options.port, function(err, url) {
      pagespeed({
        url: url,
        strategy: 'mobile'
      }, function () {
        process.exit(0);
      });
    });
  });
});

<commit_msg>Add pagespeed:express task.<commit_after>'use strict';

var gulp = require('gulp');
var _ = require('lodash');

var config = require('./_config.js');
var paths = config.paths;

var karma = require('karma').server;

var browserSync = require('browser-sync');
var pagespeed = require('psi');
var ngrok = require('ngrok');

var karmaConf = {
  browsers: ['PhantomJS'],
  frameworks: ['mocha'],
  preprocessors: {},
  files: [
    paths.tmp + "/js/main.js",
    './node_modules/should/should.min.js',
    paths.test + '/**/*.spec.js'
  ],
  reporters: ['mocha', 'osx', 'coverage'],
  coverageReporter: {
    type : 'lcov',
    dir : 'coverage/',
    subdir: function (browser) {
      return browser.toLowerCase().split(/[ /-]/)[0];
    }
  }
};

karmaConf.preprocessors[paths.tmp + '/js/main.js'] = ['coverage'];

gulp.task('test', function (done) {
  karma.start(karmaConf, done);
});

gulp.task('test:once', ['build'], function () {
  karma.start(_.assign({}, karmaConf, { singleRun: true }));
});

gulp.task('pagespeed', ['build:dist'], function () {
  browserSync({
    server: {
      baseDir: paths.dist
    },
    open: false
  }, function (err, bs) {
    if (err) {
      console.log(err);
      process.exit(0);
    }

    ngrok.connect(bs.options.port, function(err, url) {
      pagespeed({
        url: url,
        strategy: 'mobile'
      }, function () {
        process.exit(0);
      });
    });
  });
});

gulp.task('pagespeed:express', ['build:dist'], function () {
  ngrok.connect(process.env.port, function(err, url) {
    pagespeed({
      url: url,
      strategy: 'mobile'
    }, function () {
      process.exit(0);
    });
  });
});

<|endoftext|>


<commit_before><commit_msg>adds default Line styles to d3plus.js<commit_after><|endoftext|>


<commit_before>(function(global, _, $) {

  var Miso = global.Miso = (global.Miso || {});

  Miso.Rig = function( config ) {
    this._buildScenes( config.scenes );
    this._triggers = {};

     //attach extra methods
    _.each(config, function(prop, name) {
      if (_.indexOf(Rig.BLACKLIST, name) !== -1) { return; }
      this[name] = prop;
    }, this);

    if (config.defer) {
      this._initial = config.initial;
    } else {
      this.to(config.initial);
    }
  };

  var Rig = Miso.Rig;

  Rig.ERRORS = {};
  Rig.BLACKLIST = ['initial','scenes','defer'];

  _.extend(Rig.prototype, {
     attach : function(name, engine) {
      this.name = name;
      this.engine = engine;
    },

    start : function() {
      if (this._current) { //already started
        return _.Deferred().reject().promise();
      }
      return this.to(this._initial);
    },

    cancelTransition : function() {
      this._complete.reject();
      this._transitioning = false;
    },

    to : function( sceneName, argsArr, deferred ) {
      var toScene = this.scenes[sceneName],
          fromScene = this._current,
          args = argsArr ? argsArr : [],
          complete = this._complete = deferred || _.Deferred(),
          exitComplete = _.Deferred(),
          enterComplete = _.Deferred(),
          bailout = _.bind(function() {
            this._transitioning = false;
            complete.reject();
          }, this),
          success = _.bind(function() {
            this._transitioning = false;
            this._current = toScene;
            complete.resolve();
          }, this);

      //Can't fire a transition that isn't defined
      if (!toScene) {
        throw "Scene '" + sceneName + "' not found!";
      }

      //we in the middle of a transition?
      if (this._transitioning) {
        return complete.reject();
      }

      this._transitioning = true;

      //initial event so there's no from scene
      if (!fromScene) {
        exitComplete.resolve();
        toScene.to('enter', args, enterComplete)
          .fail(bailout);
      } else {
        //run before and after in order
        //if either fail, run the bailout
        fromScene.to('exit', args, exitComplete)
          .done(function() {
            toScene.to('enter', args, enterComplete).fail(bailout);
          })
          .fail(bailout);
      }

      //all events done, let's tidy up
      _.when(exitComplete, enterComplete).then(success);

      return complete.promise();
    },

    scene : function() {
      return this._current ? this._current.name : null;
    },

    is : function( scene ) {
      return (scene === this._current.name);
    },

    inTransition : function() {
      return (this._transitioning === true);
    },

    _buildScenes : function( scenes ) {
      this.scenes = {};
      _.each(scenes, function(originalScene, name) {
        var scene;
        if (originalScene instanceof Miso.Scene || originalScene instanceof Miso.Rig) {
          scene = originalScene;
        } else {
          scene = new Miso.Scene(originalScene);
        }
        scene.attach(name, this);
        this.scenes[name] = scene;
      }, this);
    },

    _publish : function(name) {
      var args = _.toArray(arguments);
      args.shift();

      if (this._triggers && this._triggers[name]) {
        _.each(this._triggers[name], function(subscription) {
          subscription.callback.apply(subscription.context || this, args);
        }, this);
      }
    },

    subscribe : function(name, callback, context, token) {
      this._triggers[name] = this._triggers[name] || [];
      var subscription = {
        callback : callback,
        token : (token || _.uniqueId('t')),
        context : context || this
      };

      this._triggers[name].push(subscription);

      return subscription.token;
    }

  });

}(this, _, $));
<commit_msg>removing src/engine.js… since that got renamed.<commit_after><|endoftext|>


<commit_before>/*jshint browser: true */
/*jshint unused: false */
/*global _, Backbone, templateEngine, window, setTimeout, clearTimeout, arangoHelper, Joi, $*/

(function() {
  "use strict";
  window.CollectionsView = Backbone.View.extend({
    el: '#content',
    el2: '#collectionsThumbnailsIn',

    searchTimeout: null,

    initialize: function () {
    },

    template: templateEngine.createTemplate("collectionsView.ejs"),

    render: function () {
      var dropdownVisible = false;
      if ($('#collectionsDropdown').is(':visible')) {
        dropdownVisible = true;
      }

      $(this.el).html(this.template.render({}));
      this.setFilterValues();

      if (dropdownVisible === true) {
        $('#collectionsDropdown2').show();
      }

      var searchOptions = this.collection.searchOptions;

      this.collection.getFiltered(searchOptions).forEach(function (arango_collection) {
        $('#collectionsThumbnailsIn', this.el).append(new window.CollectionListItemView({
          model: arango_collection,
          collectionsView: this
        }).render().el);
      }, this);

      //if type in collectionsDropdown2 is changed,
      //the page will be rerendered, so check the toggel button
      if($('#collectionsDropdown2').css('display') === 'none') {
        $('#collectionsToggle').removeClass('activated');

      } else {
        $('#collectionsToggle').addClass('activated');
      }

      $('#searchInput').val(searchOptions.searchPhrase);
      $('#searchInput').focus();
      var val = $('#searchInput').val();
      $('#searchInput').val(val);

      arangoHelper.fixTooltips(".icon_arangodb, .arangoicon", "left");

      return this;
    },

    events: {
      "click #createCollection"   : "createCollection",
      "keydown #searchInput"      : "restrictToSearchPhraseKey",
      "change #searchInput"       : "restrictToSearchPhrase",
      "click #searchSubmit"       : "restrictToSearchPhrase",
      "click #checkSystem"        : "checkSystem",
      "click #checkLoaded"        : "checkLoaded",
      "click #checkUnloaded"      : "checkUnloaded",
      "click #checkDocument"      : "checkDocument",
      "click #checkEdge"          : "checkEdge",
      "click #sortName"           : "sortName",
      "click #sortType"           : "sortType",
      "click #sortOrder"          : "sortOrder",
      "click #collectionsToggle"  : "toggleView",
      "click .css-label"          : "checkBoxes"
    },

    updateCollectionsView: function() {
      var self = this;
      this.collection.fetch({
        success: function() {
          self.render();
        }
      });
    },

    toggleView: function() {
      $('#collectionsToggle').toggleClass('activated');
      $('#collectionsDropdown2').slideToggle(200);
    },

    checkBoxes: function (e) {
      //chrome bugfix
      var clicked = e.currentTarget.id;
      $('#'+clicked).click();
    },

    checkSystem: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeSystem;

      searchOptions.includeSystem = ($('#checkSystem').is(":checked") === true);

      if (oldValue !== searchOptions.includeSystem) {
        this.render();
      }
    },
    checkEdge: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeEdge;

      searchOptions.includeEdge = ($('#checkEdge').is(":checked") === true);

      if (oldValue !== searchOptions.includeEdge) {
        this.render();
      }
    },
    checkDocument: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeDocument;

      searchOptions.includeDocument = ($('#checkDocument').is(":checked") === true);

      if (oldValue !== searchOptions.includeDocument) {
        this.render();
      }
    },
    checkLoaded: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeLoaded;

      searchOptions.includeLoaded = ($('#checkLoaded').is(":checked") === true);

      if (oldValue !== searchOptions.includeLoaded) {
        this.render();
      }
    },
    checkUnloaded: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeUnloaded;

      searchOptions.includeUnloaded = ($('#checkUnloaded').is(":checked") === true);

      if (oldValue !== searchOptions.includeUnloaded) {
        this.render();
      }
    },
    sortName: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.sortBy;

      searchOptions.sortBy = (($('#sortName').is(":checked") === true) ? 'name' : 'type');
      if (oldValue !== searchOptions.sortBy) {
        this.render();
      }
    },
    sortType: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.sortBy;

      searchOptions.sortBy = (($('#sortType').is(":checked") === true) ? 'type' : 'name');
      if (oldValue !== searchOptions.sortBy) {
        this.render();
      }
    },
    sortOrder: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.sortOrder;

      searchOptions.sortOrder = (($('#sortOrder').is(":checked") === true) ? -1 : 1);
      if (oldValue !== searchOptions.sortOrder) {
        this.render();
      }
    },

    setFilterValues: function () {
      var searchOptions = this.collection.searchOptions;
      $('#checkLoaded').attr('checked', searchOptions.includeLoaded);
      $('#checkUnloaded').attr('checked', searchOptions.includeUnloaded);
      $('#checkSystem').attr('checked', searchOptions.includeSystem);
      $('#checkEdge').attr('checked', searchOptions.includeEdge);
      $('#checkDocument').attr('checked', searchOptions.includeDocument);
      $('#sortName').attr('checked', searchOptions.sortBy !== 'type');
      $('#sortType').attr('checked', searchOptions.sortBy === 'type');
      $('#sortOrder').attr('checked', searchOptions.sortOrder !== 1);
    },

    search: function () {
      var searchOptions = this.collection.searchOptions;
      var searchPhrase = $('#searchInput').val();
      if (searchPhrase === searchOptions.searchPhrase) {
        return;
      }
      searchOptions.searchPhrase = searchPhrase;

      this.render();
    },

    resetSearch: function () {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = null;
      }

      var searchOptions = this.collection.searchOptions;
      searchOptions.searchPhrase = null;
    },

    restrictToSearchPhraseKey: function (e) {
      // key pressed in search box
      var self = this;

      // force a new a search
      this.resetSearch();

      self.searchTimeout = setTimeout(function (){
        self.search();
      }, 200);
    },

    restrictToSearchPhrase: function () {
      // force a new a search
      this.resetSearch();

      // search executed
      this.search();
    },

    createCollection: function(e) {
      e.preventDefault();
      this.createNewCollectionModal();
    },

    submitCreateCollection: function() {
      var collName = $('#new-collection-name').val();
      var collSize = $('#new-collection-size').val();
      var collType = $('#new-collection-type').val();
      var collSync = $('#new-collection-sync').val();
      var shards = 1;
      var shardBy = [];
      if (window.isCoordinator()) {
        shards = $('#new-collection-shards').val();
        if (shards === "") {
          shards = 1;
        }
        shards = parseInt(shards, 10);
        if (shards < 1) {
          arangoHelper.arangoError(
            "Number of shards has to be an integer value greater or equal 1"
          );
          return 0;
        }
        shardBy = _.pluck($('#new-collection-shardBy').select2("data"), "text");
        if (shardBy.length === 0) {
          shardBy.push("_key");
        }
      }
      //no new system collections via webinterface
      //var isSystem = (collName.substr(0, 1) === '_');
      if (collName.substr(0, 1) === '_') {
        arangoHelper.arangoError('No "_" allowed as first character!');
        return 0;
      }
      var isSystem = false;
      var wfs = (collSync === "true");
      if (collSize > 0) {
        try {
          collSize = JSON.parse(collSize) * 1024 * 1024;
        }
        catch (e) {
          arangoHelper.arangoError('Please enter a valid number');
          return 0;
        }
      }
      if (collName === '') {
        arangoHelper.arangoError('No collection name entered!');
        return 0;
      }

      var returnobj = this.collection.newCollection(
        collName, wfs, isSystem, collSize, collType, shards, shardBy
      );
      if (returnobj.status !== true) {
        arangoHelper.arangoError(returnobj.errorMessage);
      }
      this.updateCollectionsView();
      window.modalView.hide();
    },

    createNewCollectionModal: function() {
      var buttons = [],
        tableContent = [],
        advanced = {},
        advancedTableContent = [];

      tableContent.push(
        window.modalView.createTextEntry(
          "new-collection-name",
          "Name",
          "",
          false,
          "",
          true,
          [
            {
              rule: Joi.string().regex(/^[a-zA-Z]/),
              msg: "Collection name must always start with a letter."
            },
            {
              rule: Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),
              msg: 'Only Symbols "_" and "-" are allowed.'
            },
            {
              rule: Joi.string().required(),
              msg: "No collection name given."
            }
          ]
        )
      );
      tableContent.push(
        window.modalView.createSelectEntry(
          "new-collection-type",
          "Type",
          "",
          "The type of the collection to create.",
          [{value: 2, label: "Document"}, {value: 3, label: "Edge"}]
        )
      );
      if (window.isCoordinator()) {
        tableContent.push(
          window.modalView.createTextEntry(
            "new-collection-shards",
            "Shards",
            "",
            "The number of shards to create. You cannot change this afterwards. "
              + "Recommended: DBServers squared",
            "",
            true
          )
        );
        tableContent.push(
          window.modalView.createSelect2Entry(
            "new-collection-shardBy",
            "shardBy",
            "",
            "The keys used to distribute documents on shards. "
              + "Type the key and press return to add it.",
            "_key",
            false
          )
        );
      }
      buttons.push(
        window.modalView.createSuccessButton(
          "Save",
          this.submitCreateCollection.bind(this)
        )
      );
      advancedTableContent.push(
        window.modalView.createTextEntry(
          "new-collection-size",
          "Journal size",
          "",
          "The maximal size of a journal or datafile (in MB). Must be at least 1.",
          "",
          false,
          [
            {
              rule: Joi.string().required(),
              msg: "No journal size given."
            },
            {
              rule: Joi.string().regex(/^[0-9]*$/),
              msg: "Must be a number."
            }
          ]
      )
      );
      advancedTableContent.push(
        window.modalView.createSelectEntry(
          "new-collection-sync",
          "Sync",
          "",
          "Synchronise to disk before returning from a create or update of a document.",
          [{value: false, label: "No"}, {value: true, label: "Yes"}]
        )
      );
      advanced.header = "Advanced";
      advanced.content = advancedTableContent;
      window.modalView.show(
        "modalTable.ejs",
        "New Collection",
        buttons,
        tableContent,
        advanced
      );
    }

  });
}());
<commit_msg>fixed cursor positioning in collections search<commit_after>/*jshint browser: true */
/*jshint unused: false */
/*global _, Backbone, templateEngine, window, setTimeout, clearTimeout, arangoHelper, Joi, $*/

(function() {
  "use strict";
  window.CollectionsView = Backbone.View.extend({
    el: '#content',
    el2: '#collectionsThumbnailsIn',

    searchTimeout: null,

    initialize: function () {
    },

    template: templateEngine.createTemplate("collectionsView.ejs"),

    render: function () {
      var dropdownVisible = false;
      if ($('#collectionsDropdown').is(':visible')) {
        dropdownVisible = true;
      }

      $(this.el).html(this.template.render({}));
      this.setFilterValues();

      if (dropdownVisible === true) {
        $('#collectionsDropdown2').show();
      }

      var searchOptions = this.collection.searchOptions;

      this.collection.getFiltered(searchOptions).forEach(function (arango_collection) {
        $('#collectionsThumbnailsIn', this.el).append(new window.CollectionListItemView({
          model: arango_collection,
          collectionsView: this
        }).render().el);
      }, this);

      //if type in collectionsDropdown2 is changed,
      //the page will be rerendered, so check the toggel button
      if($('#collectionsDropdown2').css('display') === 'none') {
        $('#collectionsToggle').removeClass('activated');

      } else {
        $('#collectionsToggle').addClass('activated');
      }

      var length = searchOptions.searchPhrase.length;
      $('#searchInput').val(searchOptions.searchPhrase);
      $('#searchInput').focus();
      $('#searchInput')[0].setSelectionRange(length, length);

      arangoHelper.fixTooltips(".icon_arangodb, .arangoicon", "left");

      return this;
    },

    events: {
      "click #createCollection"   : "createCollection",
      "keydown #searchInput"      : "restrictToSearchPhraseKey",
      "change #searchInput"       : "restrictToSearchPhrase",
      "click #searchSubmit"       : "restrictToSearchPhrase",
      "click #checkSystem"        : "checkSystem",
      "click #checkLoaded"        : "checkLoaded",
      "click #checkUnloaded"      : "checkUnloaded",
      "click #checkDocument"      : "checkDocument",
      "click #checkEdge"          : "checkEdge",
      "click #sortName"           : "sortName",
      "click #sortType"           : "sortType",
      "click #sortOrder"          : "sortOrder",
      "click #collectionsToggle"  : "toggleView",
      "click .css-label"          : "checkBoxes"
    },

    updateCollectionsView: function() {
      var self = this;
      this.collection.fetch({
        success: function() {
          self.render();
        }
      });
    },

    toggleView: function() {
      $('#collectionsToggle').toggleClass('activated');
      $('#collectionsDropdown2').slideToggle(200);
    },

    checkBoxes: function (e) {
      //chrome bugfix
      var clicked = e.currentTarget.id;
      $('#'+clicked).click();
    },

    checkSystem: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeSystem;

      searchOptions.includeSystem = ($('#checkSystem').is(":checked") === true);

      if (oldValue !== searchOptions.includeSystem) {
        this.render();
      }
    },
    checkEdge: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeEdge;

      searchOptions.includeEdge = ($('#checkEdge').is(":checked") === true);

      if (oldValue !== searchOptions.includeEdge) {
        this.render();
      }
    },
    checkDocument: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeDocument;

      searchOptions.includeDocument = ($('#checkDocument').is(":checked") === true);

      if (oldValue !== searchOptions.includeDocument) {
        this.render();
      }
    },
    checkLoaded: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeLoaded;

      searchOptions.includeLoaded = ($('#checkLoaded').is(":checked") === true);

      if (oldValue !== searchOptions.includeLoaded) {
        this.render();
      }
    },
    checkUnloaded: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.includeUnloaded;

      searchOptions.includeUnloaded = ($('#checkUnloaded').is(":checked") === true);

      if (oldValue !== searchOptions.includeUnloaded) {
        this.render();
      }
    },
    sortName: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.sortBy;

      searchOptions.sortBy = (($('#sortName').is(":checked") === true) ? 'name' : 'type');
      if (oldValue !== searchOptions.sortBy) {
        this.render();
      }
    },
    sortType: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.sortBy;

      searchOptions.sortBy = (($('#sortType').is(":checked") === true) ? 'type' : 'name');
      if (oldValue !== searchOptions.sortBy) {
        this.render();
      }
    },
    sortOrder: function () {
      var searchOptions = this.collection.searchOptions;
      var oldValue = searchOptions.sortOrder;

      searchOptions.sortOrder = (($('#sortOrder').is(":checked") === true) ? -1 : 1);
      if (oldValue !== searchOptions.sortOrder) {
        this.render();
      }
    },

    setFilterValues: function () {
      var searchOptions = this.collection.searchOptions;
      $('#checkLoaded').attr('checked', searchOptions.includeLoaded);
      $('#checkUnloaded').attr('checked', searchOptions.includeUnloaded);
      $('#checkSystem').attr('checked', searchOptions.includeSystem);
      $('#checkEdge').attr('checked', searchOptions.includeEdge);
      $('#checkDocument').attr('checked', searchOptions.includeDocument);
      $('#sortName').attr('checked', searchOptions.sortBy !== 'type');
      $('#sortType').attr('checked', searchOptions.sortBy === 'type');
      $('#sortOrder').attr('checked', searchOptions.sortOrder !== 1);
    },

    search: function () {
      var searchOptions = this.collection.searchOptions;
      var searchPhrase = $('#searchInput').val();
      if (searchPhrase === searchOptions.searchPhrase) {
        return;
      }
      searchOptions.searchPhrase = searchPhrase;

      this.render();
    },

    resetSearch: function () {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = null;
      }

      var searchOptions = this.collection.searchOptions;
      searchOptions.searchPhrase = null;
    },

    restrictToSearchPhraseKey: function (e) {
      // key pressed in search box
      var self = this;

      // force a new a search
      this.resetSearch();

      self.searchTimeout = setTimeout(function (){
        self.search();
      }, 200);
    },

    restrictToSearchPhrase: function () {
      // force a new a search
      this.resetSearch();

      // search executed
      this.search();
    },

    createCollection: function(e) {
      e.preventDefault();
      this.createNewCollectionModal();
    },

    submitCreateCollection: function() {
      var collName = $('#new-collection-name').val();
      var collSize = $('#new-collection-size').val();
      var collType = $('#new-collection-type').val();
      var collSync = $('#new-collection-sync').val();
      var shards = 1;
      var shardBy = [];
      if (window.isCoordinator()) {
        shards = $('#new-collection-shards').val();
        if (shards === "") {
          shards = 1;
        }
        shards = parseInt(shards, 10);
        if (shards < 1) {
          arangoHelper.arangoError(
            "Number of shards has to be an integer value greater or equal 1"
          );
          return 0;
        }
        shardBy = _.pluck($('#new-collection-shardBy').select2("data"), "text");
        if (shardBy.length === 0) {
          shardBy.push("_key");
        }
      }
      //no new system collections via webinterface
      //var isSystem = (collName.substr(0, 1) === '_');
      if (collName.substr(0, 1) === '_') {
        arangoHelper.arangoError('No "_" allowed as first character!');
        return 0;
      }
      var isSystem = false;
      var wfs = (collSync === "true");
      if (collSize > 0) {
        try {
          collSize = JSON.parse(collSize) * 1024 * 1024;
        }
        catch (e) {
          arangoHelper.arangoError('Please enter a valid number');
          return 0;
        }
      }
      if (collName === '') {
        arangoHelper.arangoError('No collection name entered!');
        return 0;
      }

      var returnobj = this.collection.newCollection(
        collName, wfs, isSystem, collSize, collType, shards, shardBy
      );
      if (returnobj.status !== true) {
        arangoHelper.arangoError(returnobj.errorMessage);
      }
      this.updateCollectionsView();
      window.modalView.hide();
    },

    createNewCollectionModal: function() {
      var buttons = [],
        tableContent = [],
        advanced = {},
        advancedTableContent = [];

      tableContent.push(
        window.modalView.createTextEntry(
          "new-collection-name",
          "Name",
          "",
          false,
          "",
          true,
          [
            {
              rule: Joi.string().regex(/^[a-zA-Z]/),
              msg: "Collection name must always start with a letter."
            },
            {
              rule: Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),
              msg: 'Only Symbols "_" and "-" are allowed.'
            },
            {
              rule: Joi.string().required(),
              msg: "No collection name given."
            }
          ]
        )
      );
      tableContent.push(
        window.modalView.createSelectEntry(
          "new-collection-type",
          "Type",
          "",
          "The type of the collection to create.",
          [{value: 2, label: "Document"}, {value: 3, label: "Edge"}]
        )
      );
      if (window.isCoordinator()) {
        tableContent.push(
          window.modalView.createTextEntry(
            "new-collection-shards",
            "Shards",
            "",
            "The number of shards to create. You cannot change this afterwards. "
              + "Recommended: DBServers squared",
            "",
            true
          )
        );
        tableContent.push(
          window.modalView.createSelect2Entry(
            "new-collection-shardBy",
            "shardBy",
            "",
            "The keys used to distribute documents on shards. "
              + "Type the key and press return to add it.",
            "_key",
            false
          )
        );
      }
      buttons.push(
        window.modalView.createSuccessButton(
          "Save",
          this.submitCreateCollection.bind(this)
        )
      );
      advancedTableContent.push(
        window.modalView.createTextEntry(
          "new-collection-size",
          "Journal size",
          "",
          "The maximal size of a journal or datafile (in MB). Must be at least 1.",
          "",
          false,
          [
            {
              rule: Joi.string().required(),
              msg: "No journal size given."
            },
            {
              rule: Joi.string().regex(/^[0-9]*$/),
              msg: "Must be a number."
            }
          ]
      )
      );
      advancedTableContent.push(
        window.modalView.createSelectEntry(
          "new-collection-sync",
          "Sync",
          "",
          "Synchronise to disk before returning from a create or update of a document.",
          [{value: false, label: "No"}, {value: true, label: "Yes"}]
        )
      );
      advanced.header = "Advanced";
      advanced.content = advancedTableContent;
      window.modalView.show(
        "modalTable.ejs",
        "New Collection",
        buttons,
        tableContent,
        advanced
      );
    }

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


<commit_before>// Bretton Wade 2015.12.07
// brettonw/include.js
// Node.js has a module import system, but sometimes I just want to include another file
// at the global scope...
//
// Usage:
//   require("namespace-include");
//     .addPath ("/usr/local/js")
//     .include ("myfile");

// all of my dependencies, these SHOULD all be built-ins. note that I use the _xxx naming
// convention to avoid polluting my script namespace with these basic words.
var _fs = require ("fs");
var _vm = require ("vm");
var _path = require ("path");
var _url = require ("url");
var _http = require ("http");
var _getSync = require ("get-sync");
var _cp = require ("child_process");

// INTERNAL FUNCTIONS

// searchPath - internal function to search for <target> within <path>, using breadth
//      first recursion, in file sorted order so the first one found wins
var searchPath = function (path, target) {
    var found = null;

    // search through the file list and queue up directories for later
    var directories = [];
    _fs.readdirSync (path).sort ().some (function (leaf) {
        var leafPath = _path.join (path, leaf);
        if (leaf.toLowerCase () == target) {
            found = leafPath;
        } else if (_fs.statSync (leafPath).isDirectory ()) {
            directories.push (leafPath);
        }
        return (found);
    });

    // if we didn't find it, search through the directories
    if ((! found) && (directories.length > 0)) {
        found = searchPaths (directories, target);
    }

    // return what we got
    return found;
};

// searchPaths - internal function to search all the <paths> for <target>
var searchPaths = function (paths, target) {
    var found = null;
process.stderr.write ("searchPaths (Paths[0] = " + paths[0] + ")\n");

    // walk over all of the paths
    paths.some (function (path) {
        found = searchPath (path, target);
        return (found != null);
    });

    return found;
};

// fileExists - internal helper function because the Node.js "fs" package has
// deprecated the "exists" method, and the "approved" async way of getting stat throws
// an exception if the file doesn't exist (who is responsible for the API design here?
// amateur much?)
var fileExists = function (path) {
    try {
        var stats = _fs.statSync (path);
        return true;
    }
    catch (exc) {
    }
    return false;
};

// ensureDirectory - internal helper function because I always have to do the same operation
var ensureDirectory = function (path) {
    if (! fileExists (path)) { _fs.mkdirSync(path); }
}

// removeDirectory - internal helper to recursively remove a folder
var removeDirectory = function (path) {
    _fs.readdirSync (path).sort ().forEach (function (leaf) {
        var leafPath = _path.join (path, leaf);
        if (_fs.statSync(leafPath).isDirectory()) {
            removeDirectory(leafPath);
        } else {
            _fs.unlinkSync(leafPath);
        }
    });
    _fs.rmdirSync(path);
};

// fetchIf - an internal helper function to synchronously fetch a file from <url> and
// save it to <path>, if it's not already there (or <force> is true)
var fetchIf = function (url, path, force) {
    // if it's not already cached, try to fetch it - I launch this as a child process
    // (sync) to ensure sequential operation without forcing the end user to respond
    // to my callback, and without adding ridiculous dependencies. Ah, the joys of
    // API design.
    if (force && fileExists (path)) {
        _fs.unlinkSync(path);
    }
    if (! fileExists (path)) {
        _getSync (url, path);
    }
}

// NAMESPACE

// define the Namespace object
var Namespace = function () {
    var $ = Object.create (null);

    // setVerbose - turn debugging output (to stderr) on or off
    $.setVerbose = function (verbose) {
        if (this.verbose) { process.stderr.write ("setVerbose: " + (verbose ? "true" : "false") + "\n"); }
        this.verbose = verbose;
        if (this.verbose) { process.stderr.write ("setVerbose: " + (verbose ? "true" : "false") + "\n"); }
        return this;
    };

    // setPath - reset the list of search paths to just <path>
    $.setPath = function (path) {
        if (this.verbose) { process.stderr.write ("setPath: " + path + "\n"); }
        this.paths = [ path ];
        return this;
    };

    // addPath - append <path> to the list of search paths
    $.addPath = function (path) {
        if (this.verbose) { process.stderr.write ("addPath: " + path + "\n"); }
        this.paths.push (path);
        return this;
    };

    // includeFile - directly run the <name> in the global namespace
    $.includeFile = function (name) {
        if (this.verbose) { process.stderr.write ("includeFile: " + name + "\n"); }
        _vm.runInThisContext(_fs.readFileSync(name));
        return this;
    };

    // includePackage - open a "package" (a directory) at <path> and include the
    //      files within. If there is a namespace-package.json file, it is parsed and
    //      honored, otherwise all .js files at the top level of the package directory
    //      are included
    $.includePackage = function (path) {
        if (this.verbose) { process.stderr.write ("includePackage: " + path + "\n"); }
        if (fileExists (path)) {
            var scope = this;
            var package = _path.join (path, "namespace-package.json");
            if (fileExists (package)) {
                try {
                    package = JSON.parse(_fs.readFileSync(package, "utf8"));
                    if ((package != null) && (package.hasOwnProperty ("files"))) {
                        package.files.forEach (function (leaf) {
                            scope.includeFile (_path.join (path, leaf));
                        });
                    }
                } catch (exc) { }
            } else {
                // the javascript files are treated in sorted order
                _fs.readdirSync (path).sort ().forEach (function (leaf) {
                    if (_path.extname (leaf) == ".js") {
                        scope.includeFile (_path.join (path, leaf));
                    }
                });
            }
        } else {
            process.stderr.write ("includePackage '" + path + "' does not exist\n");
        }
        return this;
    };

    // include - find <name> within the search paths and include it. if the found entity
    //      is a directory, it is loaded as a package. if no result is found, then <name>
    //      is decorated as a .js file, and the search is repeated
    $.include = function (name) {
        if (this.verbose) { process.stderr.write ("include: " + name + "\n"); }

        // first, find the target using <name> as given. if that fails (and <name> wasn't
        // already a .js file), try looking for <name>.js
        name = name.toLowerCase ();
        var found = searchPaths (this.paths, name);
        var parse = _path.parse (name);
        if ((! found) && (parse.ext != ".js")) {
            found = searchPaths (this.paths, parse.name + ".js");
        }

        // if we found it, include it
        if (found) {
            if (_fs.statSync (found).isDirectory ()) {
                this.includePackage (found);
            } else {
                this.includeFile (found);
            }
        } else {
            process.stderr.write ("Failed to include '" + name + "'\n");
        }
        return this;
    };

    // importUrl - download a package from <url> and unpack it into the namespace-cache
    //      downloads are skipped if the package is already present in the cache, unless
    //      the optional parameter <force> is true
    $.importUrl = function (url, force) {
        if (force === undefined) { force = false; }
        if (this.verbose) { process.stderr.write ("importUrl: " + url + ", force: " + (force ? "true" : "false") + "\n"); }

        ensureDirectory (this.cacheFolderName);

        // take apart the url to get the target name, and the end package name. regardless
        // of whether the import target is a raw file or a compressed package, we import
        // it as a package folder
        var parse = _url.parse (url);
        var name = parse.pathname.split ("/").pop ();
        var ext = _path.extname (name).toLowerCase ();
        var path = _path.join (this.cacheFolderName, name);
        var package = path.substr (0, path.length - ext.length);

        // depending on the url target, we have to configure the result differently
        switch (ext) {
            case ".js": {
                ensureDirectory (package);
                path = _path.join (package, name);
                fetchIf (url, path, force);
                break;
            }
            case ".tgz": {
                fetchIf (url, path, force);
                if (force && fileExists (package)) {
                    removeDirectory (package);
                }
                if (! fileExists (package)) {
                    var cwd = process.cwd ();
                    process.chdir(this.cacheFolderName);
                    var options = this.verbose ? { stdio: ["ignore", 1, 2] } : {};
                    _cp.spawnSync("tar", ["xvf", path], options);
                    process.chdir(cwd);
                }
                break;
            }
            default: {
                process.stderr.write ("Bogus extension = " + path + " (" + _path.extname (path) + ")");
                break;
            }
        }

        // and finally, if we have everything we need, include it like normal
        this.includePackage (package);
        return this;
    };

    // setHost - use <host> as the default download site for importing packages
    $.setHost = function (host) {
        if (this.verbose) { process.stderr.write ("setHost: " + host + "\n"); }
        this.host = host;
        return this;
    }

    // import - this is a convenience method to make import calls look cleaner. it will
    //      download <name> from the host and unpack it as a normal URL import. download
    //      will be skipped if the package is already present, unless <force> is true.
    //      packages from the host must be .tgz files
    $.import = function (name, force) {
        if (force === undefined) { force = false; }
        if (this.verbose) { process.stderr.write ("import: " + name + "\n"); }

        // use the name to make the url and target path
        name = name.toLowerCase ();
        var parse = _path.parse (name);
        name = (parse.ext == ".tgz") ? name.substr (0, name.length - parse.ext.length) : name;
        var url = this.host + name + ".tgz";

        // try to import the url
        return this.importUrl (url, force);
    };

    // clearCache - empty out the cached imports
    $.clearCache = function () {
        if (this.verbose) { process.stderr.write ("clearCache\n"); }
        removeDirectory (this.cacheFolderName);
        ensureDirectory (this.cacheFolderName);
        return this;
    };

    // publish - hoist a package to the archive
    $.publish = function () {
        // take a target - directory or js file, tar and gzip it, push it to the host
    };

    // new - a helper function. you probably don't need this.
    $.new = function () {
        // create the cache folder name
        this.cacheFolderName = _path.join (_path.parse (require.main.filename).dir, "namespace-cache");

        // create the namespace and set the defaults
        return Object.create (Namespace)
            .setVerbose (false)
            .setPath (_path.parse (require.main.filename).dir)
            .setHost ("http://namespace-include.azurewebsites.net/package/");
    };

    $.bootstrap = function () {
        var path = _path.join (__dirname, "bootstrap.js");
        return this.includeFile (path);
    }

    return $;
} ();

// and export a usable namespace
module.exports = Namespace.new ();

// in order to let "included" files use the "require" mechanism, I have to hoist the name
// into the global space. this doesn't seem to cause any problems in my testing so far
global.require = module.require;
<commit_msg>remove debug output<commit_after>// Bretton Wade 2015.12.07
// brettonw/include.js
// Node.js has a module import system, but sometimes I just want to include another file
// at the global scope...
//
// Usage:
//   require("namespace-include");
//     .addPath ("/usr/local/js")
//     .include ("myfile");

// all of my dependencies, these SHOULD all be built-ins. note that I use the _xxx naming
// convention to avoid polluting my script namespace with these basic words.
var _fs = require ("fs");
var _vm = require ("vm");
var _path = require ("path");
var _url = require ("url");
var _http = require ("http");
var _getSync = require ("get-sync");
var _cp = require ("child_process");

// INTERNAL FUNCTIONS

// searchPath - internal function to search for <target> within <path>, using breadth
//      first recursion, in file sorted order so the first one found wins
var searchPath = function (path, target) {
    var found = null;

    // search through the file list and queue up directories for later
    var directories = [];
    _fs.readdirSync (path).sort ().some (function (leaf) {
        var leafPath = _path.join (path, leaf);
        if (leaf.toLowerCase () == target) {
            found = leafPath;
        } else if (_fs.statSync (leafPath).isDirectory ()) {
            directories.push (leafPath);
        }
        return (found);
    });

    // if we didn't find it, search through the directories
    if ((! found) && (directories.length > 0)) {
        found = searchPaths (directories, target);
    }

    // return what we got
    return found;
};

// searchPaths - internal function to search all the <paths> for <target>
var searchPaths = function (paths, target) {
    var found = null;

    // walk over all of the paths
    paths.some (function (path) {
        found = searchPath (path, target);
        return (found != null);
    });

    return found;
};

// fileExists - internal helper function because the Node.js "fs" package has
// deprecated the "exists" method, and the "approved" async way of getting stat throws
// an exception if the file doesn't exist (who is responsible for the API design here?
// amateur much?)
var fileExists = function (path) {
    try {
        var stats = _fs.statSync (path);
        return true;
    }
    catch (exc) {
    }
    return false;
};

// ensureDirectory - internal helper function because I always have to do the same operation
var ensureDirectory = function (path) {
    if (! fileExists (path)) { _fs.mkdirSync(path); }
}

// removeDirectory - internal helper to recursively remove a folder
var removeDirectory = function (path) {
    _fs.readdirSync (path).sort ().forEach (function (leaf) {
        var leafPath = _path.join (path, leaf);
        if (_fs.statSync(leafPath).isDirectory()) {
            removeDirectory(leafPath);
        } else {
            _fs.unlinkSync(leafPath);
        }
    });
    _fs.rmdirSync(path);
};

// fetchIf - an internal helper function to synchronously fetch a file from <url> and
// save it to <path>, if it's not already there (or <force> is true)
var fetchIf = function (url, path, force) {
    // if it's not already cached, try to fetch it - I launch this as a child process
    // (sync) to ensure sequential operation without forcing the end user to respond
    // to my callback, and without adding ridiculous dependencies. Ah, the joys of
    // API design.
    if (force && fileExists (path)) {
        _fs.unlinkSync(path);
    }
    if (! fileExists (path)) {
        _getSync (url, path);
    }
}

// NAMESPACE

// define the Namespace object
var Namespace = function () {
    var $ = Object.create (null);

    // setVerbose - turn debugging output (to stderr) on or off
    $.setVerbose = function (verbose) {
        if (this.verbose) { process.stderr.write ("setVerbose: " + (verbose ? "true" : "false") + "\n"); }
        this.verbose = verbose;
        if (this.verbose) { process.stderr.write ("setVerbose: " + (verbose ? "true" : "false") + "\n"); }
        return this;
    };

    // setPath - reset the list of search paths to just <path>
    $.setPath = function (path) {
        if (this.verbose) { process.stderr.write ("setPath: " + path + "\n"); }
        this.paths = [ path ];
        return this;
    };

    // addPath - append <path> to the list of search paths
    $.addPath = function (path) {
        if (this.verbose) { process.stderr.write ("addPath: " + path + "\n"); }
        this.paths.push (path);
        return this;
    };

    // includeFile - directly run the <name> in the global namespace
    $.includeFile = function (name) {
        if (this.verbose) { process.stderr.write ("includeFile: " + name + "\n"); }
        _vm.runInThisContext(_fs.readFileSync(name));
        return this;
    };

    // includePackage - open a "package" (a directory) at <path> and include the
    //      files within. If there is a namespace-package.json file, it is parsed and
    //      honored, otherwise all .js files at the top level of the package directory
    //      are included
    $.includePackage = function (path) {
        if (this.verbose) { process.stderr.write ("includePackage: " + path + "\n"); }
        if (fileExists (path)) {
            var scope = this;
            var package = _path.join (path, "namespace-package.json");
            if (fileExists (package)) {
                try {
                    package = JSON.parse(_fs.readFileSync(package, "utf8"));
                    if ((package != null) && (package.hasOwnProperty ("files"))) {
                        package.files.forEach (function (leaf) {
                            scope.includeFile (_path.join (path, leaf));
                        });
                    }
                } catch (exc) { }
            } else {
                // the javascript files are treated in sorted order
                _fs.readdirSync (path).sort ().forEach (function (leaf) {
                    if (_path.extname (leaf) == ".js") {
                        scope.includeFile (_path.join (path, leaf));
                    }
                });
            }
        } else {
            process.stderr.write ("includePackage '" + path + "' does not exist\n");
        }
        return this;
    };

    // include - find <name> within the search paths and include it. if the found entity
    //      is a directory, it is loaded as a package. if no result is found, then <name>
    //      is decorated as a .js file, and the search is repeated
    $.include = function (name) {
        if (this.verbose) { process.stderr.write ("include: " + name + "\n"); }

        // first, find the target using <name> as given. if that fails (and <name> wasn't
        // already a .js file), try looking for <name>.js
        name = name.toLowerCase ();
        var found = searchPaths (this.paths, name);
        var parse = _path.parse (name);
        if ((! found) && (parse.ext != ".js")) {
            found = searchPaths (this.paths, parse.name + ".js");
        }

        // if we found it, include it
        if (found) {
            if (_fs.statSync (found).isDirectory ()) {
                this.includePackage (found);
            } else {
                this.includeFile (found);
            }
        } else {
            process.stderr.write ("Failed to include '" + name + "'\n");
        }
        return this;
    };

    // importUrl - download a package from <url> and unpack it into the namespace-cache
    //      downloads are skipped if the package is already present in the cache, unless
    //      the optional parameter <force> is true
    $.importUrl = function (url, force) {
        if (force === undefined) { force = false; }
        if (this.verbose) { process.stderr.write ("importUrl: " + url + ", force: " + (force ? "true" : "false") + "\n"); }

        ensureDirectory (this.cacheFolderName);

        // take apart the url to get the target name, and the end package name. regardless
        // of whether the import target is a raw file or a compressed package, we import
        // it as a package folder
        var parse = _url.parse (url);
        var name = parse.pathname.split ("/").pop ();
        var ext = _path.extname (name).toLowerCase ();
        var path = _path.join (this.cacheFolderName, name);
        var package = path.substr (0, path.length - ext.length);

        // depending on the url target, we have to configure the result differently
        switch (ext) {
            case ".js": {
                ensureDirectory (package);
                path = _path.join (package, name);
                fetchIf (url, path, force);
                break;
            }
            case ".tgz": {
                fetchIf (url, path, force);
                if (force && fileExists (package)) {
                    removeDirectory (package);
                }
                if (! fileExists (package)) {
                    var cwd = process.cwd ();
                    process.chdir(this.cacheFolderName);
                    var options = this.verbose ? { stdio: ["ignore", 1, 2] } : {};
                    _cp.spawnSync("tar", ["xvf", path], options);
                    process.chdir(cwd);
                }
                break;
            }
            default: {
                process.stderr.write ("Bogus extension = " + path + " (" + _path.extname (path) + ")");
                break;
            }
        }

        // and finally, if we have everything we need, include it like normal
        this.includePackage (package);
        return this;
    };

    // setHost - use <host> as the default download site for importing packages
    $.setHost = function (host) {
        if (this.verbose) { process.stderr.write ("setHost: " + host + "\n"); }
        this.host = host;
        return this;
    }

    // import - this is a convenience method to make import calls look cleaner. it will
    //      download <name> from the host and unpack it as a normal URL import. download
    //      will be skipped if the package is already present, unless <force> is true.
    //      packages from the host must be .tgz files
    $.import = function (name, force) {
        if (force === undefined) { force = false; }
        if (this.verbose) { process.stderr.write ("import: " + name + "\n"); }

        // use the name to make the url and target path
        name = name.toLowerCase ();
        var parse = _path.parse (name);
        name = (parse.ext == ".tgz") ? name.substr (0, name.length - parse.ext.length) : name;
        var url = this.host + name + ".tgz";

        // try to import the url
        return this.importUrl (url, force);
    };

    // clearCache - empty out the cached imports
    $.clearCache = function () {
        if (this.verbose) { process.stderr.write ("clearCache\n"); }
        removeDirectory (this.cacheFolderName);
        ensureDirectory (this.cacheFolderName);
        return this;
    };

    // publish - hoist a package to the archive
    $.publish = function () {
        // take a target - directory or js file, tar and gzip it, push it to the host
    };

    // new - a helper function. you probably don't need this.
    $.new = function () {
        // create the cache folder name
        this.cacheFolderName = _path.join (_path.parse (require.main.filename).dir, "namespace-cache");

        // create the namespace and set the defaults
        return Object.create (Namespace)
            .setVerbose (false)
            .setPath (_path.parse (require.main.filename).dir)
            .setHost ("http://namespace-include.azurewebsites.net/package/");
    };

    $.bootstrap = function () {
        var path = _path.join (__dirname, "bootstrap.js");
        return this.includeFile (path);
    }

    return $;
} ();

// and export a usable namespace
module.exports = Namespace.new ();

// in order to let "included" files use the "require" mechanism, I have to hoist the name
// into the global space. this doesn't seem to cause any problems in my testing so far
global.require = module.require;
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('promort.viewer.services')
        .factory('ViewerService', ViewerService)
        .factory('AnnotationsViewerService', AnnotationsViewerService);

    ViewerService.$inject = ['$http'];

    function ViewerService($http) {
        var ViewerService = {
            getOMEBaseURLs: getOMEBaseURLs,
            getSlideInfo: getSlideInfo
        };

        return ViewerService;

        function getOMEBaseURLs() {
            return $http.get('api/utils/omeseadragon_base_urls/');
        }

        function getSlideInfo(slide_id) {
            return $http.get('api/slides/' + slide_id + '/');
        }
    }

    function AnnotationsViewerService() {
        var AnnotationsViewerService = {
            registerComponents: registerComponents,
            checkComponents: checkComponents,
            drawShape: drawShape,
            extendPolygonConfig: extendPolygonConfig,
            startPolygonsTool: startPolygonsTool,
            disableActiveTool: disableActiveTool,
            saveTemporaryPolygon: saveTemporaryPolygon,
            clearTemporaryPolygon: clearTemporaryPolygon,
            startFreehandDrawingTool: startFreehandDrawingTool,
            setFreehandToolLabelPrefix: setFreehandToolLabelPrefix,
            deleteShape: deleteShape,
            clear: clear,
            deleteShapes: deleteShapes,
            getCanvasLabel: getCanvasLabel,
            getShapeJSON: getShapeJSON,
            getShapeArea: getShapeArea,
            focusOnShape: focusOnShape,
        };

        return AnnotationsViewerService;

        function registerComponents(viewer_manager, rois_manager, tools_manager) {
            this.viewerManager = viewer_manager;
            this.roisManager = rois_manager;
            this.toolsManager = tools_manager;
        }

        function checkComponents() {
            console.log('Viewer Manager: ' + this.viewerManager);
            console.log('ROIs Manager: ' + this.roisManager);
            console.log('Tools Manager: ' + this.toolsManager);
        }

        function drawShape(shape_json) {
            this.roisManager.drawShapeFromJSON(shape_json);
        }

        function extendPolygonConfig(polygon_config) {
            this.roisManager.extendPolygonConfig(polygon_config);
        }

        function startPolygonsTool() {
            this.toolsManager.activateTool(AnnotationsEventsController.POLYGON_DRAWING_TOOL);
        }

        function disableActiveTool() {
            this.roisManager.disableMouseEvents();
        }

        function saveTemporaryPolygon(label_prefix) {
            console.log('Saving temporary polygon');
            this.roisManager.saveTemporaryPolygon(label_prefix);
        }

        function clearTemporaryPolygon() {
            this.roisManager.clearTemporaryPolygon();
        }

        function startFreehandDrawingTool() {
            this.toolsManager.activateTool(AnnotationsEventsController.FREEHAND_DRAWING_TOOL);
        }

        function setFreehandToolLabelPrefix(label_prefix) {
            this.roisManager.setFreehandPathLabelPrefix(label_prefix);
        }

        function deleteShape(shape_id) {
            this.roisManager.deleteShape(shape_id);
        }

        function clear() {
            this.roisManager.clear();
        }

        function deleteShapes(shapes_id) {
            this.roisManager.deleteShapes(shapes_id);
        }

        function getCanvasLabel() {
            return this.roisManager.canvas_id;
        }

        function getShapeJSON(shape_id) {
            return this.roisManager.getShapeJSON(shape_id);
        }

        function getShapeArea(shape_id) {
            return this.roisManager.getShapeDimensions(shape_id).area;
        }

        function focusOnShape(shape_id) {
            this.viewerManager.jumpToShape(shape_id, true);
        }
    }
})();<commit_msg>check if a shape is fully contained in another one<commit_after>(function () {
    'use strict';

    angular
        .module('promort.viewer.services')
        .factory('ViewerService', ViewerService)
        .factory('AnnotationsViewerService', AnnotationsViewerService);

    ViewerService.$inject = ['$http'];

    function ViewerService($http) {
        var ViewerService = {
            getOMEBaseURLs: getOMEBaseURLs,
            getSlideInfo: getSlideInfo
        };

        return ViewerService;

        function getOMEBaseURLs() {
            return $http.get('api/utils/omeseadragon_base_urls/');
        }

        function getSlideInfo(slide_id) {
            return $http.get('api/slides/' + slide_id + '/');
        }
    }

    function AnnotationsViewerService() {
        var AnnotationsViewerService = {
            registerComponents: registerComponents,
            checkComponents: checkComponents,
            drawShape: drawShape,
            extendPolygonConfig: extendPolygonConfig,
            startPolygonsTool: startPolygonsTool,
            disableActiveTool: disableActiveTool,
            saveTemporaryPolygon: saveTemporaryPolygon,
            clearTemporaryPolygon: clearTemporaryPolygon,
            startFreehandDrawingTool: startFreehandDrawingTool,
            setFreehandToolLabelPrefix: setFreehandToolLabelPrefix,
            deleteShape: deleteShape,
            clear: clear,
            deleteShapes: deleteShapes,
            getCanvasLabel: getCanvasLabel,
            getShapeJSON: getShapeJSON,
            getShapeArea: getShapeArea,
            focusOnShape: focusOnShape,
            checkContainment: checkContainment,
        };

        return AnnotationsViewerService;

        function registerComponents(viewer_manager, rois_manager, tools_manager) {
            this.viewerManager = viewer_manager;
            this.roisManager = rois_manager;
            this.toolsManager = tools_manager;
        }

        function checkComponents() {
            console.log('Viewer Manager: ' + this.viewerManager);
            console.log('ROIs Manager: ' + this.roisManager);
            console.log('Tools Manager: ' + this.toolsManager);
        }

        function drawShape(shape_json) {
            this.roisManager.drawShapeFromJSON(shape_json);
        }

        function extendPolygonConfig(polygon_config) {
            this.roisManager.extendPolygonConfig(polygon_config);
        }

        function startPolygonsTool() {
            this.toolsManager.activateTool(AnnotationsEventsController.POLYGON_DRAWING_TOOL);
        }

        function disableActiveTool() {
            this.roisManager.disableMouseEvents();
        }

        function saveTemporaryPolygon(label_prefix) {
            console.log('Saving temporary polygon');
            this.roisManager.saveTemporaryPolygon(label_prefix);
        }

        function clearTemporaryPolygon() {
            this.roisManager.clearTemporaryPolygon();
        }

        function startFreehandDrawingTool() {
            this.toolsManager.activateTool(AnnotationsEventsController.FREEHAND_DRAWING_TOOL);
        }

        function setFreehandToolLabelPrefix(label_prefix) {
            this.roisManager.setFreehandPathLabelPrefix(label_prefix);
        }

        function deleteShape(shape_id) {
            this.roisManager.deleteShape(shape_id);
        }

        function clear() {
            this.roisManager.clear();
        }

        function deleteShapes(shapes_id) {
            this.roisManager.deleteShapes(shapes_id);
        }

        function getCanvasLabel() {
            return this.roisManager.canvas_id;
        }

        function getShapeJSON(shape_id) {
            return this.roisManager.getShapeJSON(shape_id);
        }

        function getShapeArea(shape_id) {
            return this.roisManager.getShapeDimensions(shape_id).area;
        }

        function focusOnShape(shape_id) {
            this.viewerManager.jumpToShape(shape_id, true);
        }

        function checkContainment(container_label, contained_label) {
            console.log('Getting shape ' + container_label);
            var container = this.roisManager.getShape(container_label);
            console.log(container);
            var contained = this.roisManager.getShape(contained_label);
            console.log('Shape is contained in ' + container_label +'? : ' + container.containsShape(contained));
            return container.containsShape(contained);
        }
    }
})();<|endoftext|>


<commit_before>import { Component } from 'preact'
import { throwError } from 'cerebral'
import { DEPRECATE } from 'cerebral/internal'

class Container extends Component {
  getChildContext() {
    const { app, controller } = this.props

    if (controller) {
      DEPRECATE(
        'Container',
        'please change from "controller" to "app" property'
      )
    }

    if (!app && !controller) {
      throwError('You are not passing a Cerebral app to Container')
    }

    return { controller: app || controller }
  }
  render(props) {
    return props.children[0]
  }
}

export default Container
<commit_msg>fix(preact): support new Preact<commit_after>import { throwError } from 'cerebral'
import { DEPRECATE } from 'cerebral/internal'
import { Component } from 'preact'

class Container extends Component {
  getChildContext() {
    const { app, controller } = this.props

    if (controller) {
      DEPRECATE(
        'Container',
        'please change from "controller" to "app" property'
      )
    }

    if (!app && !controller) {
      throwError('You are not passing a Cerebral app to Container')
    }

    return { controller: app || controller }
  }

  render(props) {
    return props.children[0] || props.children
  }
}

export default Container
<|endoftext|>


<commit_before>/* eslint-disable security/detect-non-literal-fs-filename */
const chai = require('chai')
const sinon = require('sinon')
const { globalErrorHandler, handleStrategyError, StrategyError } = require('../server/utils/error-handler.js')
const config = require('config')

const assert = chai.assert
const expect = chai.expect

describe('error-handler.js test', () => {
  it('globalErrorHandler should exist', () => {
    assert.exists(globalErrorHandler)
  })

  it('globalErrorHandler should be function', () => {
    assert.isFunction(globalErrorHandler)
  })

  it('globalErrorHandler should redirect to login page', () => {
    const res = {
      redirect: sinon.spy()
    }

    globalErrorHandler({ stack: 'fake' }, {}, res, {})
    const failureRedirectUrl = config.get('passportConfig.failureRedirectUrl')
    expect(res.redirect.calledOnce).to.be.true
    expect(res.redirect.firstCall.args[0]).to.equal(
      `${failureRedirectUrl}?failure=An error occurred`
    )
  })

  it('StrategyError should exist', () => {
    assert.exists(StrategyError)
  })

  it('StrategyError should be function', () => {
    assert.isFunction(StrategyError)
  })

  describe('handleStrategyError', () => {
    it('should exist importable', () => {
      expect(handleStrategyError).to.exist()
    })

    it('should throw StrategyError with req.flash message', () => {
      const errorMessage = 'StrategyError: A valid strategy error message'

      const requestStub = {
        flash: (type, msg) => {
          return errorMessage
        }
      }

      const responseStub = () => {
        const res = {}
        res.status = sinon.stub().returns(res)
        res.json = sinon.stub().returns(res)
        return res
      }
      expect(
        () => {
          handleStrategyError(requestStub, responseStub())
        }
      ).to.throw()

      expect(
        () => {
          handleStrategyError(requestStub, responseStub())
        }
      ).to.throw(StrategyError)

      expect(
        () => {
          handleStrategyError(requestStub, responseStub())
        }
      ).to.throw(StrategyError, errorMessage)
    })

    it('should not throw if req.flash error does not exist', () => {
    // implement test after all tests above passes, then code.
      assert.fail('Not implemented')
    })
  })
})
<commit_msg>test(error-handler): rename test description<commit_after>/* eslint-disable security/detect-non-literal-fs-filename */
const chai = require('chai')
const sinon = require('sinon')
const { globalErrorHandler, handleStrategyError, StrategyError } = require('../server/utils/error-handler.js')
const config = require('config')

const assert = chai.assert
const expect = chai.expect

describe('error-handler.js test', () => {
  it('globalErrorHandler should exist', () => {
    assert.exists(globalErrorHandler)
  })

  it('globalErrorHandler should be function', () => {
    assert.isFunction(globalErrorHandler)
  })

  it('globalErrorHandler should call redirect with expected args', () => {
    const res = {
      redirect: sinon.spy()
    }

    globalErrorHandler({ stack: 'fake' }, {}, res, {})
    const failureRedirectUrl = config.get('passportConfig.failureRedirectUrl')
    expect(res.redirect.calledOnce).to.be.true
    expect(res.redirect.firstCall.args[0]).to.equal(
      `${failureRedirectUrl}?failure=An error occurred`
    )
  })

  it('StrategyError should exist', () => {
    assert.exists(StrategyError)
  })

  it('StrategyError should be function', () => {
    assert.isFunction(StrategyError)
  })

  describe('handleStrategyError', () => {
    it('should exist importable', () => {
      expect(handleStrategyError).to.exist()
    })

    it('should throw StrategyError with req.flash message', () => {
      const errorMessage = 'StrategyError: A valid strategy error message'

      const requestStub = {
        flash: (type, msg) => {
          return errorMessage
        }
      }

      const responseStub = () => {
        const res = {}
        res.status = sinon.stub().returns(res)
        res.json = sinon.stub().returns(res)
        return res
      }
      expect(
        () => {
          handleStrategyError(requestStub, responseStub())
        }
      ).to.throw()

      expect(
        () => {
          handleStrategyError(requestStub, responseStub())
        }
      ).to.throw(StrategyError)

      expect(
        () => {
          handleStrategyError(requestStub, responseStub())
        }
      ).to.throw(StrategyError, errorMessage)
    })

    it('should not throw if req.flash error does not exist', () => {
    // implement test after all tests above passes, then code.
      assert.fail('Not implemented')
    })
  })
})
<|endoftext|>


<commit_before>/* global malarkey:false, moment:false */
(function() {
  'use strict';

  angular
    .module('vizbox')
    .constant('malarkey', malarkey)
    .constant('moment', moment)
    .constant('c3', c3);

})();
<commit_msg>remove unnecessary `malarkey` #2<commit_after>/* global malarkey:false, moment:false */
(function() {
  'use strict';

  angular
    .module('vizbox')
    .constant('moment', moment)
    .constant('c3', c3);

})();
<|endoftext|>


<commit_before>// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
const path = require('path');

module.exports = {
  // All imported modules in your tests should be mocked automatically
  // automock: false,

  // Stop running tests after `n` failures
  // bail: 0,

  // Respect "browser" field in package.json when resolving modules
  // browser: false,

  // The directory where Jest should store its cached dependency information
  // cacheDirectory: "/private/var/folders/50/9h_5zvjd3g9df35kzszzw8840000gn/T/jest_dx",

  // Automatically clear mock calls and instances between every test
  // clearMocks: true,

  // Indicates whether the coverage information should be collected while executing the test
  // collectCoverage: false,

  // An array of glob patterns indicating a set of files for which coverage information should be collected
  // collectCoverageFrom: undefined,

  // The directory where Jest should output its coverage files
  // coverageDirectory: undefined,

  // An array of regexp pattern strings used to skip coverage collection
  // coveragePathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // A list of reporter names that Jest uses when writing coverage reports
  // coverageReporters: [
  //   "json",
  //   "text",
  //   "lcov",
  //   "clover"
  // ],

  // An object that configures minimum threshold enforcement for coverage results
  // coverageThreshold: undefined,

  // A path to a custom dependency extractor
  // dependencyExtractor: undefined,

  // Make calling deprecated APIs throw helpful error messages
  // errorOnDeprecated: false,

  // Force coverage collection from ignored files using an array of glob patterns
  // forceCoverageMatch: [],

  // A path to a module which exports an async function that is triggered once before all test suites
  // globalSetup: undefined,

  // A path to a module which exports an async function that is triggered once after all test suites
  // globalTeardown: undefined,

  // A set of global variables that need to be available in all test environments
  globals: {
    "ts-jest": {
      "tsconfig": path.join(__dirname, "tsconfig.json")
    }
  },

  // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
  // maxWorkers: "50%",

  // An array of directory names to be searched recursively up from the requiring module's location
  // moduleDirectories: [
  //   "node_modules"
  // ],

  // An array of file extensions your modules use
  // moduleFileExtensions: [
  //   "js",
  //   "json",
  //   "jsx",
  //   "ts",
  //   "tsx",
  //   "node"
  // ],

  // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
  // moduleNameMapper: {},

  // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
  // modulePathIgnorePatterns: [],

  // Activates notifications for test results
  // notify: false,

  // An enum that specifies notification mode. Requires { notify: true }
  // notifyMode: "failure-change",

  // A preset that is used as a base for Jest's configuration
  // preset: undefined,

  // Run tests from one or more projects
  // projects: undefined,

  // Use this configuration option to add custom reporters to Jest
  // reporters: undefined,

  // Automatically reset mock state between every test
  // resetMocks: false,

  // Reset the module registry before running each individual test
  // resetModules: false,

  // A path to a custom resolver
  // resolver: undefined,

  // Automatically restore mock state between every test
  // restoreMocks: false,

  // The root directory that Jest should scan for tests and modules within
  rootDir: __dirname,

  // A list of paths to directories that Jest should use to search for files in
  // roots: [
  //   "<rootDir>"
  // ],

  // Allows you to use a custom runner instead of Jest's default test runner
  // runner: "jest-runner",

  // The paths to modules that run some code to configure or set up the testing environment before each test
  // setupFiles: [],

  // A list of paths to modules that run some code to configure or set up the testing framework before each test
  // setupFilesAfterEnv: [],

  // A list of paths to snapshot serializer modules Jest should use for snapshot testing
  // snapshotSerializers: [],

  // The test environment that will be used for testing
  testEnvironment: "jest-environment-jsdom",

  // Options that will be passed to the testEnvironment
  // testEnvironmentOptions: {},

  // Adds a location field to test results
  // testLocationInResults: false,

  // The glob patterns Jest uses to detect test files
  testMatch: [
    "**/tests/**/*.test.ts"
  ],

  // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
  // testPathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // The regexp pattern or array of patterns that Jest uses to detect test files
  // testRegex: [],

  // This option allows the use of a custom results processor
  // testResultsProcessor: undefined,

  // This option allows use of a custom test runner
  // testRunner: "jasmine2",

  // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
  // testURL: "http://localhost",

  // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
  // timers: "real",

  // A map from regular expressions to paths to transformers
  transform: {
    "^.+\\.ts$": "<rootDir>/../../node_modules/ts-jest"
  },

  // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
  // transformIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
  // unmockedModulePathPatterns: undefined,

  // Indicates whether each individual test should be reported during the run
  // verbose: undefined,

  // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
  // watchPathIgnorePatterns: [],

  // Whether to use watchman for file crawling
  // watchman: true,
};
<commit_msg>jest.config.js を修正する<commit_after>// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
const path = require('path');

module.exports = {
  // All imported modules in your tests should be mocked automatically
  // automock: false,

  // Stop running tests after `n` failures
  // bail: 0,

  // Respect "browser" field in package.json when resolving modules
  // browser: false,

  // The directory where Jest should store its cached dependency information
  // cacheDirectory: "/private/var/folders/50/9h_5zvjd3g9df35kzszzw8840000gn/T/jest_dx",

  // Automatically clear mock calls and instances between every test
  // clearMocks: true,

  // Indicates whether the coverage information should be collected while executing the test
  // collectCoverage: false,

  // An array of glob patterns indicating a set of files for which coverage information should be collected
  // collectCoverageFrom: undefined,

  // The directory where Jest should output its coverage files
  // coverageDirectory: undefined,

  // An array of regexp pattern strings used to skip coverage collection
  // coveragePathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // A list of reporter names that Jest uses when writing coverage reports
  // coverageReporters: [
  //   "json",
  //   "text",
  //   "lcov",
  //   "clover"
  // ],

  // An object that configures minimum threshold enforcement for coverage results
  // coverageThreshold: undefined,

  // A path to a custom dependency extractor
  // dependencyExtractor: undefined,

  // Make calling deprecated APIs throw helpful error messages
  // errorOnDeprecated: false,

  // Force coverage collection from ignored files using an array of glob patterns
  // forceCoverageMatch: [],

  // A path to a module which exports an async function that is triggered once before all test suites
  // globalSetup: undefined,

  // A path to a module which exports an async function that is triggered once after all test suites
  // globalTeardown: undefined,

  // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
  // maxWorkers: "50%",

  // An array of directory names to be searched recursively up from the requiring module's location
  // moduleDirectories: [
  //   "node_modules"
  // ],

  // An array of file extensions your modules use
  // moduleFileExtensions: [
  //   "js",
  //   "json",
  //   "jsx",
  //   "ts",
  //   "tsx",
  //   "node"
  // ],

  // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
  // moduleNameMapper: {},

  // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
  // modulePathIgnorePatterns: [],

  // Activates notifications for test results
  // notify: false,

  // An enum that specifies notification mode. Requires { notify: true }
  // notifyMode: "failure-change",

  // A preset that is used as a base for Jest's configuration
  // preset: undefined,

  // Run tests from one or more projects
  // projects: undefined,

  // Use this configuration option to add custom reporters to Jest
  // reporters: undefined,

  // Automatically reset mock state between every test
  // resetMocks: false,

  // Reset the module registry before running each individual test
  // resetModules: false,

  // A path to a custom resolver
  // resolver: undefined,

  // Automatically restore mock state between every test
  // restoreMocks: false,

  // The root directory that Jest should scan for tests and modules within
  rootDir: __dirname,

  // A list of paths to directories that Jest should use to search for files in
  // roots: [
  //   "<rootDir>"
  // ],

  // Allows you to use a custom runner instead of Jest's default test runner
  // runner: "jest-runner",

  // The paths to modules that run some code to configure or set up the testing environment before each test
  // setupFiles: [],

  // A list of paths to modules that run some code to configure or set up the testing framework before each test
  // setupFilesAfterEnv: [],

  // A list of paths to snapshot serializer modules Jest should use for snapshot testing
  // snapshotSerializers: [],

  // The test environment that will be used for testing
  testEnvironment: "jest-environment-jsdom",

  // Options that will be passed to the testEnvironment
  // testEnvironmentOptions: {},

  // Adds a location field to test results
  // testLocationInResults: false,

  // The glob patterns Jest uses to detect test files
  testMatch: [
    "**/tests/**/*.test.ts"
  ],

  // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
  // testPathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // The regexp pattern or array of patterns that Jest uses to detect test files
  // testRegex: [],

  // This option allows the use of a custom results processor
  // testResultsProcessor: undefined,

  // This option allows use of a custom test runner
  // testRunner: "jasmine2",

  // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
  // testURL: "http://localhost",

  // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
  // timers: "real",

  // A map from regular expressions to paths to transformers
  transform: {
    "^.+\\.ts$": "<rootDir>/node_modules/ts-jest"
  },

  // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
  // transformIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
  // unmockedModulePathPatterns: undefined,

  // Indicates whether each individual test should be reported during the run
  // verbose: undefined,

  // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
  // watchPathIgnorePatterns: [],

  // Whether to use watchman for file crawling
  // watchman: true,
};
<|endoftext|>