<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

MODEL({
  package: 'foam.demos.sevenguis',
  name: 'Person',
  tableProperties: [ 'surname', 'name' ],
  properties: [ { name: 'id', hidden: true }, 'name', 'surname' ]
});

MODEL({
  package: 'foam.demos.sevenguis',
  name: 'CRUD',
  extendsModel: 'foam.ui.View',
  requires: [
    'foam.dao.EasyDAO',
    'foam.dao.IDBDAO',
    'foam.demos.sevenguis.Person',
    'foam.ui.TableView'
  ],
  properties: [
    {
      name: 'prefix',
      label: 'Filter prefix',
      postSet: function(_, prefix) {
        this.filteredDAO = this.dao.where(STARTS_WITH_IC(this.Person.SURNAME, prefix));
      }
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'dao',
      factory: function() {
        return foam.dao.EasyDAO.create({
          model: foam.demos.sevenguis.Person,
          daoType: 'IDB',
          cache: true,
          seqNo: true
        });
      }
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'filteredDAO',
      view: {
        factory_: 'foam.ui.TableView',
        title: '',
        scrollEnabled: true,
        editColumns: false
      },
      factory: function() { return this.dao; }
    },
    {
      name: 'data',
      view: { factory_: 'foam.ui.DetailView', title: '' },
      factory: function() { return this.Person.create(); }
    }
  ],
  methods: [
    function initHTML() {
      this.SUPER();
      this.filteredDAOView.hardSelection$.addListener(function(_, _, _, selection) {
        if ( selection ) this.data.copyFrom(selection);
      }.bind(this));
    }
  ],
  templates: [
    function CSS() {/*
      body { padding: 10px !important; }
      .buttons { padding-left: 592px; }
      .crud .detailView { border: none; background: white; }
      .crud span { overflow: hidden !important; }
      .crud { width: 1000px; }
      .detailPane { width: 45%; display: inline-block; margin-left: 50px; margin-top: 16px; }
      .label { color: #039; font-size: 14px; padding-top: 6px; }
      .prefix { margin-left: 10px; }
      .summaryPane { width: 49%; display: inline-block; vertical-align: top; }
      .tableView { height: 184px; outline: none; }
    */},
    function toHTML() {/*
      Filter prefix:  $$prefix{onKeyMode: true, type: 'search'}

        $$filteredDAO
        $$data

$$createItem $$updateItem $$deleteItem

    */}
  ],
  actions: [
    {
      name: 'createItem',
      label: 'Create',
      isEnabled: function() {
        var n = this.data.name, s = this.data.surname;
        return n && s;
      },
      action: function() {
        var data = this.data.clone();
        data.id = undefined;
        this.dao.put(data, {
          put: function(data) { this.data.copyFrom(data); }.bind(this)
        });
      }
    },
    {
      name: 'updateItem',
      label: 'Update',
      isEnabled: function() { return this.data.id; },
      action: function() {
        this.dao.put(this.data.clone(), {
          put: function(data) { self.data = data; }
        });
      }
    },
    {
      name: 'deleteItem',
      label: 'Delete',
      isEnabled: function() { return this.data.id; },
      action: function() {
        this.dao.remove(this.data.clone());
        this.data.id = this.data.name = this.data.surname = '';
      }
    }
  ]
});
<commit_msg>Set onKeyMode in CRUD demo so that focus works properly.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

MODEL({
  package: 'foam.demos.sevenguis',
  name: 'Person',
  tableProperties: [ 'surname', 'name' ],
  properties: [
    { name: 'id', hidden: true },
    { name: 'name',    view: { factory_: 'foam.ui.TextFieldView', onKeyMode: true } },
    { name: 'surname', view: { factory_: 'foam.ui.TextFieldView', onKeyMode: true } }
  ]
});

MODEL({
  package: 'foam.demos.sevenguis',
  name: 'CRUD',
  extendsModel: 'foam.ui.View',
  requires: [
    'foam.dao.EasyDAO',
    'foam.dao.IDBDAO',
    'foam.demos.sevenguis.Person',
    'foam.ui.TableView'
  ],
  properties: [
    {
      name: 'prefix',
      label: 'Filter prefix',
      postSet: function(_, prefix) {
        this.filteredDAO = this.dao.where(STARTS_WITH_IC(this.Person.SURNAME, prefix));
      }
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'dao',
      factory: function() {
        return foam.dao.EasyDAO.create({
          model: foam.demos.sevenguis.Person,
          daoType: 'IDB',
          cache: true,
          seqNo: true
        });
      }
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'filteredDAO',
      view: {
        factory_: 'foam.ui.TableView',
        title: '',
        scrollEnabled: true,
        editColumns: false
      },
      factory: function() { return this.dao; }
    },
    {
      name: 'data',
      view: { factory_: 'foam.ui.DetailView', title: '' },
      factory: function() { return this.Person.create(); }
    }
  ],
  methods: [
    function initHTML() {
      this.SUPER();
      this.filteredDAOView.hardSelection$.addListener(function(_, _, _, selection) {
        if ( selection ) this.data.copyFrom(selection);
      }.bind(this));
    }
  ],
  templates: [
    function CSS() {/*
      body { padding: 10px !important; }
      .buttons { padding-left: 592px; }
      .crud .detailView { border: none; background: white; }
      .crud span { overflow: hidden !important; }
      .crud { width: 1000px; }
      .detailPane { width: 45%; display: inline-block; margin-left: 50px; margin-top: 16px; }
      .label { color: #039; font-size: 14px; padding-top: 6px; }
      .prefix { margin-left: 10px; }
      .summaryPane { width: 49%; display: inline-block; vertical-align: top; }
      .tableView { height: 184px; outline: none; }
    */},
    function toHTML() {/*
      Filter prefix:  $$prefix{onKeyMode: true, type: 'search'}

        $$filteredDAO
        $$data

$$createItem $$updateItem $$deleteItem

    */}
  ],
  actions: [
    {
      name: 'createItem',
      label: 'Create',
      isEnabled: function() {
        var n = this.data.name, s = this.data.surname;
        return n && s;
      },
      action: function() {
        var data = this.data.clone();
        data.id = undefined;
        this.dao.put(data, {
          put: function(data) { this.data.copyFrom(data); }.bind(this)
        });
      }
    },
    {
      name: 'updateItem',
      label: 'Update',
      isEnabled: function() { return this.data.id; },
      action: function() {
        this.dao.put(this.data.clone(), {
          put: function(data) { self.data = data; }
        });
      }
    },
    {
      name: 'deleteItem',
      label: 'Delete',
      isEnabled: function() { return this.data.id; },
      action: function() {
        this.dao.remove(this.data.clone());
        this.data.id = this.data.name = this.data.surname = '';
      }
    }
  ]
});
<|endoftext|>


<commit_before>FieldDateTimeView = FieldView.extend({
  extension_type: 'fhdate',
  inputTime: "<input class='fh_appform_field_input col-xs-12 text-center <%= repeatingClassName%>' data-field='<%= fieldId %>' data-index='<%= index %>' type='time'>",
  inputDate: "<input class='fh_appform_field_input col-xs-12 text-center   <%= repeatingClassName%>' data-field='<%= fieldId %>' data-index='<%= index %>' type='date'>",
  inputDateTime: "<input class='fh_appform_field_input col-xs-12 text-center   <%= repeatingClassName%>' data-field='<%= fieldId %>' data-index='<%= index %>' placeholder='<%= placeholderText %>' type='text'>",
  renderInput:function(index){
    var fieldId = this.model.getFieldId();
    var repeatingClassName = this.model.isRepeating() ? this.repeatingClassName : this.nonRepeatingClassName;
    var placeholderText = "";

    var unit=this.getUnit();
    var template="";
    var buttonLabel="";
    if (unit==="datetime"){
      template=this.inputDateTime;
      placeholderText = this.getDateTimeFormat();
      buttonLabel=" &nbspGet Current Date & Time";
    }else if (unit==="date"){
      template=this.inputDate;
      buttonLabel="&nbspGet Current Date";
    }else if (unit==="time"){
      template=this.inputTime;
      buttonLabel="&nbspGet Current Time";
    }
    var html=_.template(template)({
      "fieldId":fieldId,
      "index":index,
      "repeatingClassName": repeatingClassName,
      "placeholderText": placeholderText
    });

    if(!this.readonly){
      html+=this.renderButton(index,buttonLabel,"fhdate");
    }

    return $(html);
  },
  getDateTimeFormat: function(){
    return this.model.getFieldDefinition().dateTimeFormat || "YYYY-MM-DD HH:mm:ss";
  },
  getUnit:function(){
    var def=this.model.getFieldDefinition();
    return def.datetimeUnit;
  },
  onRender:function(){
    var that=this;

    if(!this.readonly){
      this.$el.on("click","button",function(){
        that.action(this);
      });
    }
  },
  action: function(el) {
    var index=$(el).data().index;
    var self = this;
    var now=new Date();
    if (self.getUnit() === "datetime") {
      $('input[data-index="'+index+'"]', this.$el).val(self.generateDateTimeText(now)).blur();
    } else if (self.getUnit() === "date") {
      $('input[data-index="'+index+'"]', this.$el).val(self.getDate(now)).blur();
    } else if (self.getUnit() === "time") {
      $('input[data-index="'+index+'"]', this.$el).val(self.getTime(now)).blur();
    }
  },
  generateDateTimeText: function(date){
    return this.replaceTimeText(this.getDateTimeFormat(), date);
  },
  replaceTimeText: function(format, d){
    return format.replace("YYYY",d.getFullYear())
      .replace("MM",this.twoDigi(d.getMonth()+1))
      .replace("DD",this.twoDigi(d.getDate()))
      .replace("HH",this.twoDigi(d.getHours()))
      .replace("mm",this.twoDigi(d.getMinutes()))
      .replace("ss",this.twoDigi(d.getSeconds()));
  },
  getDate:function(d){
    return this.replaceTimeText("YYYY-MM-DD", d);
  },
  getTime:function(d){
    return this.replaceTimeText("HH:mm:ss", d);
  },
  twoDigi:function(num){
    if (num<10){
      return "0"+num.toString();
    }else{
      return num.toString();
    }
  }
});<commit_msg>fix(Rules for data is not working when the button is used): RHMAP-19715 - Change event<commit_after>FieldDateTimeView = FieldView.extend({
  extension_type: 'fhdate',
  inputTime: "<input class='fh_appform_field_input col-xs-12 text-center <%= repeatingClassName%>' data-field='<%= fieldId %>' data-index='<%= index %>' type='time'>",
  inputDate: "<input class='fh_appform_field_input col-xs-12 text-center   <%= repeatingClassName%>' data-field='<%= fieldId %>' data-index='<%= index %>' type='date'>",
  inputDateTime: "<input class='fh_appform_field_input col-xs-12 text-center   <%= repeatingClassName%>' data-field='<%= fieldId %>' data-index='<%= index %>' placeholder='<%= placeholderText %>' type='text'>",
  renderInput:function(index){
    var fieldId = this.model.getFieldId();
    var repeatingClassName = this.model.isRepeating() ? this.repeatingClassName : this.nonRepeatingClassName;
    var placeholderText = "";

    var unit=this.getUnit();
    var template="";
    var buttonLabel="";
    if (unit==="datetime"){
      template=this.inputDateTime;
      placeholderText = this.getDateTimeFormat();
      buttonLabel=" &nbspGet Current Date & Time";
    }else if (unit==="date"){
      template=this.inputDate;
      buttonLabel="&nbspGet Current Date";
    }else if (unit==="time"){
      template=this.inputTime;
      buttonLabel="&nbspGet Current Time";
    }
    var html=_.template(template)({
      "fieldId":fieldId,
      "index":index,
      "repeatingClassName": repeatingClassName,
      "placeholderText": placeholderText
    });

    if(!this.readonly){
      html+=this.renderButton(index,buttonLabel,"fhdate");
    }

    return $(html);
  },
  getDateTimeFormat: function(){
    return this.model.getFieldDefinition().dateTimeFormat || "YYYY-MM-DD HH:mm:ss";
  },
  getUnit:function(){
    var def=this.model.getFieldDefinition();
    return def.datetimeUnit;
  },
  onRender:function(){
    var that=this;

    if(!this.readonly){
      this.$el.on("click","button",function(){
        that.action(this);
      });
    }
  },
  action: function(el) {
    var index=$(el).data().index;
    var self = this;
    var now=new Date();
    if (self.getUnit() === "datetime") {
      $('input[data-index="'+index+'"]', this.$el).val(self.generateDateTimeText(now)).change();
    } else if (self.getUnit() === "date") {
      $('input[data-index="'+index+'"]', this.$el).val(self.getDate(now)).change();
    } else if (self.getUnit() === "time") {
      $('input[data-index="'+index+'"]', this.$el).val(self.getTime(now)).change();
    }
  },
  generateDateTimeText: function(date){
    return this.replaceTimeText(this.getDateTimeFormat(), date);
  },
  replaceTimeText: function(format, d){
    return format.replace("YYYY",d.getFullYear())
      .replace("MM",this.twoDigi(d.getMonth()+1))
      .replace("DD",this.twoDigi(d.getDate()))
      .replace("HH",this.twoDigi(d.getHours()))
      .replace("mm",this.twoDigi(d.getMinutes()))
      .replace("ss",this.twoDigi(d.getSeconds()));
  },
  getDate:function(d){
    return this.replaceTimeText("YYYY-MM-DD", d);
  },
  getTime:function(d){
    return this.replaceTimeText("HH:mm:ss", d);
  },
  twoDigi:function(num){
    if (num<10){
      return "0"+num.toString();
    }else{
      return num.toString();
    }
  }
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Transport = require('../transport')
  , XHR = require('./polling-xhr')
  , JSON = require('./polling-jsonp')
  , util = require('../util')
  , parser = require('../parser')
  , global = this

/**
 * Module exports.
 */

module.exports = Polling;

/**
 * Polling transport polymorphic constructor.
 * Decides on xhr vs jsonp based on feature detection.
 *
 * @api public
 */

function Polling (opts) {
  var xd;

  if (global.location) {
    xd = opts.host != global.location.hostname
      || global.location.port != opts.port;
  }

  var xhr = request(xd);

  if (xhr && !opts.forceJSONP) {
    return new XHR;
  } else {
    return new JSONP;
  }
};

/**
 * Inherits from Transport.
 */

util.inherits(Polling, Transport);

/**
 * Opens the socket (triggers polling). We write a PING message to determine
 * when the transport is open.
 *
 * @api private
 */

Polling.prototype.doOpen = function () {
  this.poll();
  this.write(parser.encodePacket('ping'));
};

/**
 * Pauses polling.
 *
 * @param {Function} callback upon flush
 * @api private
 */

Polling.prototype.pause = function (onFlush) {
  this.paused = true;

  var pending = 0;

  if (this.polling) {
    pending++;
    this.once('data', function () {
      --pending || onFlush();
    });
  }

  if (this.buffer) {
    pending++;
    this.once('flush', function () {
      --pending || onFlush();
    });
  }
};

/**
 * Starts polling cycle.
 *
 * @api public
 */

Polling.prototype.poll = function () {
  if (!this.paused) {
    this.polling = true;
    this.doPoll();
    this.emit('poll');
  }
};

/**
 * Overloads onData to detect payloads.
 *
 * @api private
 */

Polling.prototype.onData = function (data) {
  var packets = parser.decodePayload(data);

  for (var i = 0, l = packets.length; i < l; i++) {
    // if its a PONG to our initial ping we consider the connection open
    if ('opening' == this.readyState) {
      if ('pong' == packets[i].type) {
        this.onOpen();
        continue;
      } else {
        this.error('protocol violation');
        return;
      }
    }

    // if its a close packet, we close the ongoing requests
    if ('close' == packets[i].type) {
      // doClose will cancel existing requests, and then fire a close packet
      // to signal the server we're closed, since we can't kill the socket/s
      this.doClose();
      this.onClose();
      return;
    }

    // otherwise bypass onData and handle the message
    this.onMessage(packets[i]);
  }

  // if we got data we're not polling
  this.polling = false;

  // trigger next poll
  this.poll();
};

/**
 * For polling, send a close packet.
 *
 * @api private
 */

Polling.prototype.doClose = function () {
  this.write(parser.encodePacket('close'));
};

/**
 * Writes a packets payload.
 *
 * @param {Array} data packets
 * @api private
 */

Polling.prototype.writeMany = function (packets) {
  this.write(parser.encodePayload(packets));
};
<commit_msg>Added comment<commit_after>
/**
 * Module dependencies.
 */

var Transport = require('../transport')
  , XHR = require('./polling-xhr')
  , JSON = require('./polling-jsonp')
  , util = require('../util')
  , parser = require('../parser')
  , global = this

/**
 * Module exports.
 */

module.exports = Polling;

/**
 * Polling transport polymorphic constructor.
 * Decides on xhr vs jsonp based on feature detection.
 *
 * @api public
 */

function Polling (opts) {
  var xd;

  if (global.location) {
    xd = opts.host != global.location.hostname
      || global.location.port != opts.port;
  }

  var xhr = request(xd);

  if (xhr && !opts.forceJSONP) {
    return new XHR;
  } else {
    return new JSONP;
  }
};

/**
 * Inherits from Transport.
 */

util.inherits(Polling, Transport);

/**
 * Opens the socket (triggers polling). We write a PING message to determine
 * when the transport is open.
 *
 * @api private
 */

Polling.prototype.doOpen = function () {
  this.poll();
  this.write(parser.encodePacket('ping'));
};

/**
 * Pauses polling.
 *
 * @param {Function} callback upon flush
 * @api private
 */

Polling.prototype.pause = function (onFlush) {
  this.paused = true;

  var pending = 0;

  if (this.polling) {
    pending++;
    this.once('data', function () {
      --pending || onFlush();
    });
  }

  if (this.buffer) {
    pending++;
    this.once('flush', function () {
      --pending || onFlush();
    });
  }
};

/**
 * Starts polling cycle.
 *
 * @api public
 */

Polling.prototype.poll = function () {
  if (!this.paused) {
    this.polling = true;
    this.doPoll();
    this.emit('poll');
  }
};

/**
 * Overloads onData to detect payloads.
 *
 * @api private
 */

Polling.prototype.onData = function (data) {
  var packets = parser.decodePayload(data);

  for (var i = 0, l = packets.length; i < l; i++) {
    // if its a PONG to our initial ping we consider the connection open
    if ('opening' == this.readyState) {
      if ('pong' == packets[i].type) {
        this.onOpen();
        continue;
      } else {
        this.error('protocol violation');
        return;
      }
    }

    // if its a close packet, we close the ongoing requests
    if ('close' == packets[i].type) {
      // doClose will cancel existing requests, and then fire a close packet
      // to signal the server we're closed, since we can't kill the socket/s
      this.doClose();
      this.onClose();
      return;
    }

    // otherwise bypass onData and handle the message
    this.onMessage(packets[i]);
  }

  // if we got data we're not polling
  this.polling = false;

  // trigger next poll
  this.poll();
};

/**
 * For polling, send a close packet.
 *
 * @api private
 */

Polling.prototype.doClose = function () {
  // we mute existing buffers and bypass buffers
  this.write(parser.encodePacket('close'));
};

/**
 * Writes a packets payload.
 *
 * @param {Array} data packets
 * @api private
 */

Polling.prototype.writeMany = function (packets) {
  this.write(parser.encodePayload(packets));
};
<|endoftext|>


<commit_before>/*!
 * imagesLoaded v4.1.4
 * JavaScript is all like "You images are done yet or what?"
 * MIT License
 */

( function( window, factory ) {
  // universal module definition
  if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory( window, require('ev-emitter') );
  } else {
    // browser global
    window.imagesLoaded = factory( window, window.EvEmitter );
  }

} )( typeof window !== 'undefined' ? window : this,
    function factory( window, EvEmitter ) {

let $ = window.jQuery;
let console = window.console;

// -------------------------- helpers -------------------------- //

// extend objects
function extend( a, b ) {
  for ( let prop in b ) {
    a[ prop ] = b[ prop ];
  }
  return a;
}

let arraySlice = Array.prototype.slice;

// turn element or nodeList into an array
function makeArray( obj ) {
  if ( Array.isArray( obj ) ) {
    // use object if already an array
    return obj;
  }

  let isArrayLike = typeof obj == 'object' && typeof obj.length == 'number';
  if ( isArrayLike ) {
    // convert nodeList to array
    return arraySlice.call( obj );
  }

  // array of single index
  return [ obj ];
}

// -------------------------- imagesLoaded -------------------------- //

/**
 * @param {[Array, Element, NodeList, String]} elem
 * @param {[Object, Function]} options - if function, use as callback
 * @param {Function} onAlways - callback function
 * @returns {ImagesLoaded}
 */
function ImagesLoaded( elem, options, onAlways ) {
  // coerce ImagesLoaded() without new, to be new ImagesLoaded()
  if ( !( this instanceof ImagesLoaded ) ) {
    return new ImagesLoaded( elem, options, onAlways );
  }
  // use elem as selector string
  let queryElem = elem;
  if ( typeof elem == 'string' ) {
    queryElem = document.querySelectorAll( elem );
  }
  // bail if bad element
  if ( !queryElem ) {
    console.error( 'Bad element for imagesLoaded ' + ( queryElem || elem ) );
    return;
  }

  this.elements = makeArray( queryElem );
  this.options = extend( {}, this.options );
  // shift arguments if no options set
  if ( typeof options == 'function' ) {
    onAlways = options;
  } else {
    extend( this.options, options );
  }

  if ( onAlways ) {
    this.on( 'always', onAlways );
  }

  this.getImages();

  if ( $ ) {
    // add jQuery Deferred object
    this.jqDeferred = new $.Deferred();
  }

  // HACK check async to allow time to bind listeners
  setTimeout( this.check.bind( this ) );
}

ImagesLoaded.prototype = Object.create( EvEmitter.prototype );

ImagesLoaded.prototype.options = {};

ImagesLoaded.prototype.getImages = function() {
  this.images = [];

  // filter & find items if we have an item selector
  this.elements.forEach( this.addElementImages, this );
};

const elementNodeTypes = {
  1: true,
  9: true,
  11: true,
};

/**
 * @param {Node} elem
 */
ImagesLoaded.prototype.addElementImages = function( elem ) {
  // filter siblings
  if ( elem.nodeName == 'IMG' ) {
    this.addImage( elem );
  }
  // get background image on element
  if ( this.options.background === true ) {
    this.addElementBackgroundImages( elem );
  }

  // find children
  // no non-element nodes, #143
  let nodeType = elem.nodeType;
  if ( !nodeType || !elementNodeTypes[ nodeType ] ) {
    return;
  }
  let childImgs = elem.querySelectorAll('img');
  // concat childElems to filterFound array
  for ( let i = 0; i < childImgs.length; i++ ) {
    let img = childImgs[i];
    this.addImage( img );
  }

  // get child background images
  if ( typeof this.options.background == 'string' ) {
    let children = elem.querySelectorAll( this.options.background );
    for ( let j = 0; j < children.length; j++ ) {
      let child = children[j];
      this.addElementBackgroundImages( child );
    }
  }
};

ImagesLoaded.prototype.addElementBackgroundImages = function( elem ) {
  let style = getComputedStyle( elem );
  if ( !style ) {
    // Firefox returns null if in a hidden iframe https://bugzil.la/548397
    return;
  }
  // get url inside url("...")
  let reURL = /url\((['"])?(.*?)\1\)/gi;
  let matches = reURL.exec( style.backgroundImage );
  while ( matches !== null ) {
    let url = matches && matches[2];
    if ( url ) {
      this.addBackground( url, elem );
    }
    matches = reURL.exec( style.backgroundImage );
  }
};

/**
 * @param {Image} img
 */
ImagesLoaded.prototype.addImage = function( img ) {
  let loadingImage = new LoadingImage( img );
  this.images.push( loadingImage );
};

ImagesLoaded.prototype.addBackground = function( url, elem ) {
  let background = new Background( url, elem );
  this.images.push( background );
};

ImagesLoaded.prototype.check = function() {
  let _this = this;
  this.progressedCount = 0;
  this.hasAnyBroken = false;
  // complete if no images
  if ( !this.images.length ) {
    this.complete();
    return;
  }

  function onProgress( image, elem, message ) {
    // HACK - Chrome triggers event before object properties have changed. #83
    setTimeout( function() {
      _this.progress( image, elem, message );
    } );
  }

  this.images.forEach( function( loadingImage ) {
    loadingImage.once( 'progress', onProgress );
    loadingImage.check();
  } );
};

ImagesLoaded.prototype.progress = function( image, elem, message ) {
  this.progressedCount++;
  this.hasAnyBroken = this.hasAnyBroken || !image.isLoaded;
  // progress event
  this.emitEvent( 'progress', [ this, image, elem ] );
  if ( this.jqDeferred && this.jqDeferred.notify ) {
    this.jqDeferred.notify( this, image );
  }
  // check if completed
  if ( this.progressedCount == this.images.length ) {
    this.complete();
  }

  if ( this.options.debug && console ) {
    console.log( 'progress: ' + message, image, elem );
  }
};

ImagesLoaded.prototype.complete = function() {
  let eventName = this.hasAnyBroken ? 'fail' : 'done';
  this.isComplete = true;
  this.emitEvent( eventName, [ this ] );
  this.emitEvent( 'always', [ this ] );
  if ( this.jqDeferred ) {
    let jqMethod = this.hasAnyBroken ? 'reject' : 'resolve';
    this.jqDeferred[ jqMethod ]( this );
  }
};

// --------------------------  -------------------------- //

function LoadingImage( img ) {
  this.img = img;
}

LoadingImage.prototype = Object.create( EvEmitter.prototype );

LoadingImage.prototype.check = function() {
  // If complete is true and browser supports natural sizes,
  // try to check for image status manually.
  let isComplete = this.getIsImageComplete();
  if ( isComplete ) {
    // report based on naturalWidth
    this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' );
    return;
  }

  // If none of the checks above matched, simulate loading on detached element.
  this.proxyImage = new Image();
  this.proxyImage.addEventListener( 'load', this );
  this.proxyImage.addEventListener( 'error', this );
  // bind to image as well for Firefox. #191
  this.img.addEventListener( 'load', this );
  this.img.addEventListener( 'error', this );
  this.proxyImage.src = this.img.src;
};

LoadingImage.prototype.getIsImageComplete = function() {
  // check for non-zero, non-undefined naturalWidth
  // fixes Safari+InfiniteScroll+Masonry bug infinite-scroll#671
  return this.img.complete && this.img.naturalWidth;
};

LoadingImage.prototype.confirm = function( isLoaded, message ) {
  this.isLoaded = isLoaded;
  this.emitEvent( 'progress', [ this, this.img, message ] );
};

// ----- events ----- //

// trigger specified handler for event type
LoadingImage.prototype.handleEvent = function( event ) {
  let method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

LoadingImage.prototype.onload = function() {
  this.confirm( true, 'onload' );
  this.unbindEvents();
};

LoadingImage.prototype.onerror = function() {
  this.confirm( false, 'onerror' );
  this.unbindEvents();
};

LoadingImage.prototype.unbindEvents = function() {
  this.proxyImage.removeEventListener( 'load', this );
  this.proxyImage.removeEventListener( 'error', this );
  this.img.removeEventListener( 'load', this );
  this.img.removeEventListener( 'error', this );
};

// -------------------------- Background -------------------------- //

function Background( url, element ) {
  this.url = url;
  this.element = element;
  this.img = new Image();
}

// inherit LoadingImage prototype
Background.prototype = Object.create( LoadingImage.prototype );

Background.prototype.check = function() {
  this.img.addEventListener( 'load', this );
  this.img.addEventListener( 'error', this );
  this.img.src = this.url;
  // check if image is already complete
  let isComplete = this.getIsImageComplete();
  if ( isComplete ) {
    this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' );
    this.unbindEvents();
  }
};

Background.prototype.unbindEvents = function() {
  this.img.removeEventListener( 'load', this );
  this.img.removeEventListener( 'error', this );
};

Background.prototype.confirm = function( isLoaded, message ) {
  this.isLoaded = isLoaded;
  this.emitEvent( 'progress', [ this, this.element, message ] );
};

// -------------------------- jQuery -------------------------- //

ImagesLoaded.makeJQueryPlugin = function( jQuery ) {
  jQuery = jQuery || window.jQuery;
  if ( !jQuery ) {
    return;
  }
  // set local variable
  $ = jQuery;
  // $().imagesLoaded()
  $.fn.imagesLoaded = function( options, onAlways ) {
    let instance = new ImagesLoaded( this, options, onAlways );
    return instance.jqDeferred.promise( $( this ) );
  };
};
// try making plugin
ImagesLoaded.makeJQueryPlugin();

// --------------------------  -------------------------- //

return ImagesLoaded;

} );
<commit_msg>🛠 ES6 upgrades; use for-of loops<commit_after>/*!
 * imagesLoaded v4.1.4
 * JavaScript is all like "You images are done yet or what?"
 * MIT License
 */

( function( window, factory ) {
  // universal module definition
  if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory( window, require('ev-emitter') );
  } else {
    // browser global
    window.imagesLoaded = factory( window, window.EvEmitter );
  }

} )( typeof window !== 'undefined' ? window : this,
    function factory( window, EvEmitter ) {

let $ = window.jQuery;
let console = window.console;

// -------------------------- helpers -------------------------- //

// turn element or nodeList into an array
function makeArray( obj ) {
  // use object if already an array
  if ( Array.isArray( obj ) ) return obj;

  let isArrayLike = typeof obj == 'object' && typeof obj.length == 'number';
  // convert nodeList to array
  if ( isArrayLike ) return [ ...obj ];

  // array of single index
  return [ obj ];
}

// -------------------------- imagesLoaded -------------------------- //

/**
 * @param {[Array, Element, NodeList, String]} elem
 * @param {[Object, Function]} options - if function, use as callback
 * @param {Function} onAlways - callback function
 * @returns {ImagesLoaded}
 */
function ImagesLoaded( elem, options, onAlways ) {
  // coerce ImagesLoaded() without new, to be new ImagesLoaded()
  if ( !( this instanceof ImagesLoaded ) ) {
    return new ImagesLoaded( elem, options, onAlways );
  }
  // use elem as selector string
  let queryElem = elem;
  if ( typeof elem == 'string' ) {
    queryElem = document.querySelectorAll( elem );
  }
  // bail if bad element
  if ( !queryElem ) {
    console.error(`Bad element for imagesLoaded ${queryElem || elem}`);
    return;
  }

  this.elements = makeArray( queryElem );
  this.options = {};
  // shift arguments if no options set
  if ( typeof options == 'function' ) {
    onAlways = options;
  } else {
    Object.assign( this.options, options );
  }

  if ( onAlways ) this.on( 'always', onAlways );

  this.getImages();
  // add jQuery Deferred object
  if ( $ ) this.jqDeferred = new $.Deferred();

  // HACK check async to allow time to bind listeners
  setTimeout( this.check.bind( this ) );
}

ImagesLoaded.prototype = Object.create( EvEmitter.prototype );

ImagesLoaded.prototype.getImages = function() {
  this.images = [];

  // filter & find items if we have an item selector
  this.elements.forEach( this.addElementImages, this );
};

const elementNodeTypes = [ 1, 9, 11 ];

/**
 * @param {Node} elem
 */
ImagesLoaded.prototype.addElementImages = function( elem ) {
  // filter siblings
  if ( elem.nodeName == 'IMG' ) {
    this.addImage( elem );
  }
  // get background image on element
  if ( this.options.background === true ) {
    this.addElementBackgroundImages( elem );
  }

  // find children
  // no non-element nodes, #143
  let { nodeType } = elem;
  if ( !nodeType || !elementNodeTypes.includes( nodeType ) ) return;

  let childImgs = elem.querySelectorAll('img');
  // concat childElems to filterFound array
  for ( let img of childImgs ) {
    this.addImage( img );
  }

  // get child background images
  if ( typeof this.options.background == 'string' ) {
    let children = elem.querySelectorAll( this.options.background );
    for ( let child of children ) {
      this.addElementBackgroundImages( child );
    }
  }
};

const reURL = /url\((['"])?(.*?)\1\)/gi;

ImagesLoaded.prototype.addElementBackgroundImages = function( elem ) {
  let style = getComputedStyle( elem );
  // Firefox returns null if in a hidden iframe https://bugzil.la/548397
  if ( !style ) return;

  // get url inside url("...")
  let matches = reURL.exec( style.backgroundImage );
  while ( matches !== null ) {
    let url = matches && matches[2];
    if ( url ) {
      this.addBackground( url, elem );
    }
    matches = reURL.exec( style.backgroundImage );
  }
};

/**
 * @param {Image} img
 */
ImagesLoaded.prototype.addImage = function( img ) {
  let loadingImage = new LoadingImage( img );
  this.images.push( loadingImage );
};

ImagesLoaded.prototype.addBackground = function( url, elem ) {
  let background = new Background( url, elem );
  this.images.push( background );
};

ImagesLoaded.prototype.check = function() {
  this.progressedCount = 0;
  this.hasAnyBroken = false;
  // complete if no images
  if ( !this.images.length ) {
    this.complete();
    return;
  }

  /* eslint-disable-next-line func-style */
  let onProgress = ( image, elem, message ) => {
    // HACK - Chrome triggers event before object properties have changed. #83
    setTimeout( () => {
      this.progress( image, elem, message );
    } );
  };

  this.images.forEach( function( loadingImage ) {
    loadingImage.once( 'progress', onProgress );
    loadingImage.check();
  } );
};

ImagesLoaded.prototype.progress = function( image, elem, message ) {
  this.progressedCount++;
  this.hasAnyBroken = this.hasAnyBroken || !image.isLoaded;
  // progress event
  this.emitEvent( 'progress', [ this, image, elem ] );
  if ( this.jqDeferred && this.jqDeferred.notify ) {
    this.jqDeferred.notify( this, image );
  }
  // check if completed
  if ( this.progressedCount == this.images.length ) {
    this.complete();
  }

  if ( this.options.debug && console ) {
    console.log( 'progress: ' + message, image, elem );
  }
};

ImagesLoaded.prototype.complete = function() {
  let eventName = this.hasAnyBroken ? 'fail' : 'done';
  this.isComplete = true;
  this.emitEvent( eventName, [ this ] );
  this.emitEvent( 'always', [ this ] );
  if ( this.jqDeferred ) {
    let jqMethod = this.hasAnyBroken ? 'reject' : 'resolve';
    this.jqDeferred[ jqMethod ]( this );
  }
};

// --------------------------  -------------------------- //

function LoadingImage( img ) {
  this.img = img;
}

LoadingImage.prototype = Object.create( EvEmitter.prototype );

LoadingImage.prototype.check = function() {
  // If complete is true and browser supports natural sizes,
  // try to check for image status manually.
  let isComplete = this.getIsImageComplete();
  if ( isComplete ) {
    // report based on naturalWidth
    this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' );
    return;
  }

  // If none of the checks above matched, simulate loading on detached element.
  this.proxyImage = new Image();
  this.proxyImage.addEventListener( 'load', this );
  this.proxyImage.addEventListener( 'error', this );
  // bind to image as well for Firefox. #191
  this.img.addEventListener( 'load', this );
  this.img.addEventListener( 'error', this );
  this.proxyImage.src = this.img.src;
};

LoadingImage.prototype.getIsImageComplete = function() {
  // check for non-zero, non-undefined naturalWidth
  // fixes Safari+InfiniteScroll+Masonry bug infinite-scroll#671
  return this.img.complete && this.img.naturalWidth;
};

LoadingImage.prototype.confirm = function( isLoaded, message ) {
  this.isLoaded = isLoaded;
  this.emitEvent( 'progress', [ this, this.img, message ] );
};

// ----- events ----- //

// trigger specified handler for event type
LoadingImage.prototype.handleEvent = function( event ) {
  let method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

LoadingImage.prototype.onload = function() {
  this.confirm( true, 'onload' );
  this.unbindEvents();
};

LoadingImage.prototype.onerror = function() {
  this.confirm( false, 'onerror' );
  this.unbindEvents();
};

LoadingImage.prototype.unbindEvents = function() {
  this.proxyImage.removeEventListener( 'load', this );
  this.proxyImage.removeEventListener( 'error', this );
  this.img.removeEventListener( 'load', this );
  this.img.removeEventListener( 'error', this );
};

// -------------------------- Background -------------------------- //

function Background( url, element ) {
  this.url = url;
  this.element = element;
  this.img = new Image();
}

// inherit LoadingImage prototype
Background.prototype = Object.create( LoadingImage.prototype );

Background.prototype.check = function() {
  this.img.addEventListener( 'load', this );
  this.img.addEventListener( 'error', this );
  this.img.src = this.url;
  // check if image is already complete
  let isComplete = this.getIsImageComplete();
  if ( isComplete ) {
    this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' );
    this.unbindEvents();
  }
};

Background.prototype.unbindEvents = function() {
  this.img.removeEventListener( 'load', this );
  this.img.removeEventListener( 'error', this );
};

Background.prototype.confirm = function( isLoaded, message ) {
  this.isLoaded = isLoaded;
  this.emitEvent( 'progress', [ this, this.element, message ] );
};

// -------------------------- jQuery -------------------------- //

ImagesLoaded.makeJQueryPlugin = function( jQuery ) {
  jQuery = jQuery || window.jQuery;
  if ( !jQuery ) {
    return;
  }
  // set local variable
  $ = jQuery;
  // $().imagesLoaded()
  $.fn.imagesLoaded = function( options, onAlways ) {
    let instance = new ImagesLoaded( this, options, onAlways );
    return instance.jqDeferred.promise( $( this ) );
  };
};
// try making plugin
ImagesLoaded.makeJQueryPlugin();

// --------------------------  -------------------------- //

return ImagesLoaded;

} );
<|endoftext|>


<commit_before>//var lymbix = new $.lymbix('8c1a36ec73827cd2cfac9d943d981cbacf671d65');
//lymbix.tonalize('I think you should get off your pedestal.', function (object) { blah = object; console.log(object) });

function buildDisplay(responseObj)
{
	console.log('responseObj', responseObj);

	// handle the dominant emotion
	switch (responseObj.dominant_emotion)
	{
		case 'affection_friendliness':
			$('#dominantEmotion').addClass('affection');
			//$('#dominantEmotionText').html('Affection / Friendliness');
			break;
		case 'anger_loathing':
			$('#dominantEmotion').addClass('anger');
			//$('#dominantEmotionText').html('Anger / Loathing');
			break;
		case 'contentment_gratitude':
			$('#dominantEmotion').addClass('contentment');
			//$('#dominantEmotionText').html('Contentment / Gratitude');
			break;
		case 'enjoyment_elation':
			$('#dominantEmotion').addClass('enjoyment');
			//$('#dominantEmotionText').html('Enjoyment / Elation');
			break;
		case 'fear_uneasiness':
			$('#dominantEmotion').addClass('fear');
			//$('#dominantEmotionText').html('Fear Uneasiness');
			break;
		case 'humiliation_shame':
			$('#dominantEmotion').addClass('humiliation');
			//$('#dominantEmotionText').html('Humiliation / Shame');
			break;
		case 'sadness_grief':
			$('#dominantEmotion').addClass('sadness');
			//$('#dominantEmotionText').html('Sadness / Grief');
			break;
		case 'amusement_excitement':
			$('#dominantEmotion').addClass('amusement');
			//$('#dominantEmotionText').html('Amusement / Excitement');
			break;
	}

	// sentiment
	$('#sentiment').html(responseObj.article_sentiment.sentiment);

	// clarity
	$('#clarity').html(responseObj.clarity);

	// intense sentence
	$('#dominantEmotionText').html(responseObj.intense_sentence.sentence);

	// average_intensity
	$('#average_intensity').html(responseObj.average_intensity);

	// breakdown
	$('#affection_friendliness').html(responseObj.affection_friendliness);
	$('#amusement_excitement').html(responseObj.amusement_excitement);
	$('#anger_loathing').html(responseObj.anger_loathing);
	$('#contentment_gratitude').html(responseObj.contentment_gratitude);
	$('#enjoyment_elation').html(responseObj.enjoyment_elation);
	$('#fear_uneasiness').html(responseObj.fear_uneasiness);
	$('#humiliation_shame').html(responseObj.humiliation_shame);
	$('#sadness_grief').html(responseObj.sadness_grief);
}

$( document ).ready(function()
{
	var response = {"article":"I think you should get off your pedestal.","ignored_terms":[],"affection_friendliness":0.13,"enjoyment_elation":0.34,"amusement_excitement":0.25,"contentment_gratitude":0.57,"sadness_grief":-6.35,"anger_loathing":-10,"fear_uneasiness":-0.08,"humiliation_shame":-1.76,"dominant_emotion":"anger_loathing","average_intensity":1.21,"article_sentiment":{"sentiment":"Negative","score":-10},"coverage":95,"intense_sentence":{"sentence":"I think you should get off your pedestal.","dominant_emotion":"anger_loathing","intensity":10},"clarity":94.19};
	buildDisplay(response);
});
<commit_msg>new stuff<commit_after>//var lymbix = new $.lymbix('8c1a36ec73827cd2cfac9d943d981cbacf671d65');
//lymbix.tonalize('I think you should get off your pedestal.', function (object) { blah = object; console.log(object) });

function buildDisplay(responseObj)
{
	console.log('responseObj', responseObj);

	// handle the dominant emotion
	switch (responseObj.dominant_emotion)
	{
		case 'affection_friendliness':
			$('#dominantEmotion').addClass('affection');
			//$('#dominantEmotionText').html('Affection / Friendliness');
			break;
		case 'anger_loathing':
			$('#dominantEmotion').addClass('anger');
			//$('#dominantEmotionText').html('Anger / Loathing');
			break;
		case 'contentment_gratitude':
			$('#dominantEmotion').addClass('contentment');
			//$('#dominantEmotionText').html('Contentment / Gratitude');
			break;
		case 'enjoyment_elation':
			$('#dominantEmotion').addClass('enjoyment');
			//$('#dominantEmotionText').html('Enjoyment / Elation');
			break;
		case 'fear_uneasiness':
			$('#dominantEmotion').addClass('fear');
			//$('#dominantEmotionText').html('Fear Uneasiness');
			break;
		case 'humiliation_shame':
			$('#dominantEmotion').addClass('humiliation');
			//$('#dominantEmotionText').html('Humiliation / Shame');
			break;
		case 'sadness_grief':
			$('#dominantEmotion').addClass('sadness');
			//$('#dominantEmotionText').html('Sadness / Grief');
			break;
		case 'amusement_excitement':
			$('#dominantEmotion').addClass('amusement');
			//$('#dominantEmotionText').html('Amusement / Excitement');
			break;
	}

	// sentiment
	$('#sentiment').html(responseObj.article_sentiment.sentiment);

	// clarity
	$('#clarity').html(responseObj.clarity);

	// intense sentence
	$('#dominantEmotionText').html(responseObj.intense_sentence.sentence);

	// average_intensity
	$('#average_intensity').html(responseObj.average_intensity);

	// breakdown
	$('#affection_friendliness').html(responseObj.affection_friendliness);
	$('#amusement_excitement').html(responseObj.amusement_excitement);
	$('#anger_loathing').html(responseObj.anger_loathing);
	$('#contentment_gratitude').html(responseObj.contentment_gratitude);
	$('#enjoyment_elation').html(responseObj.enjoyment_elation);
	$('#fear_uneasiness').html(responseObj.fear_uneasiness);
	$('#humiliation_shame').html(responseObj.humiliation_shame);
	$('#sadness_grief').html(responseObj.sadness_grief);
}

$( document ).ready(function()
{
	var response = {"article":"I think you should get off your pedestal.","ignored_terms":[],"affection_friendliness":0.13,"enjoyment_elation":0.34,"amusement_excitement":0.25,"contentment_gratitude":0.57,"sadness_grief":-6.35,"anger_loathing":-10,"fear_uneasiness":-0.08,"humiliation_shame":-1.76,"dominant_emotion":"anger_loathing","average_intensity":1.21,"article_sentiment":{"sentiment":"Negative","score":-10},"coverage":95,"intense_sentence":{"sentence":"I think you should get off your pedestal.","dominant_emotion":"anger_loathing","intensity":10},"clarity":94.19};
	buildDisplay(response);
});
<|endoftext|>


<commit_before>'use strict';

const database = require('./application/helpers/database');
const directory = require('./application/helpers/directory');
const express = require('express');
const file_upload = require('express-fileupload');
const process = require('process');
const routes = require('./application/routes');

const app = express();

const port = process.env.PORT || 8000; // Choose application port

app.set('view engine', 'pug'); // Set render engine

app.use(file_upload()); // Add file upload module

app.use(express.static(directory.public())); // Set static folder

database.connect(function (err, db) {
    console.log('MongoDB is running (port ' + database.port + ', database ' + database.database + ')');

    db.close();
});

app.listen(port, function () { // Listen on specified port
    console.log('Listening on port ' + port);
});

routes.register(app); // Register routes
<commit_msg>Add session middleware<commit_after>'use strict';

const database = require('./application/helpers/database');
const directory = require('./application/helpers/directory');
const express = require('express');
const file_upload = require('express-fileupload');
const process = require('process');
const routes = require('./application/routes');
const session = require('express-session');

const app = express();

const port = process.env.PORT || 8000; // Choose application port

app.set('view engine', 'pug'); // Set render engine

app.use(file_upload()); // Add file upload module

app.use(express.static(directory.public())); // Set static folder

app.use(session({
    'cookie': {
        'secure': false
    },
    'name': 'sid',
    'resave': false,
    'saveUninitialized': true,
    'secret': process.env.SECURE || 'secure'
}));

database.connect(function (err, db) {
    console.log('MongoDB is running (port ' + database.port + ', database ' + database.database + ')');

    db.close();
});

app.listen(port, function () { // Listen on specified port
    console.log('Listening on port ' + port);
});

routes.register(app); // Register routes
<|endoftext|>


<commit_before>import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
import levelNames from "../constants/levelNames";

export default class CopyButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.copyBtnRef = React.createRef();
    this.clipboardRef = React.createRef();
  }

  static defaultProps = {
    content: '',
  };

  componentDidMount() {

    this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
      text: () => this.props.content,
    });
    this.clipboardRef.current.on('success', () => {
      // this.setState({ isSuccessMsgShow: true });
      const copyBtnRef = this.copyBtnRef.current;
      copyBtnRef.setAttribute('data-balloon', '複製成功！');
      copyBtnRef.setAttribute('data-balloon-visible', '');
      copyBtnRef.setAttribute('data-balloon-pos', 'up');
      setTimeout(function() {
        copyBtnRef.removeAttribute('data-balloon');
        copyBtnRef.removeAttribute('data-balloon-visible');
        copyBtnRef.removeAttribute('data-balloon-pos');
      }, 3000);
    });
  }

  render() {
    return (
      <button
        ref={this.copyBtnRef}
        key="copy"
        onClick={() => {}}
        className="btn-copy"
      >
        複製到剪貼簿
        <style jsx>{`
          .btn-copy {
            margin-left: 10px;
          }
        `}</style>
      </button>
    );
  }
}
<commit_msg>Use attribute object from state<commit_after>import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';

export default class CopyButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.copyBtnRef = React.createRef();
    this.clipboardRef = React.createRef();
  }

  static defaultProps = {
    content: '',
  };
  state = {
    btnAttributes: {},
  };

  componentDidMount() {
    this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
      text: () => this.props.content,
    });
    this.clipboardRef.current.on('success', () => {
      const self = this;
      this.setState({
        btnAttributes: {
          'data-balloon': '複製成功！',
          'data-balloon-visible': '',
          'data-balloon-pos': 'up',
        }});

      setTimeout(function() {
        self.setState({ btnAttributes: {} });
      }, 1000);
    });
  }

  render() {
    return (
      <button
        ref={this.copyBtnRef}
        key="copy"
        onClick={() => {}}
        className="btn-copy"
        { ...this.state.btnAttributes }
      >
        複製到剪貼簿
        <style jsx>{`
          .btn-copy {
            margin-left: 10px;
          }
        `}</style>
      </button>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

app.factory('AddressesService', ['$http', function ($http) {
	return {
		aggByAddress: aggByAddress
	}

	function aggByAddress(allMaps){
		return _.chain(allMaps)
				.groupBy('address')
				.map(function(val, key){
					return {
						id : key,
						maps : val,
						label : val[0].address_label,
						nbrMaps : _.filter(val, function(map) {
							return map.id;
						})
					}
				})
				.orderBy(function(adr){
					return adr.nbrMaps.length;
				}, 'desc')
				.value();
	}
}]);<commit_msg>sort by distance instead of nimber of maps<commit_after>'use strict';

app.factory('AddressesService', ['$http', function ($http) {
	return {
		aggByAddress: aggByAddress
	}

	function aggByAddress(allMaps){
		return _.chain(allMaps)
				.groupBy('address')
				.map(function(val, key){
					return {
						id : key,
						maps : val,
						label : val[0].address_label,
						dist : (_.maxBy(val, function(map){return map.dist})).dist,
						nbrMaps : _.filter(val, function(map) {
							return map.id;
						})
					}
				})
				.orderBy(function(adr){
					return adr.dist;
				}, 'asc')
				.value();
	}
}]);<|endoftext|>


<commit_before>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
 * See README.md for more information
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific
 *
 */

const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const git = require("git-rev-sync");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const webpack = require("webpack");

const basePath = path.resolve(__dirname);

module.exports = {
    entry: {
        app: "./client/main.js"
    },
    output: {
        path: path.join(basePath, "/dist"),
        filename: "[name].[contenthash].js"
    },
    resolve: {
        symlinks: false,
        alias: {
            svelte: path.resolve("node_modules", "svelte")
        },
        extensions: [".svelte", ".js"],
        mainFields: ["svelte", "browser", "module", "main"]
    },
    // optimization: {
    //     runtimeChunk: "single",
    //     splitChunks: {
    //         chunks: "all",
    //         minSize: 30000,
    //         maxSize: 600000,
    //         minChunks: 1,
    //         maxAsyncRequests: 8,
    //         maxInitialRequests: 4,
    //         automaticNameDelimiter: "~",
    //         name: true,
    //         cacheGroups: {
    //             vendors: {
    //                 test: /[\\/]node_modules[\\/]/,
    //                 priority: -10
    //             },
    //             default: {
    //                 minChunks: 2,
    //                 priority: -20,
    //                 reuseExistingChunk: true
    //             }
    //         }
    //     }
    // },
    watchOptions: {
        ignored: /node_modules/,
        aggregateTimeout: 800
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            title: "Waltz",
            filename: "index.html",
            template: "index.ejs",
            favicon: path.join(basePath, "images", "favicon.ico"),
            hash: true,
        }),
        new webpack.DefinePlugin({
            "__ENV__": JSON.stringify(process.env.BUILD_ENV || "dev"),
            "__REVISION__": JSON.stringify(git.long()),
        })
    ],
    module: {
        rules: [
            {
                test: /\.svelte$/,
                use: [
                    { loader: "babel-loader" },
                    {
                        loader: "svelte-loader",
                        options: {
                            preprocess: require('svelte-preprocess')({
                                postcss: true
                            }),
                            emitCss: true,
                            hotReload: true
                        }
                    }
                ],

            }, {
                test: /(\.m?jsx?$)/,
                use: ["babel-loader"]
            }, {
                test: /\.s?css$/,
                use: [
                    {
                        loader: "thread-loader",
                        options: {
                            workerParallelJobs: 2
                        }
                    },
                    "style-loader",
                    "css-loader",
                    "sass-loader"]
            }, {
                test: /\.(ttf|eot|svg|woff(2)?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader",
                options: {
                    limit: 8192
                }
            }, {
                test: /\.png$/,
                loader: "file-loader",
                options: {
                    mimetype: "image/png",
                    limit: 16384
                }
            }, {
                test: /\.html?$/,
                exclude: /node_modules/,
                loader: "html-loader"
            }
        ],
    }
};
<commit_msg>Further decomposition<commit_after>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
 * See README.md for more information
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific
 *
 */

const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const git = require("git-rev-sync");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const webpack = require("webpack");

const basePath = path.resolve(__dirname);

module.exports = {
    entry: {
        app: "./client/main.js"
    },
    output: {
        path: path.join(basePath, "/dist"),
        filename: "[name].[contenthash].js"
    },
    resolve: {
        symlinks: false,
        alias: {
            svelte: path.resolve("node_modules", "svelte")
        },
        extensions: [".svelte", ".js"],
        mainFields: ["svelte", "browser", "module", "main"]
    },
    optimization: {
        runtimeChunk: "single",
        splitChunks: {
            chunks: "all",
            minSize: 30000,
            maxSize: 600000,
            minChunks: 1,
            maxAsyncRequests: 8,
            maxInitialRequests: 4,
            automaticNameDelimiter: "~",
            name: true,
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    priority: -10
                },
                default: {
                    minChunks: 2,
                    priority: -20,
                    reuseExistingChunk: true
                }
            }
        }
    },
    watchOptions: {
        ignored: /node_modules/,
        aggregateTimeout: 800
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            title: "Waltz",
            filename: "index.html",
            template: "index.ejs",
            favicon: path.join(basePath, "images", "favicon.ico"),
            hash: true,
        }),
        new webpack.DefinePlugin({
            "__ENV__": JSON.stringify(process.env.BUILD_ENV || "dev"),
            "__REVISION__": JSON.stringify(git.long()),
        })
    ],
    module: {
        rules: [
            {
                test: /\.svelte$/,
                use: [
                    { loader: "babel-loader" },
                    {
                        loader: "svelte-loader",
                        options: {
                            preprocess: require('svelte-preprocess')({
                                postcss: true
                            }),
                            emitCss: true,
                            hotReload: true
                        }
                    }
                ],

            }, {
                test: /(\.m?jsx?$)/,
                use: ["babel-loader"]
            }, {
                test: /\.s?css$/,
                use: [
                    {
                        loader: "thread-loader",
                        options: {
                            workerParallelJobs: 2
                        }
                    },
                    "style-loader",
                    "css-loader",
                    "sass-loader"]
            }, {
                test: /\.(ttf|eot|svg|woff(2)?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader",
                options: {
                    limit: 8192
                }
            }, {
                test: /\.png$/,
                loader: "file-loader",
                options: {
                    mimetype: "image/png",
                    limit: 16384
                }
            }, {
                test: /\.html?$/,
                exclude: /node_modules/,
                loader: "html-loader"
            }
        ],
    }
};
<|endoftext|>


<commit_before>import { MODAL, TOOLBAR } from 'utils/Issuers';
import { UPDATE, CREATE, REF } from 'constants/Actions';
import joinKeys from 'utils/joinKeys';
import routerStore from 'stores/routerStore';

export default class Actions {
	get props() {
		return this._reactInstance.props;
	}

	get store() {
		return this.props.store;
	}

	get issuers() {
		return this.props.issuers;
	}

	get pageContext() {
		return this.props.pageContext;
	}

	get selectedKeys() {
		const { store, tableRowKey } = this.props;
		return tableRowKey ? [tableRowKey] : store.selectedKeys;
	}

	get selectedKeysString() {
		return joinKeys(this.selectedKeys);
	}

	get selectedKeysHead() {
		return this.selectedKeys.length ? this.selectedKeys[0] : undefined;
	}

	constructor(reactInstance) {
		this._reactInstance = reactInstance;
	}

	getSelectedKeysString = () => this.selectedKeysString;

	getData = () => this.store.getData(this.selectedKeysHead);

	dispatch = (name, modalParams) => {
		const { pageContext, modalStore, issuers, enforceModal } = this.props;
		const keys = this.selectedKeysString;
		if (
			!enforceModal &&
			!modalParams &&
			pageContext.useDetail &&
			(name === CREATE || name === UPDATE) &&
			issuers.has(TOOLBAR) &&
			!issuers.has(MODAL)
		) {
			const path = name === UPDATE ? `/update/${keys}` : '/create';
			routerStore.location.pathname += path;
		} else {
			modalStore.open({
				keys,
				...modalParams,
				name,
			});
			return modalStore.close.bind(modalStore);
		}
	};

	create = (modalParams) => {
		return this.dispatch(CREATE, modalParams);
	};

	update = (modalParams) => {
		return this.dispatch(UPDATE, modalParams);
	};

	ref = (params = {}) => {
		const { modal = {}, ...otherParams } = params;
		return this.dispatch(UPDATE, {
			fetch: 'fetch',
			save: 'request',
			...otherParams,
			modal: {
				width: 880,
				...modal,
			},
		});
	};

	open = (name, params = {}, options) => {
		const { pageContext, modalStore, issuers } = this.props;
		const keys = this.selectedKeysString;

		if (
			pageContext.useDetail &&
			(name === CREATE || name === UPDATE) &&
			issuers.has(TOOLBAR) &&
			!issuers.has(MODAL)
		) {
			const path =
				params.path || (name === UPDATE ? `/update/${keys}` : '/create');
			routerStore.location.pathname += path;
		} else {
			modalStore.open(
				{
					keys,
					...params,
					name,
				},
				options
			);
			return modalStore.close.bind(modalStore);
		}
	};

	openCreaterModal = (params = {}, options) => {
		params.keys = params.keys || '';
		return this.open(CREATE, params, options);
	};

	openUpdaterModal = (params = {}, options) => {
		const { select, ...config } = params;
		if (select && select.length) {
			config.select = select.join(',');
		}
		return this.open(UPDATE, config, options);
	};

	openRefModal = (params = {}, options) => {
		const {
			noQuery,
			fetch = 'fetch',
			save = 'request',
			width = 880,
			...other
		} = params;
		const config = { fetch, save, width, ...other };
		if (noQuery) config.noQuery = '✓';
		return this.open(REF, config, options);
	};
}
<commit_msg>deprecate Actions.open()<commit_after>import { MODAL, TOOLBAR } from 'utils/Issuers';
import { UPDATE, CREATE, REF } from 'constants/Actions';
import joinKeys from 'utils/joinKeys';
import deprecated from 'utils/deprecated';
import routerStore from 'stores/routerStore';

export default class Actions {
	get props() {
		return this._reactInstance.props;
	}

	get store() {
		return this.props.store;
	}

	get issuers() {
		return this.props.issuers;
	}

	get pageContext() {
		return this.props.pageContext;
	}

	get selectedKeys() {
		const { store, tableRowKey } = this.props;
		return tableRowKey ? [tableRowKey] : store.selectedKeys;
	}

	get selectedKeysString() {
		return joinKeys(this.selectedKeys);
	}

	get selectedKeysHead() {
		return this.selectedKeys.length ? this.selectedKeys[0] : undefined;
	}

	constructor(reactInstance) {
		this._reactInstance = reactInstance;
	}

	getSelectedKeysString = () => this.selectedKeysString;

	getData = () => this.store.getData(this.selectedKeysHead);

	dispatch = (name, modalParams) => {
		const { pageContext, modalStore, issuers, enforceModal } = this.props;
		const keys = this.selectedKeysString;
		if (
			!enforceModal &&
			!modalParams &&
			pageContext.useDetail &&
			(name === CREATE || name === UPDATE) &&
			issuers.has(TOOLBAR) &&
			!issuers.has(MODAL)
		) {
			const path = name === UPDATE ? `/update/${keys}` : '/create';
			routerStore.location.pathname += path;
		} else {
			modalStore.open({
				keys,
				...modalParams,
				name,
			});
			return modalStore.close.bind(modalStore);
		}
	};

	create = (modalParams) => {
		return this.dispatch(CREATE, modalParams);
	};

	update = (modalParams) => {
		return this.dispatch(UPDATE, modalParams);
	};

	ref = (modalParams) => {
		return this.dispatch(UPDATE, {
			fetch: 'fetch',
			save: 'request',
			width: 880,
			...modalParams,
		});
	};

	open = deprecated((name, params = {}) => {
		const { modalStore } = this.props;
		const keys = this.selectedKeysString;
		modalStore.open({
			keys,
			...params,
			name,
		});
		return modalStore.close.bind(modalStore);
	}, '`open()` is deprecated, please use dispatch() instead');

	openCreaterModal = deprecated((params = {}) => {
		return this.open(CREATE, params);
	}, '`openCreaterModal()` is deprecated, please use create() instead');

	openUpdaterModal = deprecated((params = {}) => {
		const { select, ...otherParams } = params;
		if (select && select.length) {
			otherParams.select = select.join(',');
		}
		return this.open(UPDATE, otherParams);
	}, '`openUpdaterModal()` is deprecated, please use update() instead');

	openRefModal = deprecated((params = {}) => {
		const { fetch = 'fetch', save = 'request', width = 880, ...other } = params;
		const config = { fetch, save, width, ...other };
		return this.open(REF, config);
	}, '`openRefModal()` is deprecated, please use ref() instead');
}
<|endoftext|>


<commit_before>//= require ./array

var
    Iterable;

(function($) {
    "use strict";

    try {
        $.defineProperties($, {

            constructorIs: {
                value: function(constructor) {
                    if (typeof constructor == "string") {
                        constructor = window[constructor];
                    }

                    return this.classConstructor() == constructor;
                }
            },

            normalizedAsLowerCase: {
                value: function(object) {
                    var
                        iterator,
                        attributes = Object.attributes(object),
                        clone = {};

                    Object.assign(clone, object);
                    object.length = attributes.length;
                    iterator = Iterable.Proxy.new(clone);

                    iterator.each(function(v, k) {
                        if (typeof v == "string") {
                            clone[k] = v.toLowerCase();
                        }
                    });

                    return clone;
                }
            },

            firstFromASlice: {
                value: function(object, slice, startingIndex, caseSensitive) {
                    var
                        iterator,
                        key,
                        regexp,
                        attributes = Object.attributes(object);

                    if (!startingIndex || typeof startingIndex != "number") {
                        if (typeof startingIndex == "boolean") {
                            caseSensitive = startingIndex;
                        } else if (!caseSensitive || typeof caseSensitive !=
                                   "boolean") {
                            caseSensitive = false;
                        }

                        startingIndex = 0;
                    }

                    slice = slice.trim();

                    if (!caseSensitive) {
                        regexp = new RegExp(slice, "i");
                    } else {
                        regexp = new RegExp(slice);
                    }

                    iterator = Iterable.Proxy.new(attributes);
                    iterator.each(function(k, i) {
                        if (!isNaN(i)) {
                            if (typeof object[k] == "string" && i
                                >= startingIndex) {
                                if (object[k].search(regexp) != -1) {
                                    key = k;
                                    this.finalize();
                                }
                            }
                        } else if (typeof object[k] == "string") {
                            if (object[k].search(regexp) != -1) {
                                key = k;
                                this.finalize();
                            }
                        }
                    });

                    if (key) {
                        return key;
                    }

                    return undefined;
                }
            },

            implementsMethod: {
                value: function(object, propertyName) {
                    if (object) {
                        return $.keys(object).includes(propertyName) &&
                        typeof object[propertyName] == "function";
                    }

                    return false;
                }
            },

            // o método kindOf talvez não valha a pena ser implementado, visto que o instanceof trabalha de forma parecida para saber se um objeto (instância) é um tipo de uma dada classe ou de sua superclasse.
            // para implementar o extends? basta verificar se o constructor é igual a classe passada com o parâmetro, caso não, testar recursivamente com as superclasses. Mas como saber quem é a superclasse e as subclasses?
            className: {
                value: function(object) {
                    // /[^ ]+(?=\])/g

                    if (typeof object == "object" &&
                        $.implementsMethod(object, "toString")) {
                        return /[a-zA-Z_]+[^\]]+/g.exec(object.toString())[0]
                        .split(" ")[1];
                    }

                    return /[A-Z_]+[^\]]+/g.exec($.prototype.toString
                                                 .call(object))[0]
                                                 .replace(/ /g, "");
                }
            },

            // The keys of associative arrays in JS only can be of integer or string kind. The associations that keys are of Integer kind, the items is sorted according the keys (works as HashSet of the Java); the associations that keys are String kind, works as LinkedHashMap, it’s implements a associative array and maintains the order of entrance on iterate.
            // TreeMap implements a structure based red-black tree (binary search).
            asCountableLiteralObject: {
                value: function(collection) {
                    return Iterable.parse(collection);
                }
            },

            includeKeys: {
                value: function(object, keysToFind) {
                    var
                        keys = $.keys(object),
                        argsAsArray = Array.from(arguments),
                        keysToFind = argsAsArray.slice(1, argsAsArray.length)
                            .uniq(),
                        count = 0;

                    keysToFind.forEach(function(argKey) {
                        if (keys.includes(argKey)) {
                            count += 1;
                        }
                    });

                    return count == keysToFind.length;
                }
            },

            indexOf: {
                value: function(object, value) {
                    var
                        key,
                        iterator,
                        properties = $.keys(object);

                    iterator = Iterable.Proxy.new(properties);
                    iterator.each(function(property) {
                        if ($.areEquivalents(object[property], value)) {
                            key = property;
                            this.finalize();
                        }
                    });

                    if (key) {
                        return key;
                    }

                    return undefined;
                }
            },

            count: {
                value: function(object, item) {
                    var
                        count;

                    if (item) {
                        count = $.values(object).count(item);
                    } else {
                        count = $.keys(object).length;
                    }

                    return count;
                }
            },

            some: {
                value: function(object) {
                    return $.count(object) > 0;
                }
            },

            delete: {
                value: function(object, index) {
                    if (delete object[index]) {
                        if (object.hasOwnProperty("length")) {
                            object.length -= 1;
                        }

                        return true;
                    }

                    return false;
                }
            },

            reverse: {
                value: function(object) {
                    var
                        newObject = {};

                    $.keys(object).reverse().forEach(function(k) {
                        newObject[k] = object[k];
                    });

                    return newObject;
                }
            },

            attributes: {
                value: function(getNotEnumerable, object) {
                    if (getNotEnumerable instanceof $) {
                        object = getNotEnumerable;
                        getNotEnumerable = false;
                    } else if (typeof getNotEnumerable != "boolean") {
                        getNotEnumerable = false;
                    }

                    var
                        attributes = [],
                        properties = $.keys(object);

                    if (getNotEnumerable) {
                        properties = $.keys(object);
                    }

                    properties.forEach(function(property) {
                        if (typeof object[property] != "function") {
                            attributes.push(property);
                        }
                    });

                    return attributes;
                }
            },

            methods: {
                value: function(object) {
                    var
                        properties = $.keys(object);

                    return properties.differences(this.attributes(true,
                                                                  object));
                }
            },

            areEquivalents: {
                value: function(object, comparator) {
                    var
                        attributesCount,
                        objectAttributes,
                        comparatorAttributes,
                        objectMethods,
                        comparatorMethods,
                        objectAttributeValue,
                        comparatorAttributeValue,
                        iterator,
                        count = 0,
                        primitiveTypes =
                            /(number|string|boolean|null|undefined|symbol)/;

                    if (object == comparator) {
                        return true;
                    } else if ($.getPrototypeOf(object) ==
                               $.getPrototypeOf(comparator)) {
                        if (object instanceof $ &&
                            !(object instanceof Function)) {
                            if (object instanceof window.Node) {
                                if (object.isEqualNode(comparator)) {
                                    return true;
                                }
                            } else {
                                objectAttributes = this.attributes(object);
                                comparatorAttributes = this
                                    .attributes(comparator);
                                objectMethods = this.methods(object);
                                comparatorMethods = this.methods(comparator);

                                // if doesn't have attributes
                                if (!objectAttributes.length) {
                                    if (objectMethods.length) {
                                        if (objectMethods.length ==
                                            comparatorMethods.length &&
                                            this.areEquivalents(objectMethods,
                                                comparatorMethods)) {
                                            return true;
                                        }
                                    } else if (objectMethods.length ==
                                               comparatorMethods.length) {
                                        return true;
                                    }
                                }

                                if (objectAttributes.length ==
                                    comparatorAttributes.length) {

                                    iterator = Iterable.Proxy
                                        .new(objectAttributes);

                                    iterator.each(function(attribute) {
                                        objectAttributeValue =
                                            object[attribute];
                                        comparatorAttributeValue =
                                            comparator[attribute];

                                        if (typeof objectAttributeValue ==
                                            "boolean" &&
                                            typeof comparatorAttributeValue ==
                                            "boolean") {
                                            objectAttributeValue =
                                                objectAttributeValue.toString();
                                            comparatorAttributeValue =
                                              comparatorAttributeValue
                                                .toString();
                                        }

                                        if (objectAttributeValue &&
                                            comparatorAttributeValue) {
                                            if ($.getPrototypeOf(
                                                objectAttributeValue) ==
                                                $.getPrototypeOf(
                                                    comparatorAttributeValue)) {
                                                if (objectAttributeValue instanceof
                                                    $) {

                                                    // recursivity
                                                    if ($.areEquivalents(
                                                        objectAttributeValue,
                                                        comparatorAttributeValue)) {
                                                        count += 1;
                                                    }
                                                } else
                                                    if (objectAttributeValue ==
                                                    comparatorAttributeValue) {
                                                    count += 1;
                                                }
                                            }

                                        } else if (objectAttributeValue ==
                                                   comparatorAttributeValue) {
                                            return true;
                                        }
                                    });

                                    attributesCount = objectAttributes.length;

                                    return count && count == attributesCount;
                                }
                            }

                        } else {
                            if (primitiveTypes.test(typeof object)) {
                                return object == comparator;
                            }
                        }
                    }

                    return false;
                }
            }

        });
    } catch(e) {}

})(Object);
<commit_msg>remove comment<commit_after>//= require ./array

var
    Iterable;

(function($) {
    "use strict";

    try {
        $.defineProperties($, {

            constructorIs: {
                value: function(constructor) {
                    if (typeof constructor == "string") {
                        constructor = window[constructor];
                    }

                    return this.classConstructor() == constructor;
                }
            },

            normalizedAsLowerCase: {
                value: function(object) {
                    var
                        iterator,
                        attributes = Object.attributes(object),
                        clone = {};

                    Object.assign(clone, object);
                    object.length = attributes.length;
                    iterator = Iterable.Proxy.new(clone);

                    iterator.each(function(v, k) {
                        if (typeof v == "string") {
                            clone[k] = v.toLowerCase();
                        }
                    });

                    return clone;
                }
            },

            firstFromASlice: {
                value: function(object, slice, startingIndex, caseSensitive) {
                    var
                        iterator,
                        key,
                        regexp,
                        attributes = Object.attributes(object);

                    if (!startingIndex || typeof startingIndex != "number") {
                        if (typeof startingIndex == "boolean") {
                            caseSensitive = startingIndex;
                        } else if (!caseSensitive || typeof caseSensitive !=
                                   "boolean") {
                            caseSensitive = false;
                        }

                        startingIndex = 0;
                    }

                    slice = slice.trim();

                    if (!caseSensitive) {
                        regexp = new RegExp(slice, "i");
                    } else {
                        regexp = new RegExp(slice);
                    }

                    iterator = Iterable.Proxy.new(attributes);
                    iterator.each(function(k, i) {
                        if (!isNaN(i)) {
                            if (typeof object[k] == "string" && i
                                >= startingIndex) {
                                if (object[k].search(regexp) != -1) {
                                    key = k;
                                    this.finalize();
                                }
                            }
                        } else if (typeof object[k] == "string") {
                            if (object[k].search(regexp) != -1) {
                                key = k;
                                this.finalize();
                            }
                        }
                    });

                    if (key) {
                        return key;
                    }

                    return undefined;
                }
            },

            implementsMethod: {
                value: function(object, propertyName) {
                    if (object) {
                        return $.keys(object).includes(propertyName) &&
                        typeof object[propertyName] == "function";
                    }

                    return false;
                }
            },

            className: {
                value: function(object) {
                    // /[^ ]+(?=\])/g

                    if (typeof object == "object" &&
                        $.implementsMethod(object, "toString")) {
                        return /[a-zA-Z_]+[^\]]+/g.exec(object.toString())[0]
                        .split(" ")[1];
                    }

                    return /[A-Z_]+[^\]]+/g.exec($.prototype.toString
                                                 .call(object))[0]
                                                 .replace(/ /g, "");
                }
            },

            // The keys of associative arrays in JS only can be of integer or string kind. The associations that keys are of Integer kind, the items is sorted according the keys (works as HashSet of the Java); the associations that keys are String kind, works as LinkedHashMap, it’s implements a associative array and maintains the order of entrance on iterate.
            // TreeMap implements a structure based red-black tree (binary search).
            asCountableLiteralObject: {
                value: function(collection) {
                    return Iterable.parse(collection);
                }
            },

            includeKeys: {
                value: function(object, keysToFind) {
                    var
                        keys = $.keys(object),
                        argsAsArray = Array.from(arguments),
                        keysToFind = argsAsArray.slice(1, argsAsArray.length)
                            .uniq(),
                        count = 0;

                    keysToFind.forEach(function(argKey) {
                        if (keys.includes(argKey)) {
                            count += 1;
                        }
                    });

                    return count == keysToFind.length;
                }
            },

            indexOf: {
                value: function(object, value) {
                    var
                        key,
                        iterator,
                        properties = $.keys(object);

                    iterator = Iterable.Proxy.new(properties);
                    iterator.each(function(property) {
                        if ($.areEquivalents(object[property], value)) {
                            key = property;
                            this.finalize();
                        }
                    });

                    if (key) {
                        return key;
                    }

                    return undefined;
                }
            },

            count: {
                value: function(object, item) {
                    var
                        count;

                    if (item) {
                        count = $.values(object).count(item);
                    } else {
                        count = $.keys(object).length;
                    }

                    return count;
                }
            },

            some: {
                value: function(object) {
                    return $.count(object) > 0;
                }
            },

            delete: {
                value: function(object, index) {
                    if (delete object[index]) {
                        if (object.hasOwnProperty("length")) {
                            object.length -= 1;
                        }

                        return true;
                    }

                    return false;
                }
            },

            reverse: {
                value: function(object) {
                    var
                        newObject = {};

                    $.keys(object).reverse().forEach(function(k) {
                        newObject[k] = object[k];
                    });

                    return newObject;
                }
            },

            attributes: {
                value: function(getNotEnumerable, object) {
                    if (getNotEnumerable instanceof $) {
                        object = getNotEnumerable;
                        getNotEnumerable = false;
                    } else if (typeof getNotEnumerable != "boolean") {
                        getNotEnumerable = false;
                    }

                    var
                        attributes = [],
                        properties = $.keys(object);

                    if (getNotEnumerable) {
                        properties = $.keys(object);
                    }

                    properties.forEach(function(property) {
                        if (typeof object[property] != "function") {
                            attributes.push(property);
                        }
                    });

                    return attributes;
                }
            },

            methods: {
                value: function(object) {
                    var
                        properties = $.keys(object);

                    return properties.differences(this.attributes(true,
                                                                  object));
                }
            },

            areEquivalents: {
                value: function(object, comparator) {
                    var
                        attributesCount,
                        objectAttributes,
                        comparatorAttributes,
                        objectMethods,
                        comparatorMethods,
                        objectAttributeValue,
                        comparatorAttributeValue,
                        iterator,
                        count = 0,
                        primitiveTypes =
                            /(number|string|boolean|null|undefined|symbol)/;

                    if (object == comparator) {
                        return true;
                    } else if ($.getPrototypeOf(object) ==
                               $.getPrototypeOf(comparator)) {
                        if (object instanceof $ &&
                            !(object instanceof Function)) {
                            if (object instanceof window.Node) {
                                if (object.isEqualNode(comparator)) {
                                    return true;
                                }
                            } else {
                                objectAttributes = this.attributes(object);
                                comparatorAttributes = this
                                    .attributes(comparator);
                                objectMethods = this.methods(object);
                                comparatorMethods = this.methods(comparator);

                                // if doesn't have attributes
                                if (!objectAttributes.length) {
                                    if (objectMethods.length) {
                                        if (objectMethods.length ==
                                            comparatorMethods.length &&
                                            this.areEquivalents(objectMethods,
                                                comparatorMethods)) {
                                            return true;
                                        }
                                    } else if (objectMethods.length ==
                                               comparatorMethods.length) {
                                        return true;
                                    }
                                }

                                if (objectAttributes.length ==
                                    comparatorAttributes.length) {

                                    iterator = Iterable.Proxy
                                        .new(objectAttributes);

                                    iterator.each(function(attribute) {
                                        objectAttributeValue =
                                            object[attribute];
                                        comparatorAttributeValue =
                                            comparator[attribute];

                                        if (typeof objectAttributeValue ==
                                            "boolean" &&
                                            typeof comparatorAttributeValue ==
                                            "boolean") {
                                            objectAttributeValue =
                                                objectAttributeValue.toString();
                                            comparatorAttributeValue =
                                              comparatorAttributeValue
                                                .toString();
                                        }

                                        if (objectAttributeValue &&
                                            comparatorAttributeValue) {
                                            if ($.getPrototypeOf(
                                                objectAttributeValue) ==
                                                $.getPrototypeOf(
                                                    comparatorAttributeValue)) {
                                                if (objectAttributeValue instanceof
                                                    $) {

                                                    // recursivity
                                                    if ($.areEquivalents(
                                                        objectAttributeValue,
                                                        comparatorAttributeValue)) {
                                                        count += 1;
                                                    }
                                                } else
                                                    if (objectAttributeValue ==
                                                    comparatorAttributeValue) {
                                                    count += 1;
                                                }
                                            }

                                        } else if (objectAttributeValue ==
                                                   comparatorAttributeValue) {
                                            return true;
                                        }
                                    });

                                    attributesCount = objectAttributes.length;

                                    return count && count == attributesCount;
                                }
                            }

                        } else {
                            if (primitiveTypes.test(typeof object)) {
                                return object == comparator;
                            }
                        }
                    }

                    return false;
                }
            }

        });
    } catch(e) {}

})(Object);
<|endoftext|>