<commit_before>// Dependencies

let builder = require('focus').component.builder;
let type = require('focus').component.types;

// Mixins

let valueBehaviour = require('./mixin/value-behaviour');
let validationBehaviour = require('./mixin/validation-behaviour');

// Components

let builtInComponents = require('./mixin/built-in-components');

let FieldMixin = {
    mixins: [valueBehaviour, validationBehaviour, builtInComponents],
    /**
    * Get field default properties.
    */
    getDefaultProps: function getFieldDefaultProps() {
        return {

            /**
            * Edition mode of the field.
            * @type {Boolean}
            */
            isEdit: true,
            /**
            * HTML input type.
            * @type {String}
            */
            type: 'text',
            /**
            * Field name.
            * @type {string}
            */
            name: undefined,
            /**
            * Css properties of the component.
            * @type {Object}
            */
            style: {}
        };
    },
    /** @inheritdoc */
    propTypes: {
        isEdit: type('bool'),
        type: type('string'),
        name: type('string'),
        value: type(['string', 'number'])
    },

    /** @inheritdoc */
    componentWillReceiveProps: function fieldWillReceiveProps(newProps){
        this.setState({value: newProps.value, values: newProps.values});
    },
    /**
    * Get the css class of the field component.
    */
    _className: function() {
        let stateClass = this.state.error ? "has-feedback has-error" : "";
        return `form-group ${stateClass} ${this.props.style.className}`;
    },

    render: function renderField() {
        return (

                {this.label()}
                {this.props.isEdit ? (this.props.values ? this.select() : this.input()) : this.display()}
                {this.help()}
                {this.error()}

);
        }
    };
    module.exports = builder(FieldMixin);
<commit_msg>[field] Rewrite the field.<commit_after>// Dependencies

let builder = require('focus').component.builder;
let type = require('focus').component.types;

// Mixins

let valueBehaviour = require('./mixin/value-behaviour');
let validationBehaviour = require('./mixin/validation-behaviour');

// Components

let builtInComponents = require('./mixin/built-in-components');

/**
 * Mixin for the field helper.
 * @type {Object}
 */
let FieldMixin = {
    /** @inheriteDoc */
    mixins: [valueBehaviour, validationBehaviour, builtInComponents],
    /** @inheriteDoc */
   getDefaultProps() {
        return {

            /**
            * Edition mode of the field.
            * @type {Boolean}
            */
            isEdit: true,
            /**
            * HTML input type.
            * @type {String}
            */
            type: 'text',
            /**
            * Field name.
            * @type {string}
            */
            name: undefined,
            /**
            * Css properties of the component.
            * @type {Object}
            */
            style: {}
        };
    },
    /** @inheritdoc */
    propTypes: {
        isEdit: type('bool'),
        type: type('string'),
        name: type('string'),
        value: type(['string', 'number'])
    },
    /** @inheritdoc */
    componentWillReceiveProps: function fieldWillReceiveProps(newProps){
        this.setState({value: newProps.value, values: newProps.values});
    },
    /**
    * Get the css class of the field component.
    */
    _className(){
        let stateClass = this.state.error ? 'has-feedback has-error' : '';
        return `form-group ${stateClass} ${this.props.style.className}`;
    },
    /** @inheritdoc */
    render() {
        let {domain, isRequired, isEdit, values} = this.props;
        let {input, label, select, display, help, error, _className} = this;
        return (

                {label()}
                {isEdit ? (values ? select() : input()) : display()}
                {help()}
                {error()}

        );
    }
};
module.exports = builder(FieldMixin);
<|endoftext|>


<commit_before>/* ======= Global Utilities ======= */

/**
* Compiles a template with given data
* @param {String} template
* @param {Object} data
* @return {String} Template with data rendered
*/
var compileTemplate = function(template, data) {
  var code = template,
      templateRe = /{{([A-Za-z0-9_.()\[\]]+)}}/gi;
  code.replace(templateRe, function(match, key) {
    code = code.replace(match, "' + data['" + key + "'] + '");
  });
  var compile = new Function("data", "var out = '" + code + "'; return out");
  var output = compile(data);
  return output;
}

/**
* Converts attributes into key-value pairs
* @param {Node} node
* @return {Object} Key-Value pairs of Attributes
*/
var extractAttrs = function(node) {
  var attrs = {};
  if(!node.attributes) return attrs;
  var rawAttrs = node.attributes;
  for(var i = 0; i < rawAttrs.length; i++) {
    attrs[rawAttrs[i].name] = rawAttrs[i].value
  }

  return attrs;
}

/**
* Creates a Virtual DOM Node
* @param {String} type
* @param {Array} children
* @param {Object} props
* @return {Object} Node For Virtual DOM
*/
var createElement = function(type, val, props, children) {
  return {type: type, val: val, props: props, children: children};
}

/**
* Creates Virtual DOM
* @param {Node} node
* @return {Object} Virtual DOM
*/
var createVirtualDOM = function(node) {
  var children = [];
  for(var i = 0; i < node.childNodes.length; i++) {
    children.push(createVirtualDOM(node.childNodes[i]));
  }
  return createElement(node.nodeName, node.textContent, extractAttrs(node), children);
}

/**
* Gets Root Element
* @param {String} html
* @return {Node} Root Element
*/
var getRootElement = function(html) {
  var dummy = document.createElement('div');
  dummy.innerHTML = html;
  return dummy.firstChild;
}

/**
* Merges two Objects
* @param {Object} obj
* @param {Object} obj2
* @return {Object} Merged Objects
*/
function merge(obj, obj2) {
  for (var key in obj2) {
    if (obj2.hasOwnProperty(key)) obj[key] = obj2[key];
  }
  return obj;
}

/**
 * Compiles JSX to HTML
 * @param {String} tag
 * @param {Object} attrs
 * @param {Array} children
 * @return {String} HTML compiled from JSX
 */
 var h = function() {
 	 var args = Array.prototype.slice.call(arguments);
 	 var tag = args.shift();
   var attrs = args.shift() || {};
   var kids = args;
   var formattedAttrs = Object.keys(attrs).reduce(function(all, attr) {
   		return all + " " + attr + "='" + attrs[attr] + "'";
   }, '');
   var startTag = "<" + tag + formattedAttrs + ">";
   var endTag = "</" + tag + ">";
   var html = startTag + kids.join("") + endTag;
 	 return html;
 };

/**
 * Sets the Elements Initial Value
 * @param {Node} el
 * @param {String} value
 */
var setInitialElementValue = function(el, value) {
  el.innerHTML = value;
}

/**
 * Does No Operation
 */
var noop = function() {

}
<commit_msg>escape the newlines in template<commit_after>/* ======= Global Utilities ======= */

/**
* Compiles a template with given data
* @param {String} template
* @param {Object} data
* @return {String} Template with data rendered
*/
var compileTemplate = function(template, data) {
  var code = template,
      templateRe = /{{([A-Za-z0-9_.()\[\]]+)}}/gi;
  code.replace(templateRe, function(match, key) {
    code = code.replace(match, "' + data['" + key + "'] + '");
  });
  code = code.replace("\n", "' + \n'");
  var compile = new Function("data", "var out = '" + code + "'; return out");
  var output = compile(data);
  return output;
}

/**
* Converts attributes into key-value pairs
* @param {Node} node
* @return {Object} Key-Value pairs of Attributes
*/
var extractAttrs = function(node) {
  var attrs = {};
  if(!node.attributes) return attrs;
  var rawAttrs = node.attributes;
  for(var i = 0; i < rawAttrs.length; i++) {
    attrs[rawAttrs[i].name] = rawAttrs[i].value
  }

  return attrs;
}

/**
* Creates a Virtual DOM Node
* @param {String} type
* @param {Array} children
* @param {Object} props
* @return {Object} Node For Virtual DOM
*/
var createElement = function(type, val, props, children) {
  return {type: type, val: val, props: props, children: children};
}

/**
* Creates Virtual DOM
* @param {Node} node
* @return {Object} Virtual DOM
*/
var createVirtualDOM = function(node) {
  var children = [];
  for(var i = 0; i < node.childNodes.length; i++) {
    children.push(createVirtualDOM(node.childNodes[i]));
  }
  return createElement(node.nodeName, node.textContent, extractAttrs(node), children);
}

/**
* Gets Root Element
* @param {String} html
* @return {Node} Root Element
*/
var getRootElement = function(html) {
  var dummy = document.createElement('div');
  dummy.innerHTML = html;
  return dummy.firstChild;
}

/**
* Merges two Objects
* @param {Object} obj
* @param {Object} obj2
* @return {Object} Merged Objects
*/
function merge(obj, obj2) {
  for (var key in obj2) {
    if (obj2.hasOwnProperty(key)) obj[key] = obj2[key];
  }
  return obj;
}

/**
 * Compiles JSX to HTML
 * @param {String} tag
 * @param {Object} attrs
 * @param {Array} children
 * @return {String} HTML compiled from JSX
 */
 var h = function() {
 	 var args = Array.prototype.slice.call(arguments);
 	 var tag = args.shift();
   var attrs = args.shift() || {};
   var kids = args;
   var formattedAttrs = Object.keys(attrs).reduce(function(all, attr) {
   		return all + " " + attr + "='" + attrs[attr] + "'";
   }, '');
   var startTag = "<" + tag + formattedAttrs + ">";
   var endTag = "</" + tag + ">";
   var html = startTag + kids.join("") + endTag;
 	 return html;
 };

/**
 * Sets the Elements Initial Value
 * @param {Node} el
 * @param {String} value
 */
var setInitialElementValue = function(el, value) {
  el.innerHTML = value;
}

/**
 * Does No Operation
 */
var noop = function() {

}
<|endoftext|>


<commit_before>jBone.merge = function(first, second) {
    var l = second.length,
        i = first.length,
        j = 0;

    while (j < l) {
        first[i++] = second[j];
        j++;
    }

    first.length = i;

    return first;
};

jBone.contains = function(container, contained) {
    var result;

    container.some(function(el) {
        if (el.contains(contained)) {
            return result = container;
        }
    });

    return result;
};

jBone.extend = function(target) {
    [].splice.call(arguments, 1).forEach(function(object) {
      for (var prop in object) {
        target[prop] = object[prop];
      }
    });

    return target;
};
<commit_msg>Place increment in array braces for second argument.<commit_after>jBone.merge = function(first, second) {
    var l = second.length,
        i = first.length,
        j = 0;

    while (j < l) {
        first[i++] = second[j++];
    }

    first.length = i;

    return first;
};

jBone.contains = function(container, contained) {
    var result;

    container.some(function(el) {
        if (el.contains(contained)) {
            return result = container;
        }
    });

    return result;
};

jBone.extend = function(target) {
    [].splice.call(arguments, 1).forEach(function(object) {
      for (var prop in object) {
        target[prop] = object[prop];
      }
    });

    return target;
};
<|endoftext|>


<commit_before>Stripe.setPublishableKey('$PublishKey');
var payment_form_id = '#$FormName';

$(function() {
    var payment_form = $(payment_form_id);

    payment_form.bind(
        "submit",
        function(event) {
            // Disable the submit button to prevent repeated clicks:
            payment_form
                .find('.submit')
                .prop('disabled', true);

            // Request a token from Stripe:
            Stripe.card.createToken(payment_form, stripeResponseHandler);

            // Prevent the form from being submitted:
            return false;
        }
    );

    function stripeResponseHandler(status, response) {
        // Grab the form:
        var payment_form = $(payment_form_id);

        if (response.error) { // Problem!
            // Show the errors on the form:
            payment_form
                .find(payment_form_id + '_error')
                .text(response.error.message)
                .show();

            payment_form
                .find('.submit')
                .prop('disabled', false);

        } else {
            // Get the token ID:
            var token = response.id;

            // Insert the token ID into the form so it gets submitted to the server:
            payment_form
                .find(payment_form_id + "_StripeToken")
                .val(token);

            // Submit the form:
            payment_form
                .get(0)
                .submit();
        }
    };
});<commit_msg>Make use of jquery no conflict for stripe JS<commit_after>Stripe.setPublishableKey('$PublishKey');
jQuery.noConflict();

var payment_form_id = '#$FormName';

(function($) {
    var payment_form = $(payment_form_id);

    payment_form.bind(
        "submit",
        function(event) {
            // Disable the submit button to prevent repeated clicks:
            payment_form
                .find('.submit')
                .prop('disabled', true);

            // Request a token from Stripe:
            Stripe.card.createToken(payment_form, stripeResponseHandler);

            // Prevent the form from being submitted:
            return false;
        }
    );

    function stripeResponseHandler(status, response) {
        // Grab the form:
        var payment_form = $(payment_form_id);

        if (response.error) { // Problem!
            // Show the errors on the form:
            payment_form
                .find(payment_form_id + '_error')
                .text(response.error.message)
                .show();

            payment_form
                .find('.submit')
                .prop('disabled', false);

        } else {
            // Get the token ID:
            var token = response.id;

            // Insert the token ID into the form so it gets submitted to the server:
            payment_form
                .find(payment_form_id + "_StripeToken")
                .val(token);

            // Submit the form:
            payment_form
                .get(0)
                .submit();
        }
    };
}(jQuery));<|endoftext|>


<commit_before>define(["underscore", "jquery"], function(_, $) {
  return function (averageCartype) {

    var public = {};
    var private = {};

    private.createObject = function (averageCartype) {
      var queryObject = {
        c: [],
        sc: null,
        p: null,
        ecol: []
      };

      for (var carclass in averageCartype.carclass)
        queryObject.c.push(carclass);

      for (var color in averageCartype.colors)
        queryObject.ecol.push(color);

      var seatsRange = averageCartype.min_seats + ":" + averageCartype.max_seats;
      queryObject.sc = seatsRange;

      var priceRange = averageCartype.min_price + ":" + averageCartype.max_price;
      queryObject.p = priceRange;

      return queryObject;
    };

    private.createURL = function (queryObject) {
      var url = "http://m.mobile.de/svc/s/?";
      var params = $.param(queryObject);
      url = url.concat(params);

      return url;
    };

    public.getResults = function (averageCartype) {
      var queryObject = private.createObject(averageCartype);
      var url = private.createURL(queryObject);

      var results = $.getJSON(url, function(json) {
        return json;
      });

      return results;
    };

    return public;
  };
});

<commit_msg>Add params for location based search<commit_after>define(["underscore", "jquery", "app"], function(_, $, app) {
  return function (averageCartype) {

    var public = {};
    var private = {};

    private.createObject = function (averageCartype) {
      var queryObject = {
        c: [],
        ecol: [],
        sc: null,
        p: null,
        ll: null
      };

      // Cartypes
      for (var carclass in averageCartype.carclass)
        queryObject.c.push(carclass);

      // Colors
      for (var color in averageCartype.colors)
        queryObject.ecol.push(color);

      // Seats
      var seatsRange = averageCartype.min_seats + ":" + averageCartype.max_seats;
      queryObject.sc = seatsRange;

      // Price
      var priceRange = averageCartype.min_price + ":" + averageCartype.max_price;
      queryObject.p = priceRange;

      // Location
      queryObject.ll = app.userProfile.point;

      return queryObject;
    };

    private.createURL = function (queryObject) {
      var url = "http://m.mobile.de/svc/s/?";
      var params = $.param(queryObject);
      url = url.concat(params);

      return url;
    };

    public.getResults = function (averageCartype) {
      var queryObject = private.createObject(averageCartype);
      var url = private.createURL(queryObject);

      var results = $.getJSON(url, function(json) {
        return json;
      });

      return results;
    };

    return public;
  };
});

<|endoftext|>


<commit_before>import { throttle } from 'lodash/function';
import data from './data';
import * as utils from '../../utils';
import sound from '../../sound';
import gameApi from '../../lichess/game';
import ground from './ground';
import promotion from './promotion';
import chat from './chat';
import notes from './notes';
import clockCtrl from './clock/clockCtrl';
import i18n from '../../i18n';
import gameStatus from '../../lichess/status';
import correspondenceClockCtrl from './correspondenceClock/correspondenceCtrl';
import session from '../../session';
import socket from '../../socket';
import signals from '../../signals';
import socketHandler from './socketHandler';
import atomic from './atomic';
import backbutton from '../../backbutton';
import helper from '../helper';
import * as xhr from './roundXhr';
import { toggleGameBookmark } from '../../xhr';
import { hasNetwork, saveOfflineGameData } from '../../utils';
import m from 'mithril';

export default function controller(cfg, onFeatured, onTVChannelChange, userTv, onUserTVRedirect) {

  helper.analyticsTrackView('Round');

  this.data = data(cfg);

  this.onTVChannelChange = onTVChannelChange;

  this.firstPly = function() {
    return this.data.steps[0].ply;
  }.bind(this);

  this.lastPly = function() {
    return this.data.steps[this.data.steps.length - 1].ply;
  }.bind(this);

  this.plyStep = function(ply) {
    return this.data.steps[ply - this.firstPly()];
  }.bind(this);

  this.vm = {
    flip: false,
    showingActions: false,
    headerHash: '',
    replayHash: '',
    buttonsHash: '',
    playerHash: '',
    opponentHash: '',
    ply: this.lastPly(),
    moveToSubmit: null
  };

  const connectSocket = function() {
    if (utils.hasNetwork()) {
      socket.createGame(
        this.data.url.socket,
        this.data.player.version,
        socketHandler(this, onFeatured, onUserTVRedirect),
        this.data.url.round,
        userTv
      );
    }
  }.bind(this);

  connectSocket();

  // reconnect game socket after a cancelled seek
  signals.seekCanceled.add(connectSocket);

  this.stepsHash = function(steps) {
    var h = '';
    for (var i in steps) {
      h += steps[i].san;
    }
    return h;
  };

  this.showActions = function() {
    backbutton.stack.push(this.hideActions);
    this.vm.showingActions = true;
  }.bind(this);

  this.hideActions = function(fromBB) {
    if (fromBB !== 'backbutton' && this.vm.showingActions) backbutton.stack.pop();
    this.vm.showingActions = false;
  }.bind(this);

  this.flip = function() {
    if (this.data.tv) {
      if (m.route.param('flip')) m.route('/tv');
      else m.route('/tv?flip=1');
      return;
    } else if (this.data.player.spectator) {
      m.route('/game/' + this.data.game.id + '/' +
        utils.oppositeColor(this.data.player.color));
      return;
    }
    this.vm.flip = !this.vm.flip;
    this.chessground.set({
      orientation: ground.boardOrientation(this.data, this.vm.flip)
    });
  }.bind(this);

  this.replaying = function() {
    return this.vm.ply !== this.lastPly();
  }.bind(this);

  this.jump = function(ply) {
    if (ply < this.firstPly() || ply > this.lastPly()) return false;
    const isFwd = ply > this.vm.ply;
    this.vm.ply = ply;
    const s = this.plyStep(ply);
    const config = {
      fen: s.fen,
      lastMove: s.uci ? [s.uci.substr(0, 2), s.uci.substr(2, 2)] : null,
      check: s.check,
      turnColor: this.vm.ply % 2 === 0 ? 'white' : 'black'
    };
    if (!this.replaying()) {
      config.movable = {
        color: gameApi.isPlayerPlaying(this.data) ? this.data.player.color : null,
        dests: gameApi.parsePossibleMoves(this.data.possibleMoves)
      };
    }
    this.chessground.set(config);
    if (this.replaying()) this.chessground.stop();
    if (s.san && isFwd) {
      if (s.san.indexOf('x') !== -1) sound.capture();
      else sound.move();
    }
    return true;
  }.bind(this);

  this.jumpNext = function() {
    return this.jump(this.vm.ply + 1);
  }.bind(this);

  this.jumpPrev = function() {
    return this.jump(this.vm.ply - 1);
  }.bind(this);

  this.jumpFirst = function() {
    return this.jump(this.firstPly());
  }.bind(this);

  this.jumpLast = function() {
    return this.jump(this.lastPly());
  }.bind(this);

  this.setTitle = function() {
    if (this.data.tv)
      this.title = 'Lichess TV';
    else if (this.data.userTV)
      this.title = this.data.userTV;
    else if (gameStatus.started(this.data))
      this.title = i18n('gamesBeingPlayedRightNow');
    else if (gameStatus.finished(this.data))
      this.title = i18n('gameOver');
    else if (gameStatus.aborted(this.data))
      this.title = i18n('gameAborted');
    else
      this.title = 'lichess.org';
  };
  this.setTitle();

  this.sendMove = function(orig, dest, prom) {
    var move = {
      from: orig,
      to: dest
    };
    if (prom) move.promotion = prom;
    if (this.clock && socket.getAverageLag() !== undefined)
      move.lag = Math.round(socket.getAverageLag());

    if (this.data.pref.submitMove) {
      setTimeout(function() {
        backbutton.stack.push(this.cancelMove);
        this.vm.moveToSubmit = move;
        m.redraw(false, true);
      }.bind(this), this.data.pref.animationDuration || 0);
    } else {
      socket.send('move', move, { ackable: true });
      if (this.data.game.speed === 'correspondence' && !hasNetwork()) {
        window.plugins.toast.show('You need to be connected to Internet to send your move.', 'short', 'center');
      }
    }
  };

  this.cancelMove = function(fromBB) {
    if (fromBB !== 'backbutton') backbutton.stack.pop();
    this.vm.moveToSubmit = null;
    this.jump(this.vm.ply);
  }.bind(this);

  this.submitMove = function(v) {
    if (v) {
      if (this.vm.moveToSubmit) {
        socket.send('move', this.vm.moveToSubmit, {
          ackable: true
        });
        if (this.data.game.speed === 'correspondence' && !hasNetwork()) {
          window.plugins.toast.show('You need to be connected to Internet to send your move.', 'short', 'center');
        }
      }
      this.vm.moveToSubmit = null;
    } else {
      this.cancelMove();
    }
  }.bind(this);

  var userMove = function(orig, dest, meta) {
    if (!promotion.start(this, orig, dest, meta.premove)) this.sendMove(orig, dest);
  }.bind(this);

  var onMove = function(orig, dest, capturedPiece) {
    if (capturedPiece) {
      if (this.data.game.variant.key === 'atomic') {
        atomic.capture(this, dest);
        sound.explosion();
      }
      else sound.capture();
    } else sound.move();
  }.bind(this);

  this.apiMove = function(o) {
    const d = this.data;
    d.game.turns = o.ply;
    d.game.player = o.ply % 2 === 0 ? 'white' : 'black';
    const playedColor = o.ply % 2 === 0 ? 'black' : 'white';
    if (o.status) d.game.status = o.status;
    d[d.player.color === 'white' ? 'player' : 'opponent'].offeringDraw = o.wDraw;
    d[d.player.color === 'black' ? 'player' : 'opponent'].offeringDraw = o.bDraw;
    d.possibleMoves = d.player.color === d.game.player ? o.dests : null;
    this.setTitle();

    if (!this.replaying()) {
      this.vm.ply++;

      const enpassantPieces = {};
      if (o.enpassant) {
        const p = o.enpassant;
        enpassantPieces[p.key] = null;
        if (d.game.variant.key === 'atomic') {
          atomic.enpassant(this, p.key, p.color);
        } else {
          sound.capture();
        }
      }

      const castlePieces = {};
      if (o.castle && !this.chessground.data.autoCastle) {
        const c = o.castle;
        castlePieces[c.king[0]] = null;
        castlePieces[c.rook[0]] = null;
        castlePieces[c.king[1]] = {
          role: 'king',
          color: c.color
        };
        castlePieces[c.rook[1]] = {
          role: 'rook',
          color: c.color
        };
      }

      const pieces = Object.assign({}, enpassantPieces, castlePieces);
      this.chessground.apiMove(
        o.uci.substr(0, 2),
        o.uci.substr(2, 2),
        pieces,
        {
          turnColor: d.game.player,
          movable: {
            dests: gameApi.isPlayerPlaying(d) ? gameApi.parsePossibleMoves(d.possibleMoves) : {}
          },
          check: o.check
        }
      );

      if (o.promotion) {
        ground.promote(this.chessground, o.promotion.key, o.promotion.pieceClass);
      }

      if (playedColor !== d.player.color && this.chessground.data.premovable.current) {
        // atrocious hack to prevent race condition
        // with explosions and premoves
        // https://github.com/ornicar/lila/issues/343
        const premoveDelay = d.game.variant.key === 'atomic' ? 100 : 10;
        setTimeout(this.chessground.playPremove, premoveDelay);
      }
    }

    if (o.clock) {
      const c = o.clock;
      if (this.clock) this.clock.update(c.white, c.black);
      else if (this.correspondenceClock) this.correspondenceClock.update(c.white, c.black);
    }

    d.game.threefold = !!o.threefold;
    d.steps.push({
      ply: this.lastPly() + 1,
      fen: o.fen,
      san: o.san,
      uci: o.uci,
      check: o.check
    });
    gameApi.setOnGame(d, playedColor, true);

    if (this.data.game.speed === 'correspondence') {
      session.refresh();
      saveOfflineGameData(m.route.param('id'), this.data);
    }

  }.bind(this);

  this.chessground = ground.make(this.data, cfg.game.fen, userMove, onMove);

  this.clock = this.data.clock ? new clockCtrl(
    this.data.clock,
    this.data.player.spectator ? utils.noop :
      throttle(() => socket.send('outoftime'), 500),
    this.data.player.spectator ? null : this.data.player.color
  ) : false;

  this.isClockRunning = function() {
    return this.data.clock && gameApi.playable(this.data) &&
      ((this.data.game.turns - this.data.game.startedAtTurn) > 1 || this.data.clock.running);
  }.bind(this);

  this.clockTick = function() {
    if (this.isClockRunning()) this.clock.tick(this.data.game.player);
  }.bind(this);

  var makeCorrespondenceClock = function() {
    if (this.data.correspondence && !this.correspondenceClock)
      this.correspondenceClock = new correspondenceClockCtrl(
        this,
        this.data.correspondence,
        () => socket.send('outoftime')
      );
  }.bind(this);
  makeCorrespondenceClock();

  var correspondenceClockTick = function() {
    if (this.correspondenceClock && gameApi.playable(this.data))
      this.correspondenceClock.tick(this.data.game.player);
  }.bind(this);

  var clockIntervId;
  if (this.clock) clockIntervId = setInterval(this.clockTick, 100);
  else if (this.correspondenceClock) clockIntervId = setInterval(correspondenceClockTick, 6000);

  this.chat = (this.data.opponent.ai || this.data.player.spectator) ?
    null : new chat.controller(this);

  this.notes = this.data.game.speed === 'correspondence' ? new notes.controller(this) : null;

  this.reload = function(rCfg) {
    if (this.stepsHash(rCfg.steps) !== this.stepsHash(this.data.steps))
      this.vm.ply = rCfg.steps[rCfg.steps.length - 1].ply;
    if (this.chat) this.chat.onReload(rCfg.chat);
    if (this.data.tv) rCfg.tv = this.data.tv;
    if (this.data.userTV) rCfg.userTV = this.data.userTV;
    this.data = data(rCfg);
    makeCorrespondenceClock();
    if (this.clock) this.clock.update(this.data.clock.white, this.data.clock.black);
    this.setTitle();
    if (!this.replaying()) ground.reload(this.chessground, this.data, rCfg.game.fen, this.vm.flip);
    m.redraw(false, true);
  }.bind(this);

  var reloadGameData = function() {
    xhr.reload(this).then(this.reload);
  }.bind(this);

  this.toggleBookmark = function() {
    return toggleGameBookmark(this.data.game.id).then(reloadGameData);
  }.bind(this);

  var onResize = function() {
    this.vm.replayHash = '';
  }.bind(this);

  document.addEventListener('resume', reloadGameData);
  window.addEventListener('resize', onResize);
  window.plugins.insomnia.keepAwake();

  this.onunload = function() {
    socket.destroy();
    clearInterval(clockIntervId);
    document.removeEventListener('resume', reloadGameData);
    window.removeEventListener('resize', onResize);
    window.plugins.insomnia.allowSleepAgain();
    signals.seekCanceled.remove(connectSocket);
    if (this.chat) this.chat.onunload();
    if (this.chessground) {
      this.chessground.onunload();
    }
  };
}
<commit_msg>Don't debounce all redraw<commit_after>import { throttle } from 'lodash/function';
import data from './data';
import * as utils from '../../utils';
import sound from '../../sound';
import gameApi from '../../lichess/game';
import ground from './ground';
import promotion from './promotion';
import chat from './chat';
import notes from './notes';
import clockCtrl from './clock/clockCtrl';
import i18n from '../../i18n';
import gameStatus from '../../lichess/status';
import correspondenceClockCtrl from './correspondenceClock/correspondenceCtrl';
import session from '../../session';
import socket from '../../socket';
import signals from '../../signals';
import socketHandler from './socketHandler';
import atomic from './atomic';
import backbutton from '../../backbutton';
import helper from '../helper';
import * as xhr from './roundXhr';
import { toggleGameBookmark } from '../../xhr';
import { hasNetwork, saveOfflineGameData } from '../../utils';
import m from 'mithril';

export default function controller(cfg, onFeatured, onTVChannelChange, userTv, onUserTVRedirect) {

  helper.analyticsTrackView('Round');

  this.data = data(cfg);

  this.onTVChannelChange = onTVChannelChange;

  this.firstPly = function() {
    return this.data.steps[0].ply;
  }.bind(this);

  this.lastPly = function() {
    return this.data.steps[this.data.steps.length - 1].ply;
  }.bind(this);

  this.plyStep = function(ply) {
    return this.data.steps[ply - this.firstPly()];
  }.bind(this);

  this.vm = {
    flip: false,
    showingActions: false,
    headerHash: '',
    replayHash: '',
    buttonsHash: '',
    playerHash: '',
    opponentHash: '',
    ply: this.lastPly(),
    moveToSubmit: null
  };

  const connectSocket = function() {
    if (utils.hasNetwork()) {
      socket.createGame(
        this.data.url.socket,
        this.data.player.version,
        socketHandler(this, onFeatured, onUserTVRedirect),
        this.data.url.round,
        userTv
      );
    }
  }.bind(this);

  connectSocket();

  // reconnect game socket after a cancelled seek
  signals.seekCanceled.add(connectSocket);

  this.stepsHash = function(steps) {
    var h = '';
    for (var i in steps) {
      h += steps[i].san;
    }
    return h;
  };

  this.showActions = function() {
    backbutton.stack.push(this.hideActions);
    this.vm.showingActions = true;
  }.bind(this);

  this.hideActions = function(fromBB) {
    if (fromBB !== 'backbutton' && this.vm.showingActions) backbutton.stack.pop();
    this.vm.showingActions = false;
  }.bind(this);

  this.flip = function() {
    if (this.data.tv) {
      if (m.route.param('flip')) m.route('/tv');
      else m.route('/tv?flip=1');
      return;
    } else if (this.data.player.spectator) {
      m.route('/game/' + this.data.game.id + '/' +
        utils.oppositeColor(this.data.player.color));
      return;
    }
    this.vm.flip = !this.vm.flip;
    this.chessground.set({
      orientation: ground.boardOrientation(this.data, this.vm.flip)
    });
  }.bind(this);

  this.replaying = function() {
    return this.vm.ply !== this.lastPly();
  }.bind(this);

  this.jump = function(ply) {
    if (ply < this.firstPly() || ply > this.lastPly()) return false;
    const isFwd = ply > this.vm.ply;
    this.vm.ply = ply;
    const s = this.plyStep(ply);
    const config = {
      fen: s.fen,
      lastMove: s.uci ? [s.uci.substr(0, 2), s.uci.substr(2, 2)] : null,
      check: s.check,
      turnColor: this.vm.ply % 2 === 0 ? 'white' : 'black'
    };
    if (!this.replaying()) {
      config.movable = {
        color: gameApi.isPlayerPlaying(this.data) ? this.data.player.color : null,
        dests: gameApi.parsePossibleMoves(this.data.possibleMoves)
      };
    }
    this.chessground.set(config);
    if (this.replaying()) this.chessground.stop();
    if (s.san && isFwd) {
      if (s.san.indexOf('x') !== -1) sound.capture();
      else sound.move();
    }
    return true;
  }.bind(this);

  this.jumpNext = function() {
    return this.jump(this.vm.ply + 1);
  }.bind(this);

  this.jumpPrev = function() {
    return this.jump(this.vm.ply - 1);
  }.bind(this);

  this.jumpFirst = function() {
    return this.jump(this.firstPly());
  }.bind(this);

  this.jumpLast = function() {
    return this.jump(this.lastPly());
  }.bind(this);

  this.setTitle = function() {
    if (this.data.tv)
      this.title = 'Lichess TV';
    else if (this.data.userTV)
      this.title = this.data.userTV;
    else if (gameStatus.started(this.data))
      this.title = i18n('gamesBeingPlayedRightNow');
    else if (gameStatus.finished(this.data))
      this.title = i18n('gameOver');
    else if (gameStatus.aborted(this.data))
      this.title = i18n('gameAborted');
    else
      this.title = 'lichess.org';
  };
  this.setTitle();

  this.sendMove = function(orig, dest, prom) {
    var move = {
      from: orig,
      to: dest
    };
    if (prom) move.promotion = prom;
    if (this.clock && socket.getAverageLag() !== undefined)
      move.lag = Math.round(socket.getAverageLag());

    if (this.data.pref.submitMove) {
      setTimeout(function() {
        backbutton.stack.push(this.cancelMove);
        this.vm.moveToSubmit = move;
        m.redraw();
      }.bind(this), this.data.pref.animationDuration || 0);
    } else {
      socket.send('move', move, { ackable: true });
      if (this.data.game.speed === 'correspondence' && !hasNetwork()) {
        window.plugins.toast.show('You need to be connected to Internet to send your move.', 'short', 'center');
      }
    }
  };

  this.cancelMove = function(fromBB) {
    if (fromBB !== 'backbutton') backbutton.stack.pop();
    this.vm.moveToSubmit = null;
    this.jump(this.vm.ply);
  }.bind(this);

  this.submitMove = function(v) {
    if (v) {
      if (this.vm.moveToSubmit) {
        socket.send('move', this.vm.moveToSubmit, {
          ackable: true
        });
        if (this.data.game.speed === 'correspondence' && !hasNetwork()) {
          window.plugins.toast.show('You need to be connected to Internet to send your move.', 'short', 'center');
        }
      }
      this.vm.moveToSubmit = null;
    } else {
      this.cancelMove();
    }
  }.bind(this);

  var userMove = function(orig, dest, meta) {
    if (!promotion.start(this, orig, dest, meta.premove)) this.sendMove(orig, dest);
  }.bind(this);

  var onMove = function(orig, dest, capturedPiece) {
    if (capturedPiece) {
      if (this.data.game.variant.key === 'atomic') {
        atomic.capture(this, dest);
        sound.explosion();
      }
      else sound.capture();
    } else sound.move();
  }.bind(this);

  this.apiMove = function(o) {
    const d = this.data;
    d.game.turns = o.ply;
    d.game.player = o.ply % 2 === 0 ? 'white' : 'black';
    const playedColor = o.ply % 2 === 0 ? 'black' : 'white';
    if (o.status) d.game.status = o.status;
    d[d.player.color === 'white' ? 'player' : 'opponent'].offeringDraw = o.wDraw;
    d[d.player.color === 'black' ? 'player' : 'opponent'].offeringDraw = o.bDraw;
    d.possibleMoves = d.player.color === d.game.player ? o.dests : null;
    this.setTitle();

    if (!this.replaying()) {
      this.vm.ply++;

      const enpassantPieces = {};
      if (o.enpassant) {
        const p = o.enpassant;
        enpassantPieces[p.key] = null;
        if (d.game.variant.key === 'atomic') {
          atomic.enpassant(this, p.key, p.color);
        } else {
          sound.capture();
        }
      }

      const castlePieces = {};
      if (o.castle && !this.chessground.data.autoCastle) {
        const c = o.castle;
        castlePieces[c.king[0]] = null;
        castlePieces[c.rook[0]] = null;
        castlePieces[c.king[1]] = {
          role: 'king',
          color: c.color
        };
        castlePieces[c.rook[1]] = {
          role: 'rook',
          color: c.color
        };
      }

      const pieces = Object.assign({}, enpassantPieces, castlePieces);
      this.chessground.apiMove(
        o.uci.substr(0, 2),
        o.uci.substr(2, 2),
        pieces,
        {
          turnColor: d.game.player,
          movable: {
            dests: gameApi.isPlayerPlaying(d) ? gameApi.parsePossibleMoves(d.possibleMoves) : {}
          },
          check: o.check
        }
      );

      if (o.promotion) {
        ground.promote(this.chessground, o.promotion.key, o.promotion.pieceClass);
      }

      if (playedColor !== d.player.color && this.chessground.data.premovable.current) {
        // atrocious hack to prevent race condition
        // with explosions and premoves
        // https://github.com/ornicar/lila/issues/343
        const premoveDelay = d.game.variant.key === 'atomic' ? 100 : 10;
        setTimeout(this.chessground.playPremove, premoveDelay);
      }
    }

    if (o.clock) {
      const c = o.clock;
      if (this.clock) this.clock.update(c.white, c.black);
      else if (this.correspondenceClock) this.correspondenceClock.update(c.white, c.black);
    }

    d.game.threefold = !!o.threefold;
    d.steps.push({
      ply: this.lastPly() + 1,
      fen: o.fen,
      san: o.san,
      uci: o.uci,
      check: o.check
    });
    gameApi.setOnGame(d, playedColor, true);

    if (this.data.game.speed === 'correspondence') {
      session.refresh();
      saveOfflineGameData(m.route.param('id'), this.data);
    }

  }.bind(this);

  this.chessground = ground.make(this.data, cfg.game.fen, userMove, onMove);

  this.clock = this.data.clock ? new clockCtrl(
    this.data.clock,
    this.data.player.spectator ? utils.noop :
      throttle(() => socket.send('outoftime'), 500),
    this.data.player.spectator ? null : this.data.player.color
  ) : false;

  this.isClockRunning = function() {
    return this.data.clock && gameApi.playable(this.data) &&
      ((this.data.game.turns - this.data.game.startedAtTurn) > 1 || this.data.clock.running);
  }.bind(this);

  this.clockTick = function() {
    if (this.isClockRunning()) this.clock.tick(this.data.game.player);
  }.bind(this);

  var makeCorrespondenceClock = function() {
    if (this.data.correspondence && !this.correspondenceClock)
      this.correspondenceClock = new correspondenceClockCtrl(
        this,
        this.data.correspondence,
        () => socket.send('outoftime')
      );
  }.bind(this);
  makeCorrespondenceClock();

  var correspondenceClockTick = function() {
    if (this.correspondenceClock && gameApi.playable(this.data))
      this.correspondenceClock.tick(this.data.game.player);
  }.bind(this);

  var clockIntervId;
  if (this.clock) clockIntervId = setInterval(this.clockTick, 100);
  else if (this.correspondenceClock) clockIntervId = setInterval(correspondenceClockTick, 6000);

  this.chat = (this.data.opponent.ai || this.data.player.spectator) ?
    null : new chat.controller(this);

  this.notes = this.data.game.speed === 'correspondence' ? new notes.controller(this) : null;

  this.reload = function(rCfg) {
    if (this.stepsHash(rCfg.steps) !== this.stepsHash(this.data.steps))
      this.vm.ply = rCfg.steps[rCfg.steps.length - 1].ply;
    if (this.chat) this.chat.onReload(rCfg.chat);
    if (this.data.tv) rCfg.tv = this.data.tv;
    if (this.data.userTV) rCfg.userTV = this.data.userTV;
    this.data = data(rCfg);
    makeCorrespondenceClock();
    if (this.clock) this.clock.update(this.data.clock.white, this.data.clock.black);
    this.setTitle();
    if (!this.replaying()) ground.reload(this.chessground, this.data, rCfg.game.fen, this.vm.flip);
    m.redraw();
  }.bind(this);

  var reloadGameData = function() {
    xhr.reload(this).then(this.reload);
  }.bind(this);

  this.toggleBookmark = function() {
    return toggleGameBookmark(this.data.game.id).then(reloadGameData);
  }.bind(this);

  var onResize = function() {
    this.vm.replayHash = '';
  }.bind(this);

  document.addEventListener('resume', reloadGameData);
  window.addEventListener('resize', onResize);
  window.plugins.insomnia.keepAwake();

  this.onunload = function() {
    socket.destroy();
    clearInterval(clockIntervId);
    document.removeEventListener('resume', reloadGameData);
    window.removeEventListener('resize', onResize);
    window.plugins.insomnia.allowSleepAgain();
    signals.seekCanceled.remove(connectSocket);
    if (this.chat) this.chat.onunload();
    if (this.chessground) {
      this.chessground.onunload();
    }
  };
}
<|endoftext|>


<commit_before>const through = require('through2');
const gulpUtil = require('gulp-util');
const { silent } = require('../env');

const log = function(message) {
	return through.obj(function(file, enc, callback) {
		this.push(file);

		gulpUtil.log(message);
		callback();
	});
};

const color = function(color) {
	return function(message) {
		return gulpUtil.colors[color](message);
	};
};

module.exports = Object.assign(log, {
	message(message) {
		return gulpUtil.log(message);
	},

	err(message) {
		return function(e) {
			gulpUtil.log(message);
			!silent && gulpUtil.beep();
			throw e;
		};
	},

	// all available text colors
	black:   color('black'),
	red:     color('red'),
	green:   color('green'),
	yellow:  color('yellow'),
	blue:    color('blue'),
	magenta: color('magenta'),
	cyan:    color('cyan'),
	white:   color('white'),
	gray:    color('gray'),

	beep() {
		gulpUtil.beep();
	}
});
<commit_msg>fix path to env<commit_after>const through = require('through2');
const gulpUtil = require('gulp-util');
const { silent } = require('./env');

const log = function(message) {
	return through.obj(function(file, enc, callback) {
		this.push(file);

		gulpUtil.log(message);
		callback();
	});
};

const color = function(color) {
	return function(message) {
		return gulpUtil.colors[color](message);
	};
};

module.exports = Object.assign(log, {
	message(message) {
		return gulpUtil.log(message);
	},

	err(message) {
		return function(e) {
			gulpUtil.log(message);
			!silent && gulpUtil.beep();
			throw e;
		};
	},

	// all available text colors
	black:   color('black'),
	red:     color('red'),
	green:   color('green'),
	yellow:  color('yellow'),
	blue:    color('blue'),
	magenta: color('magenta'),
	cyan:    color('cyan'),
	white:   color('white'),
	gray:    color('gray'),

	beep() {
		gulpUtil.beep();
	}
});
<|endoftext|>


<commit_before>class Validator {
  constructor (argv) {
    this.args = this.parse(argv)
  }
}

export default Validator
<commit_msg>updating validator<commit_after>class Validator {
  constructor (argv, src, dest, options) {
    this._determineExtenstions(argv, src, dest)
    this._handleOptions(options)
  }

  get src () {
    return this._src
  }

  get dest () {
    return this._dest
  }

  _determineExtenstions (argv, src, dest) {
    const cliInputs = argv ? argv._ : []

    this._src = src || cliInputs[0]
    this._dest = dest || cliInputs[1]

    if (!this._src || !this._dest) {
      throw new Error('A source and destination are required')
    }

  }

  _handleOptions (options = {}) {
    if (typeof options !== 'object') {
      throw new Error('When supplied options they must be an object')
    }

    const { excludes, override } = options

    if (excludes) this._handleExcludes(excludes)
    if (override) this._handleOverrides(override)

  }

  _handleExcludes (excludes) {
    return true
  }

  _handleOverrides (override) {
    return true
  }

}

export default Validator
<|endoftext|>


<commit_before>module.exports = {
    auth: {
        account: require("./auth/account-validator"),
        profile: require("./auth/profile-validator"),
        role: require("./auth/role-validator")
    },
    inventory: {
        expeditionDoc: require("./inventory/expedition-doc-validator"),
        expeditionSPK: require("./inventory/expedition-spk-validator"),
        finishedGoodsDoc: require("./inventory/finished-goods-doc-validator"),
        inventoryMovementApproval: require("./inventory/inventory-movement-validator"),
        inventory: require("./inventory/inventory-validator"),
        inventoryMovement: require("./inventory/inventory-movement-validator"),
        transferInDoc: require("./inventory/transfer-in-doc-validator"),
        transferInItem: require("./inventory/transfer-in-item-validator"),
        transferOutDoc: require("./inventory/transfer-out-doc-validator"),
        transferOutItem: require("./inventory/transfer-out-item-validator"),
        adjustmentDoc: require("./inventory/adjustment-doc-validator"),
        adjustmentItem: require("./inventory/adjustment-item-validator"),
        stockOpnameDoc: require("./inventory/stock-opname-doc-validator"),
        stockOpnameDocItem: require("./inventory/stock-opname-doc-item-validator"),
        inventoryDocument: require("./inventory/inventory-document-validator"),
        inventorySummary: require("./inventory/inventory-summary-validator")
    },
    master: {
        article: {
            articleApproval: require("./master/article/article-approval-validator"),
            articleBrand: require("./master/article/article-brand-validator"),
            articleCategory: require("./master/article/article-category-validator"),
            articleColor: require("./master/article/article-color-validator"),
            articleCostCalculationDetail: require("./master/article/article-cost-calculation-detail-validator"),
            articleCostCalculation: require("./master/article/article-cost-calculation-validator"),
            articleCounter: require("./master/article/article-counter-validator"),
            articleMaterial: require("./master/article/article-material-validator"),
            articleMotif: require("./master/article/article-motif-validator"),
            articleOrigin: require("./master/article/article-origin-validator"),
            articleSeason: require("./master/article/article-season-validator"),
            articleSize: require("./master/article/article-size-validator"),
            articleSubCounter: require("./master/article/article-sub-counter-validator"),
            articleTheme: require("./master/article/article-theme-validator"),
            articleType: require("./master/article/article-type-validator"),
            article: require("./master/article/article-validator"),
            articleVariant: require("./master/article/article-variant-validator"),
            articleProcess: require("./master/article/article-process-validator"),
            articleSubProcess: require("./master/article/article-sub-process-validator"),
            articleMaterialComposition: require("./master/article/article-material-composition-validator"),
            articleSubMaterialComposition: require("./master/article/article-sub-material-composition-validator"),
            articleCollection: require("./master/article/article-collection-validator"),
            articleSubCollection: require("./master/article/article-sub-collection-validator")
        },
        storage: require("./master/storage-validator"),
        supplier: require("./master/supplier-validator"),
        item: require("./master/item-w-component-validator"),
        component: require("./master/component-validator"),
        finishedGoods: require("./master/finished-goods-validator"),
        material: require("./master/material-validator"),
        bank: require("./master/bank-validator"),
        cardType: require("./master/card-type-validator"),
        module: require("./master/module-validator"),
        store: require("./master/store-validator"),
        storeShift: require("./master/store-shift-validator"),
        division: require("./master/division-validator"),
        unit: require("./master/unit-validator"),
        colour: require("./master/colour-validator"),
        expeditionServices: require("./master/expedition-service-validator"),
        rangeDiscProduct: require("./master/range-disc-product-validator"),
        designTrackingReason: require("./master/design-tracking-reason-validator"),
        budget: require('./master/budget-validator'),
        category: require('./master/category-validator'),
        currency: require('./master/currency-validator'),
        uom: require('./master/uom-validator'),
        product: require('./master/product-validator'),
        buyer: require('./master/buyer-validator'),
        vat: require('./master/vat-validator')
    },
    manufacture: {
        fabricConsumptionDocument: require("./manufacture/fabric-consumption-document-validator"),
        fabricConsumptionArticle: require("./manufacture/fabric-consumption-article-validator"),
        fabricConsumptionItem: require("./manufacture/fabric-consumption-item-validator"),
        costCalculationDocument: require("./manufacture/cost-calculation-document-validator"),
        costCalculationArticle: require("./manufacture/cost-calculation-article-validator"),
        costCalculationItem: require("./manufacture/cost-calculation-item-validator"),
        finishingItem: require("./manufacture/finishing-item-validator"),
        finishing: require("./manufacture/finishing-validator"),
        designTrackingBoard: require("./manufacture/design-tracking-board-validator"),
        designTrackingStage: require("./manufacture/design-tracking-stage-validator"),
        designTrackingDesign: require("./manufacture/design-tracking-design-validator"),
        designTrackingActivity: require("./manufacture/design-tracking-activity-validator"),
    },
    merchandiser: {
        SPKDoc: require("./merchandiser/spk-doc-validator"),
        SPKItem: require("./merchandiser/spk-item-validator")
    },
    sales: {
        salesDoc: require("./sales/sales-doc-validator"),
        salesItem: require("./sales/sales-item-validator"),
        salesDetail: require("./sales/sales-detail-validator"),
        salesReturnDoc: require("./sales/sales-return-doc-validator"),
        salesReturnItem: require("./sales/sales-return-item-validator"),
        promo: require("./sales/promo-validator"),
        promoCriteria: require("./sales/promo-criteria-validator"),
        promoReward: require("./sales/promo-reward-validator"),
        promoCriteriaSelectedProduct: require("./sales/promo-criteria-selected-product-validator"),
        promoRewardDiscountProduct: require("./sales/promo-reward-discount-product-validator"),
        promoCriteriaPackage: require("./sales/promo-criteria-package-validator"),
        promoRewardSpecialPrice: require("./sales/promo-reward-special-price-validator")
    },
    purchasing: {
        purchaseRequest: require("./purchasing/purchase-request-validator"),
        purchaseRequestItem: require("./purchasing/purchase-request-item-validator"),
        purchaseOrderItem: require('./purchasing/purchase-order-item-validator'),
        purchaseOrder: require('./purchasing/purchase-order-validator'),
        purchaseOrderExternal: require("./purchasing/purchase-order-external-validator"),
        deliveryOrder: require("./purchasing/delivery-order-validator"),
        unitPaymentCorrectionNote: require("./purchasing/unit-payment-correction-note-validator"),
        unitPaymentCorrectionNoteItem: require("./purchasing/unit-payment-correction-note-item-validator"),
        unitReceiptNote : require('./purchasing/unit-receipt-note-validator'),
        unitPaymentOrder : require('./purchasing/unit-payment-order')
    }
};
<commit_msg>update index validator for unit payment order<commit_after>module.exports = {
    auth: {
        account: require("./auth/account-validator"),
        profile: require("./auth/profile-validator"),
        role: require("./auth/role-validator")
    },
    inventory: {
        expeditionDoc: require("./inventory/expedition-doc-validator"),
        expeditionSPK: require("./inventory/expedition-spk-validator"),
        finishedGoodsDoc: require("./inventory/finished-goods-doc-validator"),
        inventoryMovementApproval: require("./inventory/inventory-movement-validator"),
        inventory: require("./inventory/inventory-validator"),
        inventoryMovement: require("./inventory/inventory-movement-validator"),
        transferInDoc: require("./inventory/transfer-in-doc-validator"),
        transferInItem: require("./inventory/transfer-in-item-validator"),
        transferOutDoc: require("./inventory/transfer-out-doc-validator"),
        transferOutItem: require("./inventory/transfer-out-item-validator"),
        adjustmentDoc: require("./inventory/adjustment-doc-validator"),
        adjustmentItem: require("./inventory/adjustment-item-validator"),
        stockOpnameDoc: require("./inventory/stock-opname-doc-validator"),
        stockOpnameDocItem: require("./inventory/stock-opname-doc-item-validator"),
        inventoryDocument: require("./inventory/inventory-document-validator"),
        inventorySummary: require("./inventory/inventory-summary-validator")
    },
    master: {
        article: {
            articleApproval: require("./master/article/article-approval-validator"),
            articleBrand: require("./master/article/article-brand-validator"),
            articleCategory: require("./master/article/article-category-validator"),
            articleColor: require("./master/article/article-color-validator"),
            articleCostCalculationDetail: require("./master/article/article-cost-calculation-detail-validator"),
            articleCostCalculation: require("./master/article/article-cost-calculation-validator"),
            articleCounter: require("./master/article/article-counter-validator"),
            articleMaterial: require("./master/article/article-material-validator"),
            articleMotif: require("./master/article/article-motif-validator"),
            articleOrigin: require("./master/article/article-origin-validator"),
            articleSeason: require("./master/article/article-season-validator"),
            articleSize: require("./master/article/article-size-validator"),
            articleSubCounter: require("./master/article/article-sub-counter-validator"),
            articleTheme: require("./master/article/article-theme-validator"),
            articleType: require("./master/article/article-type-validator"),
            article: require("./master/article/article-validator"),
            articleVariant: require("./master/article/article-variant-validator"),
            articleProcess: require("./master/article/article-process-validator"),
            articleSubProcess: require("./master/article/article-sub-process-validator"),
            articleMaterialComposition: require("./master/article/article-material-composition-validator"),
            articleSubMaterialComposition: require("./master/article/article-sub-material-composition-validator"),
            articleCollection: require("./master/article/article-collection-validator"),
            articleSubCollection: require("./master/article/article-sub-collection-validator")
        },
        storage: require("./master/storage-validator"),
        supplier: require("./master/supplier-validator"),
        item: require("./master/item-w-component-validator"),
        component: require("./master/component-validator"),
        finishedGoods: require("./master/finished-goods-validator"),
        material: require("./master/material-validator"),
        bank: require("./master/bank-validator"),
        cardType: require("./master/card-type-validator"),
        module: require("./master/module-validator"),
        store: require("./master/store-validator"),
        storeShift: require("./master/store-shift-validator"),
        division: require("./master/division-validator"),
        unit: require("./master/unit-validator"),
        colour: require("./master/colour-validator"),
        expeditionServices: require("./master/expedition-service-validator"),
        rangeDiscProduct: require("./master/range-disc-product-validator"),
        designTrackingReason: require("./master/design-tracking-reason-validator"),
        budget: require('./master/budget-validator'),
        category: require('./master/category-validator'),
        currency: require('./master/currency-validator'),
        uom: require('./master/uom-validator'),
        product: require('./master/product-validator'),
        buyer: require('./master/buyer-validator'),
        vat: require('./master/vat-validator')
    },
    manufacture: {
        fabricConsumptionDocument: require("./manufacture/fabric-consumption-document-validator"),
        fabricConsumptionArticle: require("./manufacture/fabric-consumption-article-validator"),
        fabricConsumptionItem: require("./manufacture/fabric-consumption-item-validator"),
        costCalculationDocument: require("./manufacture/cost-calculation-document-validator"),
        costCalculationArticle: require("./manufacture/cost-calculation-article-validator"),
        costCalculationItem: require("./manufacture/cost-calculation-item-validator"),
        finishingItem: require("./manufacture/finishing-item-validator"),
        finishing: require("./manufacture/finishing-validator"),
        designTrackingBoard: require("./manufacture/design-tracking-board-validator"),
        designTrackingStage: require("./manufacture/design-tracking-stage-validator"),
        designTrackingDesign: require("./manufacture/design-tracking-design-validator"),
        designTrackingActivity: require("./manufacture/design-tracking-activity-validator"),
    },
    merchandiser: {
        SPKDoc: require("./merchandiser/spk-doc-validator"),
        SPKItem: require("./merchandiser/spk-item-validator")
    },
    sales: {
        salesDoc: require("./sales/sales-doc-validator"),
        salesItem: require("./sales/sales-item-validator"),
        salesDetail: require("./sales/sales-detail-validator"),
        salesReturnDoc: require("./sales/sales-return-doc-validator"),
        salesReturnItem: require("./sales/sales-return-item-validator"),
        promo: require("./sales/promo-validator"),
        promoCriteria: require("./sales/promo-criteria-validator"),
        promoReward: require("./sales/promo-reward-validator"),
        promoCriteriaSelectedProduct: require("./sales/promo-criteria-selected-product-validator"),
        promoRewardDiscountProduct: require("./sales/promo-reward-discount-product-validator"),
        promoCriteriaPackage: require("./sales/promo-criteria-package-validator"),
        promoRewardSpecialPrice: require("./sales/promo-reward-special-price-validator")
    },
    purchasing: {
        purchaseRequest: require("./purchasing/purchase-request-validator"),
        purchaseRequestItem: require("./purchasing/purchase-request-item-validator"),
        purchaseOrderItem: require('./purchasing/purchase-order-item-validator'),
        purchaseOrder: require('./purchasing/purchase-order-validator'),
        purchaseOrderExternal: require("./purchasing/purchase-order-external-validator"),
        deliveryOrder: require("./purchasing/delivery-order-validator"),
        unitPaymentCorrectionNote: require("./purchasing/unit-payment-correction-note-validator"),
        unitPaymentCorrectionNoteItem: require("./purchasing/unit-payment-correction-note-item-validator"),
        unitReceiptNote : require('./purchasing/unit-receipt-note-validator'),
        unitPaymentOrder : require('./purchasing/unit-payment-order-validator')
    }
};
<|endoftext|>


<commit_before>(function () {
	var ns = $.namespace("pskl.controller");
	ns.PreviewFilmController = function (framesheet, container, dpi) {

		this.dpi = dpi;
		this.framesheet = framesheet;
		this.container = container;

		$.subscribe(Events.REDRAW_PREVIEWFILM, $.proxy(function(evt) {
			this.createPreviews()
		}, this));
	};

	ns.PreviewFilmController.prototype.init = function() {
      var addFrameButton = $('#add-frame-button')[0];
      addFrameButton.addEventListener('mousedown', this.addFrame.bind(this));
      this.createPreviews();

    };

    ns.PreviewFilmController.prototype.addFrame = function () {
 		this.framesheet.addEmptyFrame();
        piskel.setActiveFrameAndRedraw(this.framesheet.getFrameCount() - 1);
    };

    ns.PreviewFilmController.prototype.createPreviews = function () {
      // TODO(vincz): Full redraw on any drawing modification, optimize.
      this.container.html("");

      var frameCount = this.framesheet.getFrameCount();

      for (var i = 0, l = frameCount; i < l ; i++) {
        this.container.append(this.createInterstitialTile_(i));
        this.container.append(this.createPreviewTile_(i, this.framesheet));
      }
      this.container.append(this.createInterstitialTile_(frameCount));

      var needDragndropBehavior = !!(frameCount > 1);
      if(needDragndropBehavior) {
      	this.initDragndropBehavior_();
      }
    };

    /**
     * @private
     */
    ns.PreviewFilmController.prototype.createInterstitialTile_ = function (tileNumber) {
    	var initerstitialTile = document.createElement("div");
		initerstitialTile.className = "interstitial-tile"
		initerstitialTile.setAttribute("data-tile-type", "interstitial");
		initerstitialTile.setAttribute("data-inject-drop-tile-at", tileNumber);

		return initerstitialTile;
    };

    /**
     * @private
     */
    ns.PreviewFilmController.prototype.initDragndropBehavior_ = function () {
    	var tiles = $(".preview-tile");
    	// Each preview film tile is draggable.
    	tiles.draggable( {
	      //containment: '.left-nav',
	      stack: '.preview-tile',
	      cursor: 'move',
	      revert: true,
	      start: function(event, ui) {
	      	// We only show the fake interstitial tiles when starting the
	      	// drag n drop interaction. We hide them when the DnD is done.
	      	$('#preview-list').addClass("show-interstitial-tiles");
	      },
	      stop: function() {
	      	$('#preview-list').removeClass("show-interstitial-tiles");
	      }
	    });

    	// Each preview film tile is a drop target. This allow us to swap two tiles.
    	// However, we want to be able to insert a tile between two other tiles.
    	// For that we created fake interstitial tiles that are used as drop targets as well.
    	var droppableTiles = $(".interstitial-tile");
    	$.merge(droppableTiles, tiles);

	    droppableTiles.droppable( {
	        accept: ".preview-tile",
	        tolerance: "pointer",
			activeClass: "droppable-active",
			hoverClass: "droppable-hover-active",
			drop: $.proxy(this.onDrop_, this)
	    });
    };

    /**
     * @private
     */
    ns.PreviewFilmController.prototype.onDrop_ = function( event, ui ) {
		var activeFrame;
		// When we drag from an element, the drag could start from a nested DOM element
		// inside the drag target. We normalize that by taking the correct ancestor:
		var originTile = $(event.srcElement).closest(".preview-tile");
		var originFrameId = parseInt(originTile.data("tile-number"), 10);
		var dropTarget = $(event.target);

		if(dropTarget.data("tile-type") == "interstitial") {
			var targetInsertionId = parseInt(dropTarget.data("inject-drop-tile-at"), 10);
			// In case we drop outside of the tile container
			if(isNaN(originFrameId) || isNaN(targetInsertionId)) {
				return;
			}
			//console.log("origin-frame: "+originFrameId+" - targetInsertionId: "+ targetInsertionId)
			this.framesheet.moveFrame(originFrameId, targetInsertionId);

			activeFrame = targetInsertionId;
			// The last fake interstitial tile is outside of the framesheet array bound.
			// It allow us to append after the very last element in this fake slot.
			// However, when setting back the active frame, we have to make sure the
			// frame does exist.
			if(activeFrame > (this.framesheet.getFrameCount() - 1)) {
				activeFrame = targetInsertionId - 1;
			}
		}
		else {
			var targetSwapId = parseInt(dropTarget.data("tile-number"), 10);
			// In case we drop outside of the tile container
			if(isNaN(originFrameId) || isNaN(targetSwapId)) {
				return;
			}
			//console.log("origin-frame: "+originFrameId+" - targetSwapId: "+ targetSwapId)
			this.framesheet.swapFrames(originFrameId, targetSwapId);
			activeFrame = targetSwapId;
		}

		$('#preview-list').removeClass("show-interstitial-tiles");

		// TODO(vincz): deprecate.
		piskel.setActiveFrameAndRedraw(activeFrame);

		// TODO(vincz): move localstorage request to the model layer?
		$.publish(Events.LOCALSTORAGE_REQUEST);

	};

	/**
     * @private
     * TODO(vincz): clean this giant rendering function & remove listeners.
     */
    ns.PreviewFilmController.prototype.createPreviewTile_ = function(tileNumber, framesheet) {
    	var currentFrame = this.framesheet.getFrameByIndex(tileNumber);
    	//var width = frame.getWidth() * this.dpi,
    	//	height = frame.getHeight() * this.dpi;

		var previewTileRoot = document.createElement("li");
		var classname = "preview-tile";
		previewTileRoot.setAttribute("data-tile-number", tileNumber);

		if (piskel.getActiveFrameIndex() == tileNumber) {
			classname += " selected";
		}
		previewTileRoot.className = classname;

		var canvasContainer = document.createElement("div");
		canvasContainer.className = "canvas-container";
		//canvasContainer.setAttribute('style', 'width:' + width + 'px; height:' + height + 'px;');

		var canvasBackground = document.createElement("div");
		canvasBackground.className = "canvas-background";
		canvasContainer.appendChild(canvasBackground);
		/*
		var canvasPreview = document.createElement("canvas");
		canvasPreview.className = "canvas tile-view"

		canvasPreview.setAttribute('width', width);
		canvasPreview.setAttribute('height', height);
        */

		previewTileRoot.addEventListener('click', function(evt) {
			// has not class tile-action:
			if(!evt.target.classList.contains('tile-action')) {
				piskel.setActiveFrameAndRedraw(tileNumber);
			}
		});

		var canvasPreviewDuplicateAction = document.createElement("button");
		canvasPreviewDuplicateAction.className = "tile-action"
		canvasPreviewDuplicateAction.innerHTML = "dup"

		canvasPreviewDuplicateAction.addEventListener('click', function(evt) {
			framesheet.duplicateFrameByIndex(tileNumber);
      		$.publish('SET_ACTIVE_FRAME', [tileNumber + 1]);
		});

		//this.renderer.render(this.framesheet.getFrameByIndex(tileNumber), canvasPreview);

		// TODO(vincz): Eventually optimize this part by not recreating a FrameRenderer. Note that the real optim
		// is to make this update function (#createPreviewTile) less aggressive.
		var renderingOptions = {"dpi": this.dpi };
		var currentFrameRenderer = new pskl.rendering.FrameRenderer($(canvasContainer), renderingOptions, "tile-view");
		currentFrameRenderer.init(currentFrame);

		previewTileRoot.appendChild(canvasContainer);
		previewTileRoot.appendChild(canvasPreviewDuplicateAction);

		if(tileNumber > 0 || this.framesheet.getFrameCount() > 1) {
			var canvasPreviewDeleteAction = document.createElement("button");
			canvasPreviewDeleteAction.className = "tile-action"
			canvasPreviewDeleteAction.innerHTML = "del"
			canvasPreviewDeleteAction.addEventListener('click', function(evt) {
				piskel.removeFrame(tileNumber);
			});
			previewTileRoot.appendChild(canvasPreviewDeleteAction);
		}

		return previewTileRoot;
    };
})();<commit_msg>Removing commented outdated code<commit_after>(function () {
	var ns = $.namespace("pskl.controller");
	ns.PreviewFilmController = function (framesheet, container, dpi) {

		this.dpi = dpi;
		this.framesheet = framesheet;
		this.container = container;

		$.subscribe(Events.REDRAW_PREVIEWFILM, $.proxy(function(evt) {
			this.createPreviews()
		}, this));
	};

	ns.PreviewFilmController.prototype.init = function() {
      var addFrameButton = $('#add-frame-button')[0];
      addFrameButton.addEventListener('mousedown', this.addFrame.bind(this));
      this.createPreviews();

    };

    ns.PreviewFilmController.prototype.addFrame = function () {
 		this.framesheet.addEmptyFrame();
        piskel.setActiveFrameAndRedraw(this.framesheet.getFrameCount() - 1);
    };

    ns.PreviewFilmController.prototype.createPreviews = function () {
      // TODO(vincz): Full redraw on any drawing modification, optimize.
      this.container.html("");

      var frameCount = this.framesheet.getFrameCount();

      for (var i = 0, l = frameCount; i < l ; i++) {
        this.container.append(this.createInterstitialTile_(i));
        this.container.append(this.createPreviewTile_(i, this.framesheet));
      }
      this.container.append(this.createInterstitialTile_(frameCount));

      var needDragndropBehavior = !!(frameCount > 1);
      if(needDragndropBehavior) {
      	this.initDragndropBehavior_();
      }
    };

    /**
     * @private
     */
    ns.PreviewFilmController.prototype.createInterstitialTile_ = function (tileNumber) {
    	var initerstitialTile = document.createElement("div");
		initerstitialTile.className = "interstitial-tile"
		initerstitialTile.setAttribute("data-tile-type", "interstitial");
		initerstitialTile.setAttribute("data-inject-drop-tile-at", tileNumber);

		return initerstitialTile;
    };

    /**
     * @private
     */
    ns.PreviewFilmController.prototype.initDragndropBehavior_ = function () {
    	var tiles = $(".preview-tile");
    	// Each preview film tile is draggable.
    	tiles.draggable( {
	      //containment: '.left-nav',
	      stack: '.preview-tile',
	      cursor: 'move',
	      revert: true,
	      start: function(event, ui) {
	      	// We only show the fake interstitial tiles when starting the
	      	// drag n drop interaction. We hide them when the DnD is done.
	      	$('#preview-list').addClass("show-interstitial-tiles");
	      },
	      stop: function() {
	      	$('#preview-list').removeClass("show-interstitial-tiles");
	      }
	    });

    	// Each preview film tile is a drop target. This allow us to swap two tiles.
    	// However, we want to be able to insert a tile between two other tiles.
    	// For that we created fake interstitial tiles that are used as drop targets as well.
    	var droppableTiles = $(".interstitial-tile");
    	$.merge(droppableTiles, tiles);

	    droppableTiles.droppable( {
	        accept: ".preview-tile",
	        tolerance: "pointer",
			activeClass: "droppable-active",
			hoverClass: "droppable-hover-active",
			drop: $.proxy(this.onDrop_, this)
	    });
    };

    /**
     * @private
     */
    ns.PreviewFilmController.prototype.onDrop_ = function( event, ui ) {
		var activeFrame;
		// When we drag from an element, the drag could start from a nested DOM element
		// inside the drag target. We normalize that by taking the correct ancestor:
		var originTile = $(event.srcElement).closest(".preview-tile");
		var originFrameId = parseInt(originTile.data("tile-number"), 10);
		var dropTarget = $(event.target);

		if(dropTarget.data("tile-type") == "interstitial") {
			var targetInsertionId = parseInt(dropTarget.data("inject-drop-tile-at"), 10);
			// In case we drop outside of the tile container
			if(isNaN(originFrameId) || isNaN(targetInsertionId)) {
				return;
			}
			//console.log("origin-frame: "+originFrameId+" - targetInsertionId: "+ targetInsertionId)
			this.framesheet.moveFrame(originFrameId, targetInsertionId);

			activeFrame = targetInsertionId;
			// The last fake interstitial tile is outside of the framesheet array bound.
			// It allow us to append after the very last element in this fake slot.
			// However, when setting back the active frame, we have to make sure the
			// frame does exist.
			if(activeFrame > (this.framesheet.getFrameCount() - 1)) {
				activeFrame = targetInsertionId - 1;
			}
		}
		else {
			var targetSwapId = parseInt(dropTarget.data("tile-number"), 10);
			// In case we drop outside of the tile container
			if(isNaN(originFrameId) || isNaN(targetSwapId)) {
				return;
			}
			//console.log("origin-frame: "+originFrameId+" - targetSwapId: "+ targetSwapId)
			this.framesheet.swapFrames(originFrameId, targetSwapId);
			activeFrame = targetSwapId;
		}

		$('#preview-list').removeClass("show-interstitial-tiles");

		// TODO(vincz): deprecate.
		piskel.setActiveFrameAndRedraw(activeFrame);

		// TODO(vincz): move localstorage request to the model layer?
		$.publish(Events.LOCALSTORAGE_REQUEST);

	};

	/**
     * @private
     * TODO(vincz): clean this giant rendering function & remove listeners.
     */
    ns.PreviewFilmController.prototype.createPreviewTile_ = function(tileNumber, framesheet) {
    	var currentFrame = this.framesheet.getFrameByIndex(tileNumber);

		var previewTileRoot = document.createElement("li");
		var classname = "preview-tile";
		previewTileRoot.setAttribute("data-tile-number", tileNumber);

		if (piskel.getActiveFrameIndex() == tileNumber) {
			classname += " selected";
		}
		previewTileRoot.className = classname;

		var canvasContainer = document.createElement("div");
		canvasContainer.className = "canvas-container";

		var canvasBackground = document.createElement("div");
		canvasBackground.className = "canvas-background";
		canvasContainer.appendChild(canvasBackground);

		previewTileRoot.addEventListener('click', function(evt) {
			// has not class tile-action:
			if(!evt.target.classList.contains('tile-action')) {
				piskel.setActiveFrameAndRedraw(tileNumber);
			}
		});

		var canvasPreviewDuplicateAction = document.createElement("button");
		canvasPreviewDuplicateAction.className = "tile-action"
		canvasPreviewDuplicateAction.innerHTML = "dup"

		canvasPreviewDuplicateAction.addEventListener('click', function(evt) {
			framesheet.duplicateFrameByIndex(tileNumber);
      		$.publish('SET_ACTIVE_FRAME', [tileNumber + 1]);
		});

		//this.renderer.render(this.framesheet.getFrameByIndex(tileNumber), canvasPreview);

		// TODO(vincz): Eventually optimize this part by not recreating a FrameRenderer. Note that the real optim
		// is to make this update function (#createPreviewTile) less aggressive.
		var renderingOptions = {"dpi": this.dpi };
		var currentFrameRenderer = new pskl.rendering.FrameRenderer($(canvasContainer), renderingOptions, "tile-view");
		currentFrameRenderer.init(currentFrame);

		previewTileRoot.appendChild(canvasContainer);
		previewTileRoot.appendChild(canvasPreviewDuplicateAction);

		if(tileNumber > 0 || this.framesheet.getFrameCount() > 1) {
			var canvasPreviewDeleteAction = document.createElement("button");
			canvasPreviewDeleteAction.className = "tile-action"
			canvasPreviewDeleteAction.innerHTML = "del"
			canvasPreviewDeleteAction.addEventListener('click', function(evt) {
				piskel.removeFrame(tileNumber);
			});
			previewTileRoot.appendChild(canvasPreviewDeleteAction);
		}

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


<commit_before>// Author: Nathan Van Gheem
// Contact: nathan@vangheem.us
// Version: 1.0
//
// Description:
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

define([
  'jquery',
  'underscore',
  'backbone',
  'ui/views/Toolbar',
  'ui/views/ButtonGroup',
  'ui/views/Button',
  'structure/views/TableView',
  'structure/views/SelectionWellView',
  'structure/views/OrderView',
  'structure/views/TagsView',
  'structure/views/SelectionButtonView',
  'structure/views/PagingView',
  'structure/views/TextFilterView',
  'structure/collections/ResultCollection',
  'structure/collections/SelectedCollection',
  'mockup-patterns-dropzone',
], function($, _, Backbone, Toolbar, ButtonGroup, ButtonView, TableView, SelectionWellView,
            OrderView, TagsView, SelectionButtonView, PagingView, TextFilterView, ResultCollection,
            SelectedCollection, DropZone) {
  "use strict";

  var AppView = Backbone.View.extend({
    tagName: 'div',
    initialize: function(){
      var self = this;
      self.collection = new ResultCollection([], {
        url: self.options.collection_url
      });
      self.queryHelper = self.options.queryHelper;
      self.selected_collection = new SelectedCollection();
      self.collection.queryHelper = self.queryHelper;
      self.table_view = new TableView({app: self});
      self.paging_view = new PagingView({app: self});
      self.paste_allowed = self.options.paste_allowed;

      /* initialize buttons */
      self.setupButtons();

      self.well_view = new SelectionWellView({
        collection: self.selected_collection,
        button: self.toolbar.get('selected'),
        app: self
      });
      self.order_view = new OrderView({
        button: self.buttons.folder.get('order'),
        app: self
      });
      self.tags_view = new TagsView({
        button: self.buttons.secondary.get('tags'),
        app: self
      });

      self.toolbar.on('button.cut:click primary.button.copy:click', self.cutCopyClickEvent, self);
      self.toolbar.on('button:click', self.buttonClickEvent, self);

      self.toolbar.get('selected').disable();
      self.buttons.primary.disable();
      self.buttons.secondary.disable();

      self.selected_collection.on('add remove reset', function(modal, collection) {
        if (collection.length) {
          self.toolbar.get('selected').enable();
          self.buttons.primary.enable();
          self.buttons.secondary.enable();
          if(!self.paste_allowed){
            self.buttons.primary.get('paste').disable();
          }
        } else {
          this.toolbar.get('selected').disable();
          self.buttons.primary.disable();
          self.buttons.secondary.disable();
        }
      }, self);

      /* detect shift clicks */
      self.shift_clicked = false;
      $(document).bind('keyup keydown', function(e){
        self.shift_clicked = e.shiftKey;
      });
    },
    buttonClickEvent: function(button){
      var self = this;
      var data = null, callback = null;

      if(button.url){
        // handle ajax now
        var uids = [];
        self.selected_collection.each(function(item){
          uids.push(item.uid());
        });

        if(arguments.length > 1){
          var arg1 = arguments[1];
          if(!arg1.preventDefault){
            data = arg1;
          }
        }
        if(arguments.length > 2){
          var arg2 = arguments[2];
          if(arg2 === 'function'){
            callback = arg2;
          }
        }
        if(data === null){
          data = {
            'selection': JSON.stringify(uids)
          };
        }
        data._authenticator = $('input[name="_authenticator"]').val();

        var url = button.url.replace('{path}', self.options.queryHelper.getCurrentPath());
        $.ajax({
          url: url,
          type: 'POST',
          data: data,
          success: function(data){
            if(data.status === 'success'){
              self.collection.reset();
            }
            if(data.msg){
              // give status message somewhere...
              alert(data.msg);
            }
            if(callback !== null){
              callback(data);
            }
          },
          error: function(data){
            if(data.status === 404){
              alert('operation url "' + url + '" is not valid');
            }
          }
        });
      }
    },
    cutCopyClickEvent: function(button){
      var self = this;
      self.paste_allowed = true;
      self.buttons.primary.get('paste').enable();
    },
    setupButtons: function(){
      var self = this;
      self.buttons = {};
      var items = [];
      items.push(new SelectionButtonView({
        title: 'Selected',
        collection: this.selected_collection
      }));
      _.each(_.pairs(this.options.buttonGroups), function(group){
        var buttons = [];
        _.each(group[1], function(button){
          buttons.push(new ButtonView(button));
        });
        self.buttons[group[0]] = new ButtonGroup({
          items: buttons,
          id: group[0],
          app: self
        });
        items.push(self.buttons[group[0]]);
      });
      items.push(new TextFilterView({id: 'filter'}));
      this.toolbar = new Toolbar({
        items: items
      });
    },
    render: function(){

      this.$el.append(this.toolbar.render().el);
      this.$el.append(this.well_view.render().el);
      this.$el.append(this.order_view.render().el);
      this.$el.append(this.tags_view.render().el);

      this.$el.append(this.table_view.render().el);
      this.$el.append(this.paging_view.render().el);

      /* dropzone support */
      var self = this;
      var uploadUrl = self.options.uploadUrl;
      if(uploadUrl){
        self.dropzone = new DropZone(self.$el, {
          klass: 'structure-dropzone',
          clickable: false,
          url: uploadUrl,
          autoCleanResults: true,
          success: function(e, data){
            self.table_view.render();
          }
        }).dropzone;
        self.dropzone.on('sending', function(){
          self.$el.addClass('dropping');
        });
        self.dropzone.on('complete', function(){
          self.$el.removeClass('dropping');
        });
      }
      return this;
    }
  });

  return AppView;
});
<commit_msg>fix klass to className<commit_after>// Author: Nathan Van Gheem
// Contact: nathan@vangheem.us
// Version: 1.0
//
// Description:
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

define([
  'jquery',
  'underscore',
  'backbone',
  'ui/views/Toolbar',
  'ui/views/ButtonGroup',
  'ui/views/Button',
  'structure/views/TableView',
  'structure/views/SelectionWellView',
  'structure/views/OrderView',
  'structure/views/TagsView',
  'structure/views/SelectionButtonView',
  'structure/views/PagingView',
  'structure/views/TextFilterView',
  'structure/collections/ResultCollection',
  'structure/collections/SelectedCollection',
  'mockup-patterns-dropzone',
], function($, _, Backbone, Toolbar, ButtonGroup, ButtonView, TableView, SelectionWellView,
            OrderView, TagsView, SelectionButtonView, PagingView, TextFilterView, ResultCollection,
            SelectedCollection, DropZone) {
  "use strict";

  var AppView = Backbone.View.extend({
    tagName: 'div',
    initialize: function(){
      var self = this;
      self.collection = new ResultCollection([], {
        url: self.options.collection_url
      });
      self.queryHelper = self.options.queryHelper;
      self.selected_collection = new SelectedCollection();
      self.collection.queryHelper = self.queryHelper;
      self.table_view = new TableView({app: self});
      self.paging_view = new PagingView({app: self});
      self.paste_allowed = self.options.paste_allowed;

      /* initialize buttons */
      self.setupButtons();

      self.well_view = new SelectionWellView({
        collection: self.selected_collection,
        button: self.toolbar.get('selected'),
        app: self
      });
      self.order_view = new OrderView({
        button: self.buttons.folder.get('order'),
        app: self
      });
      self.tags_view = new TagsView({
        button: self.buttons.secondary.get('tags'),
        app: self
      });

      self.toolbar.on('button.cut:click primary.button.copy:click', self.cutCopyClickEvent, self);
      self.toolbar.on('button:click', self.buttonClickEvent, self);

      self.toolbar.get('selected').disable();
      self.buttons.primary.disable();
      self.buttons.secondary.disable();

      self.selected_collection.on('add remove reset', function(modal, collection) {
        if (collection.length) {
          self.toolbar.get('selected').enable();
          self.buttons.primary.enable();
          self.buttons.secondary.enable();
          if(!self.paste_allowed){
            self.buttons.primary.get('paste').disable();
          }
        } else {
          this.toolbar.get('selected').disable();
          self.buttons.primary.disable();
          self.buttons.secondary.disable();
        }
      }, self);

      /* detect shift clicks */
      self.shift_clicked = false;
      $(document).bind('keyup keydown', function(e){
        self.shift_clicked = e.shiftKey;
      });
    },
    buttonClickEvent: function(button){
      var self = this;
      var data = null, callback = null;

      if(button.url){
        // handle ajax now
        var uids = [];
        self.selected_collection.each(function(item){
          uids.push(item.uid());
        });

        if(arguments.length > 1){
          var arg1 = arguments[1];
          if(!arg1.preventDefault){
            data = arg1;
          }
        }
        if(arguments.length > 2){
          var arg2 = arguments[2];
          if(arg2 === 'function'){
            callback = arg2;
          }
        }
        if(data === null){
          data = {
            'selection': JSON.stringify(uids)
          };
        }
        data._authenticator = $('input[name="_authenticator"]').val();

        var url = button.url.replace('{path}', self.options.queryHelper.getCurrentPath());
        $.ajax({
          url: url,
          type: 'POST',
          data: data,
          success: function(data){
            if(data.status === 'success'){
              self.collection.reset();
            }
            if(data.msg){
              // give status message somewhere...
              alert(data.msg);
            }
            if(callback !== null){
              callback(data);
            }
          },
          error: function(data){
            if(data.status === 404){
              alert('operation url "' + url + '" is not valid');
            }
          }
        });
      }
    },
    cutCopyClickEvent: function(button){
      var self = this;
      self.paste_allowed = true;
      self.buttons.primary.get('paste').enable();
    },
    setupButtons: function(){
      var self = this;
      self.buttons = {};
      var items = [];
      items.push(new SelectionButtonView({
        title: 'Selected',
        collection: this.selected_collection
      }));
      _.each(_.pairs(this.options.buttonGroups), function(group){
        var buttons = [];
        _.each(group[1], function(button){
          buttons.push(new ButtonView(button));
        });
        self.buttons[group[0]] = new ButtonGroup({
          items: buttons,
          id: group[0],
          app: self
        });
        items.push(self.buttons[group[0]]);
      });
      items.push(new TextFilterView({id: 'filter'}));
      this.toolbar = new Toolbar({
        items: items
      });
    },
    render: function(){

      this.$el.append(this.toolbar.render().el);
      this.$el.append(this.well_view.render().el);
      this.$el.append(this.order_view.render().el);
      this.$el.append(this.tags_view.render().el);

      this.$el.append(this.table_view.render().el);
      this.$el.append(this.paging_view.render().el);

      /* dropzone support */
      var self = this;
      var uploadUrl = self.options.uploadUrl;
      if(uploadUrl){
        self.dropzone = new DropZone(self.$el, {
          className: 'structure-dropzone',
          clickable: false,
          url: uploadUrl,
          autoCleanResults: true,
          success: function(e, data){
            self.table_view.render();
          }
        }).dropzone;
        self.dropzone.on('sending', function(){
          self.$el.addClass('dropping');
        });
        self.dropzone.on('complete', function(){
          self.$el.removeClass('dropping');
        });
      }
      return this;
    }
  });

  return AppView;
});
<|endoftext|>