<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

/**
 * Provide the PanZoomModule class.
 *
 * @module topology
 * @submodule topology.panzoom
 */

YUI.add('juju-topology-panzoom', function(Y) {
  var views = Y.namespace('juju.views'),
      models = Y.namespace('juju.models'),
      d3ns = Y.namespace('d3');

  /**
   * Handle PanZoom within a Topology.
   *
   * ## Emitted events:
   *
   * - *rescaled:* post-zoom event, after the scene has been rescaled,
   *   queried object positions should be accurate.
   *
   * @class PanZoomModule
   */
  var PanZoomModule = Y.Base.create('PanZoomModule', d3ns.Module, [], {

    events: {
      scene: {
        '#zoom-out-btn': {
          click: 'zoom_out',
          mouseover: 'add_hover_out',
          mouseout: 'remove_hover_out'
        },
        '#zoom-in-btn': {
          click: 'zoom_in',
          mouseover: 'add_hover_in',
          mouseout: 'remove_hover_in'
        }
      },
      yui: {
        /**
          Fired when the canvas is zoomed.

          @event zoom
        */
        zoom: 'zoomHandler',
        /**
          Build pan and zoom functionality when the canvas is rendered.

          @event rendered
        */
        rendered: 'renderedHandler',
        zoom_in: 'zoom_in',
        zoom_out: 'zoom_out',
        panToPoint: 'panToPoint'
      }
    },

    componentBound: function() {
      var topo = this.get('component'),
          options = topo.options;

      this.toScale = d3.scale.linear()
                            .domain([options.minSlider, options.maxSlider])
                            .range([options.minZoom, options.maxZoom])
                            .clamp(true);
      this.toSlider = d3.scale.linear()
                            .domain([options.minZoom, options.maxZoom])
                            .range([options.minSlider, options.maxSlider])
                            .clamp(true);
    },

    renderSlider: function() {
      var self = this,
          topo = this.get('component'),
          options = topo.options,
          currentScale = topo.get('scale'),
          slider;

      if (self.slider) {
        return;
      }

      slider = new Y.Slider({
        // Vertical sliders normally have min at the top and max at the
        // bottom.  Switch them in the definition for our needs.
        min: options.maxSlider,
        max: options.minSlider,
        axis: 'y',
        length: '300px',
        thumbUrl: '/juju-ui/assets/images/non-sprites/zoom-handle.png',
        value: this.toSlider(currentScale)
      });
      // XXX: selection to module option
      slider.render('#slider-parent');
      topo.recordSubscription(this,
                              slider.after('valueChange', function(evt) {
                                if (d3.event && d3.event.scale &&
                                    d3.event.translate) {
                                  return;
                                }
                                self._fire_zoom(self.toScale(evt.newVal));
                              }));
      this.slider = slider;
    },

    /**
     * Handler for 'zoom' event.
     *
     * @method zoomHandler
     */
    zoomHandler: function(evt) {
      var slider = this.slider;

      // Don't zoom if we don't have a slider yet.
      if (!slider) {
        return;
      }
      // Set the slider value to match our new zoom level.
      slider._set('value', this.toSlider(evt.scale));
      // Let rescale handle the actual transformation; evt.scale and
      // evt.translate have both been set by D3 at this point.
      this.rescale(evt);
    },

    /**
     * Zoom out event handler.
     *
     * @method zoom_out
     */
    zoom_out: function(data, self) {
      var slider = this.slider || self.slider,
          val = slider.get('value');
      slider.set('value', val - 25);
    },

    /**
     * Zoom in event handler.
     *
     * @method zoom_in
     */
    zoom_in: function(data, self) {
      var slider = this.slider || self.slider,
          val = slider.get('value');
      slider.set('value', val + 25);
    },

    /**
     * Mouseover event handler.
     *
     * @method add_hover
     */
    add_hover_out: function(data, self) {
      this.className = this.className + ' zoom_m_h';
    },

    /**
     * Mouseover event handler.
     *
     * @method add_hover
     */
    add_hover_in: function(data, self) {
      this.className = this.className + ' zoom_p_h';
    },

    /**
     * Mouseout event handler
     *
     * @method remove_hover
     */
    remove_hover_out: function(data, self) {
      this.className = this.className.replace(' zoom_m_h', '');
    },

    /**
     * Mouseout event handler
     *
     * @method remove_hover
     */
    remove_hover_in: function(data, self) {
      this.className = this.className.replace(' zoom_p_h', '');
    },

    /**
     * Wrapper around the actual rescale method for zoom buttons.
     *
     * @method _fire_zoom
     */
    _fire_zoom: function(scale) {
      var topo = this.get('component'),
          vis = topo.vis,
          zoom = topo.zoom,
          size = topo.get('size'),
          delta,
          evt = {};

      delta = scale - topo.get('scale');

      // Build a temporary event that rescale can use of a similar
      // construction to d3.event.
      evt.scale = scale;
      // Update the scale in our zoom behavior manager to maintain state.
      zoom.scale(Math.floor(scale));
      // Update the translate so that we scale from the center
      // instead of the origin.
      evt.translate = zoom.translate();
      evt.translate[0] -= (size[0] / 2) * delta;
      evt.translate[1] -= (size[1] / 2) * delta;

      this.rescale(evt);
      // TODO Makyo - pan to center of canvas, card on board.
      topo.fire('panToCenter');
    },

    /**
     * Rescale the visualization on a zoom/pan event.
     *
     * @method rescale
     */
    rescale: function(evt) {
      // Make sure we don't scale outside of our bounds.
      // This check is needed because we're messing with d3's zoom
      // behavior outside of mouse events (e.g.: with the slider),
      // and can't trust that zoomExtent will play well.
      var topo = this.get('component'),
          options = topo.options,
          vis = topo.vis;

      if (!vis) {
        return;
      }

      // Ensure that we're definitely within bounds by coercing the scale
      // to fit within our range.
      evt.scale = this.toScale(this.toSlider(evt.scale));

      // Store the current value of scale so that it can be restored later.
      topo.set('scale', evt.scale);
      // Store the current value of translate as well, by copying the event
      // array in order to avoid reference sharing.
      topo.set('translate', Y.mix(evt.translate));
      vis.attr('transform', 'translate(' + topo.get('translate') + ')' +
              ' scale(' + topo.get('scale') + ')');
      var bgPosition = evt.translate[0] + 'px ' + evt.translate[1] + 'px';
      Y.one('.topology-canvas').setStyle('background-position', bgPosition);
      topo.fire('rescaled');
    },

    renderedHandler: function(evt) {
      // Preserve zoom when the scene is updated.
      var topo = this.get('component'),
          changed = false,
          currentScale = topo.get('scale'),
          currentTranslate = topo.get('translate');

      this.renderSlider();
      if (currentTranslate && currentTranslate !== topo.get('translate')) {
        topo.zoom.translate(currentTranslate);
        changed = true;
      }
      if (currentScale && currentScale !== topo.zoom.scale()) {
        topo.zoom.scale(currentScale);
        changed = true;
      }
      if (changed) {
        this.rescale({scale: currentScale, translate: currentTranslate});
      }
    },

    /**
      Pans the environment so that the given point is in the center of the
      viewport.

      @method panToPoint
      @param {object} evt The event handler with a 'point' attribute.
      @return {undefined} Side effects only.
    */
    panToPoint: function(evt) {
      var point = evt.point,
          topo = this.get('component'),
          scale = topo.get('scale'),
          size = topo.get('size');
      this.rescale({
        scale: scale,
        translate: point.map(function(d, i) {
          return ((0 - d) * scale) + (size[i] / 2);
        })
      });
    }
  }, {
    ATTRS: {
      /**
        @property {d3ns.Component} component
      */
      component: {}
    }

  });
  views.PanZoomModule = PanZoomModule;
}, '0.1.0', {
  requires: [
    'node',
    'event',
    'slider',
    'd3',
    'd3-components',
    'juju-models',
    'juju-env'
  ]
});
<commit_msg>Fixed in Firefox<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

/**
 * Provide the PanZoomModule class.
 *
 * @module topology
 * @submodule topology.panzoom
 */

YUI.add('juju-topology-panzoom', function(Y) {
  var views = Y.namespace('juju.views'),
      models = Y.namespace('juju.models'),
      d3ns = Y.namespace('d3');

  /**
   * Handle PanZoom within a Topology.
   *
   * ## Emitted events:
   *
   * - *rescaled:* post-zoom event, after the scene has been rescaled,
   *   queried object positions should be accurate.
   *
   * @class PanZoomModule
   */
  var PanZoomModule = Y.Base.create('PanZoomModule', d3ns.Module, [], {

    events: {
      scene: {
        '#zoom-out-btn': {
          click: 'zoom_out',
          mouseover: 'add_hover_out',
          mouseout: 'remove_hover_out'
        },
        '#zoom-in-btn': {
          click: 'zoom_in',
          mouseover: 'add_hover_in',
          mouseout: 'remove_hover_in'
        }
      },
      yui: {
        /**
          Fired when the canvas is zoomed.

          @event zoom
        */
        zoom: 'zoomHandler',
        /**
          Build pan and zoom functionality when the canvas is rendered.

          @event rendered
        */
        rendered: 'renderedHandler',
        zoom_in: 'zoom_in',
        zoom_out: 'zoom_out',
        panToPoint: 'panToPoint'
      }
    },

    componentBound: function() {
      var topo = this.get('component'),
          options = topo.options;

      this.toScale = d3.scale.linear()
                            .domain([options.minSlider, options.maxSlider])
                            .range([options.minZoom, options.maxZoom])
                            .clamp(true);
      this.toSlider = d3.scale.linear()
                            .domain([options.minZoom, options.maxZoom])
                            .range([options.minSlider, options.maxSlider])
                            .clamp(true);
    },

    renderSlider: function() {
      var self = this,
          topo = this.get('component'),
          options = topo.options,
          currentScale = topo.get('scale'),
          slider;

      if (self.slider) {
        return;
      }

      slider = new Y.Slider({
        // Vertical sliders normally have min at the top and max at the
        // bottom.  Switch them in the definition for our needs.
        min: options.maxSlider,
        max: options.minSlider,
        axis: 'y',
        length: '300px',
        thumbUrl: '/juju-ui/assets/images/non-sprites/zoom-handle.png',
        value: this.toSlider(currentScale)
      });
      // XXX: selection to module option
      slider.render('#slider-parent');
      topo.recordSubscription(this,
                              slider.after('valueChange', function(evt) {
                                if (d3.event && d3.event.scale &&
                                    d3.event.translate) {
                                  return;
                                }
                                self._fire_zoom(self.toScale(evt.newVal));
                              }));
      this.slider = slider;
    },

    /**
     * Handler for 'zoom' event.
     *
     * @method zoomHandler
     */
    zoomHandler: function(evt) {
      var slider = this.slider;

      // Don't zoom if we don't have a slider yet.
      if (!slider) {
        return;
      }
      // Set the slider value to match our new zoom level.
      slider._set('value', this.toSlider(evt.scale));
      // Let rescale handle the actual transformation; evt.scale and
      // evt.translate have both been set by D3 at this point.
      this.rescale(evt);
    },

    /**
     * Zoom out event handler.
     *
     * @method zoom_out
     */
    zoom_out: function(data, self) {
      var slider = this.slider || self.slider,
          val = slider.get('value');
      slider.set('value', val - 25);
    },

    /**
     * Zoom in event handler.
     *
     * @method zoom_in
     */
    zoom_in: function(data, self) {
      var slider = this.slider || self.slider,
          val = slider.get('value');
      slider.set('value', val + 25);
    },

    /**
     * Mouseover event handler.
     *
     * @method add_hover
     */
    add_hover_out: function(data, self) {
      this.className = this.className + ' zoom_m_h';
    },

    /**
     * Mouseover event handler.
     *
     * @method add_hover
     */
    add_hover_in: function(data, self) {
      this.className = this.className + ' zoom_p_h';
    },

    /**
     * Mouseout event handler
     *
     * @method remove_hover
     */
    remove_hover_out: function(data, self) {
      this.className = this.className.replace(' zoom_m_h', '');
    },

    /**
     * Mouseout event handler
     *
     * @method remove_hover
     */
    remove_hover_in: function(data, self) {
      this.className = this.className.replace(' zoom_p_h', '');
    },

    /**
     * Wrapper around the actual rescale method for zoom buttons.
     *
     * @method _fire_zoom
     */
    _fire_zoom: function(scale) {
      var topo = this.get('component'),
          vis = topo.vis,
          zoom = topo.zoom,
          size = topo.get('size'),
          delta,
          evt = {};

      delta = scale - topo.get('scale');

      // Build a temporary event that rescale can use of a similar
      // construction to d3.event.
      evt.scale = scale;
      // Update the scale in our zoom behavior manager to maintain state.
      zoom.scale(Math.floor(scale));
      // Update the translate so that we scale from the center
      // instead of the origin.
      evt.translate = zoom.translate();
      evt.translate[0] -= (size[0] / 2) * delta;
      evt.translate[1] -= (size[1] / 2) * delta;

      this.rescale(evt);
      // TODO Makyo - pan to center of canvas, card on board.
      topo.fire('panToCenter');
    },

    /**
     * Rescale the visualization on a zoom/pan event.
     *
     * @method rescale
     */
    rescale: function(evt) {
      // Make sure we don't scale outside of our bounds.
      // This check is needed because we're messing with d3's zoom
      // behavior outside of mouse events (e.g.: with the slider),
      // and can't trust that zoomExtent will play well.
      var topo = this.get('component'),
          options = topo.options,
          vis = topo.vis;

      if (!vis) {
        return;
      }

      // Ensure that we're definitely within bounds by coercing the scale
      // to fit within our range.
      evt.scale = this.toScale(this.toSlider(evt.scale));

      // Store the current value of scale so that it can be restored later.
      topo.set('scale', evt.scale);
      // Store the current value of translate as well, by copying the event
      // array in order to avoid reference sharing.
      topo.set('translate', Y.mix(evt.translate));
      vis.attr('transform', 'translate(' + topo.get('translate') + ')' +
              ' scale(' + topo.get('scale') + ')');
      var bgPosition = evt.translate[0] + 'px ' + evt.translate[1] + 'px';
      Y.one('.topology-canvas').setStyle('backgroundPosition', bgPosition);
      topo.fire('rescaled');
    },

    renderedHandler: function(evt) {
      // Preserve zoom when the scene is updated.
      var topo = this.get('component'),
          changed = false,
          currentScale = topo.get('scale'),
          currentTranslate = topo.get('translate');

      this.renderSlider();
      if (currentTranslate && currentTranslate !== topo.get('translate')) {
        topo.zoom.translate(currentTranslate);
        changed = true;
      }
      if (currentScale && currentScale !== topo.zoom.scale()) {
        topo.zoom.scale(currentScale);
        changed = true;
      }
      if (changed) {
        this.rescale({scale: currentScale, translate: currentTranslate});
      }
    },

    /**
      Pans the environment so that the given point is in the center of the
      viewport.

      @method panToPoint
      @param {object} evt The event handler with a 'point' attribute.
      @return {undefined} Side effects only.
    */
    panToPoint: function(evt) {
      var point = evt.point,
          topo = this.get('component'),
          scale = topo.get('scale'),
          size = topo.get('size');
      this.rescale({
        scale: scale,
        translate: point.map(function(d, i) {
          return ((0 - d) * scale) + (size[i] / 2);
        })
      });
    }
  }, {
    ATTRS: {
      /**
        @property {d3ns.Component} component
      */
      component: {}
    }

  });
  views.PanZoomModule = PanZoomModule;
}, '0.1.0', {
  requires: [
    'node',
    'event',
    'slider',
    'd3',
    'd3-components',
    'juju-models',
    'juju-env'
  ]
});
<|endoftext|>


<commit_before>var Manager,
    ASSETS_NS = 'http://www.wso2.org/governance/metadata';

var log = new Log();

var ASSET_LCSTATE_PROP = 'lifecycleState';
var DEFAULT_ASSET_VIEW_STATE = 'published';

(function () {

    var dataInjector=require('/modules/data/data.injector.js').dataInjectorModule();
    var DataInjectorModes=dataInjector.Modes;

    var matchAttr = function (searchAttr, artifactAttr) {
        var attribute, attr, val, match;
        for (attribute in searchAttr) {
            if (searchAttr.hasOwnProperty(attribute)) {
                attr = searchAttr[attribute];
                val = artifactAttr[attribute];
                match = (attr instanceof RegExp) ? attr.test(val) : (attr == val);
                if (!match) {
                    return false;
                }
            }
        }
        return true;
    };

    /*
     The function checks whether two artifacts are similar
     @searchArtifact: The artifact containing the search criteria
     @artifact: The artifact to which the searchArtifact must be compared
     @return: If the two artifacts are similar True ,else False.
     */
    var matchArtifact = function (searchArtifact, artifact) {
        var status = true;//We assume that all attributes will match
        var ignoredProperty = 'attributes';
        var term = '';

        log.debug('Invoked matchArtifact: '+artifact.attributes.overview_name);
        log.debug('Ignoring property: ' + ignoredProperty);

        //First go through all of the non attribute properties
        for (var searchKey in searchArtifact) {

            log.debug('Examining property: ' + searchKey);

            if ((searchKey != ignoredProperty) && (artifact.hasOwnProperty(searchKey))) {

                //Match against spaces and lower case
                term = artifact[searchKey] || '';
                term = term.toString().toLowerCase().trim() + '';

                //Determine if the searchKey points to an array
                if (searchArtifact[searchKey] instanceof Array) {

                    log.debug('Checking against array of values: ' + searchArtifact[searchKey]);
                    log.debug('Artifact value '+term);
                    //Check if the value of the artifact property is defined in the
                    //searchArtifact property array.
                    status = (searchArtifact[searchKey].indexOf(term) != -1) ? true : false;
                }
                else {
                    log.debug('Artifact value: '+term);
                    log.debug('Searched value:'+searchArtifact[searchKey]);
                    //Update the status
                    status = (searchArtifact[searchKey] == term);
                }

            }
        }

        log.debug('Properties match: ' + status);

        //If it is not a match at this time then return false, no need to check
        //if the attributes match.
        if(status==false){

            log.debug(artifact.attributes.overview_name+' no match.');
            return status;
        }

        //Only search attributes if the user has provided any
        if (searchArtifact.attributes) {

            //Check if the attributes match
            status = matchAttr(searchArtifact.attributes, artifact.attributes);

            log.debug('Attribute match : ' + status);

        }

        return status;
    }

	var search = function(that, options, paging) {
		var assets;
        var configs = require('/config/store.js').config();

		if(options.tag) {
			var registry = that.registry, tag = options.tag;
			assets = that.manager.find(function(artifact) {
				if(registry.tags(artifact.path).indexOf(tag) != -1) {
					//return matchAttr(options.attributes, artifact.attributes); -To accommodate filtering by lifecycle state
					return matchArtifact(options, artifact);
				}
				return false;
			}, paging);
			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;
		}
		if(options.query) {
			var query = options.query;
			assets = that.manager.search(query, paging);

			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;

		} else if(options.attributes) {

			//TODO need proper way to distinguish search and parameter search
			if(options.attributes.length != null){
				options.attributes = {"overview_name":options.attributes,"lcState":configs.lifeCycleBehaviour.visibleIn};
			}else{
				options.attributes["lcState"] = configs.lifeCycleBehaviour.visibleIn;
			}
            var searchArtifact = options.attributes;
			assets = that.manager.search(searchArtifact, paging);

			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;
		} else if(options) {
			assets = that.manager.search(null, paging);
			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;
		}

		return [];
	};

    var loadRatings = function (manager, items) {
        var i, asset,
            username = manager.username,
            length = items.length;
        for (i = 0; i < length; i++) {
            asset = items[i];
            asset.rating = manager.registry.rating(asset.path, username);
        }
        return items;
    };

    Manager = function (registry, type) {
        var carbon = require('carbon');
        this.registry = registry;
        this.type = type;
        this.username = registry.username;
        Packages.org.wso2.carbon.governance.api.util.GovernanceUtils.loadGovernanceArtifacts(registry.registry);
        this.manager = new carbon.registry.ArtifactManager(registry, type);
        this.sorter = new Sorter(registry);
    };

    var Sorter = function (registry) {
        this.registry = registry;
    };

    Sorter.prototype.recent = function (items) {
        var registry = this.registry;
        items.sort(function (l, r) {
            return registry.get(l.path).created.time < registry.get(r.path).created.time;
        });
        return items;
    };

    Sorter.prototype.popular = function (items) {
        var registry = this.registry;
        items.sort(function (l, r) {
            return registry.rating(l.path).average < registry.rating(r.path).average;
        });
        return items;
    };

    Sorter.prototype.unpopular = function (items) {
        var registry = this.registry;
        items.sort(function (l, r) {
            return registry.rating(l.path).average > registry.rating(r.path).average;
        });
        return items;
    };

    Sorter.prototype.older = function (items) {
        var registry = this.registry;
        items.sort(function (l, r) {
            return registry.get(l.path).created.time > registry.get(r.path).created.time;
        });
        return items;
    };

    Sorter.prototype.az = function (items) {
        items.sort(function (l, r) {
            return l['overview_name'] > r['overview_name'];
        });
        return items;
    };

    Sorter.prototype.za = function (items) {
        items.sort(function (l, r) {
            return l['overview_name'] < r['overview_name'];
        });
        return items;
    };

    Sorter.prototype.paginate = function (items, paging) {
        switch (paging.sort) {
            case 'recent':
                this.recent(items);
                break;
            case 'older':
                this.older(items);
                break;
            case 'popular':
                this.popular(items);
                break;
            case 'unpopular':
                this.unpopular(items);
                break;
            case 'az':
                this.az(items);
                break;
            case 'za':
                this.za(items);
                break;
            default:
                this.recent(items);
        }
        return items.slice(paging.start, (paging.start + paging.count));
    };

    Manager.prototype.search = function (options, paging) {
        return loadRatings(this, search(this, options,paging), paging);
    };

    Manager.prototype.checkTagAssets = function (options) {
        return search(this, options,null);
    };

    /*
     * Assets matching the filter
     */
    Manager.prototype.get = function (id) {
        var asset=this.manager.get(id);

        dataInjector.cached().inject(asset,DataInjectorModes.DISPLAY);

        return asset;
    };

    /*
     * Assets matching the filter
     */
    Manager.prototype.add = function (options) {
        return this.manager.add(options);
    };

    /*
     * Assets matching the filter
     */
    Manager.prototype.update = function (options) {
        return this.manager.update(options);
    };

    /*
     * Assets matching the filter
     */
    Manager.prototype.remove = function (options) {
        var assets;
        if (options.id) {
            this.manager.remove(options.id);
            return;
        }
        assets = this.search(options);
        if (assets.length > 0) {
            this.manager.remove(assets[0].id);
        }
    };

    /*
     * Assets matching the filter
     * METHOD IS DEPRECATED
     */
    Manager.prototype.list = function (paging) {
        log.info('Calling deprecated method list - A method from down under-give him a vegimite sandwich');
        //Obtain the visible states from the
        /*var storeConfig = require('/store.json').lifeCycleBehaviour;
        var visibleStates = storeConfig.visibleIn || DEFAULT_ASSET_VIEW_STATE;

        log.info('Searching for assets in the ' + visibleStates + ' states.');

        var all = this.search({
            lifecycleState: visibleStates
        }, paging);

        log.debug('Obtained assets: ' + all.length + ' in the ' + visibleStates + ' states');

        return loadRatings(this, this.sorter.paginate(all, paging));*/
        return null;
    };

    /*
     *
     * Add comment
     Manager.prototype.comment = function (path, comment) {
     this.registry.comment(path, comment);
     };

     */
    /**
     * Get comments
     */
    /*

     Manager.prototype.comments = function () {
     return this.registry.comments();
     };

     Manager.prototype.rate = function () {

     };

     Manager.prototype.rating = function () {

     };

     Manager.prototype.invokeAspect = function () {

     };

     Manager.prototype.lifecycles = function () {

     };*/
}());
<commit_msg>fixing STORE-306<commit_after>var Manager,
    ASSETS_NS = 'http://www.wso2.org/governance/metadata';

var log = new Log();

var ASSET_LCSTATE_PROP = 'lifecycleState';
var DEFAULT_ASSET_VIEW_STATE = 'published';

(function () {

    var dataInjector=require('/modules/data/data.injector.js').dataInjectorModule();
    var DataInjectorModes=dataInjector.Modes;

    var matchAttr = function (searchAttr, artifactAttr) {
        var attribute, attr, val, match;
        for (attribute in searchAttr) {
            if (searchAttr.hasOwnProperty(attribute)) {
                attr = searchAttr[attribute];
                val = artifactAttr[attribute];
                match = (attr instanceof RegExp) ? attr.test(val) : (attr == val);
                if (!match) {
                    return false;
                }
            }
        }
        return true;
    };

    /*
     The function checks whether two artifacts are similar
     @searchArtifact: The artifact containing the search criteria
     @artifact: The artifact to which the searchArtifact must be compared
     @return: If the two artifacts are similar True ,else False.
     */
    var matchArtifact = function (searchArtifact, artifact) {
        var status = true;//We assume that all attributes will match
        var ignoredProperty = 'attributes';
        var term = '';

        log.debug('Invoked matchArtifact: '+artifact.attributes.overview_name);
        log.debug('Ignoring property: ' + ignoredProperty);

        //First go through all of the non attribute properties
        for (var searchKey in searchArtifact) {

            log.debug('Examining property: ' + searchKey);

            if ((searchKey != ignoredProperty) && (artifact.hasOwnProperty(searchKey))) {

                //Match against spaces and lower case
                term = artifact[searchKey] || '';
                term = term.toString().toLowerCase().trim() + '';

                //Determine if the searchKey points to an array
                if (searchArtifact[searchKey] instanceof Array) {

                    log.debug('Checking against array of values: ' + searchArtifact[searchKey]);
                    log.debug('Artifact value '+term);
                    //Check if the value of the artifact property is defined in the
                    //searchArtifact property array.
                    status = (searchArtifact[searchKey].indexOf(term) != -1) ? true : false;
                }
                else {
                    log.debug('Artifact value: '+term);
                    log.debug('Searched value:'+searchArtifact[searchKey]);
                    //Update the status
                    status = (searchArtifact[searchKey] == term);
                }

            }
        }

        log.debug('Properties match: ' + status);

        //If it is not a match at this time then return false, no need to check
        //if the attributes match.
        if(status==false){

            log.debug(artifact.attributes.overview_name+' no match.');
            return status;
        }

        //Only search attributes if the user has provided any
        if (searchArtifact.attributes) {

            //Check if the attributes match
            status = matchAttr(searchArtifact.attributes, artifact.attributes);

            log.debug('Attribute match : ' + status);

        }

        return status;
    }

	var search = function(that, options, paging) {
		var assets;
        var configs = require('/config/store.js').config();

		if(options.tag) {
			var registry = that.registry, tag = options.tag;
			assets = that.manager.find(function(artifact) {
				if(registry.tags(artifact.path).indexOf(tag) != -1) {
					//return matchAttr(options.attributes, artifact.attributes); -To accommodate filtering by lifecycle state
					return matchArtifact(options, artifact);
				}
				return false;
			}, paging);
			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;
		}
		if(options.query) {
			var query = options.query;
			assets = that.manager.search(query, paging);

			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;

		} else if(options.attributes) {

			//TODO need proper way to distinguish search and parameter search
			if(options.attributes.length != null){
				options.attributes = {"overview_name":options.attributes,"lcState":configs.lifeCycleBehaviour.visibleIn};
			}else{
				options.attributes["lcState"] = configs.lifeCycleBehaviour.visibleIn;
			}
            var searchArtifact = options.attributes;
			assets = that.manager.search(searchArtifact, paging);

			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;

		} else if(options.lcState) {
			assets = that.manager.search(options, paging);
			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;

		} else if(options) {
			assets = that.manager.search(null, paging);
			dataInjector.cached().inject(assets, DataInjectorModes.DISPLAY);

			return assets;
		}

		return [];
	};

    var loadRatings = function (manager, items) {
        var i, asset,
            username = manager.username,
            length = items.length;
        for (i = 0; i < length; i++) {
            asset = items[i];
            asset.rating = manager.registry.rating(asset.path, username);
        }
        return items;
    };

    Manager = function (registry, type) {
        var carbon = require('carbon');
        this.registry = registry;
        this.type = type;
        this.username = registry.username;
        Packages.org.wso2.carbon.governance.api.util.GovernanceUtils.loadGovernanceArtifacts(registry.registry);
        this.manager = new carbon.registry.ArtifactManager(registry, type);
        this.sorter = new Sorter(registry);
    };

    var Sorter = function (registry) {
        this.registry = registry;
    };

    Sorter.prototype.recent = function (items) {
        var registry = this.registry;
        items.sort(function (l, r) {
            return registry.get(l.path).created.time < registry.get(r.path).created.time;
        });
        return items;
    };

    Sorter.prototype.popular = function (items) {
        var registry = this.registry;
        items.sort(function (l, r) {
            return registry.rating(l.path).average < registry.rating(r.path).average;
        });
        return items;
    };

    Sorter.prototype.unpopular = function (items) {
        var registry = this.registry;
        items.sort(function (l, r) {
            return registry.rating(l.path).average > registry.rating(r.path).average;
        });
        return items;
    };

    Sorter.prototype.older = function (items) {
        var registry = this.registry;
        items.sort(function (l, r) {
            return registry.get(l.path).created.time > registry.get(r.path).created.time;
        });
        return items;
    };

    Sorter.prototype.az = function (items) {
        items.sort(function (l, r) {
            return l['overview_name'] > r['overview_name'];
        });
        return items;
    };

    Sorter.prototype.za = function (items) {
        items.sort(function (l, r) {
            return l['overview_name'] < r['overview_name'];
        });
        return items;
    };

    Sorter.prototype.paginate = function (items, paging) {
        switch (paging.sort) {
            case 'recent':
                this.recent(items);
                break;
            case 'older':
                this.older(items);
                break;
            case 'popular':
                this.popular(items);
                break;
            case 'unpopular':
                this.unpopular(items);
                break;
            case 'az':
                this.az(items);
                break;
            case 'za':
                this.za(items);
                break;
            default:
                this.recent(items);
        }
        return items.slice(paging.start, (paging.start + paging.count));
    };

    Manager.prototype.search = function (options, paging) {
        return loadRatings(this, search(this, options,paging), paging);
    };

    Manager.prototype.checkTagAssets = function (options) {
        return search(this, options,null);
    };

    /*
     * Assets matching the filter
     */
    Manager.prototype.get = function (id) {
        var asset=this.manager.get(id);

        dataInjector.cached().inject(asset,DataInjectorModes.DISPLAY);

        return asset;
    };

    /*
     * Assets matching the filter
     */
    Manager.prototype.add = function (options) {
        return this.manager.add(options);
    };

    /*
     * Assets matching the filter
     */
    Manager.prototype.update = function (options) {
        return this.manager.update(options);
    };

    /*
     * Assets matching the filter
     */
    Manager.prototype.remove = function (options) {
        var assets;
        if (options.id) {
            this.manager.remove(options.id);
            return;
        }
        assets = this.search(options);
        if (assets.length > 0) {
            this.manager.remove(assets[0].id);
        }
    };

    /*
     * Assets matching the filter
     * METHOD IS DEPRECATED
     */
    Manager.prototype.list = function (paging) {
        log.info('Calling deprecated method list - A method from down under-give him a vegimite sandwich');
        //Obtain the visible states from the
        /*var storeConfig = require('/store.json').lifeCycleBehaviour;
        var visibleStates = storeConfig.visibleIn || DEFAULT_ASSET_VIEW_STATE;

        log.info('Searching for assets in the ' + visibleStates + ' states.');

        var all = this.search({
            lifecycleState: visibleStates
        }, paging);

        log.debug('Obtained assets: ' + all.length + ' in the ' + visibleStates + ' states');

        return loadRatings(this, this.sorter.paginate(all, paging));*/
        return null;
    };

    /*
     *
     * Add comment
     Manager.prototype.comment = function (path, comment) {
     this.registry.comment(path, comment);
     };

     */
    /**
     * Get comments
     */
    /*

     Manager.prototype.comments = function () {
     return this.registry.comments();
     };

     Manager.prototype.rate = function () {

     };

     Manager.prototype.rating = function () {

     };

     Manager.prototype.invokeAspect = function () {

     };

     Manager.prototype.lifecycles = function () {

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


<commit_before>import React from "react"

function css(strings, ...keys) {
  const lastIndex = strings.length - 1
  return (
    strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], ``) +
    strings[lastIndex]
  )
}

const Style = () => (
  <style
    dangerouslySetInnerHTML={{
      __html: css`
        :host {
          --purple-60: #663399;
          --gatsby: var(--purple-60);
          --purple-40: #b17acc;
          --purple-20: #f1defa;
          --dimmedWhite: rgba(255, 255, 255, 0.8);
          --white: #ffffff;
          --black: #000000;
          --grey-90: #232129;
          --radii: 4px;
          --z-index-normal: 5;
          --z-index-elevated: 10;
          --shadow: 0px 2px 4px rgba(46, 41, 51, 0.08),
            0px 4px 8px rgba(71, 63, 79, 0.16);
        }

        [data-gatsby-loading-indicator="root"] {
          font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
            Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
            "Segoe UI Symbol" !important;
          background: var(--white);
          color: var(--grey-90);
          position: fixed;
          bottom: 1.5em;
          left: 1.5em;
          box-shadow: var(--shadow);
          border-radius: var(--radii);
          z-index: var(--z-index-elevated);
          border-left: 0.25em solid var(--purple-40);
          display: flex;
          align-items: center;
          justify-content: space-between;
          flex-wrap: nowrap;
          padding: 0.75em 1.15em;
          min-width: 196px;
        }

        [data-gatsby-loading-indicator-visible="false"] {
          opacity: 0;
          visibility: hidden;
          will-change: opacity, transform;
          transform: translateY(45px);
          transition: all 0.3s ease-in-out;
        }

        [data-gatsby-loading-indicator-visible="true"] {
          opacity: 1;
          visibility: visible;
          transform: translateY(0px);
          transition: all 0.3s ease-in-out;
        }

        [data-gatsby-loading-indicator="spinner"] {
          animation: spin 1s linear infinite;
          height: 18px;
          width: 18px;
          color: var(--gatsby);
        }

        [data-gatsby-loading-indicator="text"] {
          margin-left: 0.75em;
          line-height: 18px;
        }

        @keyframes spin {
          0% {
            transform: rotate(0);
          }
          100% {
            transform: rotate(360deg);
          }
        }

        @media (prefers-reduced-motion: reduce) {
          [data-gatsby-loading-indicator="spinner"] {
            animation: none;
          }
          [data-gatsby-loading-indicator-visible="false"] {
            transition: none;
          }

          [data-gatsby-loading-indicator-visible="true"] {
            transition: none;
          }
        }

        @media (prefers-color-scheme: dark) {
          [data-gatsby-loading-indicator="root"] {
            background: var(--grey-90);
            color: var(--white);
          }
          [data-gatsby-loading-indicator="spinner"] {
            color: var(--purple-20);
          }
        }
      `,
    }}
  />
)

export default Style
<commit_msg>fix(gatsby): z-index for loading-indicator (#30888)<commit_after>import React from "react"

function css(strings, ...keys) {
  const lastIndex = strings.length - 1
  return (
    strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], ``) +
    strings[lastIndex]
  )
}

const Style = () => (
  <style
    dangerouslySetInnerHTML={{
      __html: css`
        :host {
          --purple-60: #663399;
          --gatsby: var(--purple-60);
          --purple-40: #b17acc;
          --purple-20: #f1defa;
          --dimmedWhite: rgba(255, 255, 255, 0.8);
          --white: #ffffff;
          --black: #000000;
          --grey-90: #232129;
          --radii: 4px;
          --z-index-indicator: 9000;
          --shadow: 0px 2px 4px rgba(46, 41, 51, 0.08),
            0px 4px 8px rgba(71, 63, 79, 0.16);
        }

        [data-gatsby-loading-indicator="root"] {
          font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
            Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
            "Segoe UI Symbol" !important;
          background: var(--white);
          color: var(--grey-90);
          position: fixed;
          bottom: 1.5em;
          left: 1.5em;
          box-shadow: var(--shadow);
          border-radius: var(--radii);
          z-index: var(--z-index-indicator);
          border-left: 0.25em solid var(--purple-40);
          display: flex;
          align-items: center;
          justify-content: space-between;
          flex-wrap: nowrap;
          padding: 0.75em 1.15em;
          min-width: 196px;
        }

        [data-gatsby-loading-indicator-visible="false"] {
          opacity: 0;
          visibility: hidden;
          will-change: opacity, transform;
          transform: translateY(45px);
          transition: all 0.3s ease-in-out;
        }

        [data-gatsby-loading-indicator-visible="true"] {
          opacity: 1;
          visibility: visible;
          transform: translateY(0px);
          transition: all 0.3s ease-in-out;
        }

        [data-gatsby-loading-indicator="spinner"] {
          animation: spin 1s linear infinite;
          height: 18px;
          width: 18px;
          color: var(--gatsby);
        }

        [data-gatsby-loading-indicator="text"] {
          margin-left: 0.75em;
          line-height: 18px;
        }

        @keyframes spin {
          0% {
            transform: rotate(0);
          }
          100% {
            transform: rotate(360deg);
          }
        }

        @media (prefers-reduced-motion: reduce) {
          [data-gatsby-loading-indicator="spinner"] {
            animation: none;
          }
          [data-gatsby-loading-indicator-visible="false"] {
            transition: none;
          }

          [data-gatsby-loading-indicator-visible="true"] {
            transition: none;
          }
        }

        @media (prefers-color-scheme: dark) {
          [data-gatsby-loading-indicator="root"] {
            background: var(--grey-90);
            color: var(--white);
          }
          [data-gatsby-loading-indicator="spinner"] {
            color: var(--purple-20);
          }
        }
      `,
    }}
  />
)

export default Style
<|endoftext|>


<commit_before>/* eslint-disable max-len */
import React from "react";
import Immutable from "immutable";
import { Provider } from "react-redux";
import { shallow, mount } from "enzyme";

import renderer from "react-test-renderer";

import { displayOrder, transforms } from "@nteract/transforms";
import Cell from "../../src/components/cell/cell";
import { Notebook, getLanguageMode } from "../../src/providers/notebook";

import { dummyStore, dummyCommutable } from "../../src/dummy";

const dummyCellStatuses = dummyCommutable
  .get("cellOrder")
  .reduce(
    (statuses, cellID) =>
      statuses.set(
        cellID,
        Immutable.fromJS({ outputHidden: false, inputHidden: false })
      ),
    new Immutable.Map()
  );

// Boilerplate test to make sure the testing setup is configured
describe("Notebook", () => {
  test("accepts an Immutable.List of cells", () => {
    const stickyCells = new Immutable.Set().add(
      dummyCommutable.getIn(["cellOrder", 0])
    );

    const component = shallow(
      <Notebook
        cellOrder={dummyCommutable.get("cellOrder")}
        cellMap={dummyCommutable.get("cellMap")}
        transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
        cellPagers={new Immutable.Map()}
        cellStatuses={new Immutable.Map()}
        // Sticky the first cell of the notebook so that the sticky code gets
        // triggered.
        stickyCells={stickyCells}
        CellComponent={Cell}
      />
    );
    expect(component).not.toBeNull();
  });

  describe("getLanguageMode", () => {
    test("determines the right language from the notebook metadata", () => {
      const lang = getLanguageMode(dummyCommutable.get("metadata"));
      expect(lang).toBe("ipython");

      const lang2 = getLanguageMode(
        dummyCommutable
          .setIn(["metadata", "language_info", "codemirror_mode", "name"], "r")
          .get("metadata")
      );
      expect(lang2).toBe("r");
    });
  });

  describe("keyDown", () => {
    test("detects a cell execution keypress", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <Notebook
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set()}
          CellComponent={Cell}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.ctrlKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).toHaveBeenCalledWith({
        type: "EXECUTE_CELL",
        id: focusedCell,
        source: dummyCommutable.getIn(["cellMap", focusedCell, "source"])
      });
    });
    test("detects a focus to next cell keypress", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <Notebook
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set()}
          CellComponent={Cell}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.shiftKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).toHaveBeenCalledWith({
        type: "FOCUS_NEXT_CELL",
        id: focusedCell,
        createCellIfUndefined: true
      });
    });
    test("handles a focus to next cell keypress on a sticky cell", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <Notebook
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set([focusedCell])}
          CellComponent={Cell}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.shiftKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).not.toHaveBeenCalledWith({
        type: "FOCUS_NEXT_CELL",
        id: focusedCell,
        createCellIfUndefined: true
      });
    });
  });
});
<commit_msg>remove deprecated CellComponent passing<commit_after>/* eslint-disable max-len */
import React from "react";
import Immutable from "immutable";
import { Provider } from "react-redux";
import { shallow, mount } from "enzyme";

import renderer from "react-test-renderer";

import { displayOrder, transforms } from "@nteract/transforms";
import { Notebook, getLanguageMode } from "../../src/providers/notebook";

import { dummyStore, dummyCommutable } from "../../src/dummy";

const dummyCellStatuses = dummyCommutable
  .get("cellOrder")
  .reduce(
    (statuses, cellID) =>
      statuses.set(
        cellID,
        Immutable.fromJS({ outputHidden: false, inputHidden: false })
      ),
    new Immutable.Map()
  );

// Boilerplate test to make sure the testing setup is configured
describe("Notebook", () => {
  test("accepts an Immutable.List of cells", () => {
    const stickyCells = new Immutable.Set().add(
      dummyCommutable.getIn(["cellOrder", 0])
    );

    const component = shallow(
      <Notebook
        cellOrder={dummyCommutable.get("cellOrder")}
        cellMap={dummyCommutable.get("cellMap")}
        transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
        cellPagers={new Immutable.Map()}
        cellStatuses={new Immutable.Map()}
        // Sticky the first cell of the notebook so that the sticky code gets
        // triggered.
        stickyCells={stickyCells}
      />
    );
    expect(component).not.toBeNull();
  });

  describe("getLanguageMode", () => {
    test("determines the right language from the notebook metadata", () => {
      const lang = getLanguageMode(dummyCommutable.get("metadata"));
      expect(lang).toBe("ipython");

      const lang2 = getLanguageMode(
        dummyCommutable
          .setIn(["metadata", "language_info", "codemirror_mode", "name"], "r")
          .get("metadata")
      );
      expect(lang2).toBe("r");
    });
  });

  describe("keyDown", () => {
    test("detects a cell execution keypress", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <Notebook
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set()}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.ctrlKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).toHaveBeenCalledWith({
        type: "EXECUTE_CELL",
        id: focusedCell,
        source: dummyCommutable.getIn(["cellMap", focusedCell, "source"])
      });
    });
    test("detects a focus to next cell keypress", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <Notebook
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set()}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.shiftKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).toHaveBeenCalledWith({
        type: "FOCUS_NEXT_CELL",
        id: focusedCell,
        createCellIfUndefined: true
      });
    });
    test("handles a focus to next cell keypress on a sticky cell", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <Notebook
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set([focusedCell])}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.shiftKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).not.toHaveBeenCalledWith({
        type: "FOCUS_NEXT_CELL",
        id: focusedCell,
        createCellIfUndefined: true
      });
    });
  });
});
<|endoftext|>


<commit_before>appshell = {}

$(document).ready(function(){

    $('.dropdown-select').click(function(e) {
        if (!$(e.target).hasClass("custom-select-item")){
            e.stopPropagation();
        }
    }) ;

    $('.custom-select-item').click(function(e){
        var tgt = $(e.currentTarget);
        var cont = tgt.parents('.custom-select-container');
        var name = cont.data('custom-select-name');

        var value = tgt.data('value')
        var text = tgt.data('text')
        if (!text){
            text = tgt.text()
        }

        $("#"+name+"-text").text(text);
        $("#"+name).val(value)

        tgt.parents('.modal').modal('hide');
    });

    appshell.datatables = {}

    $('.tablefilter').on('keyup change', function (e){
        var tgt = $(e.currentTarget);
        var id = tgt.data('tablefilter-target');
        var t = appshell.datatables[id];

        var column = tgt.data('tablefilter-column');
        var value = tgt.val()

        if (t.column(column).search() != value){
            t.column(column).search(value).draw();
        }
    })

    $('.tablefilter-range').each(function(i, elem){
        var eq =$(elem);
        var id = eq.data('tablefilter-target');
        var column = eq.data('tablefilter-column');
        function update(e){
            var t = appshell.datatables[id];
            var value = eq.find('.range-from').val() + ';' + eq.find('.range-to').val();
            if (t.column(column).search() != value){
                t.column(column).search(value).draw();
            }
        }
        eq.find('.range-from').on('keyup change', update);
        eq.find('.range-to').on('keyup change', update);
    });

    $('.checklist').each(function(i, e){
        var name = $(e).data('custom-select-name');
        function value_from_checks(){
            var value = ""
            var text = ""

            $(e).find('input[type="checkbox"]').each(function(i, c){
                if ($(c).prop('checked')){
                    value += $(c).val()+";";
                    if (text == ""){
                        text = $(c).parent().text();
                    } else {
                        text = "[..., ...]"
                    }
                }
            });

            $("#"+name+"-text").text(text);
            $("#"+name).val(value)
            $("#"+name).trigger('change');
        }
        function checks_from_value(){

        }
        console.log(e);
        $(e).find('input[type="checkbox"]').on("change", function f(){
            value_from_checks();
        });
    });

    $('.checktree').each(function(i, e){
        var name = $(e).data('custom-select-name');
        var changing = false;
        var tree = $(e);
        function value_from_checks(){
            var value = ""
            var text = ""
            $(e).find('input[type="checkbox"]').each(function(i, c){
                if ($(c).prop('checked')){
                    value += $(c).val()+";";
                    if (text == ""){
                        text = $(c).val();
                    } else {
                        text = "[..., ...]"
                    }
                }
            });

            $("#"+name+"-text").text(text);
            $("#"+name).val(value)
            $("#"+name).trigger('change');
        }
        function checks_from_value(){

        }
        $(e).find('input[type="checkbox"]').on("change", function f(e){
            var self = $(e.currentTarget);
            if (changing == false){
                changing = true;

                var checked = self.prop('checked');
                var myval = self.val()
                var desc = tree.find('input[type="checkbox"][value^="'+myval+'/"]')
                console.log(desc)
                desc.prop('checked', checked);
                console.log(checked);
                if (!checked){
                    var path = myval.split('/');
                    var i;
                    var s = path[0];
                    for (i = 1; i < (path.length); i++){
                        console.log(s)
                        tree.find("input[type='checkbox'][value='"+s+"']").prop('checked', false);
                        s = s + '/' + path[i];
                    }
                }

                changing = false;
                value_from_checks();
            }
        });

    });

    $('.bootstrap-markdown').markdown({"autofocus": false});

    $('.datatable-action').click(function(e){
        var tgt = $(e.currentTarget);
        var id = tgt.data('target');
        var action = tgt.data('action');
        var t = appshell.datatables[id];
        var url = t.ajax.url()
        var paramstring = $.param(t.ajax.params());

        window.location = (url +
                           ((url.indexOf('?') == -1) ? '?' : '&') +
                           'action=' + action +
                           '&' + paramstring);
    });

    function treegrid_expand_all(tgt){
        var sts = tgt.treegrid('getTreeContainer').data('settings');
        if (sts.appshellDisabledState){
            return;
        }
        sts.appshellDisabledState = true;
        tgt.treegrid('saveState');
        sts.saveState = false;
        tgt.treegrid('expandAll');
    }

    function treegrid_restore(tgt){
        var sts = tgt.treegrid('getTreeContainer').data('settings');
        if (sts.appshellDisabledState){
            sts.appshellDisabledState = false;
            sts.saveState = true;
            tgt.treegrid('getAllNodes').each(function(idx, i){
                $(i).treegrid('restoreState');
            });
        }
    }

    $('.treegrid-search').on('keyup change', function(e){
        var myself = $(e.currentTarget);
        var tgt = $(myself.data('target'));
        var str = myself.val().toLowerCase()
        if (str != ""){
            treegrid_expand_all(tgt);
            tgt.treegrid('getAllNodes').each(function(idx, i){
                var self = $(i);
                if (self.text().toLowerCase().indexOf(str) != -1){
                    self.css('display', 'table-row');
                } else {
                    self.css('display', 'none');
                }
            });
        } else {
            tgt.treegrid('getAllNodes').each(function(idx, i){
                $(i).css('display', 'table-row');
            });
            treegrid_restore(tgt);
        }
    });
});

(function(){
    var timeout;
    $(document).ajaxStart(function(){
        timeout = setTimeout("$('.appshell-spinner').show()", 200);
    });
    $(document).ajaxStop(function(){
        if (timeout){
            clearTimeout(timeout);
        }
        timeout = null;
        $('#appshell-ajax-spinner').hide();
    });
})()

/* file-size plugin */
jQuery.fn.dataTable.ext.type.detect.unshift( function ( data ) {
    if ( typeof data !== 'string' ) {
        return null;
    }

    var units = data.replace( /[\d\.]/g, '' ).toLowerCase();
    if ( units !== '' && units !== 'b' && units !== 'kb' && units !== 'mb' && units !== 'gb' ) {
        return null;
    }

    return isNaN( parseFloat( data ) ) ?
        null :
        'file-size';
} );
jQuery.fn.dataTable.ext.type.order['file-size-pre'] = function ( data ) {
    var units = data.replace( /[\d\.]/g, '' ).toLowerCase();
    var multiplier = 1;

    if ( units === 'kb' ) {
        multiplier = 1000;
    }
    else if ( units === 'mb' ) {
        multiplier = 1000000;
    }
    else if ( units === 'gb' ) {
        multiplier = 1000000000;
    }

    return parseFloat( data ) * multiplier;
};
<commit_msg>restore tree state correctly<commit_after>appshell = {}

$(document).ready(function(){

    $('.dropdown-select').click(function(e) {
        if (!$(e.target).hasClass("custom-select-item")){
            e.stopPropagation();
        }
    }) ;

    $('.custom-select-item').click(function(e){
        var tgt = $(e.currentTarget);
        var cont = tgt.parents('.custom-select-container');
        var name = cont.data('custom-select-name');

        var value = tgt.data('value')
        var text = tgt.data('text')
        if (!text){
            text = tgt.text()
        }

        $("#"+name+"-text").text(text);
        $("#"+name).val(value)

        tgt.parents('.modal').modal('hide');
    });

    appshell.datatables = {}

    $('.tablefilter').on('keyup change', function (e){
        var tgt = $(e.currentTarget);
        var id = tgt.data('tablefilter-target');
        var t = appshell.datatables[id];

        var column = tgt.data('tablefilter-column');
        var value = tgt.val()

        if (t.column(column).search() != value){
            t.column(column).search(value).draw();
        }
    })

    $('.tablefilter-range').each(function(i, elem){
        var eq =$(elem);
        var id = eq.data('tablefilter-target');
        var column = eq.data('tablefilter-column');
        function update(e){
            var t = appshell.datatables[id];
            var value = eq.find('.range-from').val() + ';' + eq.find('.range-to').val();
            if (t.column(column).search() != value){
                t.column(column).search(value).draw();
            }
        }
        eq.find('.range-from').on('keyup change', update);
        eq.find('.range-to').on('keyup change', update);
    });

    $('.checklist').each(function(i, e){
        var name = $(e).data('custom-select-name');
        function value_from_checks(){
            var value = ""
            var text = ""

            $(e).find('input[type="checkbox"]').each(function(i, c){
                if ($(c).prop('checked')){
                    value += $(c).val()+";";
                    if (text == ""){
                        text = $(c).parent().text();
                    } else {
                        text = "[..., ...]"
                    }
                }
            });

            $("#"+name+"-text").text(text);
            $("#"+name).val(value)
            $("#"+name).trigger('change');
        }
        function checks_from_value(){

        }
        console.log(e);
        $(e).find('input[type="checkbox"]').on("change", function f(){
            value_from_checks();
        });
    });

    $('.checktree').each(function(i, e){
        var name = $(e).data('custom-select-name');
        var changing = false;
        var tree = $(e);
        function value_from_checks(){
            var value = ""
            var text = ""
            $(e).find('input[type="checkbox"]').each(function(i, c){
                if ($(c).prop('checked')){
                    value += $(c).val()+";";
                    if (text == ""){
                        text = $(c).val();
                    } else {
                        text = "[..., ...]"
                    }
                }
            });

            $("#"+name+"-text").text(text);
            $("#"+name).val(value)
            $("#"+name).trigger('change');
        }
        function checks_from_value(){

        }
        $(e).find('input[type="checkbox"]').on("change", function f(e){
            var self = $(e.currentTarget);
            if (changing == false){
                changing = true;

                var checked = self.prop('checked');
                var myval = self.val()
                var desc = tree.find('input[type="checkbox"][value^="'+myval+'/"]')
                console.log(desc)
                desc.prop('checked', checked);
                console.log(checked);
                if (!checked){
                    var path = myval.split('/');
                    var i;
                    var s = path[0];
                    for (i = 1; i < (path.length); i++){
                        console.log(s)
                        tree.find("input[type='checkbox'][value='"+s+"']").prop('checked', false);
                        s = s + '/' + path[i];
                    }
                }

                changing = false;
                value_from_checks();
            }
        });

    });

    $('.bootstrap-markdown').markdown({"autofocus": false});

    $('.datatable-action').click(function(e){
        var tgt = $(e.currentTarget);
        var id = tgt.data('target');
        var action = tgt.data('action');
        var t = appshell.datatables[id];
        var url = t.ajax.url()
        var paramstring = $.param(t.ajax.params());

        window.location = (url +
                           ((url.indexOf('?') == -1) ? '?' : '&') +
                           'action=' + action +
                           '&' + paramstring);
    });

    function treegrid_expand_all(tgt){
        var sts = tgt.treegrid('getTreeContainer').data('settings');
        if (sts.appshellDisabledState){
            return;
        }
        sts.appshellDisabledState = true;
        tgt.treegrid('saveState');
        sts.saveState = false;
        tgt.treegrid('expandAll');
    }

    function treegrid_restore(tgt){
        var sts = tgt.treegrid('getTreeContainer').data('settings');
        if (sts.appshellDisabledState){
            tgt.treegrid('getAllNodes').each(function(idx, i){
                $(i).css('display', 'table-row');
            });

            sts.appshellDisabledState = false;
            sts.saveState = true;
            tgt.treegrid('getAllNodes').each(function(idx, i){
                $(i).treegrid('restoreState');
            });
        }
    }

    $('.treegrid-search').on('keyup change', function(e){
        var myself = $(e.currentTarget);
        var tgt = $(myself.data('target'));
        var str = myself.val().toLowerCase()
        if (str != ""){
            treegrid_expand_all(tgt);
            tgt.treegrid('getAllNodes').each(function(idx, i){
                var self = $(i);
                if (self.text().toLowerCase().indexOf(str) != -1){
                    self.css('display', 'table-row');
                } else {
                    self.css('display', 'none');
                }
            });
        } else {
            treegrid_restore(tgt);
        }
    });
});

(function(){
    var timeout;
    $(document).ajaxStart(function(){
        timeout = setTimeout("$('.appshell-spinner').show()", 200);
    });
    $(document).ajaxStop(function(){
        if (timeout){
            clearTimeout(timeout);
        }
        timeout = null;
        $('#appshell-ajax-spinner').hide();
    });
})()

/* file-size plugin */
jQuery.fn.dataTable.ext.type.detect.unshift( function ( data ) {
    if ( typeof data !== 'string' ) {
        return null;
    }

    var units = data.replace( /[\d\.]/g, '' ).toLowerCase();
    if ( units !== '' && units !== 'b' && units !== 'kb' && units !== 'mb' && units !== 'gb' ) {
        return null;
    }

    return isNaN( parseFloat( data ) ) ?
        null :
        'file-size';
} );
jQuery.fn.dataTable.ext.type.order['file-size-pre'] = function ( data ) {
    var units = data.replace( /[\d\.]/g, '' ).toLowerCase();
    var multiplier = 1;

    if ( units === 'kb' ) {
        multiplier = 1000;
    }
    else if ( units === 'mb' ) {
        multiplier = 1000000;
    }
    else if ( units === 'gb' ) {
        multiplier = 1000000000;
    }

    return parseFloat( data ) * multiplier;
};
<|endoftext|>


<commit_before>'use strict'
const mongoose = require('mongoose')
const api = require('./api')
const trends = require('./twitter/trends')
const config = require('./config')
const dbUtils = require('./utils/db-utils')
const TweetStream = require('./twitter/tweet-stream')
const tweetSearch = require('./twitter/tweet-search')
const news = require('./news/news')

mongoose.Promise = global.Promise

var db = mongoose.connection
db.on('error', console.error)
db.once('open', () => {
  console.log('Successfully connected to mongodb')

  // Run updateTrends when the backend starts
  updateTrends()

  // Then set up updateTrends to run each server interval
  setInterval(updateTrends, config.intervalLength * 1000)

  api.start().then(() => {
    console.log('API Listening on port ' + config.apiPort.toString())
  })
})
mongoose.connect('mongodb://' + config.dbAddress + '/' + config.dbName)

var tweetStream = new TweetStream()

/**
 * Function run once every server interval, gets trends from the
 * Twitter API, news from the news API and stores all relavant
 * information in the database.
 *
 */
function updateTrends () {
  tweetStream.closeStream()
  let streamData = tweetStream.getData()

  // At the beginning of each interval get all trends
  trends.getTrends()
  // Then update the trend info in the database
  .then(trends => {
    trends.forEach(trend => {
      tweetSearch.getTweetSample(trend.name)
      .then(tweets => {
        news.getNews(trend.name, news => {
          dbUtils.processTrend(trend, news, tweets, streamData[trend.name])
        })
      })
    })

    // Start tracking the new trends
    tweetStream.startTracking(trends.map(trendData => { return trendData.name }))
  })
}
<commit_msg>Output Mongo server address at startup<commit_after>'use strict'
const mongoose = require('mongoose')
const api = require('./api')
const trends = require('./twitter/trends')
const config = require('./config')
const dbUtils = require('./utils/db-utils')
const TweetStream = require('./twitter/tweet-stream')
const tweetSearch = require('./twitter/tweet-search')
const news = require('./news/news')

mongoose.Promise = global.Promise

var db = mongoose.connection
db.on('error', console.error)
db.once('open', () => {
  console.log('Successfully connected to MongoDB server ' + config.dbAddress)

  // Run updateTrends when the backend starts
  updateTrends()

  // Then set up updateTrends to run each server interval
  setInterval(updateTrends, config.intervalLength * 1000)

  api.start().then(() => {
    console.log('API Listening on port ' + config.apiPort.toString())
  })
})
mongoose.connect('mongodb://' + config.dbAddress + '/' + config.dbName)

var tweetStream = new TweetStream()

/**
 * Function run once every server interval, gets trends from the
 * Twitter API, news from the news API and stores all relavant
 * information in the database.
 *
 */
function updateTrends () {
  tweetStream.closeStream()
  let streamData = tweetStream.getData()

  // At the beginning of each interval get all trends
  trends.getTrends()
  // Then update the trend info in the database
  .then(trends => {
    trends.forEach(trend => {
      tweetSearch.getTweetSample(trend.name)
      .then(tweets => {
        news.getNews(trend.name, news => {
          dbUtils.processTrend(trend, news, tweets, streamData[trend.name])
        })
      })
    })

    // Start tracking the new trends
    tweetStream.startTracking(trends.map(trendData => { return trendData.name }))
  })
}
<|endoftext|>


<commit_before>import Vue from 'vue';
import App from './app.vue';
import Slide from './stores/slide.js';
import SlideDeck from './stores/slide-deck.js';

new Vue({
  data: {
    Slide,
    SlideDeck,
  },
  el: 'body',
  components: {
    App,
  },
});
<commit_msg>Remove silly references.<commit_after>import Vue from 'vue';
import App from './app.vue';

new Vue({
  el: 'body',
  components: {
    App,
  },
});
<|endoftext|>


<commit_before>define(['format'],
function (format) {
    "use strict";
    function Xcon () {

        // skins a console.log message to display the primitive type as well
        // as the expected output of a vanilla .log() command
        // opts: {
        //     "color": "#f9f9f9", // specify a css color
        //     "log": true //
        // }
        // sometimes this function is called from console.run() to output
        // function return values.  In that case,
        // opts: {
        //     "color": "darkgreen", // or red
        //     "fnName": "nameOfFunction",
        //     "fnArgs": "all passed arguments",
        //     "error": true // indicates a thrown error
        // }
        this.out = function (blob, opts) {
            opts = opts || {};
            var logPart = format(blob, opts);
            console.log(logPart[0], logPart[1]);
            if (opts.log) {
                console.log(blob);
            }
        };

        // given a function, calls that function, returns the output,
        // and calls .out() to skin the output in green (success)
        // or red (failure).  Arguments, function name, and any error
        // messages are logged.
        this.run = function (fn, args, context) {
            if (typeof fn !== 'function') {
                this.out(arguments[0], arguments[1]);
                return arguments[0];
            }
            context = context || this;
            args = args || [];
            var result,
                opts = {
                    "fnName": fn.name || 'anonymous function',
                    "fnArgs": args.toString()
                };
            try {
                result = fn.apply(context, args);
                opts.color = 'darkgreen';
                this.out(result, opts);
                return result;
            } catch (e) {
                opts.color = 'red';
                opts.error = true;
                this.out(e.message, opts);
            }
        };
        return this;
    }

    return Xcon.call(window.console);
});
<commit_msg>add a default to any future native console namespace of run or out<commit_after>define(['format'],
function (format) {
    "use strict";
    function Xcon () {

        // skins a console.log message to display the primitive type as well
        // as the expected output of a vanilla .log() command
        // opts: {
        //     "color": "#f9f9f9", // specify a css color
        //     "log": true //
        // }
        // sometimes this function is called from console.run() to output
        // function return values.  In that case,
        // opts: {
        //     "color": "darkgreen", // or red
        //     "fnName": "nameOfFunction",
        //     "fnArgs": "all passed arguments",
        //     "error": true // indicates a thrown error
        // }
        this.out = this.out || function (blob, opts) {
            opts = opts || {};
            var logPart = format(blob, opts);
            console.log(logPart[0], logPart[1]);
            if (opts.log) {
                console.log(blob);
            }
        };

        // given a function, calls that function, returns the output,
        // and calls .out() to skin the output in green (success)
        // or red (failure).  Arguments, function name, and any error
        // messages are logged.
        this.run = this.run || function (fn, args, context) {
            if (typeof fn !== 'function') {
                this.out(arguments[0], arguments[1]);
                return arguments[0];
            }
            context = context || this;
            args = args || [];
            var result,
                opts = {
                    "fnName": fn.name || 'anonymous function',
                    "fnArgs": args.toString()
                };
            try {
                result = fn.apply(context, args);
                opts.color = 'darkgreen';
                this.out(result, opts);
                return result;
            } catch (e) {
                opts.color = 'red';
                opts.error = true;
                this.out(e.message, opts);
            }
        };
        return this;
    }

    return Xcon.call(window.console);
});
<|endoftext|>


<commit_before>'use strict';
angular.module('resourcify', [])

// This is just an example service you should delete
// You should put all files (directives/services/filters, etc) in their own file
.service('stub', [function Stub() {

	Stub.prototype.getOne = function () {
		return 1;
	};

}]);
<commit_msg>Start the awesome<commit_after>'use strict';

var resourcify = angular.module('resourcify', []);

function resourcificator ($http, $q) {

	var $resourcifyError = angular.$$minErr('resourcify'),
			requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'],
			requestMethods = {
				'query': 'GET',
				'get': 'GET',
				'$get': 'GET',
				'$save': 'POST',
				'$update': 'PUT',
				'$delete': 'DELETE'
			},
			validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'],
			bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH'];

	function validMethod (method) {
		if (!~validMethods.indexOf(method)) {
			throw $resourcifyError('requesttype', '"@{0}" is not a valid request method.', method);
		}
		return method;
	}

	function replaceParams (params, url) {

	}
}

resourcificator.$inject = ['$http', '$q'];

resourcify.service('resourcify', resourcificator);
<|endoftext|>


<commit_before>/* global requirejs */
requirejs.config({
    // For some reason when using the map config as suggested by some of the
    // plugins' documentation, and only when including vellum in another
    // app, it tries to get requirejs-promise instead of
    // requirejs-promise.js, so using packages instead.  This might be a bug
    // that should be reported.
    packages: [
        {
            name: 'less',
            location: '../bower_components/require-less',
            main: 'less.js'
        },
        {
            name: 'css',
            location: '../bower_components/require-css',
            main: 'css.js'
        },
        {
            name: 'text',
            location: '../bower_components/requirejs-text',
            main: 'text.js'
        },
        {
            name: 'tpl',
            location: '../bower_components/requirejs-tpl',
            main: 'tpl.js'
        },
        {
            name: 'json',
            location: '../bower_components/requirejs-plugins/src',
            main: 'json.js'
        }
    ],
    paths: {
        'vellum': '.',

        'codemirror': '../lib/codemirror/xml',
        'codemirrorBase': '../lib/codemirror/codemirror',
        'CryptoJS': '../lib/sha1',
        'diff-match-patch': '../lib/diff_match_patch',
        'jquery': '../bower_components/jquery/dist/jquery',
        'jquery-ui': '../bower_components/jquery-ui/jquery-ui',
        'jquery.jstree': '../bower_components/jstree/dist/jstree',
        'jquery.fancybox': '../lib/fancybox/jquery.fancybox-1.3.4',
        'jquery.bootstrap': '../lib/bootstrap',
        'jquery.bootstrap-popout': '../lib/bootstrap-popout',
        'jquery.bootstrap-better-typeahead': '../bower_components/bootstrap-better-typeahead/js/bootstrap-better-typeahead',
        'underscore': '../bower_components/underscore/underscore',
        'XMLWriter': '../bower_components/XMLWriter/XMLWriter',

        // todo: should convert xpath submodule to AMD
        'xpath': '../bower_components/xpath/xpath',
        'xpathmodels': '../bower_components/xpath/models',
        'scheme-number': '../bower_components/xpath/lib/schemeNumber',
        'biginteger': '../bower_components/xpath/lib/biginteger',

        'langCodes': '../bower_components/langcodes/langs.json',

        'save-button': '../lib/SaveButton',

        'yui-base': '../bower_components/MediaUploader/yui-base',
        'yui-combo': '../bower_components/MediaUploader/yui-combo',
        'yui-loader': '../bower_components/MediaUploader/yui-loader',
        'yui-uploader': '../bower_components/MediaUploader/yui-uploader',

        'swfobject': '../bower_components/MediaUploader/swfobject',
        'file-uploader': '../bower_components/MediaUploader/hqmedia.upload_controller',
    },
    shim: {
        'codemirror': {
            deps: ['codemirrorBase', 'css!../lib/codemirror/codemirror'],
            exports: 'CodeMirror',
        },
        'codemirrorBase': {
            exports: 'CodeMirror'
        },
        'CryptoJS': {
            exports: 'CryptoJS'
        },
        'diff-match-patch': {
            exports: 'diff_match_patch'
        },

        'jquery-ui': {
            deps: ['jquery', 'css!../bower_components/jquery-ui/themes/redmond/jquery-ui'],
            exports: '$.fn.autocomplete'
        },
        'jquery.jstree': {
            deps: ['jquery', 'css!../bower_components/jstree/dist/themes/default/style'],
            exports: '$.fn.jstree'
        },
        'jquery.fancybox': {
            deps: ['jquery', 'css!../lib/fancybox/jquery.fancybox-1.3.4'],
            exports: '$.fn.fancybox'
        },
        'jquery.bootstrap': {
            deps: ['jquery'],
            exports: '$.fn.popover'
        },
        'jquery.bootstrap-popout': {
            deps: ['jquery.bootstrap'],
            exports: '$.fn.popout'
        },
        'jquery.bootstrap-better-typeahead': {
            deps: ['jquery.bootstrap']
        },
        'underscore': {
            exports: '_'
        },
        'XMLWriter': {
            exports: 'XMLWriter'
        },

        'save-button': {
            deps: ['jquery'],
            exports: 'SaveButton'
        },

        'yui-base': {
            exports: 'YUI'
        },
        'yui-loader': {
            deps: ['yui-base'],
            exports: 'YUI'
        },
        'yui-uploader': {
            deps: ['yui-base', 'yui-loader', 'css!yui-combo'],
            exports: 'YUI'
        },
        'swfobject': {
            exports: 'swfobject'
        },
        'file-uploader': {
            deps: ['yui-uploader', 'swfobject', 'underscore', 'jquery'],
            exports: 'HQMediaFileUploadController'
        },

        'xpath': {
            deps: ['xpathmodels'],
            exports: 'xpath'
        },
        'xpathmodels': {
            deps: ['scheme-number'],
            exports: 'xpathmodels'
        },
        'scheme-number': {
            deps: ['biginteger'],
            exports: 'SchemeNumber'
        },
        'biginteger': {
            exports: 'BigInteger'
        }
    },
    less: {
        logLevel: 1
    }
});

// If jQuery was loaded before RequireJS, use the existing instance.
// http://www.manuel-strehl.de/dev/load_jquery_before_requirejs.en.html
if (window.jQuery) {
    define('jquery', [], function() {
        return window.jQuery;
    });
    if (window.jQuery.fn.typeahead) {
        define('jquery.bootstrap', [], function () {});
    }
    if (window.jQuery.fn.popout) {
        define('jquery.bootstrap-popout', [], function () {});
    }

    if (window.jQuery.fn.datepicker) {
        define('jquery-ui', [], function () {});
    }
}

define([
    // begin buildmain.py delimiter
    'vellum/core',
    'vellum/ignoreButRetain',
    'vellum/intentManager',
    'vellum/itemset',
    'vellum/javaRosa',
    'vellum/lock',
    'vellum/modeliteration',
    'vellum/uploader',
    'vellum/window',
    'vellum/polyfills'
    // end buildmain.py delimiter
], function () {
    // adds $.vellum as a side-effect
});
<commit_msg>Add commtrack module to main components<commit_after>/* global requirejs */
requirejs.config({
    // For some reason when using the map config as suggested by some of the
    // plugins' documentation, and only when including vellum in another
    // app, it tries to get requirejs-promise instead of
    // requirejs-promise.js, so using packages instead.  This might be a bug
    // that should be reported.
    packages: [
        {
            name: 'less',
            location: '../bower_components/require-less',
            main: 'less.js'
        },
        {
            name: 'css',
            location: '../bower_components/require-css',
            main: 'css.js'
        },
        {
            name: 'text',
            location: '../bower_components/requirejs-text',
            main: 'text.js'
        },
        {
            name: 'tpl',
            location: '../bower_components/requirejs-tpl',
            main: 'tpl.js'
        },
        {
            name: 'json',
            location: '../bower_components/requirejs-plugins/src',
            main: 'json.js'
        }
    ],
    paths: {
        'vellum': '.',

        'codemirror': '../lib/codemirror/xml',
        'codemirrorBase': '../lib/codemirror/codemirror',
        'CryptoJS': '../lib/sha1',
        'diff-match-patch': '../lib/diff_match_patch',
        'jquery': '../bower_components/jquery/dist/jquery',
        'jquery-ui': '../bower_components/jquery-ui/jquery-ui',
        'jquery.jstree': '../bower_components/jstree/dist/jstree',
        'jquery.fancybox': '../lib/fancybox/jquery.fancybox-1.3.4',
        'jquery.bootstrap': '../lib/bootstrap',
        'jquery.bootstrap-popout': '../lib/bootstrap-popout',
        'jquery.bootstrap-better-typeahead': '../bower_components/bootstrap-better-typeahead/js/bootstrap-better-typeahead',
        'underscore': '../bower_components/underscore/underscore',
        'XMLWriter': '../bower_components/XMLWriter/XMLWriter',

        // todo: should convert xpath submodule to AMD
        'xpath': '../bower_components/xpath/xpath',
        'xpathmodels': '../bower_components/xpath/models',
        'scheme-number': '../bower_components/xpath/lib/schemeNumber',
        'biginteger': '../bower_components/xpath/lib/biginteger',

        'langCodes': '../bower_components/langcodes/langs.json',

        'save-button': '../lib/SaveButton',

        'yui-base': '../bower_components/MediaUploader/yui-base',
        'yui-combo': '../bower_components/MediaUploader/yui-combo',
        'yui-loader': '../bower_components/MediaUploader/yui-loader',
        'yui-uploader': '../bower_components/MediaUploader/yui-uploader',

        'swfobject': '../bower_components/MediaUploader/swfobject',
        'file-uploader': '../bower_components/MediaUploader/hqmedia.upload_controller',
    },
    shim: {
        'codemirror': {
            deps: ['codemirrorBase', 'css!../lib/codemirror/codemirror'],
            exports: 'CodeMirror',
        },
        'codemirrorBase': {
            exports: 'CodeMirror'
        },
        'CryptoJS': {
            exports: 'CryptoJS'
        },
        'diff-match-patch': {
            exports: 'diff_match_patch'
        },

        'jquery-ui': {
            deps: ['jquery', 'css!../bower_components/jquery-ui/themes/redmond/jquery-ui'],
            exports: '$.fn.autocomplete'
        },
        'jquery.jstree': {
            deps: ['jquery', 'css!../bower_components/jstree/dist/themes/default/style'],
            exports: '$.fn.jstree'
        },
        'jquery.fancybox': {
            deps: ['jquery', 'css!../lib/fancybox/jquery.fancybox-1.3.4'],
            exports: '$.fn.fancybox'
        },
        'jquery.bootstrap': {
            deps: ['jquery'],
            exports: '$.fn.popover'
        },
        'jquery.bootstrap-popout': {
            deps: ['jquery.bootstrap'],
            exports: '$.fn.popout'
        },
        'jquery.bootstrap-better-typeahead': {
            deps: ['jquery.bootstrap']
        },
        'underscore': {
            exports: '_'
        },
        'XMLWriter': {
            exports: 'XMLWriter'
        },

        'save-button': {
            deps: ['jquery'],
            exports: 'SaveButton'
        },

        'yui-base': {
            exports: 'YUI'
        },
        'yui-loader': {
            deps: ['yui-base'],
            exports: 'YUI'
        },
        'yui-uploader': {
            deps: ['yui-base', 'yui-loader', 'css!yui-combo'],
            exports: 'YUI'
        },
        'swfobject': {
            exports: 'swfobject'
        },
        'file-uploader': {
            deps: ['yui-uploader', 'swfobject', 'underscore', 'jquery'],
            exports: 'HQMediaFileUploadController'
        },

        'xpath': {
            deps: ['xpathmodels'],
            exports: 'xpath'
        },
        'xpathmodels': {
            deps: ['scheme-number'],
            exports: 'xpathmodels'
        },
        'scheme-number': {
            deps: ['biginteger'],
            exports: 'SchemeNumber'
        },
        'biginteger': {
            exports: 'BigInteger'
        }
    },
    less: {
        logLevel: 1
    }
});

// If jQuery was loaded before RequireJS, use the existing instance.
// http://www.manuel-strehl.de/dev/load_jquery_before_requirejs.en.html
if (window.jQuery) {
    define('jquery', [], function() {
        return window.jQuery;
    });
    if (window.jQuery.fn.typeahead) {
        define('jquery.bootstrap', [], function () {});
    }
    if (window.jQuery.fn.popout) {
        define('jquery.bootstrap-popout', [], function () {});
    }

    if (window.jQuery.fn.datepicker) {
        define('jquery-ui', [], function () {});
    }
}

define([
    // begin buildmain.py delimiter
    'vellum/core',
    'vellum/ignoreButRetain',
    'vellum/intentManager',
    'vellum/itemset',
    'vellum/javaRosa',
    'vellum/lock',
    'vellum/commtrack',
    'vellum/modeliteration',
    'vellum/uploader',
    'vellum/window',
    'vellum/polyfills'
    // end buildmain.py delimiter
], function () {
    // adds $.vellum as a side-effect
});
<|endoftext|>