<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Pagimagic from 'react-pagimagic';

import './PaginatedList.css';

const propTypes = {
    changePageIndex: PropTypes.func.isRequired,
    currentPageIndex: PropTypes.number.isRequired,
    itemsPerPage: PropTypes.number.isRequired,
    list: PropTypes.arrayOf(PropTypes.object).isRequired,
    maximumVisiblePaginators: PropTypes.number.isRequired,
    renderChildren: PropTypes.func.isRequired,
};

const PaginatedList = ({
    list,
    currentPageIndex,
    changePageIndex,
    itemsPerPage,
    maximumVisiblePaginators,
    renderChildren,
}) => (
    <Pagimagic
        list={list}
        itemsPerPage={itemsPerPage}
        currentPageIndex={currentPageIndex}
        changePageIndex={changePageIndex}
        className="j-pagination"
        maximumVisiblePaginators={
            maximumVisiblePaginators ?
                maximumVisiblePaginators :
                5
        }
        renderChildren={renderChildren}
        arrow
    />
);

PaginatedList.propTypes = propTypes;

export default PaginatedList;
<commit_msg>Minor refactor defaults assignment<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Pagimagic from 'react-pagimagic';

import './PaginatedList.css';

const propTypes = {
    changePageIndex: PropTypes.func.isRequired,
    currentPageIndex: PropTypes.number.isRequired,
    itemsPerPage: PropTypes.number.isRequired,
    list: PropTypes.arrayOf(PropTypes.object).isRequired,
    maximumVisiblePaginators: PropTypes.number.isRequired,
    renderChildren: PropTypes.func.isRequired,
};

const PaginatedList = ({
    list,
    currentPageIndex,
    changePageIndex,
    itemsPerPage,
    maximumVisiblePaginators = 3,
    renderChildren,
}) => (
    <Pagimagic
        list={list}
        itemsPerPage={itemsPerPage}
        currentPageIndex={currentPageIndex}
        changePageIndex={changePageIndex}
        className="j-pagination"
        maximumVisiblePaginators={maximumVisiblePaginators}
        renderChildren={renderChildren}
        arrow
    />
);

PaginatedList.propTypes = propTypes;

export default PaginatedList;
<|endoftext|>


<commit_before>/**
 * Created by zarges on 15/02/16.
 */
var MwMenuEntries = Backbone.Collection.extend({
  model: window.mwUI.Menu.MwMenuEntry,
  comparator: 'order',
  _isAlreadyRegistered: function(entry) {
    return (
      this.get(entry.id) ||
      (entry.url && this.findWhere({url: entry.url}))
    );
  },
  _throwIsAlreadyRegisteredError: function(entry){
    if(entry.url){
      throw new Error('The entry with the id ' + entry.id + ' and the url ' + entry.url + ' has already been registered');
    } else {
      throw new Error('The entry with the id ' + entry.id + ' has already been registered');
    }
  },
  add: function(entries){
    if(_.isArray(entries)){
      entries.forEach(function(entry){
        if(this._isAlreadyRegistered(entry)){
          this._throwIsAlreadyRegisteredError(entry);
        }
      }.bind(this));
    } else {
      if(this._isAlreadyRegistered(entries)){
        this._throwIsAlreadyRegisteredError(entries);
      }
    }
    return Backbone.Collection.prototype.add.apply(this, arguments);
  },
  addEntry: function(id, url, label, options){
    options = options || {};
    var addObj = {
      id: id,
      url: url,
      label: label,
      icon: options.icon,
      activeUrls: options.activeUrls || [],
      order: options.order,
      subEntries: options.subEntries || [],
      type: 'ENTRY'
    };

    return this.add(addObj);
  },
  addDivider: function(id, options){
    options = options || {};
    var addObj = {
      id: id,
      label: options.label,
      order: options.order,
      type: 'DIVIDER'
    };

    return this.add(addObj);
  },

  getActiveEntryForUrl: function(url){
    var activeEntryFound = false,
        activeEntry = null;

    this.each(function(model){
      if(!activeEntryFound && model.hasActiveSubEntryOrIsActiveForUrl(url)){
        activeEntryFound = true;
        activeEntry = model;
      }
    });

    return activeEntry;
  }
});

window.mwUI.Menu.MwMenuEntries = MwMenuEntries;<commit_msg>add set default order functionality<commit_after>/**
 * Created by zarges on 15/02/16.
 */
var MwMenuEntries = Backbone.Collection.extend({
  model: window.mwUI.Menu.MwMenuEntry,
  comparator: 'order',
  _currentOrder: 0,
  _setDefaultOrder: function(entry) {
    if (entry instanceof Backbone.Model) {
      if (!entry.get('order')) {
        entry.set('order', this._currentOrder++);
      }
    } else if (_.isObject(entry)) {
      if (!entry.order) {
        entry.order = this._currentOrder++;
      }
    }
  },
  _isAlreadyRegistered: function(entry) {
    return (
      this.get(entry.id) ||
      (entry.url && this.findWhere({url: entry.url}))
    );
  },
  _throwIsAlreadyRegisteredError: function(entry){
    if(entry.url){
      throw new Error('The entry with the id ' + entry.id + ' and the url ' + entry.url + ' has already been registered');
    } else {
      throw new Error('The entry with the id ' + entry.id + ' has already been registered');
    }
  },
  add: function(entries){
    if(_.isArray(entries)){
      entries.forEach(function(entry){
        if(this._isAlreadyRegistered(entry)){
          this._throwIsAlreadyRegisteredError(entry);
          this._setDefaultOrder(entry);
        }
        this._setDefaultOrder(entry);
      }.bind(this));
    } else {
      if(this._isAlreadyRegistered(entries)){
        this._throwIsAlreadyRegisteredError(entries);
      }
      this._setDefaultOrder(entries);
    }
    return Backbone.Collection.prototype.add.apply(this, arguments);
  },
  addEntry: function(id, url, label, options){
    options = options || {};
    if(!options.order){
      options.order = this._currentOrder++;
    }
    var addObj = {
      id: id,
      url: url,
      label: label,
      icon: options.icon,
      activeUrls: options.activeUrls || [],
      order: options.order,
      subEntries: options.subEntries || [],
      type: 'ENTRY'
    };

    return this.add(addObj);
  },
  addDivider: function(id, options){
    options = options || {};
    var addObj = {
      id: id,
      label: options.label,
      order: options.order,
      type: 'DIVIDER'
    };

    return this.add(addObj);
  },

  getActiveEntryForUrl: function(url){
    var activeEntryFound = false,
        activeEntry = null;

    this.each(function(model){
      if(!activeEntryFound && model.hasActiveSubEntryOrIsActiveForUrl(url)){
        activeEntryFound = true;
        activeEntry = model;
      }
    });

    return activeEntry;
  }
});

window.mwUI.Menu.MwMenuEntries = MwMenuEntries;<|endoftext|>


<commit_before>'use strict'

import _ from 'lodash'
import d3 from 'd3'

import browser from 'util/browser'
import label from 'chart/renderer/label'
import color from 'util/color'

var defaults = {
  margin: {
    top: 12,
    right: 0,
    bottom: 12,
    left: 0
  },
  name: _.partial(_.get, _, 'name', ''),
  padding: 0.1,
  values: _.property('values'),
  x: _.property('x'),
  xFormat: String,
  y: _.property('y'),
  y0: _.partial(_.get, _, 'y0', 0),
  yFormat: String,
  yScale: d3.scale.linear
}

function ColumnChart () {
}

_.extend(ColumnChart.prototype, {
  classNames: 'chart stacked-column',
  defaults: defaults,

  initialize: function (el, data, options) {
    options = this._options = _.defaults({}, options, this.defaults)

    var aspect = _.get(options, 'aspect', 1)
    this._width = _.get(options, 'width', el.clientWidth)
    this._height = _.get(options, 'height', this._width / aspect)

    var svg = this._svg = d3.select(el).append('svg')
      .attr({
        'viewBox': '0 0 ' + this._width + ' ' + this._height,
        'class': this.classNames
      })

    if (browser.isIE()) {
      svg.attr({
        'width': this._width,
        'height': this._height
      })
    }

    var h = this._height - options.margin.top - options.margin.bottom

    svg.append('rect').attr({
      'class': 'bg',
      'height': h + options.margin.top,
      'width': this._width - options.margin.left - options.margin.right,
      'x': options.margin.left
    })

    var g = svg.append('g')
      .attr('transform', 'translate(' + options.margin.left + ', ' +
      options.margin.top + ')')

    g.append('g').attr('class', 'data')

    g.append('g').attr('class', 'y axis')
    g.append('g').attr({
      'class': 'x axis',
      'transform': 'translate(0, ' + h + ')'
    })
    g.append('g').attr('class', 'legend')
    g.append('g').attr('class', 'annotation')

    this.update(data, options)
  },

  update: function (data, options) {
    options = _.assign(this._options, options)
    var margin = options.margin

    var h = this._height - margin.top - margin.bottom
    var w = this._width - margin.left - margin.right
    var dataMarginLeft = 20

    var domain

    if (_.isFunction(options.domain)) {
      domain = options.domain(data)
    } else {
      domain = _(data).map(options.values).flatten().map(options.x).value()
    }

    var xScale = d3.scale.ordinal()
      .domain(domain)
      .rangeBands([0, w], options.padding)

    var dataXScale = d3.scale.ordinal()
      .domain(domain)
      .rangeBands([dataMarginLeft, w], options.padding)

    var x = _.flow(options.x, dataXScale)

    var range
    if (_.isFunction(options.range)) {
      range = options.range(data)
    } else {
      range = d3.extent(_(data).map(options.values).flatten().value(), function (d) {
        return options.y0(d) + options.y(d)
      })

      // Make sure we always have at least a 0 baseline
      range[0] = Math.min(0, range[0])
    }

    var yScale = options.yScale()
      .domain(range)
      .range([h, 0])

    var y = function (d) {
      return yScale(options.y0(d) + options.y(d))
    }

    var height = function (d) {
      var y0 = options.y0(d)
      var y = options.y(d)

      return yScale(y0) - yScale(y0 + y)
    }

    var svg = this._svg
    var g = svg.select('.data')
    var series = g.selectAll('.bar').data(data)

    svg.select('.bg')
      .attr({
        'height': h + margin.top,
        'width': w,
        'x': margin.left
      })

    series.enter().append('g')
      .attr('class', 'bar')

    var fill = options.hasOwnProperty('color')
      ? options.color
      : _.flow(options.name, color.scale(_.map(data, options.name)))

    series.style('fill', fill)
    series.exit().remove()

    var hover = d3.dispatch('over', 'out')

    var column = series.selectAll('rect').data(options.values)

    column.enter()
      .append('rect')
      .style('fill', 'inherit')

    column.attr({
      'height': height,
      'width': xScale.rangeBand(),
      'x': x,
      'y': y
    })
      .on('mouseover', hover.over)
      .on('mouseout', hover.out)

    column.exit().remove()

    svg.select('.x.axis')
      .call(d3.svg.axis()
        .orient('bottom')
        .tickSize(0)
        .tickPadding(4)
        .tickValues(_.filter(xScale.domain(), function (d, i, domain) {
          // Include every fourth tick value unless that tick is within three
          // ticks of the last value. Always include the last tick. We have to
          // do this manually because D3 ignores the ticks() value for
          // ordinal scales
          return (i % 4 === 0 && i + 3 < domain.length) || (i + 1) === domain.length
        }))
        .tickFormat(options.xFormat)
        .scale(dataXScale))

    svg.select('.y.axis')
      .call(d3.svg.axis()
        .orient('right')
        .tickFormat(options.yFormat)
        .tickSize(w)
        .ticks(3)
        .scale(yScale))

    svg.selectAll('.y.axis text')
      .attr({
        'dx': -w,
        'dy': -4
      })

    var fmt = _.flow(options.y, options.yFormat)

    var seriesLabel = label()
      .addClass('series')
      .width(w)
      .height(h)
      .align(false)

    var legendText = _(data)
      .map(function (d) {
        return options.name(d)
      })
      .value()

    var fillColor = d3.scale.ordinal().range(['#B6D0D4', '#D95449'])
    var legend = svg.select('.legend').selectAll('*')
      .data(legendText)
      .enter().append('g')
      .attr('class', 'series')
      .attr('transform', function (d, i) { return 'translate(0,' + i * 15 + ')' })

    legend.append('rect')
      .attr('x', w - 15)
      .attr('y', -25)
      .attr('width', 10)
      .attr('height', 10)
      .style('fill', fillColor)

    legend.append('text')
      .attr('x', w - 20)
      .attr('y', -25)
      .attr('dy', '0.85em')
      .style({
        'text-anchor': 'end',
        'fill': '#999999'
      })
      .text(function (d) { return d })

    var timeout = null

    hover.on('out', function () {
      timeout = window.setTimeout(function () {
        timeout = null

        g.selectAll('rect')
          .transition()
          .duration(300)
          .style('opacity', 1)

        svg.selectAll('.x.axis text').style('opacity', 1)

        svg.select('.annotation').selectAll('*').remove()
      }, 200)
    })

    hover.on('over', function (d) {
      if (_.isNumber(timeout)) {
        window.clearTimeout(timeout)
        timeout = null
      }

      g.selectAll('rect')
        .transition()
        .duration(500)
        .style('opacity', function (e) {
          return options.x(d) === options.x(e) ? 1 : 0.5
        })

      svg.selectAll('.x.axis text').style('opacity', 0)
      var annotations = _(data)
        .map(function (s) {
          return _.assign({},
            _.find(options.values(s), function (e) {
              return options.x(d) === options.x(e)
            }),
            { name: options.name(s) }
          )
        })
        .map(function (d) {
          return {
            text: d.name + ' ' + fmt(d),
            x: x(d),
            y: y(d),
            defined: _.isFinite(d.value)
          }
        })
        .tap(list => {
          if (_(list).some(item => (item.y >= h || item.y < 0))) {
            list.forEach(item => {
              item.y = 0
            })
          }
        })
        .each(item => { item.y = 0 })
        .reverse()
        .value()

      svg.select('.annotation').selectAll('.series.label')
        .data(annotations)
        .call(seriesLabel.align(true))

      var axisLabel = svg.select('.annotation')
        .selectAll('.axis.label')
        .data([options.x(d)])

      axisLabel.enter()
        .append('text')
        .attr('class', 'axis label')
        .style('text-anchor', 'middle')

      axisLabel
        .attr({
          'transform': 'translate(' + x(d) + ', ' + (h + margin.bottom) + ')',
          'dx': xScale.rangeBand() / 2
        })
        .text(options.xFormat)
    })
  }

})

export default ColumnChart
<commit_msg>delete the 0% display in column charts<commit_after>'use strict'

import _ from 'lodash'
import d3 from 'd3'

import browser from 'util/browser'
import label from 'chart/renderer/label'
import color from 'util/color'

var defaults = {
  margin: {
    top: 12,
    right: 0,
    bottom: 12,
    left: 0
  },
  name: _.partial(_.get, _, 'name', ''),
  padding: 0.1,
  values: _.property('values'),
  x: _.property('x'),
  xFormat: String,
  y: _.property('y'),
  y0: _.partial(_.get, _, 'y0', 0),
  yFormat: String,
  yScale: d3.scale.linear
}

function ColumnChart () {
}

_.extend(ColumnChart.prototype, {
  classNames: 'chart stacked-column',
  defaults: defaults,

  initialize: function (el, data, options) {
    options = this._options = _.defaults({}, options, this.defaults)

    var aspect = _.get(options, 'aspect', 1)
    this._width = _.get(options, 'width', el.clientWidth)
    this._height = _.get(options, 'height', this._width / aspect)

    var svg = this._svg = d3.select(el).append('svg')
      .attr({
        'viewBox': '0 0 ' + this._width + ' ' + this._height,
        'class': this.classNames
      })

    if (browser.isIE()) {
      svg.attr({
        'width': this._width,
        'height': this._height
      })
    }

    var h = this._height - options.margin.top - options.margin.bottom

    svg.append('rect').attr({
      'class': 'bg',
      'height': h + options.margin.top,
      'width': this._width - options.margin.left - options.margin.right,
      'x': options.margin.left
    })

    var g = svg.append('g')
      .attr('transform', 'translate(' + options.margin.left + ', ' +
      options.margin.top + ')')

    g.append('g').attr('class', 'data')

    g.append('g').attr('class', 'y axis')
    g.append('g').attr({
      'class': 'x axis',
      'transform': 'translate(0, ' + h + ')'
    })
    g.append('g').attr('class', 'legend')
    g.append('g').attr('class', 'annotation')

    this.update(data, options)
  },

  update: function (data, options) {
    options = _.assign(this._options, options)
    var margin = options.margin

    var h = this._height - margin.top - margin.bottom
    var w = this._width - margin.left - margin.right
    var dataMarginLeft = 20

    var domain

    if (_.isFunction(options.domain)) {
      domain = options.domain(data)
    } else {
      domain = _(data).map(options.values).flatten().map(options.x).value()
    }

    var xScale = d3.scale.ordinal()
      .domain(domain)
      .rangeBands([0, w], options.padding)

    var dataXScale = d3.scale.ordinal()
      .domain(domain)
      .rangeBands([dataMarginLeft, w], options.padding)

    var x = _.flow(options.x, dataXScale)

    var range
    if (_.isFunction(options.range)) {
      range = options.range(data)
    } else {
      range = d3.extent(_(data).map(options.values).flatten().value(), function (d) {
        return options.y0(d) + options.y(d)
      })

      // Make sure we always have at least a 0 baseline
      range[0] = Math.min(0, range[0])
    }

    var yScale = options.yScale()
      .domain(range)
      .range([h, 0])

    var y = function (d) {
      return yScale(options.y0(d) + options.y(d))
    }

    var height = function (d) {
      var y0 = options.y0(d)
      var y = options.y(d)

      return yScale(y0) - yScale(y0 + y)
    }

    var svg = this._svg
    var g = svg.select('.data')
    var series = g.selectAll('.bar').data(data)

    svg.select('.bg')
      .attr({
        'height': h + margin.top,
        'width': w,
        'x': margin.left
      })

    series.enter().append('g')
      .attr('class', 'bar')

    var fill = options.hasOwnProperty('color')
      ? options.color
      : _.flow(options.name, color.scale(_.map(data, options.name)))

    series.style('fill', fill)
    series.exit().remove()

    var hover = d3.dispatch('over', 'out')

    var column = series.selectAll('rect').data(options.values)

    column.enter()
      .append('rect')
      .style('fill', 'inherit')

    column.attr({
      'height': height,
      'width': xScale.rangeBand(),
      'x': x,
      'y': y
    })
      .on('mouseover', hover.over)
      .on('mouseout', hover.out)

    column.exit().remove()

    svg.select('.x.axis')
      .call(d3.svg.axis()
        .orient('bottom')
        .tickSize(0)
        .tickPadding(4)
        .tickValues(_.filter(xScale.domain(), function (d, i, domain) {
          // Include every fourth tick value unless that tick is within three
          // ticks of the last value. Always include the last tick. We have to
          // do this manually because D3 ignores the ticks() value for
          // ordinal scales
          return (i % 4 === 0 && i + 3 < domain.length) || (i + 1) === domain.length
        }))
        .tickFormat(options.xFormat)
        .scale(dataXScale))

    svg.select('.y.axis')
      .call(d3.svg.axis()
        .orient('right')
        .tickFormat(options.yFormat)
        .tickSize(w)
        .ticks(3)
        .scale(yScale))

    svg.selectAll('.y.axis text')
      .attr({
        'dx': -w,
        'dy': 8
      })

    d3.select(svg.selectAll('.y.axis text')[0][0]).attr('visibility', 'hidden')

    var fmt = _.flow(options.y, options.yFormat)

    var seriesLabel = label()
      .addClass('series')
      .width(w)
      .height(h)
      .align(false)

    var legendText = _(data)
      .map(function (d) {
        return options.name(d)
      })
      .value()

    var fillColor = d3.scale.ordinal().range(['#B6D0D4', '#D95449'])
    var legend = svg.select('.legend').selectAll('*')
      .data(legendText)
      .enter().append('g')
      .attr('class', 'series')
      .attr('transform', function (d, i) { return 'translate(0,' + i * 15 + ')' })

    legend.append('rect')
      .attr('x', w - 15)
      .attr('y', -25)
      .attr('width', 10)
      .attr('height', 10)
      .style('fill', fillColor)

    legend.append('text')
      .attr('x', w - 20)
      .attr('y', -25)
      .attr('dy', '0.85em')
      .style({
        'text-anchor': 'end',
        'fill': '#999999'
      })
      .text(function (d) { return d })

    var timeout = null

    hover.on('out', function () {
      timeout = window.setTimeout(function () {
        timeout = null

        g.selectAll('rect')
          .transition()
          .duration(300)
          .style('opacity', 1)

        svg.selectAll('.x.axis text').style('opacity', 1)

        svg.select('.annotation').selectAll('*').remove()
      }, 200)
    })

    hover.on('over', function (d) {
      if (_.isNumber(timeout)) {
        window.clearTimeout(timeout)
        timeout = null
      }

      g.selectAll('rect')
        .transition()
        .duration(500)
        .style('opacity', function (e) {
          return options.x(d) === options.x(e) ? 1 : 0.5
        })

      svg.selectAll('.x.axis text').style('opacity', 0)
      var annotations = _(data)
        .map(function (s) {
          return _.assign({},
            _.find(options.values(s), function (e) {
              return options.x(d) === options.x(e)
            }),
            { name: options.name(s) }
          )
        })
        .map(function (d) {
          return {
            text: d.name + ' ' + fmt(d),
            x: x(d),
            y: y(d),
            defined: _.isFinite(d.value)
          }
        })
        .tap(list => {
          if (_(list).some(item => (item.y >= h || item.y < 0))) {
            list.forEach(item => {
              item.y = 0
            })
          }
        })
        .each(item => { item.y = 0 })
        .reverse()
        .value()

      svg.select('.annotation').selectAll('.series.label')
        .data(annotations)
        .call(seriesLabel.align(true))

      var axisLabel = svg.select('.annotation')
        .selectAll('.axis.label')
        .data([options.x(d)])

      axisLabel.enter()
        .append('text')
        .attr('class', 'axis label')
        .style('text-anchor', 'middle')

      axisLabel
        .attr({
          'transform': 'translate(' + x(d) + ', ' + (h + margin.bottom) + ')',
          'dx': xScale.rangeBand() / 2
        })
        .text(options.xFormat)
    })
  }

})

export default ColumnChart
<|endoftext|>


<commit_before>/**
 * Created by tlzhang on 2015/12/9.
 */
var Controller = (function($){
    var controller = function(){};
    controller.fn = controller.prototype;

    controller.fn.proxy = function(func,obj,args,funcBef){
        if(!func) return;
        var self = this;
        return (function(){
            if(typeof funcBef === "function")
                funcBef.call(obj || self);
            return func.call(obj || self,args);
        });
    };

    controller.fn.load = function(func){
        return $(this.proxy(func));
    };

    controller.fn.include = function(obj){
        return $.extend(this,obj);
    };

    return controller;
})(jQuery);

var Map = (function (document) {

    function Map(){
        if(!(this instanceof Map)){
            return new Map();
        }

        this.container = {};
    }

    Map.prototype = function(){

        /*
         * put the key and value into container
         */
        put = function(key,value){
            try{
                var reg = /^[ ]+$/;
                if(key!=null && key!="" && !reg.test(key)){
                    this.container[key] = value;
                }

            }catch(e){
                throw new Error("Map Error:"+e.message);
            }
        };

        /*
         * get the value from Map by key
         */
        get = function(key){
            try{
                var reg = /^[ ]+$/;
                if(key!=null && key!="" && !reg.test(key)){
                    return this.container[key] == undefined ? null : this.container[key];
                }
                return null;
            }catch(e){
                throw new Error("Map Error:"+e.message);
            }
        };

        /*
         * remove from Map
         */
        remove = function(key){
            try{
                if(this.containsKey(key))
                    delete this.container[key];
            }catch(e){
                throw new Error("Map Error:"+e.message);
            }
        };

        /*
         * return all keys
         */
        keyArray = function(){
            var keys = new Array();
            for(var p in this.container){
                keys.push(p);
            }
            return keys;
        };

        /*
         * return all values
         */
        valueArray = function(){
            var values = new Array();
            var keys=this.keyArray();
            for(var i=0;i<keys.length;i++){
                values.push(this.container[keys[i]]);
            }
            return values;
        };

        /*
         * clear Map
         */
        clear = function(){
            try{
                delete this.container;
                this.container = {};
            }catch(e){
                throw new Error("Map Error:"+e.message);
            }
        };

        /*
         * judge Map is empty
         */
        isEmpty = function(){
            if(this.keyArray().length == 0)
                return true;
            else
                return false;
        };

        /*
         * the size of Map
         */
        size = function(){
            return this.keyArray().length;
        };

        return{
            put:this.put,
            get:this.get,
            remove:this.remove,
            clear:this.clear,
            isEmpty:this.isEmpty,
            size:this.size,
            keyArray:this.keyArray,
            valueArray:this.valueArray
        }
    }();

    return Map;

})(document);

(function($,document,Controller,Map){

    var Menu = (function($){
        function menu(options,obj){
            this.option = $.extend({},options || {},this._default());
            if(!this.option || !obj) return;
            this.defaultImageWidth = 25;
            this.defaultImageHeight = 25;
            this.defaultImageSrc = 'images/default.jpg';
            this._controller = new Controller();
            this._obj = obj;
            this.map = Map;
            this._getKey.call(this);//生成随机数
            this._onContextMenu(obj);
            return this;
        }

        menu.fn = menu.prototype;
        menu.extend = menu.fn.extend = $.extend;

        menu.fn.extend({

            _getKey : function(){
                var num = "";
                for(var i= 0;i < 15;i++){
                    num += Math.floor(Math.random()*10);
                }

                this._key = num;
            },

            /**
             * 获取默认属性
             * @private
             */
            _default : function(){
                return {
                    menu_box_cls:'menu_box',
                    menu_body_cls:'menu_body',
                    menu_ul_cls:'menu_ul',
                    menu_li_cls:'menu_li',
                    menu_li_a_cls:'menu_a',
                    menu_arrow_cls:'menu_triangle',
                    onContextMenu:null
                };
            },

            /**
             * 绑定对象右键菜单事件
             * @param obj
             * @private
             */
            _onContextMenu : function(obj){
                var self = this;
                $(obj).bind('contextmenu',function(e){
                    if ($(e.target).attr("data-key") == obj.attr("data-key")){
                        var _left = e.pageX;
                        var _top = e.pageY;

                        if(self._menu){
                            var _len = $("body").find('.menu_box').length;
                            if(_len > 0){
                                $("body").find('.menu_box').hide();
                            }
                            self._setMenuPosition.call(self,_left,_top);
                            self._menu.show();
                            return false;
                        }

                        var isShowContext = (!!self.option.onContextMenu) ? self.option.onContextMenu(e) : true;
                        if(isShowContext) self._showMenu.call(self,_left,_top);
                        return false;
                    }
                });

                /*$(document).bind('contextmenu',function(e){
                    if (!$(e.target).attr("data-key") || $(e.target).attr("data-key") != obj.attr("data-key")){
                        var _node = self._getMenu.call(self);
                        if(_node){
                            _node.hide();
                            return false;
                        }

                        return false;
                    }
                });*/

                $(document).on('click',function(){
                    if(self._menu)
                        self._menu.hide();
                });
            },

            _setMenuPosition : function(_left,_top){
                var _menu = this._menu;
                var top = _top,left = _left;
                if (_left + _menu.outerWidth() > $(document.body).width()) {//$(document).height() || $(window).height()
                    _left -= _menu.outerWidth();
                }

                if (_top + _menu.outerHeight() > $(document.body).height()) {
                    _top -= _menu.outerHeight();
                }

                if(_top > $(document.body).height()) _top =  $(document.body).height();
                if(_left > $(document.body).width()) _left =  $(document.body).width();

                this._menu.css({ 'left': _left, 'top': _top });
            },

            _getMenu : function(){
                var _node,self = this;
                var _menu_box = $("body").find(".menu_box");
                if(_menu_box.length > 0){
                    _menu_box.each(function(){
                        if($(this).attr("data-key") == self._key){
                            _node = $(this);
                            return false;
                        }
                    });
                }

                return _node;
            },

            _executeFun :function(func){
                if(typeof func !== "function") return;
                this._controller.proxy(func,this);
            },

            _createMenuLi : function(data,isChildren,i,key){
                var _menu_body_img = $('');
                var _menu_body_a = $(''+(data.text || '')+'');
                var _menu_body_li = '';

                if(isChildren){
                    _menu_body_a.append($(''));
                }
                if(key){
                    _menu_body_li = $('

');
                }else{
                    _menu_body_li = $('

');
                }

                var _menu_body_li_div = $('

');
                _menu_body_li_div.append(_menu_body_img);
                _menu_body_li_div.append(_menu_body_a);

                _menu_body_li.append(_menu_body_li_div);
                return _menu_body_li;
            },

            _bindLiClick : function(obj,map){
                var self = this;
                obj.find('li').each(function(){
                    if($(this).hasClass(self.option.menu_li_cls)){
                        if($(this).attr('tab-index')){
                            var func = map.get($(this).attr('tab-index'));
                            if(func){
                                if(typeof func == "function"){
                                    $(this).click(self._controller.proxy(func,self,undefined,function(){
                                        obj.hide();
                                    }));
                                }
                            }
                        }
                    }
                });
            },

            _showMenu : function(_left,_top){
                if(this._getMenu.call(this)) return;

                var _menu_box = $('

');
                var _menu_body = $('

');
                var _menu_body_ul = $('

');

                var _map = new Map();
                var _cMap = new Map();
                var _cLiHover = new Array();
                var _childrenBox = new Array();

                if(this.option.data && this.option.data.length > 0){
                    for(var i = 0,len = this.option.data.length;i < len;i++){
                        var _data = this.option.data[i];
                        if(!_data) continue;

                        if(!_data.img) _data.img = {};

                        //children
                        if(_data.children && _data.children.length > 0){
                            var _menu_box_c = $('

');
                            var _menu_body_c = $('

');
                            var _menu_body_ul_c = $('

');

                            for(var j = 0,cLen = _data.children.length;j < cLen;j++){
                                var _cData = _data.children[j];
                                if(!_cData) continue;

                                if(!_cData.img) _cData.img = {};
                                var _cDataKey = this._key + "_children_" + i +"_"+ (j + 1) +"_" + this._key+"_children_" + j;
                                _menu_body_ul_c.append(this._createMenuLi.call(this,_cData,false,j,_cDataKey));

                                _cMap.put(_cDataKey,_cData.click);
                            }

                            _menu_body_c.append(_menu_body_ul_c);
                            _menu_box_c.append(_menu_body_c);
                            var _menu_body_li = this._createMenuLi.call(this,_data,true,i);
                            _menu_body_li.prepend(_menu_box_c);
                            _menu_box_c.hide();
                            _menu_body_ul.append(_menu_body_li);
                            _childrenBox.push(_menu_box_c);
                            _cLiHover.push(_menu_body_li);
                        }else{
                            _map.put( i + 1 +"_" + this._key,_data.click);
                            //_menu_body_a.click(this._executeFun.call(this,_func));
                            _menu_body_ul.append(this._createMenuLi.call(this,_data,false,i));
                        }

                    }
                }

                _menu_body.append(_menu_body_ul);
                _menu_box.append(_menu_body);

                if(!_map.isEmpty()){
                    this._bindLiClick.call(this,_menu_box,_map);
                }

                if(!_cMap.isEmpty()){
                    if(_childrenBox && _childrenBox.length > 0){
                        for(var i = 0,len = _childrenBox.length;i < len;i++){
                            this._bindLiClick.call(this,_childrenBox[i],_cMap);
                        }
                    }
                }

                //bind hover event
                if(_cLiHover && _cLiHover.length > 0){
                    for(var i = 0,len = _cLiHover.length;i < len;i++){
                        var _li = _cLiHover[i];
                        if(!_li) continue;
                        _li.hover(function(){
                            $(this).find('.menu_box').show();
                            $(this).addClass('menu_li_hover');
                        },function(){
                            $(this).find('.menu_box').hide();
                            $(this).removeClass('menu_li_hover');
                        });
                    }
                }

                var _len = $("body").find('.menu_box').length;
                if(_len > 0){
                    $("body").find('.menu_box').hide();
                }
                $("body").append(_menu_box);
                this._menu = _menu_box;
                this._setMenuPosition(_left,_top);
                /*this._menu.bind('click',function(e){
                    e.stopPropagation();
                });*/
            }

        });

        return menu;
    })($);

    $.fn.contextMenu = function(options){
        if(!options) return;
        return new Menu(options,this);
    };

})(jQuery,document,Controller,Map);
<commit_msg>Update jquery.menu.js<commit_after>/**
 * Created by tlzhang on 2015/12/9.
 */
var Controller = (function($){
    var controller = function(){};
    controller.fn = controller.prototype;

    controller.fn.proxy = function(func,obj,args,funcBef){
        if(!func) return;
        var self = this;
        return (function(){
            if(typeof funcBef === "function")
                funcBef.call(obj || self);
            return func.call(obj || self,args);
        });
    };

    controller.fn.load = function(func){
        return $(this.proxy(func));
    };

    controller.fn.include = function(obj){
        return $.extend(this,obj);
    };

    return controller;
})(jQuery);

var Map = (function (document) {

    function Map(){
        if(!(this instanceof Map)){
            return new Map();
        }

        this.container = {};
    }

    Map.prototype = function(){

        /*
         * put the key and value into container
         */
        put = function(key,value){
            try{
                var reg = /^[ ]+$/;
                if(key!=null && key!="" && !reg.test(key)){
                    this.container[key] = value;
                }

            }catch(e){
                throw new Error("Map Error:"+e.message);
            }
        };

        /*
         * get the value from Map by key
         */
        get = function(key){
            try{
                var reg = /^[ ]+$/;
                if(key!=null && key!="" && !reg.test(key)){
                    return this.container[key] == undefined ? null : this.container[key];
                }
                return null;
            }catch(e){
                throw new Error("Map Error:"+e.message);
            }
        };

        /*
         * remove from Map
         */
        remove = function(key){
            try{
                if(this.containsKey(key))
                    delete this.container[key];
            }catch(e){
                throw new Error("Map Error:"+e.message);
            }
        };

        /*
         * return all keys
         */
        keyArray = function(){
            var keys = new Array();
            for(var p in this.container){
                keys.push(p);
            }
            return keys;
        };

        /*
         * return all values
         */
        valueArray = function(){
            var values = new Array();
            var keys=this.keyArray();
            for(var i=0;i<keys.length;i++){
                values.push(this.container[keys[i]]);
            }
            return values;
        };

        /*
         * clear Map
         */
        clear = function(){
            try{
                delete this.container;
                this.container = {};
            }catch(e){
                throw new Error("Map Error:"+e.message);
            }
        };

        /*
         * judge Map is empty
         */
        isEmpty = function(){
            if(this.keyArray().length == 0)
                return true;
            else
                return false;
        };

        /*
         * the size of Map
         */
        size = function(){
            return this.keyArray().length;
        };

        return{
            put:this.put,
            get:this.get,
            remove:this.remove,
            clear:this.clear,
            isEmpty:this.isEmpty,
            size:this.size,
            keyArray:this.keyArray,
            valueArray:this.valueArray
        }
    }();

    return Map;

})(document);

(function($,document,Controller,Map){

    var Menu = (function($){
        function menu(options,obj){
            this.option = $.extend({},options || {},this._default());
            if(!this.option || !obj) return;
            this.defaultImageWidth = 25;
            this.defaultImageHeight = 25;
            this.defaultImageSrc = 'images/default.jpg';
            this._controller = new Controller();
            this._obj = obj;
            this.map = Map;
            this._getKey.call(this);//生成随机数
            this._onContextMenu(obj);
            return this;
        }

        menu.fn = menu.prototype;
        menu.extend = menu.fn.extend = $.extend;

        menu.fn.extend({

            _getKey : function(){
                var num = "";
                for(var i= 0;i < 15;i++){
                    num += Math.floor(Math.random()*10);
                }

                this._key = num;
            },

            /**
             * 获取默认属性
             * @private
             */
            _default : function(){
                return {
                    menu_box_cls:'menu_box',
                    menu_body_cls:'menu_body',
                    menu_ul_cls:'menu_ul',
                    menu_li_cls:'menu_li',
                    menu_li_a_cls:'menu_a',
                    menu_arrow_cls:'menu_triangle',
                    onContextMenu:null
                };
            },

            /**
             * 绑定对象右键菜单事件
             * @param obj
             * @private
             */
            _onContextMenu : function(obj){
                var self = this;
                $(obj).bind('contextmenu',function(e){
                    if ($(e.target).attr("data-key") == obj.attr("data-key")){
                        var _left = e.pageX;
                        var _top = e.pageY;

                        if(self._menu){
                            var _len = $("body").find('.menu_box').length;
                            if(_len > 0){
                                $("body").find('.menu_box').hide();
                            }
                            self._setMenuPosition.call(self,_left,_top);
                            self._menu.show();
                            return false;
                        }

                        var isShowContext = (!!self.option.onContextMenu) ? self.option.onContextMenu(e) : true;
                        if(isShowContext) self._showMenu.call(self,_left,_top);
                        return false;
                    }
                });

                /*$(document).bind('contextmenu',function(e){
                    if (!$(e.target).attr("data-key") || $(e.target).attr("data-key") != obj.attr("data-key")){
                        var _node = self._getMenu.call(self);
                        if(_node){
                            _node.hide();
                            return false;
                        }

                        return false;
                    }
                });*/

                $(document).on('click',function(){
                    if(self._menu)
                        self._menu.hide();
                });
            },

            _setMenuPosition : function(_left,_top){
                var _menu = this._menu;
                var top = _top,left = _left;
                if (_left + _menu.outerWidth() > $(document.body).width()) {//$(document).height() || $(window).height()
                    _left -= _menu.outerWidth();
                }

                if (_top + _menu.outerHeight() > $(document.body).height()) {
                    _top -= _menu.outerHeight();
                }

                if(_top > $(document.body).height() && $(document.body).height() > 0) _top =  $(document.body).height();
                if(_left > $(document.body).width() && $(document.body).width() > 0) _left =  $(document.body).width();

                if(_top < 0){
                    _top = top;
                }

                if(_left < 0){
                    _left = left;
                }

                this._menu.css({ 'left': _left, 'top': _top });
            },

            _getMenu : function(){
                var _node,self = this;
                var _menu_box = $("body").find(".menu_box");
                if(_menu_box.length > 0){
                    _menu_box.each(function(){
                        if($(this).attr("data-key") == self._key){
                            _node = $(this);
                            return false;
                        }
                    });
                }

                return _node;
            },

            _executeFun :function(func){
                if(typeof func !== "function") return;
                this._controller.proxy(func,this);
            },

            _createMenuLi : function(data,isChildren,i,key){
                var _menu_body_img = $('');
                var _menu_body_a = $(''+(data.text || '')+'');
                var _menu_body_li = '';

                if(isChildren){
                    _menu_body_a.append($(''));
                }
                if(key){
                    _menu_body_li = $('

');
                }else{
                    _menu_body_li = $('

');
                }

                var _menu_body_li_div = $('

');
                _menu_body_li_div.append(_menu_body_img);
                _menu_body_li_div.append(_menu_body_a);

                _menu_body_li.append(_menu_body_li_div);
                return _menu_body_li;
            },

            _bindLiClick : function(obj,map){
                var self = this;
                obj.find('li').each(function(){
                    if($(this).hasClass(self.option.menu_li_cls)){
                        if($(this).attr('tab-index')){
                            var func = map.get($(this).attr('tab-index'));
                            if(func){
                                if(typeof func == "function"){
                                    $(this).click(self._controller.proxy(func,self,undefined,function(){
                                        obj.hide();
                                    }));
                                }
                            }
                        }
                    }
                });
            },

            _showMenu : function(_left,_top){
                if(this._getMenu.call(this)) return;

                var _menu_box = $('

');
                var _menu_body = $('

');
                var _menu_body_ul = $('

');

                var _map = new Map();
                var _cMap = new Map();
                var _cLiHover = new Array();
                var _childrenBox = new Array();

                if(this.option.data && this.option.data.length > 0){
                    for(var i = 0,len = this.option.data.length;i < len;i++){
                        var _data = this.option.data[i];
                        if(!_data) continue;

                        if(!_data.img) _data.img = {};

                        //children
                        if(_data.children && _data.children.length > 0){
                            var _menu_box_c = $('

');
                            var _menu_body_c = $('

');
                            var _menu_body_ul_c = $('

');

                            for(var j = 0,cLen = _data.children.length;j < cLen;j++){
                                var _cData = _data.children[j];
                                if(!_cData) continue;

                                if(!_cData.img) _cData.img = {};
                                var _cDataKey = this._key + "_children_" + i +"_"+ (j + 1) +"_" + this._key+"_children_" + j;
                                _menu_body_ul_c.append(this._createMenuLi.call(this,_cData,false,j,_cDataKey));

                                _cMap.put(_cDataKey,_cData.click);
                            }

                            _menu_body_c.append(_menu_body_ul_c);
                            _menu_box_c.append(_menu_body_c);
                            var _menu_body_li = this._createMenuLi.call(this,_data,true,i);
                            _menu_body_li.prepend(_menu_box_c);
                            _menu_box_c.hide();
                            _menu_body_ul.append(_menu_body_li);
                            _childrenBox.push(_menu_box_c);
                            _cLiHover.push(_menu_body_li);
                        }else{
                            _map.put( i + 1 +"_" + this._key,_data.click);
                            //_menu_body_a.click(this._executeFun.call(this,_func));
                            _menu_body_ul.append(this._createMenuLi.call(this,_data,false,i));
                        }

                    }
                }

                _menu_body.append(_menu_body_ul);
                _menu_box.append(_menu_body);

                if(!_map.isEmpty()){
                    this._bindLiClick.call(this,_menu_box,_map);
                }

                if(!_cMap.isEmpty()){
                    if(_childrenBox && _childrenBox.length > 0){
                        for(var i = 0,len = _childrenBox.length;i < len;i++){
                            this._bindLiClick.call(this,_childrenBox[i],_cMap);
                        }
                    }
                }

                //bind hover event
                if(_cLiHover && _cLiHover.length > 0){
                    for(var i = 0,len = _cLiHover.length;i < len;i++){
                        var _li = _cLiHover[i];
                        if(!_li) continue;
                        _li.hover(function(){
                            $(this).find('.menu_box').show();
                            $(this).addClass('menu_li_hover');
                        },function(){
                            $(this).find('.menu_box').hide();
                            $(this).removeClass('menu_li_hover');
                        });
                    }
                }

                var _len = $("body").find('.menu_box').length;
                if(_len > 0){
                    $("body").find('.menu_box').hide();
                }
                $("body").append(_menu_box);
                this._menu = _menu_box;
                this._setMenuPosition(_left,_top);
                /*this._menu.bind('click',function(e){
                    e.stopPropagation();
                });*/
            }

        });

        return menu;
    })($);

    $.fn.contextMenu = function(options){
        if(!options) return;
        return new Menu(options,this);
    };

})(jQuery,document,Controller,Map);
<|endoftext|>


<commit_before>'use strict'

$(function() {
    var getListings = require('./firebase.js')['getListings'];
    var getFavorites = require('./firebase.js')['getFavorites'];
    var df
    var auth = require('./firebase.js')["auth"];
    var itemImagesRef = require('./firebase.js')["itemImagesRef"];
    var addFavoriteToProfile = require('./firebase.js')['addFavoriteToProfile'];
    var removeFavorite = require('./firebase.js')['removeFavorite'];
    var getFavoriteObjects = require('./firebase.js')['getFavoriteObjects'];
    var getImage = require('./firebase.js')['getImage'];
    var initializeMessage = require('./firebase.js')['initializeMessage'];
    var getItemsById = require('./firebase.js')['getItemsById'];
    var getUserInfoProper = require('./firebase.js')['getUserInfoProper'];

    var favoriteTemplate = $('#favorite-template');
    $('#message-popup-confirmation').hide();

    var showFavoritesInSidebar = function(favorites) {
        var str = $('#favorite-template').text();
        var compiled = _.template(str);

        $('#favorite-holder').empty();
        $('#favorite-holder').append(compiled({favorites: favorites}));

        for (var i = 0; i < favorites.length; i += 1) {
            (function (x) {
                getImage(favorites[x]['id'] + '/imageOne', function(url) {
                    let tagToAdd = ".favorite-image img:eq(" + x  + " )";
                    $(tagToAdd).attr({src: url});
                });
            })(i);
        }
    };

    auth.onAuthStateChanged(function(user) {
        if (user && $(favoriteTemplate).length > 0) {
            getFavoriteObjects(showFavoritesInSidebar);
            $("#find-favorite-logged-in").css('display', 'block');
            $("#find-favorite-logged-out").css('display', 'none');

            // favorite icon highlight/changes
            $('body').on('mouseenter', '.find-result-favorite-image', function() {
                $(this).attr('src', '../media/ic_heart_hover.png');
                $(this).css('opacity', 1);
            }).on('mouseout', '.find-result-favorite-image', function() {
                if (!this.favorited) {
                    $(this).attr('src', '../media/ic_heart.png');
                    $(this).css('opacity', '0.3');
                }
            }).on('click', '.find-result-favorite-image', function() {
                this.favorited = this.favorited || false;
                if (!this.favorited) {
                    $(this).attr('src', '../media/ic_heart_hover.png');
                    addFavoriteToProfile(auth.currentUser.uid, $(this).attr('uid'));
                    getFavoriteObjects(showFavoritesInSidebar);

                } else {
                    $(this).attr('src', '../media/ic_heart.png');
                    removeFavorite($(this).attr('uid'));
                    getFavoriteObjects(showFavoritesInSidebar);
                }
                this.favorited = !this.favorited;
            });
        } else {
            $("#find-favorite-logged-in").css('display', 'none');
            $("#find-favorite-logged-out").css('display', 'block');
        }
    });

    var newSearch = function(currentItems, keywords = [], tags = [], hubs = [], priceRange = []) {
        Promise.resolve(currentItems).then(function(itemList) {

            console.log(hubs);
            console.log(keywords);
            console.log(tags);
            console.log(priceRange);
            var str = $('#find-results-template').text();
            var compiled = _.template(str);
            var imagePaths = [];
            var filteredItemList = {};

            for (var item in itemList) {
                var currentItem = itemList[item];
                var itemID = currentItem['id'];
                var itemDescription = currentItem['description'].toLowerCase();
                var itemTitle = currentItem['title'].toLowerCase();
                var itemPrice = parseInt(currentItem['price'])
                imagePaths.push(itemID);

                if (hubs.length > 0 && !hubs.some(hub => currentItem['hubs'].includes(hub))) {
                    continue;
                }

                if (tags.length > 0 && !tags.some(tag => currentItem['tags'].includes(tag))) {
                    continue;
                }

                if (keywords.length > 0 && (!keywords.some(key => itemTitle.includes(key)) &&
                    !keywords.some(key => itemDescription.includes(key)))) {
                        continue
                }

                if (itemPrice < priceRange[0] || itemPrice > priceRange[1]) {
                    continue;
                }

                filteredItemList[itemID] = currentItem
            }

            $("#find-content-presearch").hide()
            $('#find-results-holder').empty();
            $('#find-results-holder').append(compiled({filteredItemList: filteredItemList}));

            getFavorites(showFavoritesInSearches);

            for (var i = 0; i < imagePaths.length; i += 1) {
                (function (x) {
                    getImage(imagePaths[x] + '/imageOne', function(url) {
                        $("#" + imagePaths[x]).attr({src: url});
                    });
                })(i);
            }
        });
    };

    function updateSliderRange ( min, max ) {
        updateSlider.noUiSlider.updateOptions({
            range: {
                'min': min,
                'max': max
            }
        });
    }

    var showItemsBasedOnHash = function() {
        if (location.hash.length > 0) {
            let hashKeys = location.hash.split('?');
            let key = hashKeys[0].split("=")[1];
            let hubs = hashKeys[1].split("=")[1];
            let tags = hashKeys[2].split("=")[1];

            if (tags.length === 0) {
                tags = [];
            } else {
                tags = tags.split(',');
            }

            if (key.length === 0) {
                key = [];
            } else {
                key = key.split(',');
            }

            if (hubs.length === 0) {
                hubs = [];
            } else {
                hubs = hubs.split(',');
            }

            let priceRange = [parseInt(hashKeys[3].split("=")[1]), parseInt(hashKeys[4].split("=")[1])];
            updateSliderRange(priceRange[0], priceRange[1]);

            $("#find-keywords").val(key.join(" "));
            $('#find-tags').textext()[0].tags().addTags(tags);

            newSearch(getListings(), key, tags, hubs, priceRange);
        }
    }

    var slider = $("#search-slider");
    if (window.location.pathname === "/find/find.html") {
        // Add dropdown hub selector
        $('select').material_select();
        // add slider
        noUiSlider.create(slider[0], {
            start: [1, 500],
            connect: true,
            step: 1,
            tooltips: true,
            format: wNumb({
                decimals: 0,
                thousand: ',',
                prefix: '$',
            }),
            range: {
                'min': 1,
                'max': 3000
            }
        });

        slider[0].noUiSlider.get()

        // add autofill tags
        var findTags = $('#find-tags');
        findTags.textext({plugins : 'tags autocomplete'})
            .bind('getSuggestions', function(e, data){
                var list = [
                        'Table',
                        'Desk',
                        'Computer',
                        'Electronics',
                        'iPhone',
                        'Cell-Phone',
                        'Apple',
                        'Macbook',
                        'Chair',
                        'Leather',
                        'Clothing',
                        'Bedroom',
                        'Bathroom',
                        'Couch',
                        'Kitchen',
                        'Living-Room',
                        'Dinner-Table'
                    ],
                    textext = $(e.target).textext()[0],
                    query = (data ? data.query : '') || '';

                $(this).trigger('setSuggestions',{
                    result : textext.itemManager().filter(list, query) }
                );
        });

        showItemsBasedOnHash();
    }

    var showFavoritesInSearches = function(currentFavorites) {
        $('.find-result-favorite-image').each(function() {
            var  currentImageID = $(this).attr('uid');
            if(currentFavorites && currentFavorites[currentImageID]) {
                $(this).attr('src', '../media/ic_heart_hover.png');
                $(this).css('opacity', 1);
                this.favorited = true;

            }

        });
    };

    $("#find-search-button").click(function () {
        let query = "key=";
        let keywords = $("#find-keywords").val().toLowerCase().trim().split(/\s+/);
        let hubs = $("#find-hubs").val();
        let tags = $('#find-tags').textext()[0].tags()._formData;
        let priceRange = slider[0].noUiSlider.get();

        for (let i = 0; i < priceRange.length; i += 1) {
            priceRange[i] = parseInt(priceRange[i].replace(/[^0-9.]/g, ''));
        }

        for (let i = 0; i < tags.length; i += 1) {
            tags[i] = tags[i].toLowerCase();
        }

        query += `${keywords}?hub=${hubs}?tags=${tags}?priceMin=${priceRange[0]}?priceMax=${priceRange[1]}`;
        location.hash = query;

        newSearch(getListings(), keywords, tags, hubs, priceRange);
    });

    $('.close-button').click(function () {
        $('#message-popup').animate({
            opacity: 0,
            'z-index': -100
        }, 100);
    });

    let newMessageId;
    let newMessageImagePath;

    $('body').on('click', '.card-contact', function () {
        let parentDiv = $(this).parent().parent();
        let imageDiv = parentDiv[0].children[2];
        newMessageImagePath = $(imageDiv)[0].children[0].src;
        newMessageId = $(imageDiv)[0].children[0].id;

        $('#message-popup').css('z-index', '100').animate({
            opacity: 1
        }, 50);
    });

    $('#message-popup-send-button').click(function() {
        let newMessageSellerId;
        let newMessageContent = $($(this).parent()[0].children[2]).val();

        Promise.resolve(getItemsById([newMessageId]))
            .then(function(items) {

                for (let item in items) {
                    newMessageSellerId = items[item].uid;
                }

                return Promise.all([getUserInfoProper(newMessageSellerId),
                    getUserInfoProper(auth.currentUser.uid)]);
            })
            .then(function(results) {
                let currentUser = results[1];
                let otherUser = results[0]
                let myUsername = currentUser['username'];
                let otherUsername = otherUser['username'];
                initializeMessage(auth.currentUser.uid, newMessageSellerId,
                    newMessageId, newMessageImagePath, newMessageContent, otherUsername, myUsername);

                $('#message-popup-content').fadeOut(500);

                setTimeout(function () {
                    $('#message-popup-inner').css({
                        'display': 'flex',
                        'align-items': 'center',
                        'justify-content': 'center'
                    });
                    $('#message-popup-confirmation').fadeIn();
                }, 500);

            })
    });

});
<commit_msg>preparing merge<commit_after>'use strict'

$(function() {
    var getListings = require('./firebase.js')['getListings'];
    var getFavorites = require('./firebase.js')['getFavorites'];
    var df
    var auth = require('./firebase.js')["auth"];
    var itemImagesRef = require('./firebase.js')["itemImagesRef"];
    var addFavoriteToProfile = require('./firebase.js')['addFavoriteToProfile'];
    var removeFavorite = require('./firebase.js')['removeFavorite'];
    var getFavoriteObjects = require('./firebase.js')['getFavoriteObjects'];
    var getImage = require('./firebase.js')['getImage'];
    var initializeMessage = require('./firebase.js')['initializeMessage'];
    var getItemsById = require('./firebase.js')['getItemsById'];
    var getUserInfoProper = require('./firebase.js')['getUserInfoProper'];

    var favoriteTemplate = $('#favorite-template');
    $('#message-popup-confirmation').hide();

    var showFavoritesInSidebar = function(favorites) {
        var str = $('#favorite-template').text();
        var compiled = _.template(str);

        $('#favorite-holder').empty();
        $('#favorite-holder').append(compiled({favorites: favorites}));

        for (var i = 0; i < favorites.length; i += 1) {
            (function (x) {
                getImage(favorites[x]['id'] + '/imageOne', function(url) {
                    let tagToAdd = ".favorite-image img:eq(" + x  + " )";
                    $(tagToAdd).attr({src: url});
                });
            })(i);
        }
    };

    auth.onAuthStateChanged(function(user) {
        if (user && $(favoriteTemplate).length > 0) {
            getFavoriteObjects(showFavoritesInSidebar);
            $("#find-favorite-logged-in").css('display', 'block');
            $("#find-favorite-logged-out").css('display', 'none');

            // favorite icon highlight/changes
            $('body').on('mouseenter', '.find-result-favorite-image', function() {
                $(this).attr('src', '../media/ic_heart_hover.png');
                $(this).css('opacity', 1);
            }).on('mouseout', '.find-result-favorite-image', function() {
                if (!this.favorited) {
                    $(this).attr('src', '../media/ic_heart.png');
                    $(this).css('opacity', '0.3');
                }
            }).on('click', '.find-result-favorite-image', function() {
                this.favorited = this.favorited || false;
                if (!this.favorited) {
                    $(this).attr('src', '../media/ic_heart_hover.png');
                    addFavoriteToProfile(auth.currentUser.uid, $(this).attr('uid'));
                    getFavoriteObjects(showFavoritesInSidebar);

                } else {
                    $(this).attr('src', '../media/ic_heart.png');
                    removeFavorite($(this).attr('uid'));
                    getFavoriteObjects(showFavoritesInSidebar);
                }
                this.favorited = !this.favorited;
            });
        } else {
            $("#find-favorite-logged-in").css('display', 'none');
            $("#find-favorite-logged-out").css('display', 'block');
        }
    });

    var newSearch = function(currentItems, keywords = [], tags = [], hubs = [], priceRange = []) {
        Promise.resolve(currentItems).then(function(itemList) {

            console.log(hubs);
            console.log(keywords);
            console.log(tags);
            console.log(priceRange);
            var str = $('#find-results-template').text();
            var compiled = _.template(str);
            var imagePaths = [];
            var filteredItemList = {};

            for (var item in itemList) {
                var currentItem = itemList[item];
                var itemID = currentItem['id'];
                var itemDescription = currentItem['description'].toLowerCase();
                var itemTitle = currentItem['title'].toLowerCase();
                var itemPrice = parseInt(currentItem['price'])
                imagePaths.push(itemID);

                if (hubs.length > 0 && !hubs.some(hub => currentItem['hubs'].includes(hub))) {
                    continue;
                }

                if (tags.length > 0 && !tags.some(tag => currentItem['tags'].includes(tag))) {
                    continue;
                }

                if (keywords.length > 0 && (!keywords.some(key => itemTitle.includes(key)) &&
                    !keywords.some(key => itemDescription.includes(key)))) {
                        continue
                }

                if (itemPrice < priceRange[0] || itemPrice > priceRange[1]) {
                    continue;
                }

                filteredItemList[itemID] = currentItem
            }

            $("#find-content-presearch").hide()
            $('#find-results-holder').empty();
            $('#find-results-holder').append(compiled({filteredItemList: filteredItemList}));

            getFavorites(showFavoritesInSearches);

            for (var i = 0; i < imagePaths.length; i += 1) {
                (function (x) {
                    getImage(imagePaths[x] + '/imageOne', function(url) {
                        $("#" + imagePaths[x]).attr({src: url});
                    });
                })(i);
            }
        });
    };

    function updateSliderRange ( min, max ) {
        updateSlider.noUiSlider.updateOptions({
            range: {
                'min': min,
                'max': max
            }
        });
    }

    var showItemsBasedOnHash = function() {
        if (location.hash.length > 0) {
            let hashKeys = location.hash.split('?');
            let key = hashKeys[0].split("=")[1];
            let hubs = hashKeys[1].split("=")[1];
            let tags = hashKeys[2].split("=")[1];

            if (tags.length === 0) {
                tags = [];
            } else {
                tags = tags.split(',');
            }

            if (key.length === 0) {
                key = [];
            } else {
                key = key.split(',');
            }

            if (hubs.length === 0) {
                hubs = [];
            } else {
                hubs = hubs.split(',');
            }

            let priceRange = [parseInt(hashKeys[3].split("=")[1]), parseInt(hashKeys[4].split("=")[1])];
            updateSliderRange(priceRange[0], priceRange[1]);

            $("#find-keywords").val(key.join(" "));
            $('#find-tags').textext()[0].tags().addTags(tags);

            newSearch(getListings(), key, tags, hubs, priceRange);
        }
    }

    var slider = $("#search-slider");
    if (window.location.pathname === "/find/find.html") {
        // Add dropdown hub selector
        $('select').material_select();
        // add slider
        noUiSlider.create(slider[0], {
            start: [1, 500],
            connect: true,
            step: 1,
            tooltips: true,
            format: wNumb({
                decimals: 0,
                thousand: ',',
                prefix: '$',
            }),
            range: {
                'min': 1,
                'max': 3000
            }
        });

        slider[0].noUiSlider.get()

        // add autofill tags
        var findTags = $('#find-tags');
        findTags.textext({plugins : 'tags autocomplete'})
            .bind('getSuggestions', function(e, data){
                var list = [
                        'Table',
                        'Desk',
                        'Computer',
                        'Electronics',
                        'iPhone',
                        'Cell-Phone',
                        'Apple',
                        'Macbook',
                        'Chair',
                        'Leather',
                        'Clothing',
                        'Bedroom',
                        'Bathroom',
                        'Couch',
                        'Kitchen',
                        'Living-Room',
                        'Dinner-Table'
                    ],
                    textext = $(e.target).textext()[0],
                    query = (data ? data.query : '') || '';

                $(this).trigger('setSuggestions',{
                    result : textext.itemManager().filter(list, query) }
                );
        });

        showItemsBasedOnHash();
    }

    var showFavoritesInSearches = function(currentFavorites) {
        $('.find-result-favorite-image').each(function() {
            var  currentImageID = $(this).attr('uid');
            if(currentFavorites && currentFavorites[currentImageID]) {
                $(this).attr('src', '../media/ic_heart_hover.png');
                $(this).css('opacity', 1);
                this.favorited = true;

            }

        });
    };

    $("#find-search-button").click(function () {
        let query = "key=";
        let keywords = $("#find-keywords").val().toLowerCase().trim().split(/\s+/);
        let hubs = $("#find-hubs").val();
        let tags = $('#find-tags').textext()[0].tags()._formData;
        let priceRange = slider[0].noUiSlider.get();

        for (let i = 0; i < priceRange.length; i += 1) {
            priceRange[i] = parseInt(priceRange[i].replace(/[^0-9.]/g, ''));
        }

        for (let i = 0; i < tags.length; i += 1) {
            tags[i] = tags[i].toLowerCase();
        }

        query += `${keywords}?hub=${hubs}?tags=${tags}?priceMin=${priceRange[0]}?priceMax=${priceRange[1]}`;
        location.hash = query;

        newSearch(getListings(), keywords, tags, hubs, priceRange);
    });

    $('.close-button').click(function () {
        $('#message-popup').animate({
            opacity: 0,
            'z-index': -100
        }, 100);
    });

    let newMessageId;
    let newMessageImagePath;

    $('body').on('click', '.card-contact', function () {
        let parentDiv = $(this).parent().parent();
        let imageDiv = parentDiv[0].children[2];
        newMessageImagePath = $(imageDiv)[0].children[0].src;
        newMessageId = $(imageDiv)[0].children[0].id;

        $('#message-popup').css('z-index', '100').animate({
            opacity: 1
        }, 50);
    });

    $('#message-popup-send-button').click(function() {
        let newMessageSellerId;
        let newMessageContent = $($(this).parent()[0].children[2]).val();

        Promise.resolve(getItemsById([newMessageId]))
            .then(function(items) {

                for (let item in items) {
                    newMessageSellerId = items[item].uid;
                }

                return Promise.all([getUserInfoProper(newMessageSellerId),
                    getUserInfoProper(auth.currentUser.uid)]);
            })
            .then(function(results) {
                let currentUser = results[1];
                let otherUser = results[0]
                let myUsername = currentUser['username'];
                let otherUsername = otherUser['username'];
                initializeMessage(auth.currentUser.uid, newMessageSellerId,
                    newMessageId, newMessageImagePath, newMessageContent, otherUsername, myUsername);

                $('#message-popup-content').fadeOut(500);

                setTimeout(function () {
                    $('#message-popup-inner').css({
                        'display': 'flex',
                        'align-items': 'center',
                        'justify-content': 'center'
                    });
                    $('#message-popup-confirmation').fadeIn();
                }, 500);

            })
    });

});
<|endoftext|>


<commit_before>'use strict';

const { sep } = require('path');

const isNodeModule = new RegExp(`${sep}node_modules${sep}`);
const isTestUtil = new RegExp(`teatime-test-utils${sep}tool`);

const cssModulesRequireHook = require('css-modules-require-hook');
cssModulesRequireHook({
  generateScopedName: '[name]--[local]',
});

const babelRegister = require('babel-register');
babelRegister({
  ignore: filename =>
    !isTestUtil.test(filename) && isNodeModule.test(filename),
  presets: [
    'babel-preset-power-assert',
  ],
});
<commit_msg>possibility to adjust the scoped name<commit_after>'use strict';

const { sep } = require('path');

const isNodeModule = new RegExp(`${sep}node_modules${sep}`);
const isTestUtil = new RegExp(`teatime-test-utils${sep}tool`);

const cssModulesRequireHook = require('css-modules-require-hook');
cssModulesRequireHook({
  generateScopedName: typeof process.env.GENERATE_SCOPED_NAME !== 'undefined'
    ? process.env.GENERATE_SCOPED_NAME
    : '[name]--[local]',
});

const babelRegister = require('babel-register');
babelRegister({
  ignore: filename =>
    !isTestUtil.test(filename) && isNodeModule.test(filename),
  presets: [
    'babel-preset-power-assert',
  ],
});
<|endoftext|>