<commit_before>'use strict';

var pagesdb = require('../../../db/pagesdb')
var checkAndCoerceDateFilterParams = require('../../../utils/checkAndCoerceDateFilterParams')
var processSearchTerms = require('./processSearchTerms')

function search(req, res, next){

  var processedSearchTerms = processSearchTerms(req.params.searchTerms)
  var domainToSearchFor = processedSearchTerms.domainToSearchFor
  var searchTerms = processedSearchTerms.processedSearchTerms
  var dateFilter = checkAndCoerceDateFilterParams(req.body)
  var knexSQL = null

  if(!searchTerms.length){
    /****
     * If user just wants to list all saved pages by a domain (with no text search)
     */
    if(domainToSearchFor){
      knexSQL = pagesdb.db('pages').where({pageDomain: domainToSearchFor})
      if(dateFilter){
        /****
         * knex will automatically convert additional WHERE's to AND WHERE
         */
        knexSQL = knexSQL
          .where('dateCreated', '>=', dateFilter.dateFilterStartDate)
          .where('dateCreated', '<=', dateFilter.dateFilterEndDate)
      }
      knexSQL = knexSQL.orderBy('dateCreated', 'desc')
    }
    else{
      /****
       * If there are no search terms and they are not searching for domain
       * results, then send back zero results as an empty array.
       */
      res.json([])
    }
  }
  else{
    knexSQL = pagesdb
      .db
      .select(
        `rank`,
        `pageUrl`,
        `dateCreated`,
        `pageDomain`,
        `pageTitle`,
        `pageText`,
        `pageDescription`,
        `archiveLink`,
        `safeBrowsing`,
        pagesdb.db.raw(
          `snippet(fts, -1, '',
          '', '...', 64) as snippet`
        )
      )
      .from('fts')

    if(domainToSearchFor){
      knexSQL = knexSQL.where({pageDomain: domainToSearchFor})
    }
    if(dateFilter){
      knexSQL = knexSQL
        .where('dateCreated', '>=', dateFilter.dateFilterStartDate)
        .where('dateCreated', '<=', dateFilter.dateFilterEndDate)
    }
    /****
     * https://sqlite.org/fts5.html#section_5_1_1
     * bm25(fts, 4.0, 1.0, 2.0) - Give pageTitle a boost of 4,
     * and pageDescription a boost of 2.
     * Note: the SQL operators in the 'searchTerm OR NEAR()` are case-sensitive
     * and must be in uppercase!
     * The final SQL statement should be something like this:
     * select "rank", "pageUrl", "dateCreated", "pageDomain", "pageTitle", "pageText", "pageDescription", "archiveLink", "safeBrowsing", snippet(fts, -1, '', '', '...', 64) as snippet from "fts" where fts match 'foo bar' order by bm25(fts, 4.0, 1.0, 2.0)
     */
    knexSQL = knexSQL
      //.whereRaw(`fts match ? order by bm25(fts, 4.0, 1.0, 2.0)`, `"${searchTerms}" OR NEAR(${searchTerms})`)
      .whereRaw(`fts match ? order by bm25(fts, 4.0, 1.0, 2.0)`, `${searchTerms}`)
  }

  knexSQL
    .then( rows => {
      res.json(rows)
    })
    .catch( err => {
      console.error(err)
      res
        .status(500)
        .json({
          searchError: `There was an issue with the search, check your search text is correct.`
        })
    })

}

module.exports = search<commit_msg>Comment update<commit_after>'use strict';

var pagesdb = require('../../../db/pagesdb')
var checkAndCoerceDateFilterParams = require('../../../utils/checkAndCoerceDateFilterParams')
var processSearchTerms = require('./processSearchTerms')

function search(req, res, next){

  var processedSearchTerms = processSearchTerms(req.params.searchTerms)
  var domainToSearchFor = processedSearchTerms.domainToSearchFor
  var searchTerms = processedSearchTerms.processedSearchTerms
  var dateFilter = checkAndCoerceDateFilterParams(req.body)
  var knexSQL = null

  if(!searchTerms.length){
    /****
     * If user just wants to list all saved pages by a domain (with no text search)
     */
    if(domainToSearchFor){
      knexSQL = pagesdb.db('pages').where({pageDomain: domainToSearchFor})
      if(dateFilter){
        /****
         * knex will automatically convert additional WHERE's to AND WHERE
         */
        knexSQL = knexSQL
          .where('dateCreated', '>=', dateFilter.dateFilterStartDate)
          .where('dateCreated', '<=', dateFilter.dateFilterEndDate)
      }
      knexSQL = knexSQL.orderBy('dateCreated', 'desc')
    }
    else{
      /****
       * If there are no search terms and they are not searching for domain
       * results, then send back zero results as an empty array.
       */
      res.json([])
    }
  }
  else{
    knexSQL = pagesdb
      .db
      .select(
        `rank`,
        `pageUrl`,
        `dateCreated`,
        `pageDomain`,
        `pageTitle`,
        `pageText`,
        `pageDescription`,
        `archiveLink`,
        `safeBrowsing`,
        pagesdb.db.raw(
          `snippet(fts, -1, '',
          '', '...', 64) as snippet`
        )
      )
      .from('fts')

    if(domainToSearchFor){
      knexSQL = knexSQL.where({pageDomain: domainToSearchFor})
    }
    if(dateFilter){
      knexSQL = knexSQL
        .where('dateCreated', '>=', dateFilter.dateFilterStartDate)
        .where('dateCreated', '<=', dateFilter.dateFilterEndDate)
    }
    /****
     * https://sqlite.org/fts5.html#section_5_1_1
     * bm25(fts, 4.0, 1.0, 2.0) - Give pageTitle a boost of 4,
     * and pageDescription a boost of 2.
     * Note: the SQL operators in the 'searchTerm OR NEAR()` are case-sensitive
     * and must be in uppercase!
     * The final SQL statement (when searching with search terms) should be
     * something like this: http://bit.ly/1TxvdZa
     */
    knexSQL = knexSQL
      //.whereRaw(`fts match ? order by bm25(fts, 4.0, 1.0, 2.0)`, `"${searchTerms}" OR NEAR(${searchTerms})`)
      .whereRaw(`fts match ? order by bm25(fts, 4.0, 1.0, 2.0)`, `${searchTerms}`)
  }

  knexSQL
    .then( rows => {
      res.json(rows)
    })
    .catch( err => {
      console.error(err)
      res
        .status(500)
        .json({
          searchError: `There was an issue with the search, check your search text is correct.`
        })
    })

}

module.exports = search<|endoftext|>


<commit_before>var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/HomeAutomation';

MongoClient.connect(url, function(err, db){
    if(err) {
        console.error("MongoDB_Core (startup): An error occurred while connecting to the database.");
        console.error(err);
    }else{
        console.log("Conntected to MondyDB instance.");
        db.close();
    }
});

var insertFacts = function(facts){
    return new Promise(function(resolve, reject){
        MongoClient.connect(url, function(err, db){
            if(err) {
                reject({type: "error", data: err, msg:"MongoDB_Core insertFacts: An error occurred while connecting to the database."});
            } else {
                var collection = db.collection('facts');
                collection.insertMany(facts, function(err, result){
                    if(err){
                        reject({type: "error", data: err, msg: "MongoDB_Core insertFacts: An error occurred while inserting into collection."});
                    } else {
                        resolve(result);
                    }
                });
                db.close();
            }
        });
    });
};

var getFacts = function(params){
    return new Promise(function(resolve, reject) {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                reject({type: "error", data: err, msg:"MongoDB_Core getFacts: An error occurred while connecting to the database."});
            } else {
                var collection = db.collection('facts');
                collection.find(params).toArray(function (err, data) {
                    if (err) {
                        reject({type: "error", data: err, msg: "MongoDB_Core getFacts: An error occurred while inserting into collection."});
                    } else {
                        resolve(data);
                    }
                });
                db.close();
            }
        });
    });
};

module.exports = {
    getFacts: getFacts,
    insertFacts: insertFacts
};

<commit_msg>Added a new collection definition to mongodb and renamed the "facts" one to something more descriptive.<commit_after>var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/HomeAutomation';

MongoClient.connect(url, function(err, db){
    if(err) {
        console.error("MongoDB_Core (startup): An error occurred while connecting to the database.");
        console.error(err);
    }else{
        console.log("Conntected to MongoDB instance.");
        db.close();
    }
});

var insertStatus = function(facts){
    return new Promise(function(resolve, reject){
        MongoClient.connect(url, function(err, db){
            if(err) {
                reject({type: "error", data: err, msg:"MongoDB_Core insertFacts: An error occurred while connecting to the database."});
            } else {
                var collection = db.collection('status');
                collection.insertMany(facts, function(err, result){
                    if(err){
                        reject({type: "error", data: err, msg: "MongoDB_Core insertFacts: An error occurred while inserting into collection."});
                    } else {
                        resolve(result);
                    }
                });
                db.close();
            }
        });
    });
};

var getStatus = function(params){
    return new Promise(function(resolve, reject) {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                reject({type: "error", data: err, msg:"MongoDB_Core getFacts: An error occurred while connecting to the database."});
            } else {
                var collection = db.collection('status');
                collection.find(params).toArray(function (err, data) {
                    if (err) {
                        reject({type: "error", data: err, msg: "MongoDB_Core getFacts: An error occurred while inserting into collection."});
                    } else {
                        resolve(data);
                    }
                });
                db.close();
            }
        });
    });
};

var insertEvent = function(facts){
    return new Promise(function(resolve, reject){
        MongoClient.connect(url, function(err, db){
            if(err) {
                reject({type: "error", data: err, msg:"MongoDB_Core insertFacts: An error occurred while connecting to the database."});
            } else {
                var collection = db.collection('events');
                collection.insertMany(facts, function(err, result){
                    if(err){
                        reject({type: "error", data: err, msg: "MongoDB_Core insertFacts: An error occurred while inserting into collection."});
                    } else {
                        resolve(result);
                    }
                });
                db.close();
            }
        });
    });
};

var getEvent = function(params){
    return new Promise(function(resolve, reject) {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                reject({type: "error", data: err, msg:"MongoDB_Core getFacts: An error occurred while connecting to the database."});
            } else {
                var collection = db.collection('events');
                collection.find(params).toArray(function (err, data) {
                    if (err) {
                        reject({type: "error", data: err, msg: "MongoDB_Core getFacts: An error occurred while inserting into collection."});
                    } else {
                        resolve(data);
                    }
                });
                db.close();
            }
        });
    });
};

module.exports = {
    insertStatus: insertStatus,
    getStatus: getStatus,
    insertEvent: insertEvent,
    getEvent: getEvent
};

<|endoftext|>


<commit_before>import { values } from 'lodash'

export function connect () {
  this.connectPorts()
}

export function connectPorts () {
  this.checkProject()
  this.checkWeb()
  const { project: { config, dir } } = this
  this.availablePortsBySubDomain = {}
  values(config.typesByName)
  .forEach(type => {
    if (type.subDomain) {
      this.availablePortsBySubDomain[type.subDomain] = this.getAvailablePorts(type.subDomain)
    }
  })
  if (config.backend && config.backend.serversByName) {
    Object.keys(config.backend.serversByName)
      .forEach((serverName, index) => {
        const server = config.backend.serversByName[serverName]
        Object.keys(config.typesByName).forEach(typeName => {
          let run = server.runsByTypeName[typeName]
          if (typeof run === 'undefined') {
            run = server.runsByTypeName[typeName] = {}
          }
          const subDomain = run.subDomain || config.typesByName[typeName].subDomain
          if (typeof subDomain === 'undefined') {
            return
          }
          if (this.availablePortsBySubDomain[subDomain]) {
            const availablePorts = this.availablePortsBySubDomain[subDomain]
            if (availablePorts.length < 1) {
              this.consoleWarn('Unfortunately, there are not enough available ports for your services... You need to get some as free before.')
              process.exit()
            }
            run.port = availablePorts[0].toString()
            this.availablePortsBySubDomain[subDomain] = availablePorts.slice(1)
          }
        })
      })
  }
  this.writeConfig(dir, config)
}
<commit_msg>rewrite busy port log warning<commit_after>import { values } from 'lodash'

export function connect () {
  this.connectPorts()
}

export function connectPorts () {
  this.checkProject()
  this.checkWeb()
  const { project: { config, dir } } = this
  this.availablePortsBySubDomain = {}
  values(config.typesByName)
  .forEach(type => {
    if (type.subDomain) {
      this.availablePortsBySubDomain[type.subDomain] = this.getAvailablePorts(type.subDomain)
    }
  })
  if (config.backend && config.backend.serversByName) {
    Object.keys(config.backend.serversByName)
      .forEach((serverName, index) => {
        const server = config.backend.serversByName[serverName]
        Object.keys(config.typesByName).forEach(typeName => {
          let run = server.runsByTypeName[typeName]
          if (typeof run === 'undefined') {
            run = server.runsByTypeName[typeName] = {}
          }
          const subDomain = run.subDomain || config.typesByName[typeName].subDomain
          if (typeof subDomain === 'undefined') {
            return
          }
          if (this.availablePortsBySubDomain[subDomain]) {
            const availablePorts = this.availablePortsBySubDomain[subDomain]
            if (availablePorts.length < 1) {
              this.consoleWarn('The required ports are unavailable. Free them up and retry.')
              process.exit()
            }
            run.port = availablePorts[0].toString()
            this.availablePortsBySubDomain[subDomain] = availablePorts.slice(1)
          }
        })
      })
  }
  this.writeConfig(dir, config)
}
<|endoftext|>


<commit_before>/*
 * GScroll v0.2.2
 *
 * https://github.com/gesanchez/GScroll
 *
 * Copyright (c) 2014 German Sanchez
 * Licensed under the MIT license.
 *
 */

;(function ( $, window, document, undefined ) {

    var pluginName = "GScroll",
        defaults = {
            width: "300px",
            height: "300px"
        };

    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options) ;
        this.init();
    }

    Plugin.prototype = {

        init: function() {
            var self = this;
            self.node = $(self.element);
            self.node.wrap('

')
            .wrap('

')
            .parent().after('

');

            self.container = self.node.closest('.GScroll');
            self.scrollable = self.node.parent();
            self.bar = self.node.parent().next();

            self.adjust.call(self);
            self.events.call(self);
        },

        /**
        *
        * Method for adjust bar height
        */
        adjust: function(callback) {
            var self = this;

            self.conHeight = self.container.height();
            self.scrollHeight = 0;

            if (self.node.is(':not(:visible)')){
                var clone = self.node.clone();
                clone.css({
                    width: self.options.width,
                    'visibility' : 'hidden'
                }).removeAttr('id').show();
                $('body').append(clone);
                self.scrollHeight = clone.outerHeight();
                clone.remove();

            }else{

                self.scrollHeight = self.scrollable.outerHeight();
            }
            self.barHeight = Math.max(20,(self.conHeight - Math.abs(self.conHeight - self.scrollHeight)));

            self.bar.css('height',self.barHeight + 'px');

            if (callback){
                callback.call(self);
            }
        },

        events: function(){
            var self = this;
            self.dragActive = false;
            self.y = 0;
            /**
            * Added event to container
            */

            self.container.on({
                'DOMMouseScroll mousewheel' : function(e){
                    var o = e.originalEvent,
                        delta = (o.detail < 0 || o.wheelDelta > 0) ? 1 : -1;

                    self.wheel.call(self, delta);

                    return false;
                },
                'mouseenter' : function(){
                    if (self.scrollHeight > self.conHeight){
                        self.bar.stop(true,true).fadeIn();
                    }
                },
                'mouseleave' : function(){
                    self.bar.stop(true,true).fadeOut();
                    self.dragActive = false;
                },
                'mousemove' : function(e){
                    e.preventDefault();
                    self.drag.call(self, e);
                },
                'mouseup' : function(e){
                    self.dragActive = false;
                },
                'focusin' : function(e){
                    self.onFocusIn.call(self, e);
                }
            });

            /**
            * Added event for scroll bar
            */
            self.bar.on({
                'mousedown' : function(e){
                    e.preventDefault();
                    self.dragActive = true;
                    self.y = e.pageY;
                },
                'mouseup' : function(e){
                    self.dragActive = false;
                },
                'mousemove' : function(e){
                    e.preventDefault();
                    self.drag.call(self, e);
                }
            });

            /**
            * Added event to element
            */
            self.node.on('adjust.' + pluginName, function(){
                self.adjust.call(self, function(){
                    self.onResize.call(self);
                });

            }).on('destroy.' + pluginName, function(){
                $.removeData(self.element, 'plugin_' + pluginName);
                self.node.off('.' + pluginName);
                self.node.unwrap().unwrap();
                self.bar.remove();
                self.element = null;
                self = null;
            });

            $(window).on('adjust.' + pluginName, function(){
                self.adjust.call(self, function(){
                    self.onResize.call(self);
                });
            });
        },
        /* Method for move bar and scrollable on mousewheel event */
        wheel: function(delta){
            var self = this,
                maxTop = self.conHeight - self.barHeight,
                maxScrollBottom = self.conHeight - self.scrollHeight,
                top = Math.abs(maxTop / (Math.abs(maxScrollBottom)) * 15);

            if (delta > 0){

                self.bar.css({
                    'top' : Math.max(0, parseFloat(self.bar.css('top')) - top)
                });

            }else if (delta < 0){

                self.bar.css({
                    'top' : Math.min(maxTop, parseFloat(self.bar.css('top')) + top)
                });

            }

            self.scrollable.css({
                'top' : Math.min(0 ,Math.max(maxScrollBottom, (maxScrollBottom / maxTop) * parseFloat(self.bar.css('top'))))
            });
        },
        /**
        * Method for move bar and scrollable when bar is dragged
        */
        drag : function(e){
            var self = this,
                maxTop = self.conHeight - self.barHeight,
                maxScrollBottom = self.conHeight - self.scrollHeight;

            if (self.dragActive === true){

                var top = parseFloat(self.bar.position().top) + e.pageY - self.y;
                top = Math.min(top, maxTop);

                self.bar.css({
                    top: Math.max(0 ,top) + 'px'
                });

                self.scrollable.css({
                    'top' : Math.min(0 ,Math.max(maxScrollBottom, (maxScrollBottom / maxTop) * top))
                });

                self.y = e.pageY;
            }
        },
        onResize : function(){
            var self = this,
                scrollable_top = Math.abs(parseFloat(self.scrollable.css('top'))),
                bar_top = parseFloat(self.bar.css('top')),
                maxScrollBottom = Math.abs(self.conHeight - self.scrollHeight),
                maxTop = self.conHeight - self.barHeight,
                top = (maxScrollBottom / maxTop) * bar_top;

            if (self.scrollHeight < self.conHeight){
                self.bar.hide();
            }

            if (scrollable_top > maxScrollBottom){
                self.scrollable.css({
                    'top' : -maxScrollBottom
                });
            }

            var div = top / bar_top,
                newTop = (top - scrollable_top) / div;

            self.bar.css({
                'top': Math.min(maxTop, Math.max(0, bar_top - newTop))
            });
        },
        onFocusIn : function(e){
            var self = this,
                target = $(e.target),
                target_top = target.offset().top,
                maxTop = self.conHeight - self.barHeight,
                maxScrollBottom = Math.abs(self.conHeight - self.scrollHeight),
                topScrollable = maxScrollBottom - ((target_top + target.outerHeight(true) + 1) / maxTop);

            self.bar.css({
                'top': Math.min(maxTop, Math.max(0, maxTop - (topScrollable / maxTop)))
            });

            self.scrollable.css({
                'top': Math.min(maxScrollBottom, -topScrollable)
            });
        }
    };

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName,
                new Plugin( this, options ));
            }
        });
    };

})( jQuery, window, document );<commit_msg>- Working with focus in event (in progress)<commit_after>/*
 * GScroll v0.2.2
 *
 * https://github.com/gesanchez/GScroll
 *
 * Copyright (c) 2014 German Sanchez
 * Licensed under the MIT license.
 *
 */

;(function ( $, window, document, undefined ) {

    var pluginName = "GScroll",
        defaults = {
            width: "300px",
            height: "200px"
        };

    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options) ;
        this.init();
    }

    Plugin.prototype = {

        init: function() {
            var self = this;
            self.node = $(self.element);
            self.node.wrap('

')
            .wrap('

')
            .parent().after('

');

            self.container = self.node.closest('.GScroll');
            self.scrollable = self.node.parent();
            self.bar = self.node.parent().next();

            self.adjust.call(self);
            self.events.call(self);
        },

        /**
        *
        * Method for adjust bar height
        */
        adjust: function(callback) {
            var self = this;

            self.conHeight = self.container.height();
            self.scrollHeight = 0;

            if (self.node.is(':not(:visible)')){
                var clone = self.node.clone();
                clone.css({
                    width: self.options.width,
                    'visibility' : 'hidden'
                }).removeAttr('id').show();
                $('body').append(clone);
                self.scrollHeight = clone.outerHeight();
                clone.remove();

            }else{

                self.scrollHeight = self.scrollable.outerHeight();
            }
            self.barHeight = Math.max(20,(self.conHeight - Math.abs(self.conHeight - self.scrollHeight)));

            self.bar.css('height',self.barHeight + 'px');

            if (callback){
                callback.call(self);
            }
        },

        events: function(){
            var self = this;
            self.dragActive = false;
            self.y = 0;
            /**
            * Added event to container
            */

            self.container.on({
                'DOMMouseScroll mousewheel' : function(e){
                    var o = e.originalEvent,
                        delta = (o.detail < 0 || o.wheelDelta > 0) ? 1 : -1;

                    self.wheel.call(self, delta);

                    return false;
                },
                'mouseenter' : function(){
                    if (self.scrollHeight > self.conHeight){
                        self.bar.stop(true,true).fadeIn();
                    }
                },
                'mouseleave' : function(){
                    self.bar.stop(true,true).fadeOut();
                    self.dragActive = false;
                },
                'mousemove' : function(e){
                    e.preventDefault();
                    self.drag.call(self, e);
                },
                'mouseup' : function(e){
                    self.dragActive = false;
                },
                'focusin' : function(e){
                    self.onFocusIn.call(self, e);
                }
            });

            /**
            * Added event for scroll bar
            */
            self.bar.on({
                'mousedown' : function(e){
                    e.preventDefault();
                    self.dragActive = true;
                    self.y = e.pageY;
                },
                'mouseup' : function(e){
                    self.dragActive = false;
                },
                'mousemove' : function(e){
                    e.preventDefault();
                    self.drag.call(self, e);
                }
            });

            /**
            * Added event to element
            */
            self.node.on('adjust.' + pluginName, function(){
                self.adjust.call(self, function(){
                    self.onResize.call(self);
                });

            }).on('destroy.' + pluginName, function(){
                $.removeData(self.element, 'plugin_' + pluginName);
                self.node.off('.' + pluginName);
                self.node.unwrap().unwrap();
                self.bar.remove();
                self.element = null;
                self = null;
            });

            $(window).on('adjust.' + pluginName, function(){
                self.adjust.call(self, function(){
                    self.onResize.call(self);
                });
            });
        },
        /* Method for move bar and scrollable on mousewheel event */
        wheel: function(delta){
            var self = this,
                maxTop = self.conHeight - self.barHeight,
                maxScrollBottom = self.conHeight - self.scrollHeight,
                top = Math.abs(maxTop / (Math.abs(maxScrollBottom)) * 15);

            if (delta > 0){

                self.bar.css({
                    'top' : Math.max(0, parseFloat(self.bar.css('top')) - top)
                });

            }else if (delta < 0){

                self.bar.css({
                    'top' : Math.min(maxTop, parseFloat(self.bar.css('top')) + top)
                });

            }

            self.scrollable.css({
                'top' : Math.min(0 ,Math.max(maxScrollBottom, (maxScrollBottom / maxTop) * parseFloat(self.bar.css('top'))))
            });
        },
        /**
        * Method for move bar and scrollable when bar is dragged
        */
        drag : function(e){
            var self = this,
                maxTop = self.conHeight - self.barHeight,
                maxScrollBottom = self.conHeight - self.scrollHeight;

            if (self.dragActive === true){

                var top = parseFloat(self.bar.position().top) + e.pageY - self.y;
                top = Math.min(top, maxTop);

                self.bar.css({
                    top: Math.max(0 ,top) + 'px'
                });

                self.scrollable.css({
                    'top' : Math.min(0 ,Math.max(maxScrollBottom, (maxScrollBottom / maxTop) * top))
                });

                self.y = e.pageY;
            }
        },
        onResize : function(){
            var self = this,
                scrollable_top = Math.abs(parseFloat(self.scrollable.css('top'))),
                bar_top = parseFloat(self.bar.css('top')),
                maxScrollBottom = Math.abs(self.conHeight - self.scrollHeight),
                maxTop = self.conHeight - self.barHeight,
                top = (maxScrollBottom / maxTop) * bar_top;

            if (self.scrollHeight < self.conHeight){
                self.bar.hide();
            }

            if (scrollable_top > maxScrollBottom){
                self.scrollable.css({
                    'top' : -maxScrollBottom
                });
            }

            var div = top / bar_top,
                newTop = (top - scrollable_top) / div;

            self.bar.css({
                'top': Math.min(maxTop, Math.max(0, bar_top - newTop))
            });
        },
        onFocusIn : function(e){

            var self = this,
                target = $(e.target),
                target_top = target.get(0).getBoundingClientRect().top + (target.outerHeight() - self.barHeight) - $(window).scrollTop() + Math.abs(parseFloat(self.scrollable.css('top'))),
                maxTop = self.conHeight - self.barHeight,
                maxScrollBottom = self.conHeight - self.scrollHeight,
                top = (maxTop * target_top) / self.scrollHeight;

            if (top < Math.abs(parseFloat(self.scrollable.css('top'))) + self.conHeight){

                if (target_top < 0){
                    self.bar.css({
                        'top': Math.min(maxTop, Math.max(0, top))
                    }, 200);
                }else{
                    self.bar.css({
                        'top': Math.min(maxTop, Math.max(0, top))
                    }, 200);
                }

                self.scrollable.css({
                    'top' : Math.min(0 ,Math.max(maxScrollBottom, (maxScrollBottom / maxTop) * parseFloat(self.bar.css('top'))))
                },200);
            }
        }
    };

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName,
                new Plugin( this, options ));
            }
        });
    };

})( jQuery, window, document );<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Lightbox from 'react-images';
import Image from './Image.js';

class Gallery extends Component {
    constructor (props) {
        super(props);
        console.log(this.props);
        this.state = {
            images: this.props.images,
            thumbnails: [],
            lightboxIsOpen: this.props.isOpen,
            currentImage: this.props.currentImage,
            containerWidth: 0
        };
        this.onResize = this.onResize.bind(this);
        this.closeLightbox = this.closeLightbox.bind(this);
        this.gotoImage = this.gotoImage.bind(this);
        this.gotoNext = this.gotoNext.bind(this);
        this.gotoPrevious = this.gotoPrevious.bind(this);
        this.onClickImage = this.onClickImage.bind(this);
        this.openLightbox = this.openLightbox.bind(this);
        this.onSelectImage = this.onSelectImage.bind(this);
    }

    componentDidMount () {
        this.onResize();
        console.log(this.props.editing)
        window.addEventListener('resize', this.onResize);
    }

    componentWillReceiveProps (np) {
        if(this.state.images != np.images || this.props.maxRows != np.maxRows){
            this.setState({
                images: np.images,
                thumbnails: this.renderThumbs(this._gallery.clientWidth,
                                              np.images)
            });
        }
    }

    componentDidUpdate () {
        if (!this._gallery) return;
        if (this._gallery.clientWidth
            !== this.state.containerWidth){
            this.onResize();
        }
    }

    onResize () {
        if (!this._gallery) return;
        this.setState({
            containerWidth: Math.floor(this._gallery.clientWidth),
            thumbnails: this.renderThumbs(this._gallery.clientWidth)
        });
    }

    openLightbox (index, event) {
        if (event) {
            event.preventDefault();
        }
        if (this.props.lightboxWillOpen) {
            this.props.lightboxWillOpen.call(this, index);
        }

        this.setState({
            currentImage: index,
            lightboxIsOpen: true
        });
    }

    closeLightbox () {
        if (this.props.lightboxWillClose) {
            this.props.lightboxWillClose.call(this);
        }

        this.setState({
            currentImage: 0,
            lightboxIsOpen: false
        });
    }

    gotoPrevious () {
        this.setState({
            currentImage: this.state.currentImage - 1
        });
    }

    gotoNext () {
        this.setState({
            currentImage: this.state.currentImage + 1
        });
    }

    onClickImage () {
        if (this.state.currentImage === this.props.images.length - 1)
            return;
        this.gotoNext();
    }

    onSelectImage (index, event) {
        event.preventDefault();
        if(this.props.onSelectImage)
            this.props.onSelectImage.call(this, index, this.state.images[index]);
    }

    gotoImage (index) {
        this.setState({
            currentImage: index
        });
    }

    getOnClickThumbnailFn () {
        if(!this.props.onClickThumbnail && this.props.enableLightbox)
            return this.openLightbox;
        if(this.props.onClickThumbnail)
            return this.props.onClickThumbnail;
        return null;
    }

    getOnClickLightboxThumbnailFn () {
        if(!this.props.onClickLightboxThumbnail
           && this.props.showLightboxThumbnails)
            return this.gotoImage;
        if(this.props.onClickLightboxThumbnail
           && this.props.showLightboxThumbnails)
            return this.props.onClickLightboxThumbnail;
        return null;
    }

    getOnClickImageFn () {
        if(this.props.onClickImage)
            return this.props.onClickImage;
        return this.onClickImage;
    }

    getOnClickPrevFn () {
        if(this.props.onClickPrev)
            return this.props.onClickPrev;
        return this.gotoPrevious;
    }

    getOnClickNextFn () {
        if(this.props.onClickNext)
            return this.props.onClickNext;
        return this.gotoNext;
    }

    calculateCutOff (len, delta, items) {
        var cutoff = [];
        var cutsum = 0;
        for(var i in items) {
            var item = items[i];
            var fractOfLen = item.scaletwidth / len;
            cutoff[i] = Math.floor(fractOfLen * delta);
            cutsum += cutoff[i];
        }

        var stillToCutOff = delta - cutsum;
        while(stillToCutOff > 0) {
            for(i in cutoff) {
                cutoff[i]++;
                stillToCutOff--;
                if (stillToCutOff < 0) break;
            }
        }
        return cutoff;
    }

    buildImageRow (items, containerWidth) {
        var row = [];
        var len = 0;
        var imgMargin = 2 * this.props.margin;
        while(items.length > 0 && len < containerWidth) {
            var item = items.shift();
            row.push(item);
            len += (item.scaletwidth + imgMargin);
        }

        var delta = len - containerWidth;
        if(row.length > 0 && delta > 0) {
            var cutoff = this.calculateCutOff(len, delta, row);
            for(var i in row) {
                var pixelsToRemove = cutoff[i];
                item = row[i];
                item.marginLeft = -Math.abs(Math.floor(pixelsToRemove / 2));
                item.vwidth = item.scaletwidth - pixelsToRemove;
            }
        }
        else {
            for(var j in row) {
                item = row[j];
                item.marginLeft = 0;
                item.vwidth = item.scaletwidth;
            }
        }
        return row;
    }

    setThumbScale (item) {
        item.scaletwidth =
            Math.floor(this.props.rowHeight
                       * (item.thumbnailWidth / item.thumbnailHeight));
    }

    renderThumbs (containerWidth, images = this.state.images) {
        if (!images) return [];
        if (containerWidth == 0) return [];

        var items = images.slice();
        for (var t in items) {
            this.setThumbScale(items[t]);
        }

        var thumbs = [];
        var rows = [];
        while(items.length > 0) {
            rows.push(this.buildImageRow(items, containerWidth));
        }

        for(var r in rows) {
            for(var i in rows[r]) {
                var item = rows[r][i];
                if(this.props.maxRows) {
                    if(r < this.props.maxRows) {
                        thumbs.push(item);
                    }
                }
                else {
                    thumbs.push(item);
                }
            }
        }
        return thumbs;
    }

    render () {
        var images = this.state.thumbnails.map((item, idx) => {
            return <Image
            key={"Image-"+idx+"-"+item.src}
            item={item}
            index={idx}
            margin={this.props.margin}
            height={this.props.rowHeight}
            isSelectable={this.props.enableImageSelection}
            onClick={this.getOnClickThumbnailFn()}
            onSelectImage={this.onSelectImage}
            tagStyle={this.props.tagStyle}
            tileViewportStyle={this.props.tileViewportStyle}
            thumbnailStyle={this.props.thumbnailStyle}
            editing={this.props.editing}
            />;});

        return (

 this._gallery = c}>
                {images}
                <Lightbox
            images={this.props.images}
            backdropClosesModal={this.props.backdropClosesModal}
            currentImage={this.state.currentImage}
            customControls={this.props.customControls}
            enableKeyboardInput={this.props.enableKeyboardInput}
            imageCountSeparator={this.props.imageCountSeparator}
            isOpen={this.state.lightboxIsOpen}
            onClickImage={this.getOnClickImageFn()}
            onClickNext={this.getOnClickNextFn()}
            onClickPrev={this.getOnClickPrevFn()}
            showCloseButton={this.props.showCloseButton}
            showImageCount={this.props.showImageCount}
            onClose={this.closeLightbox}
            width={this.props.lightboxWidth}
            theme={this.props.theme}
            onClickThumbnail={this.getOnClickLightboxThumbnailFn()}
            showThumbnails={this.props.showLightboxThumbnails}
                />

        );
    }
}

Gallery.displayName = 'Gallery';

Gallery.propTypes = {
    images: PropTypes.arrayOf(
        PropTypes.shape({
            src: PropTypes.string.isRequired,
            thumbnail: PropTypes.string.isRequired,
            srcset: PropTypes.array,
            caption: PropTypes.string,
            tags: PropTypes.arrayOf(
                PropTypes.shape({
                    value: PropTypes.string.isRequired,
                    title: PropTypes.string.isRequired
                })
            ),
            thumbnailWidth: PropTypes.number.isRequired,
            thumbnailHeight: PropTypes.number.isRequired,
            isSelected: PropTypes.bool
        })
    ).isRequired,
    id: PropTypes.string,
    enableImageSelection: PropTypes.bool,
    onSelectImage: PropTypes.func,
    rowHeight: PropTypes.number,
    maxRows: PropTypes.number,
    margin: PropTypes.number,
    onClickThumbnail: PropTypes.func,
    lightboxWillOpen: PropTypes.func,
    lightboxWillClose: PropTypes.func,
    enableLightbox: PropTypes.bool,
    backdropClosesModal: PropTypes.bool,
    currentImage: PropTypes.number,
    preloadNextImage: PropTypes.bool,
    customControls: PropTypes.arrayOf(PropTypes.node),
    enableKeyboardInput: PropTypes.bool,
    imageCountSeparator: PropTypes.string,
    isOpen: PropTypes.bool,
    onClickImage: PropTypes.func,
    onClickNext: PropTypes.func,
    onClickPrev: PropTypes.func,
    onClose: PropTypes.func,
    showCloseButton: PropTypes.bool,
    showImageCount: PropTypes.bool,
    lightboxWidth: PropTypes.number,
    tileViewportStyle: PropTypes.func,
    thumbnailStyle: PropTypes.func,
    showLightboxThumbnails: PropTypes.bool,
    editing: PropTypes.bool,
    onClickLightboxThumbnail: PropTypes.func,
    tagStyle: PropTypes.object
};

Gallery.defaultProps = {
    id: "ReactGridGallery",
    enableImageSelection: true,
    rowHeight: 180,
    margin: 2,
    enableLightbox: true,
    backdropClosesModal: false,
    currentImage: 0,
    preloadNextImage: true,
    enableKeyboardInput: true,
    imageCountSeparator: ' of ',
    isOpen: false,
    showCloseButton: true,
    showImageCount: true,
    lightboxWidth: 1024,
    showLightboxThumbnails: false,
    editing: true,
};

module.exports = Gallery;
<commit_msg>14:34 2017-8-23<commit_after>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Lightbox from 'react-images';
import Image from './Image.js';

class Gallery extends Component {
    constructor (props) {
        super(props);
        console.log(this.props);
        this.state = {
            images: this.props.images,
            thumbnails: [],
            lightboxIsOpen: this.props.isOpen,
            currentImage: this.props.currentImage,
            containerWidth: 0
        };
        this.onResize = this.onResize.bind(this);
        this.closeLightbox = this.closeLightbox.bind(this);
        this.gotoImage = this.gotoImage.bind(this);
        this.gotoNext = this.gotoNext.bind(this);
        this.gotoPrevious = this.gotoPrevious.bind(this);
        this.onClickImage = this.onClickImage.bind(this);
        this.openLightbox = this.openLightbox.bind(this);
        this.onSelectImage = this.onSelectImage.bind(this);
    }

    componentDidMount () {
        this.onResize();
        console.log(this.props.editing)
        window.addEventListener('resize', this.onResize);
    }

    componentWillReceiveProps (np) {
        if(this.state.images != np.images || this.props.maxRows != np.maxRows){
            this.setState({
                images: np.images,
                thumbnails: this.renderThumbs(this._gallery.clientWidth,
                                              np.images)
            });
        }
    }

    componentDidUpdate () {
        if (!this._gallery) return;
        if (this._gallery.clientWidth
            !== this.state.containerWidth){
            this.onResize();
        }
    }

    onResize () {
        if (!this._gallery) return;
        this.setState({
            containerWidth: Math.floor(this._gallery.clientWidth),
            thumbnails: this.renderThumbs(this._gallery.clientWidth)
        });
    }

    openLightbox (index, event) {
        if (event) {
            event.preventDefault();
        }
        if (this.props.lightboxWillOpen) {
            this.props.lightboxWillOpen.call(this, index);
        }

        this.setState({
            currentImage: index,
            lightboxIsOpen: true
        });
    }

    closeLightbox () {
        if (this.props.lightboxWillClose) {
            this.props.lightboxWillClose.call(this);
        }

        this.setState({
            currentImage: 0,
            lightboxIsOpen: false
        });
    }

    gotoPrevious () {
        this.setState({
            currentImage: this.state.currentImage - 1
        });
    }

    gotoNext () {
        this.setState({
            currentImage: this.state.currentImage + 1
        });
    }

    onClickImage () {
        if (this.state.currentImage === this.props.images.length - 1)
            return;
        this.gotoNext();
    }

    onSelectImage (index, event) {
        event.preventDefault();
        if(this.props.onSelectImage)
            this.props.onSelectImage.call(this, index, this.state.images[index]);
    }

    gotoImage (index) {
        this.setState({
            currentImage: index
        });
    }

    getOnClickThumbnailFn () {
        if(!this.props.onClickThumbnail && this.props.enableLightbox)
            return this.openLightbox;
        if(this.props.onClickThumbnail)
            return this.props.onClickThumbnail;
        return null;
    }

    getOnClickLightboxThumbnailFn () {
        if(!this.props.onClickLightboxThumbnail
           && this.props.showLightboxThumbnails)
            return this.gotoImage;
        if(this.props.onClickLightboxThumbnail
           && this.props.showLightboxThumbnails)
            return this.props.onClickLightboxThumbnail;
        return null;
    }

    getOnClickImageFn () {
        if(this.props.onClickImage)
            return this.props.onClickImage;
        return this.onClickImage;
    }

    getOnClickPrevFn () {
        if(this.props.onClickPrev)
            return this.props.onClickPrev;
        return this.gotoPrevious;
    }

    getOnClickNextFn () {
        if(this.props.onClickNext)
            return this.props.onClickNext;
        return this.gotoNext;
    }

    calculateCutOff (len, delta, items) {
        var cutoff = [];
        var cutsum = 0;
        for(var i in items) {
            var item = items[i];
            var fractOfLen = item.scaletwidth / len;
            cutoff[i] = Math.floor(fractOfLen * delta);
            cutsum += cutoff[i];
        }

        var stillToCutOff = delta - cutsum;
        while(stillToCutOff > 0) {
            for(i in cutoff) {
                cutoff[i]++;
                stillToCutOff--;
                if (stillToCutOff < 0) break;
            }
        }
        return cutoff;
    }

    buildImageRow (items, containerWidth) {
        var row = [];
        var len = 0;
        var imgMargin = 2 * this.props.margin;
        while(items.length > 0 && len < containerWidth) {
            var item = items.shift();
            row.push(item);
            len += (item.scaletwidth + imgMargin);
        }

        var delta = len - containerWidth;
        if(row.length > 0 && delta > 0) {
            var cutoff = this.calculateCutOff(len, delta, row);
            for(var i in row) {
                var pixelsToRemove = cutoff[i];
                item = row[i];
                item.marginLeft = -Math.abs(Math.floor(pixelsToRemove / 2));
                item.vwidth = item.scaletwidth - pixelsToRemove;
            }
        }
        else {
            for(var j in row) {
                item = row[j];
                item.marginLeft = 0;
                item.vwidth = item.scaletwidth;
            }
        }
        return row;
    }

    setThumbScale (item) {
        item.scaletwidth =
            Math.floor(this.props.rowHeight
                       * (item.thumbnailWidth / item.thumbnailHeight));
    }

    renderThumbs (containerWidth, images = this.state.images) {
        if (!images) return [];
        if (containerWidth == 0) return [];

        var items = images.slice();
        for (var t in items) {
            this.setThumbScale(items[t]);
        }

        var thumbs = [];
        var rows = [];
        while(items.length > 0) {
            rows.push(this.buildImageRow(items, containerWidth));
        }

        for(var r in rows) {
            for(var i in rows[r]) {
                var item = rows[r][i];
                if(this.props.maxRows) {
                    if(r < this.props.maxRows) {
                        thumbs.push(item);
                    }
                }
                else {
                    thumbs.push(item);
                }
            }
        }
        return thumbs;
    }

    render () {
        var images = this.state.thumbnails.map((item, idx) => {
            return <Image
            key={"Image-"+idx+"-"+item.src}
            editing={this.props.editing}
            item={item}
            index={idx}
            margin={this.props.margin}
            height={this.props.rowHeight}
            isSelectable={this.props.enableImageSelection}
            onClick={this.getOnClickThumbnailFn()}
            onSelectImage={this.onSelectImage}
            tagStyle={this.props.tagStyle}
            tileViewportStyle={this.props.tileViewportStyle}
            thumbnailStyle={this.props.thumbnailStyle}
            />;});

        return (

 this._gallery = c}>
                {images}
                <Lightbox
            images={this.props.images}
            backdropClosesModal={this.props.backdropClosesModal}
            currentImage={this.state.currentImage}
            customControls={this.props.customControls}
            enableKeyboardInput={this.props.enableKeyboardInput}
            imageCountSeparator={this.props.imageCountSeparator}
            isOpen={this.state.lightboxIsOpen}
            onClickImage={this.getOnClickImageFn()}
            onClickNext={this.getOnClickNextFn()}
            onClickPrev={this.getOnClickPrevFn()}
            showCloseButton={this.props.showCloseButton}
            showImageCount={this.props.showImageCount}
            onClose={this.closeLightbox}
            width={this.props.lightboxWidth}
            theme={this.props.theme}
            onClickThumbnail={this.getOnClickLightboxThumbnailFn()}
            showThumbnails={this.props.showLightboxThumbnails}
                />

        );
    }
}

Gallery.displayName = 'Gallery';

Gallery.propTypes = {
    images: PropTypes.arrayOf(
        PropTypes.shape({
            src: PropTypes.string.isRequired,
            thumbnail: PropTypes.string.isRequired,
            srcset: PropTypes.array,
            caption: PropTypes.string,
            tags: PropTypes.arrayOf(
                PropTypes.shape({
                    value: PropTypes.string.isRequired,
                    title: PropTypes.string.isRequired
                })
            ),
            thumbnailWidth: PropTypes.number.isRequired,
            thumbnailHeight: PropTypes.number.isRequired,
            isSelected: PropTypes.bool
        })
    ).isRequired,
    id: PropTypes.string,
    enableImageSelection: PropTypes.bool,
    onSelectImage: PropTypes.func,
    rowHeight: PropTypes.number,
    maxRows: PropTypes.number,
    margin: PropTypes.number,
    onClickThumbnail: PropTypes.func,
    lightboxWillOpen: PropTypes.func,
    lightboxWillClose: PropTypes.func,
    enableLightbox: PropTypes.bool,
    backdropClosesModal: PropTypes.bool,
    currentImage: PropTypes.number,
    preloadNextImage: PropTypes.bool,
    customControls: PropTypes.arrayOf(PropTypes.node),
    enableKeyboardInput: PropTypes.bool,
    imageCountSeparator: PropTypes.string,
    isOpen: PropTypes.bool,
    onClickImage: PropTypes.func,
    onClickNext: PropTypes.func,
    onClickPrev: PropTypes.func,
    onClose: PropTypes.func,
    showCloseButton: PropTypes.bool,
    showImageCount: PropTypes.bool,
    lightboxWidth: PropTypes.number,
    tileViewportStyle: PropTypes.func,
    thumbnailStyle: PropTypes.func,
    showLightboxThumbnails: PropTypes.bool,
    editing: PropTypes.bool,
    onClickLightboxThumbnail: PropTypes.func,
    tagStyle: PropTypes.object
};

Gallery.defaultProps = {
    id: "ReactGridGallery",
    enableImageSelection: true,
    rowHeight: 180,
    margin: 2,
    enableLightbox: true,
    backdropClosesModal: false,
    currentImage: 0,
    preloadNextImage: true,
    enableKeyboardInput: true,
    imageCountSeparator: ' of ',
    isOpen: false,
    showCloseButton: true,
    showImageCount: true,
    lightboxWidth: 1024,
    showLightboxThumbnails: false,
    editing: true,
};

module.exports = Gallery;
<|endoftext|>


<commit_before>/**
* Spatial HashMap for broad phase collision
*
* @author Louis Stowasser
*/
(function (parent) {

	/**@
	* #Crafty.HashMap.constructor
	* @comp Crafty.HashMap
	* @sign public void Crafty.HashMap([cellsize])
	* @param cellsize - the cell size. If omitted, `cellsize` is 64.
	*
    * Set `cellsize`.
    * And create `this.map`.
	*/
	var cellsize,

	HashMap = function (cell) {
		cellsize = cell || 64;
		this.map = {};
	},

	SPACE = " ";

	HashMap.prototype = {
	/**@
	* #Crafty.map.insert
	* @comp Crafty.map
    * @sign public Object Crafty.map.insert(Object obj)
	* @param obj - An entity to be inserted.
	*
    * `obj` is inserted in '.map' of the corresponding broad phase cells. An object of the following fields is returned.
    * ~~~
    * - the object that keep track of cells (keys)
    * - `obj`
    * - the HashMap object
    * ~~~
	*/
		insert: function (obj) {
			var keys = HashMap.key(obj),
			entry = new Entry(keys, obj, this),
			i = 0,
			j,
			hash;

			//insert into all x buckets
			for (i = keys.x1; i <= keys.x2; i++) {
				//insert into all y buckets
				for (j = keys.y1; j <= keys.y2; j++) {
					hash = i + SPACE + j;
					if (!this.map[hash]) this.map[hash] = [];
					this.map[hash].push(obj);
				}
			}

			return entry;
		},

	/**@
	* #Crafty.map.search
	* @comp Crafty.map
    * @sign public Object Crafty.map.search(Object rect[, Boolean filter])
	* @param rect - the rectangular region to search for entities.
	* @param filter - Default value is true. Otherwise, must be false.
	*
    * - If `filter` is `false`, just search for all the entries in the give `rect` region by broad phase collision. Entity may be returned duplicated.
    * - If `filter` is `true`, filter the above results by checking that they actually overlap `rect`.
    * The easier usage is with `filter`=`true`. For performance reason, you may use `filter`=`false`, and filter the result yourself. See examples in drawing.js and collision.js
	*/
		search: function (rect, filter) {
			var keys = HashMap.key(rect),
			i, j,
			hash,
			results = [];

			if (filter === undefined) filter = true; //default filter to true

			//search in all x buckets
			for (i = keys.x1; i <= keys.x2; i++) {
				//insert into all y buckets
				for (j = keys.y1; j <= keys.y2; j++) {
					hash = i + SPACE + j;

					if (this.map[hash]) {
						results = results.concat(this.map[hash]);
					}
				}
			}

			if (filter) {
				var obj, id, finalresult = [], found = {};
				//add unique elements to lookup table with the entity ID as unique key
				for (i = 0, l = results.length; i < l; i++) {
					obj = results[i];
					if (!obj) continue; //skip if deleted
					id = obj[0]; //unique ID

					//check if not added to hash and that actually intersects
					if (!found[id] && obj.x < rect._x + rect._w && obj._x + obj._w > rect._x &&
								 obj.y < rect._y + rect._h && obj._h + obj._y > rect._y)
						found[id] = results[i];
				}

				//loop over lookup table and copy to final array
				for (obj in found) finalresult.push(found[obj]);

				return finalresult;
			} else {
				return results;
			}
		},

	/**@
	* #Crafty.map.remove
	* @comp Crafty.map
	* @sign public void Crafty.map.remove([Object keys, ]Object obj)
	* @param keys - key region. If omitted, it will be derived from obj by `Crafty.HashMap.key`.
	* @param obj - need more document.
	*
	* Remove an entity in a broad phase map.
	* - The second form is only used in Crafty.HashMap to save time for computing keys again, where keys were computed previously from obj. End users should not call this form directly.
	*
	* @example
	* ~~~
	* Crafty.map.remove(e);
	* ~~~
	*/
		remove: function (keys, obj) {
			var i = 0, j, hash;

			if (arguments.length == 1) {
				obj = keys;
				keys = HashMap.key(obj);
			}

			//search in all x buckets
			for (i = keys.x1; i <= keys.x2; i++) {
				//insert into all y buckets
				for (j = keys.y1; j <= keys.y2; j++) {
					hash = i + SPACE + j;

					if (this.map[hash]) {
						var cell = this.map[hash],
						m,
						n = cell.length;
						//loop over objs in cell and delete
						for (m = 0; m < n; m++)
							if (cell[m] && cell[m][0] === obj[0])
								cell.splice(m, 1);
					}
				}
			}
		},

	/**@
	* #Crafty.map.boundaries
	* @comp Crafty.map
	* @sign public Object Crafty.map.boundaries()
	*
    * The return `Object` is of the following format.
    * ~~~
	* {
    *   min: {
    *     x: val_x,
    *     y: val_y
    *   },
    *   max: {
    *     x: val_x,
    *     y: val_y
    *   }
    * }
    * ~~~
	*/
		boundaries: function () {
			var k, ent,
			hash = {
				max: { x: -Infinity, y: -Infinity },
				min: { x: Infinity, y: Infinity }
			},
			coords = {
				max: { x: -Infinity, y: -Infinity },
				min: { x: Infinity, y: Infinity }
			};

      //Using broad phase hash to speed up the computation of boundaries.
			for (var h in this.map) {
				if (!this.map[h].length) continue;

        //broad phase coordinate
				var map_coord = h.split(SPACE),
					i=map_coord[0],
					j=map_coord[0];
				if (i >= hash.max.x) {
					hash.max.x = i;
					for (k in this.map[h]) {
						ent = this.map[h][k];
						//make sure that this is a Crafty entity
						if (typeof ent == 'object' && 'requires' in ent) {
							coords.max.x = Math.max(coords.max.x, ent.x + ent.w);
						}
					}
				}
				if (i <= hash.min.x) {
					hash.min.x = i;
					for (k in this.map[h]) {
						ent = this.map[h][k];
						if (typeof ent == 'object' && 'requires' in ent) {
							coords.min.x = Math.min(coords.min.x, ent.x);
						}
					}
				}
				if (j >= hash.max.y) {
					hash.max.y = j;
					for (k in this.map[h]) {
						ent = this.map[h][k];
						if (typeof ent == 'object' && 'requires' in ent) {
							coords.max.y = Math.max(coords.max.y, ent.y + ent.h);
						}
					}
				}
				if (j <= hash.min.y) {
					hash.min.y = j;
					for (k in this.map[h]) {
						ent = this.map[h][k];
						if (typeof ent == 'object' && 'requires' in ent) {
							coords.min.y = Math.min(coords.min.y, ent.y);
						}
					}
				}
			}

			return coords;
		}
	};

/**@
* #Crafty.HashMap
* @category 2D
* Broad-phase collision detection engine. See background information at
*
* ~~~
* - [N Tutorial B - Broad-Phase Collision](http://www.metanetsoftware.com/technique/tutorialB.html)
* - [Broad-Phase Collision Detection with CUDA](http.developer.nvidia.com/GPUGems3/gpugems3_ch32.html)
* ~~~
* @see Crafty.map
*/

	/**@
	* #Crafty.HashMap.key
	* @comp Crafty.HashMap
	* @sign public Object Crafty.HashMap.key(Object obj)
	* @param obj - an Object that has .mbr() or _x, _y, _w and _h.
    * Get the rectangular region (in terms of the grid, with grid size `cellsize`), where the object may fall in. This region is determined by the object's bounding box.
    * The `cellsize` is 64 by default.
    *
    * @see Crafty.HashMap.constructor
	*/
	HashMap.key = function (obj) {
		if (obj.hasOwnProperty('mbr')) {
			obj = obj.mbr();
		}
		var x1 = Math.floor(obj._x / cellsize),
		y1 = Math.floor(obj._y / cellsize),
		x2 = Math.floor((obj._w + obj._x) / cellsize),
		y2 = Math.floor((obj._h + obj._y) / cellsize);
		return { x1: x1, y1: y1, x2: x2, y2: y2 };
	};

	HashMap.hash = function (keys) {
		return keys.x1 + SPACE + keys.y1 + SPACE + keys.x2 + SPACE + keys.y2;
	};

	function Entry(keys, obj, map) {
		this.keys = keys;
		this.map = map;
		this.obj = obj;
	}

	Entry.prototype = {
		update: function (rect) {
			//check if buckets change
			if (HashMap.hash(HashMap.key(rect)) != HashMap.hash(this.keys)) {
				this.map.remove(this.keys, this.obj);
				var e = this.map.insert(this.obj);
				this.keys = e.keys;
			}
		}
	};

	parent.HashMap = HashMap;
})(Crafty);
<commit_msg>Reduce Garbage: Each use of concat creates a new array, so avoid using it inside HashMap.search()<commit_after>/**
* Spatial HashMap for broad phase collision
*
* @author Louis Stowasser
*/
(function (parent) {

	/**@
	* #Crafty.HashMap.constructor
	* @comp Crafty.HashMap
	* @sign public void Crafty.HashMap([cellsize])
	* @param cellsize - the cell size. If omitted, `cellsize` is 64.
	*
    * Set `cellsize`.
    * And create `this.map`.
	*/
	var cellsize,

	HashMap = function (cell) {
		cellsize = cell || 64;
		this.map = {};
	},

	SPACE = " ";

	HashMap.prototype = {
	/**@
	* #Crafty.map.insert
	* @comp Crafty.map
    * @sign public Object Crafty.map.insert(Object obj)
	* @param obj - An entity to be inserted.
	*
    * `obj` is inserted in '.map' of the corresponding broad phase cells. An object of the following fields is returned.
    * ~~~
    * - the object that keep track of cells (keys)
    * - `obj`
    * - the HashMap object
    * ~~~
	*/
		insert: function (obj) {
			var keys = HashMap.key(obj),
			entry = new Entry(keys, obj, this),
			i = 0,
			j,
			hash;

			//insert into all x buckets
			for (i = keys.x1; i <= keys.x2; i++) {
				//insert into all y buckets
				for (j = keys.y1; j <= keys.y2; j++) {
					hash = i + SPACE + j;
					if (!this.map[hash]) this.map[hash] = [];
					this.map[hash].push(obj);
				}
			}

			return entry;
		},

	/**@
	* #Crafty.map.search
	* @comp Crafty.map
    * @sign public Object Crafty.map.search(Object rect[, Boolean filter])
	* @param rect - the rectangular region to search for entities.
	* @param filter - Default value is true. Otherwise, must be false.
	*
    * - If `filter` is `false`, just search for all the entries in the give `rect` region by broad phase collision. Entity may be returned duplicated.
    * - If `filter` is `true`, filter the above results by checking that they actually overlap `rect`.
    * The easier usage is with `filter`=`true`. For performance reason, you may use `filter`=`false`, and filter the result yourself. See examples in drawing.js and collision.js
	*/
		search: function (rect, filter) {
			var keys = HashMap.key(rect),
			i, j,k,
			hash,
			results = [];

			if (filter === undefined) filter = true; //default filter to true

			//search in all x buckets
			for (i = keys.x1; i <= keys.x2; i++) {
				//insert into all y buckets
				for (j = keys.y1; j <= keys.y2; j++) {
					hash = i + SPACE + j;

					if (this.map[hash]) {
                        for (k = 0; k<this.map[hash].length; k++)
                            results.push(this.map[hash][k]);
						//results = results.concat(this.map[hash]);
					}
				}
			}

			if (filter) {
				var obj, id, finalresult = [], found = {};
				//add unique elements to lookup table with the entity ID as unique key
				for (i = 0, l = results.length; i < l; i++) {
					obj = results[i];
					if (!obj) continue; //skip if deleted
					id = obj[0]; //unique ID

					//check if not added to hash and that actually intersects
					if (!found[id] && obj.x < rect._x + rect._w && obj._x + obj._w > rect._x &&
								 obj.y < rect._y + rect._h && obj._h + obj._y > rect._y)
						found[id] = results[i];
				}

				//loop over lookup table and copy to final array
				for (obj in found) finalresult.push(found[obj]);

				return finalresult;
			} else {
				return results;
			}
		},

	/**@
	* #Crafty.map.remove
	* @comp Crafty.map
	* @sign public void Crafty.map.remove([Object keys, ]Object obj)
	* @param keys - key region. If omitted, it will be derived from obj by `Crafty.HashMap.key`.
	* @param obj - need more document.
	*
	* Remove an entity in a broad phase map.
	* - The second form is only used in Crafty.HashMap to save time for computing keys again, where keys were computed previously from obj. End users should not call this form directly.
	*
	* @example
	* ~~~
	* Crafty.map.remove(e);
	* ~~~
	*/
		remove: function (keys, obj) {
			var i = 0, j, hash;

			if (arguments.length == 1) {
				obj = keys;
				keys = HashMap.key(obj);
			}

			//search in all x buckets
			for (i = keys.x1; i <= keys.x2; i++) {
				//insert into all y buckets
				for (j = keys.y1; j <= keys.y2; j++) {
					hash = i + SPACE + j;

					if (this.map[hash]) {
						var cell = this.map[hash],
						m,
						n = cell.length;
						//loop over objs in cell and delete
						for (m = 0; m < n; m++)
							if (cell[m] && cell[m][0] === obj[0])
								cell.splice(m, 1);
					}
				}
			}
		},

	/**@
	* #Crafty.map.boundaries
	* @comp Crafty.map
	* @sign public Object Crafty.map.boundaries()
	*
    * The return `Object` is of the following format.
    * ~~~
	* {
    *   min: {
    *     x: val_x,
    *     y: val_y
    *   },
    *   max: {
    *     x: val_x,
    *     y: val_y
    *   }
    * }
    * ~~~
	*/
		boundaries: function () {
			var k, ent,
			hash = {
				max: { x: -Infinity, y: -Infinity },
				min: { x: Infinity, y: Infinity }
			},
			coords = {
				max: { x: -Infinity, y: -Infinity },
				min: { x: Infinity, y: Infinity }
			};

      //Using broad phase hash to speed up the computation of boundaries.
			for (var h in this.map) {
				if (!this.map[h].length) continue;

        //broad phase coordinate
				var map_coord = h.split(SPACE),
					i=map_coord[0],
					j=map_coord[0];
				if (i >= hash.max.x) {
					hash.max.x = i;
					for (k in this.map[h]) {
						ent = this.map[h][k];
						//make sure that this is a Crafty entity
						if (typeof ent == 'object' && 'requires' in ent) {
							coords.max.x = Math.max(coords.max.x, ent.x + ent.w);
						}
					}
				}
				if (i <= hash.min.x) {
					hash.min.x = i;
					for (k in this.map[h]) {
						ent = this.map[h][k];
						if (typeof ent == 'object' && 'requires' in ent) {
							coords.min.x = Math.min(coords.min.x, ent.x);
						}
					}
				}
				if (j >= hash.max.y) {
					hash.max.y = j;
					for (k in this.map[h]) {
						ent = this.map[h][k];
						if (typeof ent == 'object' && 'requires' in ent) {
							coords.max.y = Math.max(coords.max.y, ent.y + ent.h);
						}
					}
				}
				if (j <= hash.min.y) {
					hash.min.y = j;
					for (k in this.map[h]) {
						ent = this.map[h][k];
						if (typeof ent == 'object' && 'requires' in ent) {
							coords.min.y = Math.min(coords.min.y, ent.y);
						}
					}
				}
			}

			return coords;
		}
	};

/**@
* #Crafty.HashMap
* @category 2D
* Broad-phase collision detection engine. See background information at
*
* ~~~
* - [N Tutorial B - Broad-Phase Collision](http://www.metanetsoftware.com/technique/tutorialB.html)
* - [Broad-Phase Collision Detection with CUDA](http.developer.nvidia.com/GPUGems3/gpugems3_ch32.html)
* ~~~
* @see Crafty.map
*/

	/**@
	* #Crafty.HashMap.key
	* @comp Crafty.HashMap
	* @sign public Object Crafty.HashMap.key(Object obj)
	* @param obj - an Object that has .mbr() or _x, _y, _w and _h.
    * Get the rectangular region (in terms of the grid, with grid size `cellsize`), where the object may fall in. This region is determined by the object's bounding box.
    * The `cellsize` is 64 by default.
    *
    * @see Crafty.HashMap.constructor
	*/
	HashMap.key = function (obj) {
		if (obj.hasOwnProperty('mbr')) {
			obj = obj.mbr();
		}
		var x1 = Math.floor(obj._x / cellsize),
		y1 = Math.floor(obj._y / cellsize),
		x2 = Math.floor((obj._w + obj._x) / cellsize),
		y2 = Math.floor((obj._h + obj._y) / cellsize);
		return { x1: x1, y1: y1, x2: x2, y2: y2 };
	};

	HashMap.hash = function (keys) {
		return keys.x1 + SPACE + keys.y1 + SPACE + keys.x2 + SPACE + keys.y2;
	};

	function Entry(keys, obj, map) {
		this.keys = keys;
		this.map = map;
		this.obj = obj;
	}

	Entry.prototype = {
		update: function (rect) {
			//check if buckets change
			if (HashMap.hash(HashMap.key(rect)) != HashMap.hash(this.keys)) {
				this.map.remove(this.keys, this.obj);
				var e = this.map.insert(this.obj);
				this.keys = e.keys;
			}
		}
	};

	parent.HashMap = HashMap;
})(Crafty);
<|endoftext|>


<commit_before>hljs.LANGUAGES.cpp = {
  defaultMode: {
    lexems: [hljs.UNDERSCORE_IDENT_RE],
    illegal: '</',
    contains: ['comment', 'string', 'number', 'preprocessor'],
    keywords: {'false': 1, 'int': 1, 'float': 1, 'while': 1, 'private': 1, 'char': 1, 'catch': 1, 'export': 1, 'virtual': 1, 'operator': 2, 'sizeof': 2, 'dynamic_cast': 2, 'typedef': 2, 'const_cast': 2, 'const': 1, 'struct': 1, 'for': 1, 'static_cast': 2, 'union': 1, 'namespace': 1, 'unsigned': 1, 'long': 1, 'throw': 1, 'volatile': 2, 'static': 1, 'protected': 1, 'bool': 1, 'template': 1, 'mutable': 1, 'if': 1, 'public': 1, 'friend': 2, 'do': 1, 'return': 1, 'goto': 1, 'auto': 1, 'void': 2, 'enum': 1, 'else': 1, 'break': 1, 'new': 1, 'extern': 1, 'using': 1, 'true': 1, 'class': 1, 'asm': 1, 'case': 1, 'typeid': 1, 'short': 1, 'reinterpret_cast': 2, 'default': 1, 'double': 1, 'register': 1, 'explicit': 1, 'signed': 1, 'typename': 1, 'try': 1, 'this': 1, 'switch': 1, 'continue': 1, 'wchar_t': 1, 'inline': 1, 'delete': 1}
  },
  modes: [
    hljs.C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    hljs.C_NUMBER_MODE,
    hljs.QUOTE_STRING_MODE,
    hljs.BACKSLASH_ESCAPE,
    {
      className: 'string',
      begin: '\'', end: '[^\\\\]\'',
      illegal: '[^\\\\][^\']'
    },
    {
      className: 'preprocessor',
      begin: '#', end: '$'
    }
  ]
};//cpp

/*

Java definition (с) Vsevolod Solovyov <vsevolod.solovyov@gmail.com>

*/
hljs.LANGUAGES.java  = {
  defaultMode: {
    lexems: [hljs.UNDERSCORE_IDENT_RE],
    contains: ['comment', 'string', 'class', 'number', 'javadoc', 'annotation'],
    keywords: {'false': 1, 'synchronized': 1, 'int': 1, 'abstract': 1, 'float': 1, 'private': 1, 'char': 1, 'interface': 1, 'boolean': 1, 'static': 1, 'null': 1, 'if': 1, 'const': 1, 'for': 1, 'true': 1, 'while': 1, 'long': 1, 'throw': 1, 'strictfp': 1, 'finally': 1, 'protected': 1, 'extends': 1, 'import': 1, 'native': 1, 'final': 1, 'implements': 1, 'return': 1, 'void': 1, 'enum': 1, 'else': 1, 'break': 1, 'transient': 1, 'new': 1, 'catch': 1, 'instanceof': 1, 'byte': 1, 'super': 1, 'class': 1, 'volatile': 1, 'case': 1, 'assert': 1, 'short': 1, 'package': 1, 'default': 1, 'double': 1, 'public': 1, 'try': 1, 'this': 1, 'switch': 1, 'continue': 1, 'throws': 1}
  },
  modes: [
    {
      className: 'class',
      lexems: [hljs.UNDERSCORE_IDENT_RE],
      begin: '(class |interface )', end: '{',
      illegal: ':',
      keywords: {'class': 1, 'interface': 1},
      contains: ['inheritance', 'title']
    },
    {
      className: 'inheritance',
      begin: '(implements|extends)', end: '^',
      lexems: [hljs.IDENT_RE],
      keywords: {'extends': 1, 'implements': 1},
      relevance: 10
    },
    {
      className: 'title',
      begin: hljs.UNDERSCORE_IDENT_RE, end: '^'
    },
    {
      className: 'params',
      begin: '\\(', end: '\\)',
      contains: ['string', 'annotation']
    },
    hljs.C_NUMBER_MODE,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    hljs.BACKSLASH_ESCAPE,
    hljs.C_LINE_COMMENT_MODE,
    {
      className: 'javadoc',
      begin: '/\\*\\*', end: '\\*/',
      relevance: 10
    },
    hljs.C_BLOCK_COMMENT_MODE,
    {
      className: 'annotation',
      begin: '@[A-Za-z]+', end: '^'
    }
  ]
};//java

hljs.DELPHI_KEYWORDS = {'and': 1, 'safecall': 1, 'cdecl': 1, 'then': 1, 'string': 1, 'exports': 1, 'library': 1, 'not': 1, 'pascal': 1, 'set': 1, 'virtual': 1, 'file': 1, 'in': 1, 'array': 1, 'label': 1, 'packed': 1, 'end.': 1, 'index': 1, 'while': 1, 'const': 1, 'raise': 1, 'for': 1, 'to': 1, 'implementation': 1, 'with': 1, 'except': 1, 'overload': 1, 'destructor': 1, 'downto': 1, 'finally': 1, 'program': 1, 'exit': 1, 'unit': 1, 'inherited': 1, 'override': 1, 'if': 1, 'type': 1, 'until': 1, 'function': 1, 'do': 1, 'begin': 1, 'repeat': 1, 'goto': 1, 'nil': 1, 'far': 1, 'initialization': 1, 'object': 1, 'else': 1, 'var': 1, 'uses': 1, 'external': 1, 'resourcestring': 1, 'interface': 1, 'end': 1, 'finalization': 1, 'class': 1, 'asm': 1, 'mod': 1, 'case': 1, 'on': 1, 'shr': 1, 'shl': 1, 'of': 1, 'register': 1, 'xorwrite': 1, 'threadvar': 1, 'try': 1, 'record': 1, 'near': 1, 'stored': 1, 'constructor': 1, 'stdcall': 1, 'inline': 1, 'div': 1, 'out': 1, 'or': 1, 'procedure': 1};
hljs.DELPHI_CLASS_KEYWORDS = {'safecall': 1, 'stdcall': 1, 'pascal': 1, 'stored': 1, 'const': 1, 'implementation': 1, 'finalization': 1, 'except': 1, 'to': 1, 'finally': 1, 'program': 1, 'inherited': 1, 'override': 1, 'then': 1, 'exports': 1, 'string': 1, 'read': 1, 'not': 1, 'mod': 1, 'shr': 1, 'try': 1, 'div': 1, 'shl': 1, 'set': 1, 'library': 1, 'message': 1, 'packed': 1, 'index': 1, 'for': 1, 'near': 1, 'overload': 1, 'label': 1, 'downto': 1, 'exit': 1, 'public': 1, 'goto': 1, 'interface': 1, 'asm': 1, 'on': 1, 'of': 1, 'constructor': 1, 'or': 1, 'private': 1, 'array': 1, 'unit': 1, 'raise': 1, 'destructor': 1, 'var': 1, 'type': 1, 'until': 1, 'function': 1, 'else': 1, 'external': 1, 'with': 1, 'case': 1, 'default': 1, 'record': 1, 'while': 1, 'protected': 1, 'property': 1, 'procedure': 1, 'published': 1, 'and': 1, 'cdecl': 1, 'do': 1, 'threadvar': 1, 'file': 1, 'in': 1, 'if': 1, 'end': 1, 'virtual': 1, 'write': 1, 'far': 1, 'out': 1, 'begin': 1, 'repeat': 1, 'nil': 1, 'initialization': 1, 'object': 1, 'uses': 1, 'resourcestring': 1, 'class': 1, 'register': 1, 'xorwrite': 1, 'inline': 1};

hljs.LANGUAGES.delphi = {
  defaultMode: {
    lexems: [hljs.IDENT_RE],
    illegal: '("|\\$[G-Zg-z]|\\/\\*|</)',
    contains: ['comment', 'string', 'number', 'function', 'class'],
    keywords: hljs.DELPHI_KEYWORDS
  },
  case_insensitive: true,
  modes: [
    {
      className: 'comment',
      begin: '{', end: '}'
    },
    {
      className: 'comment',
      begin: '\\(\\*', end: '\\*\\)',
      relevance: 10
    },
    hljs.C_LINE_COMMENT_MODE,
    {
      className: 'number',
      begin: hljs.NUMBER_RE, end: '^',
      relevance: 0
    },
    {
      className: 'string',
      begin: '\'', end: '\'',
      contains: ['quote'],
      relevance: 0
    },
    {
      className: 'string',
      begin: '(#\\d+)+', end: '^'
    },
    {
      className: 'quote',
      begin: '\'\'', end: '^'
    },
    {
      className: 'function',
      begin: 'function', end: '[:;]',
      lexems: [hljs.IDENT_RE],
      keywords: {'function': 1},
      contains: ['title', 'params', 'comment'],
      relevance: 0
    },
    {
      className: 'function',
      begin: '(procedure|constructor|destructor)', end: ';',
      lexems: [hljs.IDENT_RE],
      keywords: {'constructor': 1, 'destructor': 1, 'procedure': 1},
      contains: ['title', 'params', 'comment'],
      relevance: 10
    },
    {
      className: 'title',
      begin: hljs.IDENT_RE, end: '^'
    },
    {
      className: 'params',
      begin: '\\(', end: '\\)',
      lexems: [hljs.IDENT_RE],
      keywords: hljs.DELPHI_KEYWORDS,
      contains: ['string']
    },
    {
      className: 'class',
      begin: '=\\s*class', end: 'end;',
      lexems: [hljs.IDENT_RE],
      keywords: hljs.DELPHI_CLASS_KEYWORDS,
      contains: ['string', 'comment', 'function']
    }
  ]
};//delphi<commit_msg>Фикс javadoc и новый javadoctag<commit_after>hljs.LANGUAGES.cpp = {
  defaultMode: {
    lexems: [hljs.UNDERSCORE_IDENT_RE],
    illegal: '</',
    contains: ['comment', 'string', 'number', 'preprocessor'],
    keywords: {'false': 1, 'int': 1, 'float': 1, 'while': 1, 'private': 1, 'char': 1, 'catch': 1, 'export': 1, 'virtual': 1, 'operator': 2, 'sizeof': 2, 'dynamic_cast': 2, 'typedef': 2, 'const_cast': 2, 'const': 1, 'struct': 1, 'for': 1, 'static_cast': 2, 'union': 1, 'namespace': 1, 'unsigned': 1, 'long': 1, 'throw': 1, 'volatile': 2, 'static': 1, 'protected': 1, 'bool': 1, 'template': 1, 'mutable': 1, 'if': 1, 'public': 1, 'friend': 2, 'do': 1, 'return': 1, 'goto': 1, 'auto': 1, 'void': 2, 'enum': 1, 'else': 1, 'break': 1, 'new': 1, 'extern': 1, 'using': 1, 'true': 1, 'class': 1, 'asm': 1, 'case': 1, 'typeid': 1, 'short': 1, 'reinterpret_cast': 2, 'default': 1, 'double': 1, 'register': 1, 'explicit': 1, 'signed': 1, 'typename': 1, 'try': 1, 'this': 1, 'switch': 1, 'continue': 1, 'wchar_t': 1, 'inline': 1, 'delete': 1}
  },
  modes: [
    hljs.C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    hljs.C_NUMBER_MODE,
    hljs.QUOTE_STRING_MODE,
    hljs.BACKSLASH_ESCAPE,
    {
      className: 'string',
      begin: '\'', end: '[^\\\\]\'',
      illegal: '[^\\\\][^\']'
    },
    {
      className: 'preprocessor',
      begin: '#', end: '$'
    }
  ]
};//cpp

/*

Java definition (с) Vsevolod Solovyov <vsevolod.solovyov@gmail.com>

*/
hljs.LANGUAGES.java  = {
  defaultMode: {
    lexems: [hljs.UNDERSCORE_IDENT_RE],
    contains: ['javadoc', 'comment', 'string', 'class', 'number', 'annotation'],
    keywords: {'false': 1, 'synchronized': 1, 'int': 1, 'abstract': 1, 'float': 1, 'private': 1, 'char': 1, 'interface': 1, 'boolean': 1, 'static': 1, 'null': 1, 'if': 1, 'const': 1, 'for': 1, 'true': 1, 'while': 1, 'long': 1, 'throw': 1, 'strictfp': 1, 'finally': 1, 'protected': 1, 'extends': 1, 'import': 1, 'native': 1, 'final': 1, 'implements': 1, 'return': 1, 'void': 1, 'enum': 1, 'else': 1, 'break': 1, 'transient': 1, 'new': 1, 'catch': 1, 'instanceof': 1, 'byte': 1, 'super': 1, 'class': 1, 'volatile': 1, 'case': 1, 'assert': 1, 'short': 1, 'package': 1, 'default': 1, 'double': 1, 'public': 1, 'try': 1, 'this': 1, 'switch': 1, 'continue': 1, 'throws': 1}
  },
  modes: [
    {
      className: 'class',
      lexems: [hljs.UNDERSCORE_IDENT_RE],
      begin: '(class |interface )', end: '{',
      illegal: ':',
      keywords: {'class': 1, 'interface': 1},
      contains: ['inheritance', 'title']
    },
    {
      className: 'inheritance',
      begin: '(implements|extends)', end: '^',
      lexems: [hljs.IDENT_RE],
      keywords: {'extends': 1, 'implements': 1},
      relevance: 10
    },
    {
      className: 'title',
      begin: hljs.UNDERSCORE_IDENT_RE, end: '^'
    },
    {
      className: 'params',
      begin: '\\(', end: '\\)',
      contains: ['string', 'annotation']
    },
    hljs.C_NUMBER_MODE,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    hljs.BACKSLASH_ESCAPE,
    hljs.C_LINE_COMMENT_MODE,
    {
      className: 'javadoc',
      begin: '/\\*\\*', end: '\\*/',
      contains: ['javadoctag'],
      relevance: 10
    },
    {
      className: 'javadoctag',
      begin: '@[A-Za-z]+', end: '^'
    },
    hljs.C_BLOCK_COMMENT_MODE,
    {
      className: 'annotation',
      begin: '@[A-Za-z]+', end: '^'
    }
  ]
};//java

hljs.DELPHI_KEYWORDS = {'and': 1, 'safecall': 1, 'cdecl': 1, 'then': 1, 'string': 1, 'exports': 1, 'library': 1, 'not': 1, 'pascal': 1, 'set': 1, 'virtual': 1, 'file': 1, 'in': 1, 'array': 1, 'label': 1, 'packed': 1, 'end.': 1, 'index': 1, 'while': 1, 'const': 1, 'raise': 1, 'for': 1, 'to': 1, 'implementation': 1, 'with': 1, 'except': 1, 'overload': 1, 'destructor': 1, 'downto': 1, 'finally': 1, 'program': 1, 'exit': 1, 'unit': 1, 'inherited': 1, 'override': 1, 'if': 1, 'type': 1, 'until': 1, 'function': 1, 'do': 1, 'begin': 1, 'repeat': 1, 'goto': 1, 'nil': 1, 'far': 1, 'initialization': 1, 'object': 1, 'else': 1, 'var': 1, 'uses': 1, 'external': 1, 'resourcestring': 1, 'interface': 1, 'end': 1, 'finalization': 1, 'class': 1, 'asm': 1, 'mod': 1, 'case': 1, 'on': 1, 'shr': 1, 'shl': 1, 'of': 1, 'register': 1, 'xorwrite': 1, 'threadvar': 1, 'try': 1, 'record': 1, 'near': 1, 'stored': 1, 'constructor': 1, 'stdcall': 1, 'inline': 1, 'div': 1, 'out': 1, 'or': 1, 'procedure': 1};
hljs.DELPHI_CLASS_KEYWORDS = {'safecall': 1, 'stdcall': 1, 'pascal': 1, 'stored': 1, 'const': 1, 'implementation': 1, 'finalization': 1, 'except': 1, 'to': 1, 'finally': 1, 'program': 1, 'inherited': 1, 'override': 1, 'then': 1, 'exports': 1, 'string': 1, 'read': 1, 'not': 1, 'mod': 1, 'shr': 1, 'try': 1, 'div': 1, 'shl': 1, 'set': 1, 'library': 1, 'message': 1, 'packed': 1, 'index': 1, 'for': 1, 'near': 1, 'overload': 1, 'label': 1, 'downto': 1, 'exit': 1, 'public': 1, 'goto': 1, 'interface': 1, 'asm': 1, 'on': 1, 'of': 1, 'constructor': 1, 'or': 1, 'private': 1, 'array': 1, 'unit': 1, 'raise': 1, 'destructor': 1, 'var': 1, 'type': 1, 'until': 1, 'function': 1, 'else': 1, 'external': 1, 'with': 1, 'case': 1, 'default': 1, 'record': 1, 'while': 1, 'protected': 1, 'property': 1, 'procedure': 1, 'published': 1, 'and': 1, 'cdecl': 1, 'do': 1, 'threadvar': 1, 'file': 1, 'in': 1, 'if': 1, 'end': 1, 'virtual': 1, 'write': 1, 'far': 1, 'out': 1, 'begin': 1, 'repeat': 1, 'nil': 1, 'initialization': 1, 'object': 1, 'uses': 1, 'resourcestring': 1, 'class': 1, 'register': 1, 'xorwrite': 1, 'inline': 1};

hljs.LANGUAGES.delphi = {
  defaultMode: {
    lexems: [hljs.IDENT_RE],
    illegal: '("|\\$[G-Zg-z]|\\/\\*|</)',
    contains: ['comment', 'string', 'number', 'function', 'class'],
    keywords: hljs.DELPHI_KEYWORDS
  },
  case_insensitive: true,
  modes: [
    {
      className: 'comment',
      begin: '{', end: '}'
    },
    {
      className: 'comment',
      begin: '\\(\\*', end: '\\*\\)',
      relevance: 10
    },
    hljs.C_LINE_COMMENT_MODE,
    {
      className: 'number',
      begin: hljs.NUMBER_RE, end: '^',
      relevance: 0
    },
    {
      className: 'string',
      begin: '\'', end: '\'',
      contains: ['quote'],
      relevance: 0
    },
    {
      className: 'string',
      begin: '(#\\d+)+', end: '^'
    },
    {
      className: 'quote',
      begin: '\'\'', end: '^'
    },
    {
      className: 'function',
      begin: 'function', end: '[:;]',
      lexems: [hljs.IDENT_RE],
      keywords: {'function': 1},
      contains: ['title', 'params', 'comment'],
      relevance: 0
    },
    {
      className: 'function',
      begin: '(procedure|constructor|destructor)', end: ';',
      lexems: [hljs.IDENT_RE],
      keywords: {'constructor': 1, 'destructor': 1, 'procedure': 1},
      contains: ['title', 'params', 'comment'],
      relevance: 10
    },
    {
      className: 'title',
      begin: hljs.IDENT_RE, end: '^'
    },
    {
      className: 'params',
      begin: '\\(', end: '\\)',
      lexems: [hljs.IDENT_RE],
      keywords: hljs.DELPHI_KEYWORDS,
      contains: ['string']
    },
    {
      className: 'class',
      begin: '=\\s*class', end: 'end;',
      lexems: [hljs.IDENT_RE],
      keywords: hljs.DELPHI_CLASS_KEYWORDS,
      contains: ['string', 'comment', 'function']
    }
  ]
};//delphi<|endoftext|>


<commit_before>import Contextualable from './contextualable'
import Input from './input'

export default {
  mixins: [Contextualable, Input],

  model: {
    prop: 'inputValue',
    event: 'change'
  },

  props: {
    inputValue: [Array, Boolean, String],
    falseValue: String,
    trueValue: String
  },

  computed: {
    isActive () {
      if ((Array.isArray(this.inputValue))
      ) {
        return this.inputValue.indexOf(this.value) !== -1
      }

      if (!this.trueValue || !this.falseValue) {
        return this.value
          ? this.value === this.inputValue
          : Boolean(this.inputValue)
      }

      return this.inputValue === this.trueValue
    }
  },

  watch: {
    indeterminate (val) {
      this.inputDeterminate = val
    }
  },

  methods: {
    genLabel () {
      return this.$createElement('label', { on: { click: this.toggle }}, this.label)
    },
    toggle () {
      if (this.disabled) {
        return
      }

      let input = this.inputValue.slice()
      if (Array.isArray(input)) {
        const i = input.indexOf(this.value)

        if (i === -1) {
          input.push(this.value)
        } else {
          input.splice(i, 1)
        }
      } else if (this.trueValue || this.falseValue) {
        input = input === this.trueValue ? this.falseValue : this.trueValue
      } else if (this.value) {
        input = this.value === this.inputValue
          ? null
          : this.value
      } else {
        input = !input
      }

      this.$emit('change', input)
    }
  }
}
<commit_msg>Fixed bug introduced by 4286891<commit_after>import Contextualable from './contextualable'
import Input from './input'

export default {
  mixins: [Contextualable, Input],

  model: {
    prop: 'inputValue',
    event: 'change'
  },

  props: {
    inputValue: [Array, Boolean, String],
    falseValue: String,
    trueValue: String
  },

  computed: {
    isActive () {
      if ((Array.isArray(this.inputValue))
      ) {
        return this.inputValue.indexOf(this.value) !== -1
      }

      if (!this.trueValue || !this.falseValue) {
        return this.value
          ? this.value === this.inputValue
          : Boolean(this.inputValue)
      }

      return this.inputValue === this.trueValue
    }
  },

  watch: {
    indeterminate (val) {
      this.inputDeterminate = val
    }
  },

  methods: {
    genLabel () {
      return this.$createElement('label', { on: { click: this.toggle }}, this.label)
    },
    toggle () {
      if (this.disabled) {
        return
      }

      let input = this.inputValue
      if (Array.isArray(input)) {
        input = input.slice()
        const i = input.indexOf(this.value)

        if (i === -1) {
          input.push(this.value)
        } else {
          input.splice(i, 1)
        }
      } else if (this.trueValue || this.falseValue) {
        input = input === this.trueValue ? this.falseValue : this.trueValue
      } else if (this.value) {
        input = this.value === this.inputValue
          ? null
          : this.value
      } else {
        input = !input
      }

      this.$emit('change', input)
    }
  }
}
<|endoftext|>