<commit_before>var extend, getCookie, host, request, setCookie,
  __slice = [].slice;

host = function(url) {
  var parent, parser;
  parent = document.createElement('div');
  parent.innerHTML = "x";
  parser = parent.firstChild;
  return "" + parser.host;
};

request = function(url, params, callback) {
  var image, k, v;
  if (params == null) {
    params = {};
  }
  params.i = new Date().getTime();
  params = ((function() {
    var _results;
    _results = [];
    for (k in params) {
      v = params[k];
      _results.push("" + k + "=" + (encodeURIComponent(v)));
    }
    return _results;
  })()).join('&');
  image = new Image;
  if (callback) {
    image.onload = callback;
  }
  image.src = "" + url + "?" + params;
  return true;
};

setCookie = function(name, value, options) {
  var cookie, expires;
  if (options == null) {
    options = {};
  }
  if (options.expires === true) {
    options.expires = -1;
  }
  if (typeof options.expires === 'number') {
    expires = new Date;
    expires.setTime(expires.getTime() + options.expires * 24 * 60 * 60 * 1000);
    options.expires = expires;
  }
  value = (value + '').replace(/[^!#-+\--:<-\[\]-~]/g, encodeURIComponent);
  cookie = encodeURIComponent(name) + '=' + value;
  if (options.expires) {
    cookie += ';expires=' + options.expires.toGMTString();
  }
  if (options.path) {
    cookie += ';path=' + options.path;
  }
  if (options.domain) {
    cookie += ';domain=' + options.domain;
  }
  return document.cookie = cookie;
};

getCookie = function(name) {
  var cookie, cookies, index, key, value, _i, _len;
  cookies = document.cookie.split('; ');
  for (_i = 0, _len = cookies.length; _i < _len; _i++) {
    cookie = cookies[_i];
    index = cookie.indexOf('=');
    key = decodeURIComponent(cookie.substr(0, index));
    value = decodeURIComponent(cookie.substr(index + 1));
    if (key === name) {
      return value;
    }
  }
  return null;
};

extend = function() {
  var args, key, source, target, value, _i, _len;
  target = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
  for (_i = 0, _len = args.length; _i < _len; _i++) {
    source = args[_i];
    for (key in source) {
      value = source[key];
      if (value != null) {
        target[key] = value;
      }
    }
  }
  return target;
};

this.Abba = (function() {
  Abba.prototype.endpoint = 'http://localhost:4567';

  Abba.prototype.defaults = {
    path: '/',
    expires: 600
  };

  function Abba(name, options) {
    if (options == null) {
      options = {};
    }
    if (!name) {
      throw new Error('Experiment name required');
    }
    if (!(this instanceof Abba)) {
      return new Abba(name, options);
    }
    this.name = name;
    this.options = options;
    this.variants = [];
    this.endpoint = this.options.endpoint || this.constructor.endpoint;
  }

  Abba.prototype.variant = function(name, options, callback) {
    if (typeof name !== 'string') {
      throw new Error('Variant name required');
    }
    if (typeof options !== 'object') {
      callback = options;
      options = {};
    }
    options.name = name;
    options.callback = callback;
    if (options.weight == null) {
      options.weight = 1;
    }
    this.variants.push(options);
    return this;
  };

  Abba.prototype.control = function(name, options, callback) {
    if (name == null) {
      name = 'Control';
    }
    if (typeof options !== 'object') {
      callback = options;
      options = {};
    }
    options.control = true;
    return this.variant(name, options, callback);
  };

  Abba.prototype["continue"] = function() {
    var variant;
    if (variant = this.getPreviousVariant()) {
      this.useVariant(variant);
    }
    return this;
  };

  Abba.prototype.start = function(name, options) {
    var randomWeight, totalWeight, v, variant, variantWeight, _i, _j, _len, _len1, _ref, _ref1;
    if (options == null) {
      options = {};
    }
    if (variant = this.getPreviousVariant()) {
      this.useVariant(variant);
      return this;
    }
    if (name != null) {
      variant = this.getVariantForName(name);
      variant || (variant = {
        name: name,
        control: options.control
      });
    } else {
      totalWeight = 0;
      _ref = this.variants;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        v = _ref[_i];
        totalWeight += v.weight;
      }
      randomWeight = Math.random() * totalWeight;
      variantWeight = 0;
      _ref1 = this.variants;
      for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
        variant = _ref1[_j];
        variantWeight += variant.weight;
        if (variantWeight >= randomWeight) {
          break;
        }
      }
    }
    if (!variant) {
      throw new Error('No variants added');
    }
    this.recordStart(variant);
    this.useVariant(variant);
    return this;
  };

  Abba.prototype.complete = function(name) {
    name || (name = this.getVariantCookie());
    if (!name) {
      return this;
    }
    if (this.hasPersistCompleteCookie()) {
      return this;
    }
    if (this.options.persist) {
      this.setPersistCompleteCookie();
    } else {
      this.reset();
    }
    this.recordComplete(name);
    return this;
  };

  Abba.prototype.reset = function() {
    this.removeVariantCookie();
    this.removePersistCompleteCookie();
    this.result = null;
    return this;
  };

  Abba.prototype.getVariantForName = function(name) {
    var v;
    return ((function() {
      var _i, _len, _ref, _results;
      _ref = this.variants;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        v = _ref[_i];
        if (v.name === name) {
          _results.push(v);
        }
      }
      return _results;
    }).call(this))[0];
  };

  Abba.prototype.useVariant = function(variant) {
    if (variant != null) {
      if (typeof variant.callback === "function") {
        variant.callback();
      }
    }
    return this.chosen = variant;
  };

  Abba.prototype.recordStart = function(variant) {
    request("" + this.endpoint + "/start", {
      experiment: this.name,
      variant: variant.name,
      control: variant.control || false
    });
    return this.setVariantCookie(variant.name);
  };

  Abba.prototype.recordComplete = function(name) {
    return request("" + this.endpoint + "/complete", {
      experiment: this.name,
      variant: name
    });
  };

  Abba.prototype.getPreviousVariant = function() {
    var name;
    if (name = this.getVariantCookie()) {
      return this.getVariantForName(name);
    }
  };

  Abba.prototype.getVariantCookie = function() {
    return this.getCookie("abbaVariant_" + this.name);
  };

  Abba.prototype.setVariantCookie = function(value) {
    return this.setCookie("abbaVariant_" + this.name, value, {
      expires: this.options.expires
    });
  };

  Abba.prototype.removeVariantCookie = function() {
    return this.setCookie("abbaVariant_" + this.name, '', {
      expires: true
    });
  };

  Abba.prototype.setPersistCompleteCookie = function() {
    return this.setCookie("abbaPersistComplete_" + this.name, '1', {
      expires: this.options.expires
    });
  };

  Abba.prototype.hasPersistCompleteCookie = function() {
    return !!this.getCookie("abbaPersistComplete_" + this.name);
  };

  Abba.prototype.removePersistCompleteCookie = function() {
    return this.setCookie("abbaPersistComplete_" + this.name, '', {
      expires: true
    });
  };

  Abba.prototype.setCookie = function(name, value, options) {
    if (options == null) {
      options = {};
    }
    return setCookie(name, value, extend({}, this.defaults, options));
  };

  Abba.prototype.getCookie = function(name, options) {
    if (options == null) {
      options = {};
    }
    return getCookie(name, extend({}, this.defaults, options));
  };

  return Abba;

})();

(function() {
  var script, scripts;
  scripts = document.getElementsByTagName('script');
  scripts = (function() {
    var _i, _len, _results;
    _results = [];
    for (_i = 0, _len = scripts.length; _i < _len; _i++) {
      script = scripts[_i];
      if (/\/abba\.js$/.test(script.src)) {
        _results.push(script.src);
      }
    }
    return _results;
  })();
  if (scripts[0]) {
    return Abba.endpoint = "//" + (host(scripts[0]));
  }
})();
<commit_msg>Progress on client<commit_after>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['exports'], function (exports) {
      root.Abcd = factory(root, exports);
    });
  } else if (typeof exports !== 'undefined') {
    factory(root, exports);
  } else {
    root.Abcd = factory(root, {});
  }
}(this, function (root, Abcd) {
  // options.persists
  // options.endpoint
  var Experiment = function (name, options) {
    if (typeof name !== 'string' || name.length === 0) {
      throw new Error('No name specified for event');
    }
    this.name = name;
    this.options = options || {};
    this.variants = [];
  };

  var _Variant = function (name, options, callback) {
    if (typeof name !== 'string' || name.length === 0) {
      throw new Error('No name specified for variant');
    }
    this.name = name;
    this.options = options || {};
    this.callback = callback || function () {};
    this.options.weight = this.options.weight || 1;
  };

  Experiment.prototype.addVariant = function (name, options, callback) {
    this.variants.push(new _Variant(name, options, callback));
    return this;
  };

  // Experiment.prototype.continue = function () {
  // };

  Experiment.prototype.start = function (name) {
    if (name) {
      request = new XMLHttpRequest();
      request.open('GET', '/my/url', true);

      request.onload = function() {
        if (request.status >= 200 && request.status < 400){
          // Success!
          resp = request.responseText;
        } else {
          // We reached our target server, but it returned an error

        }
      };

      request.onerror = function() {
        // There was a connection error of some sort
      };

      request.send();
    } else {
      var absoluteWeight = 0;
      for (var i = 0; i < this.variant.length; i++) {
        absoluteWeight
      }

    }
  };

  Experiment.prototype.complete = function () {

  };

  Experiment.prototype.reset = function () {

  };

  Experiment.prototype.continue = function () {

  };
});
<|endoftext|>


<commit_before>var Card = (function() {
    function Card(card_name, variable, expr, parameters) {
        this.card_name = card_name;

        if (typeof this.card_name === "undefined") {
            return;
        }
        this.variable = variable;
        this.expr = expr;
        this.parameters = parameters;
        this.parameterValues = {};
    }

    Card.prototype.parameter = function(key, val) {
        if (val != null) {
            this.parameterValues[key] = val;
        }
        return this.parameterValues[key];
    };

    // TODO use Deferred to replace parameters
    Card.prototype.evaluate = function(finished, error) {
        if (finished == null) {
            finished = $.proxy(this.evaluateFinished, this);
        }
        if (error == null) {
            error = $.proxy(this.evaluateError, this);
        }
        if (typeof this.card_name !== "undefined") {
            var url = '/card/' + this.card_name;
            var parms = {
                variable: this.variable,
                expression: this.expr
            };
            $.extend(parms, this.parameterValues);
            var deferred = $.getJSON(url, parms, finished);
            deferred.error(error);
            return deferred;
        }
        var result = new $.Deferred();
        result.reject();
        return result;
    };

    Card.prototype.evaluateFinished = function(data) {
        if (typeof data.output !== "undefined") {
            this.result.html(data.output);

            MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
        }
        else {
            var error = $("
")
                .addClass('cell_output_plain')
                .html(data.error);
            this.output.append(error);
            this.element.addClass('result_card_error');
        }
        this.output.children('.loader').fadeOut(500);
    };

    Card.prototype.evaluateError = function() {
        this.output.append($("
").html("Error occurred"));
        this.element.addClass('result_card_error');
        this.output.children('.loader').fadeOut(500);
    };

    Card.prototype.addOptionsSection = function() {
        this._optionsSection = $("
").addClass('card_options');
        this.output.append(this._optionsSection);
    };

    Card.prototype.addToOptionsSection = function(el) {
        this._optionsSection.append(el);
    };

    Card.prototype.addOptionsButton = function(text) {
        var button = $('<button/>').addClass('card_options_toggle').html(text);
        this.addToOptionsSection(button);
        return button;
    };

    Card.prototype.initSpecificFunctionality = function() {
        if (typeof this.card_name !== "undefined") {
            if (this.parameters.indexOf('digits') !== -1) {
                this.addOptionsSection();
                var moreDigits = this.addOptionsButton('More Digits');

                this.parameter('digits', 15);
                moreDigits.click($.proxy(function() {
                    var delta = 10;
                    if (this.parameter('digits') <= 15) {
                        delta = 35;
                    }
                    this.parameter('digits', this.parameter('digits') + delta);
                    this.evaluate();
                }, card));
            }

            if (this.card_name === 'integral' || this.card_name === 'diff') {
                this.addOptionsSection();
                var seeSteps = this.addOptionsButton('See Steps');

                if (this.card_name === 'integral') {
                    var title = "Integral steps:";
                    var card_name = 'intsteps';
                }
                else if (this.card_name === 'diff') {
                    var title = "Derivative steps:";
                    var card_name = 'diffsteps';
                }

                seeSteps.click($.proxy(function() {
                    new_card = this.cloneEl();
                    new_card.find('.card_title').html(title);
                    new_card.find('.cell_output') .data('card-name', card_name);
                    new_card.hide();

                    this.element.after(new_card);
                    Card.loadNewCard(new_card);
                    seeSteps.remove();
                }, this));
            }

            else if (this.card_name === 'graph') {
                this.addOptionsSection();
            }
        }
        else {
            this.element.addClass('no_actions');
        }
    };

    Card.prototype.setElement = function(el) {
        this.element = el;
        this.output = el.find('.cell_output');
        this.result = $("
");
        this.output.append(this.result);

        if (typeof this.card_name !== "undefined") {
            this.element.append($("
").append([
                $("
Simplify
")
            ]).addClass('card_actions'));
        }
    };

    Card.prototype.clone = function() {
        var new_card = $.extend(true, {}, this);
        new_card.setElement(this.cloneEl());
        return new_card;
    };

    Card.prototype.cloneEl = function() {
        var el = this.element.clone();
        el.find('.cell_output').html("");
        el.find('.card_options').remove();
        el.find('.card_actions').remove();
        return el;
    };

    Card.fromCardEl = function(el) {
        var output = el.find('.cell_output');
        var card_name = output.data('card-name');
        var variable = encodeURIComponent(output.data('variable'));
        var expr = encodeURIComponent(output.data('expr'));
        var parameters = output.data('parameters');
        var card = new Card(card_name, variable, expr, parameters);
        card.setElement(el);
        return card;
    };

    Card.loadNewCard = function(el) {
        var card = Card.fromCardEl(el);
        var loader = $("
").addClass('loader');
        el.before(loader);
        card.evaluate().always(function() {
            el.slideDown(500);
            loader.slideUp(200);
        });
        return card;
    };

    return Card;
})();
<commit_msg>Fix show steps button for integral card<commit_after>var Card = (function() {
    function Card(card_name, variable, expr, parameters) {
        this.card_name = card_name;

        if (typeof this.card_name === "undefined") {
            return;
        }
        this.variable = variable;
        this.expr = expr;
        this.parameters = parameters;
        this.parameterValues = {};
    }

    Card.prototype.parameter = function(key, val) {
        if (val != null) {
            this.parameterValues[key] = val;
        }
        return this.parameterValues[key];
    };

    // TODO use Deferred to replace parameters
    Card.prototype.evaluate = function(finished, error) {
        if (finished == null) {
            finished = $.proxy(this.evaluateFinished, this);
        }
        if (error == null) {
            error = $.proxy(this.evaluateError, this);
        }
        if (typeof this.card_name !== "undefined") {
            var url = '/card/' + this.card_name;
            var parms = {
                variable: this.variable,
                expression: this.expr
            };
            $.extend(parms, this.parameterValues);
            var deferred = $.getJSON(url, parms, finished);
            deferred.error(error);
            return deferred;
        }
        var result = new $.Deferred();
        result.reject();
        return result;
    };

    Card.prototype.evaluateFinished = function(data) {
        if (typeof data.output !== "undefined") {
            this.result.html(data.output);

            MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
        }
        else {
            var error = $("
")
                .addClass('cell_output_plain')
                .html(data.error);
            this.output.append(error);
            this.element.addClass('result_card_error');
        }
        this.output.children('.loader').fadeOut(500);
    };

    Card.prototype.evaluateError = function() {
        this.output.append($("
").html("Error occurred"));
        this.element.addClass('result_card_error');
        this.output.children('.loader').fadeOut(500);
    };

    Card.prototype.addOptionsSection = function() {
        this._optionsSection = $("
").addClass('card_options');
        this.output.append(this._optionsSection);
    };

    Card.prototype.addToOptionsSection = function(el) {
        this._optionsSection.append(el);
    };

    Card.prototype.addOptionsButton = function(text) {
        var button = $('<button/>').addClass('card_options_toggle').html(text);
        this.addToOptionsSection(button);
        return button;
    };

    Card.prototype.initSpecificFunctionality = function() {
        if (typeof this.card_name !== "undefined") {
            if (this.parameters.indexOf('digits') !== -1) {
                this.addOptionsSection();
                var moreDigits = this.addOptionsButton('More Digits');

                this.parameter('digits', 15);
                moreDigits.click($.proxy(function() {
                    var delta = 10;
                    if (this.parameter('digits') <= 15) {
                        delta = 35;
                    }
                    this.parameter('digits', this.parameter('digits') + delta);
                    this.evaluate();
                }, card));
            }

            if (this.card_name === 'integral_alternate' || this.card_name === 'diff') {
                this.addOptionsSection();
                var seeSteps = this.addOptionsButton('See Steps');

                if (this.card_name === 'integral_alternate') {
                    var title = "Integral steps:";
                    var card_name = 'intsteps';
                }
                else if (this.card_name === 'diff') {
                    var title = "Derivative steps:";
                    var card_name = 'diffsteps';
                }

                seeSteps.click($.proxy(function() {
                    new_card = this.cloneEl();
                    new_card.find('.card_title').html(title);
                    new_card.find('.cell_output') .data('card-name', card_name);
                    new_card.hide();

                    this.element.after(new_card);
                    Card.loadNewCard(new_card);
                    seeSteps.remove();
                }, this));
            }

            else if (this.card_name === 'graph') {
                this.addOptionsSection();
            }
        }
        else {
            this.element.addClass('no_actions');
        }
    };

    Card.prototype.setElement = function(el) {
        this.element = el;
        this.output = el.find('.cell_output');
        this.result = $("
");
        this.output.append(this.result);

        if (typeof this.card_name !== "undefined") {
            this.element.append($("
").append([
                $("
Simplify
")
            ]).addClass('card_actions'));
        }
    };

    Card.prototype.clone = function() {
        var new_card = $.extend(true, {}, this);
        new_card.setElement(this.cloneEl());
        return new_card;
    };

    Card.prototype.cloneEl = function() {
        var el = this.element.clone();
        el.find('.cell_output').html("");
        el.find('.card_options').remove();
        el.find('.card_actions').remove();
        return el;
    };

    Card.fromCardEl = function(el) {
        var output = el.find('.cell_output');
        var card_name = output.data('card-name');
        var variable = encodeURIComponent(output.data('variable'));
        var expr = encodeURIComponent(output.data('expr'));
        var parameters = output.data('parameters');
        var card = new Card(card_name, variable, expr, parameters);
        card.setElement(el);
        return card;
    };

    Card.loadNewCard = function(el) {
        var card = Card.fromCardEl(el);
        var loader = $("
").addClass('loader');
        el.before(loader);
        card.evaluate().always(function() {
            el.slideDown(500);
            loader.slideUp(200);
        });
        return card;
    };

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


<commit_before>/******************************************************************************/
/*                                                                            */
/*  Poetic Generator Reloaded is a multiplayer and collaborative art          */
/*  experience.                                                               */
/*                                                                            */
/*  Copyright (C) 2011 - Gnuside                                              */
/*                                                                            */
/*  This program is free software: you can redistribute it and/or modify it   */
/*  under the terms of the GNU Affero General Public License as published by  */
/*  the Free Software Foundation, either version 3 of the License, or (at     */
/*  your option) any later version.                                           */
/*                                                                            */
/*  This program is distributed in the hope that it will be useful, but       */
/*  WITHOUT ANY WARRANTY; without even the implied warranty of                */
/*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero  */
/*  General Public License for more details.                                  */
/*                                                                            */
/*  You should have received a copy of the GNU Affero General Public License  */
/*  along with this program.  If not, see <http://www.gnu.org/licenses/>.     */
/*                                                                            */
/******************************************************************************/

"use strict";

function Chat( p_session ) {
    var self = this,
    _template_received = [
        '
',
        '
from: ',
        "",
        '

',
        '
',
        '
',
        "",
        '

'
    ],
    _template_sent = [
        '
',
        '
',
        "",
        '

',
        '
',
        '
to: ',
        "",
        '

'
    ], _session;

    this._queue = [];

    this.name = "Chat";

    /**
     * Constructor
     */
    this.initialize = function (p_session) {
        // register chat to session
        _session = p_session;
        _session.register(self);

        // initialize list of users for the send message form
        this.refresh_user_list();

        // attach submit event
        $("#send-message-form").submit(function(event){
            var content = $(this).find("#send-message-form-content");
            event.preventDefault();
            var user_dst = parseInt($(this).find("#send-message-form-to").val(), 10),
            message = {
                content: content.val(),
                stamp: new Date(),
                user_dst: user_dst
            };
            self.queue_message( message );
            self.display_message({
                content: content.val(),
                user_dst: user_dst
            }, true);
            // Reset field value.
            content.val("");
        });

        // when the messages page is shown reset unread messages count
        $("#session-chat").live("pageshow", function () {
            $("span.ui-li-count").text(0);
        });
    };

    this.display_message = function (message, is_sent_message) {
        var html;
        if (is_sent_message) {
            html = _template_sent;
            html[2] = message.content;
            html[6] = _session.get_user_name(message.user_dst);
        } else {
            html = _template_received;
            html[2] = _session.get_user_name(message.user_dst);
            html[6] = message.content;
        }
        $("#message-contener").prepend(html.join(""));
    };

    this.queue_message = function (message) {
        this._queue.push(message);
    };

    /**
     *
     */
    this.get_messages = function () {
        var queue   = self._queue;
        self._queue = [];
        return queue;
    };

    /**
     *
     */
    this.handle_event = function( ev ) {
        console.log("chat/handle_event : %s", JSON.stringify( ev ));
        switch (ev.type) {
            case "join" : // on both join and leave refresh users list
            case "leave" :
                this.refresh_user_list();
                break;
            default : // all other events are ignored
                break;
        }
    };

    /**
     *
     */
    this.handle_message = function( msg ) {
        console.log("chat/handle_message : %s", JSON.stringify( msg ));
        var liCount = $("span.ui-li-count"), count = parseInt($(liCount).text(), 10), link;
        // refresh unread count and blink for notification only when not on messages page
        if ("session-chat" !== $.mobile.activePage.attr("id")) {
            $(liCount).text(count + 1);
            link = $(liCount).closest("a")
                .removeClass("ui-btn-up-a").addClass("ui-btn-up-e");
            setTimeout(function () {
                $(link).removeClass("ui-btn-up-e").addClass("ui-btn-up-a");
            }, 100);
        }
        this.display_message(msg, false);
    };

    /**
     * Refresh user list
     */
    this.refresh_user_list = function () {
        console.log("chat/refresh_user_list : %s", JSON.stringify( _session.other_users ));
        var select = $("#send-message-form-to");
        select.empty().selectmenu();
        for (var i=0; i < _session.other_users.length; i++) {
            select.append('<option value="'
                + _session.other_users[i].id + '">'
                + _session.other_users[i].name
                + '</option>'
            );
        }
        select.selectmenu("refresh");
    };

    // call initialize method
    this.initialize( p_session );
}

<commit_msg>chat : inversion around dst and src<commit_after>/******************************************************************************/
/*                                                                            */
/*  Poetic Generator Reloaded is a multiplayer and collaborative art          */
/*  experience.                                                               */
/*                                                                            */
/*  Copyright (C) 2011 - Gnuside                                              */
/*                                                                            */
/*  This program is free software: you can redistribute it and/or modify it   */
/*  under the terms of the GNU Affero General Public License as published by  */
/*  the Free Software Foundation, either version 3 of the License, or (at     */
/*  your option) any later version.                                           */
/*                                                                            */
/*  This program is distributed in the hope that it will be useful, but       */
/*  WITHOUT ANY WARRANTY; without even the implied warranty of                */
/*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero  */
/*  General Public License for more details.                                  */
/*                                                                            */
/*  You should have received a copy of the GNU Affero General Public License  */
/*  along with this program.  If not, see <http://www.gnu.org/licenses/>.     */
/*                                                                            */
/******************************************************************************/

"use strict";

function Chat( p_session ) {
    var self = this,
    _template_received = [
        '
',
        '
from: ',
        "",
        '

',
        '
',
        '
',
        "",
        '

'
    ],
    _template_sent = [
        '
',
        '
',
        "",
        '

',
        '
',
        '
to: ',
        "",
        '

'
    ], _session;

    this._queue = [];

    this.name = "Chat";

    /**
     * Constructor
     */
    this.initialize = function (p_session) {
        // register chat to session
        _session = p_session;
        _session.register(self);

        // initialize list of users for the send message form
        this.refresh_user_list();

        // attach submit event
        $("#send-message-form").submit(function(event){
            var content = $(this).find("#send-message-form-content");
            event.preventDefault();
            var user_dst = parseInt($(this).find("#send-message-form-to").val(), 10),
            message = {
                content: content.val(),
                stamp: new Date(),
                user_dst: user_dst
            };
            self.queue_message( message );
            self.display_message({
                content: content.val(),
                user_dst: user_dst
            }, true);
            // Reset field value.
            content.val("");
        });

        // when the messages page is shown reset unread messages count
        $("#session-chat").live("pageshow", function () {
            $("span.ui-li-count").text(0);
        });
    };

    this.display_message = function (message, is_sent_message) {
        var html;
        if (is_sent_message) {
            html = _template_sent;
            html[2] = message.content;
            html[6] = _session.get_user_name(message.user_dst);
        } else {
            html = _template_received;
            html[2] = _session.get_user_name(message.user_from);
            html[6] = message.content;
        }
        $("#message-contener").prepend(html.join(""));
    };

    this.queue_message = function (message) {
        this._queue.push(message);
    };

    /**
     *
     */
    this.get_messages = function () {
        var queue   = self._queue;
        self._queue = [];
        return queue;
    };

    /**
     *
     */
    this.handle_event = function( ev ) {
        console.log("chat/handle_event : %s", JSON.stringify( ev ));
        switch (ev.type) {
            case "join" : // on both join and leave refresh users list
            case "leave" :
                this.refresh_user_list();
                break;
            default : // all other events are ignored
                break;
        }
    };

    /**
     *
     */
    this.handle_message = function( msg ) {
        console.log("chat/handle_message : %s", JSON.stringify( msg ));
        var liCount = $("span.ui-li-count"), count = parseInt($(liCount).text(), 10), link;
        // refresh unread count and blink for notification only when not on messages page
        if ("session-chat" !== $.mobile.activePage.attr("id")) {
            $(liCount).text(count + 1);
            link = $(liCount).closest("a")
                .removeClass("ui-btn-up-a").addClass("ui-btn-up-e");
            setTimeout(function () {
                $(link).removeClass("ui-btn-up-e").addClass("ui-btn-up-a");
            }, 100);
        }
        this.display_message(msg, false);
    };

    /**
     * Refresh user list
     */
    this.refresh_user_list = function () {
        console.log("chat/refresh_user_list : %s", JSON.stringify( _session.other_users ));
        var select = $("#send-message-form-to");
        select.empty().selectmenu();
        for (var i=0; i < _session.other_users.length; i++) {
            select.append('<option value="'
                + _session.other_users[i].id + '">'
                + _session.other_users[i].name
                + '</option>'
            );
        }
        select.selectmenu("refresh");
    };

    // call initialize method
    this.initialize( p_session );
}

<|endoftext|>


<commit_before>Paloquiz = {};
Paloquiz.states = {};
Paloquiz.orientated = false;
Paloquiz.orientationBlock;
Paloquiz.booted = false;

Paloquiz.MAX_WIDTH_RATIO = 11.0 / 16.0;
Paloquiz.MAX_HEIGHT_RATIO = 16.0 / 9.0;

var GAME_CONTAINER_ID = 'game-container';
var ORIENTATION_BLOCK_ID = 'orientation';
var FB_BUTTONS_ID = 'fb-buttons';

window.onload = function() {

    // Check Facebook status
    fbInit();

    // Game container
    Paloquiz.gameContainer = document.getElementById(GAME_CONTAINER_ID);

    // Element with orientation image
    Paloquiz.orientationBlock = document.getElementById(ORIENTATION_BLOCK_ID);

    // Facebook buttons
    Paloquiz.fbButtons = document.getElementById(FB_BUTTONS_ID);

    // // Get game dimensions
    // var gameSize = Paloquiz.getGameScale();

    var renderer = Phaser.AUTO; // Phaser.CANVAS / Phaser.WEBGL / Phaser.AUTO
    var transparent = true;
    var antialias = true;

    var width = 640;
    var height = 960;
    Paloquiz.game = new Phaser.Game(width, height,
        renderer, GAME_CONTAINER_ID, {}, transparent, antialias);

    // Does this do something?
    PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST;
    if (Paloquiz.game.renderType == Phaser.CANVAS) {
        Phaser.Canvas.setImageRenderingCrisp(game.canvas);
        Phaser.Canvas.setSmoothingEnabled(game.context, false);
    }

    Paloquiz.game.state.add('Boot', Paloquiz.states.Boot);
    Paloquiz.game.state.add('Preloader', Paloquiz.states.Preloader);
    Paloquiz.game.state.add('Router', Paloquiz.states.Router);
    Paloquiz.game.state.add('Start', Paloquiz.states.Start);
    Paloquiz.game.state.add('Main', Paloquiz.states.Main);
    Paloquiz.game.state.add('Highscores', Paloquiz.states.Highscores);
    Paloquiz.game.state.add('Finish', Paloquiz.states.Finish);

    Paloquiz.game.state.start('Boot');
}

// Common game functions

Paloquiz.init = function() {
    Paloquiz.setupLoader();

    // Avoid multiple pointer input
    Paloquiz.game.input.maxPointers = 1;

    // Do not pause when focus is lost
    Paloquiz.game.stage.disableVisibilityChange = true;

    Paloquiz.setupScale();

    Paloquiz.game.state.onStateChange.add(Paloquiz.stateChanged);
}

Paloquiz.setupLoader = function() {
    // Base URL for the loader
    Paloquiz.game.load.baseURL = '/static/';
    // Enable cross-origin image loading
    Paloquiz.game.load.crossOrigin = 'anonymous';
}

Paloquiz.setupScale = function() {
    Paloquiz.orientated = true;

    var game = Paloquiz.game;

    // Stretch
    game.scale.scaleMode = Phaser.ScaleManager.USER_SCALE;

    // Center
    game.scale.pageAlignHorizontally = true;
    game.scale.pageAlignVertically = true;

    // Check device
    if (game.device.desktop) {
        // On desktop
    } else {
        // On mobile
        // Force portrait
        game.scale.forceOrientation(false, true);
        // Game orientation callbacks
        game.scale.enterIncorrectOrientation.add(function() {
            Paloquiz.orientated = false;
            if (Paloquiz.orientationBlock) {
                Paloquiz.orientationBlock.style.display = 'block';
            }
        }, this);
        game.scale.leaveIncorrectOrientation.add(function() {
            Paloquiz.orientated = true;
            if (Paloquiz.orientationBlock) {
                Paloquiz.orientationBlock.style.display = 'none';
            }
        }, this);
    }

    // Game resizing callback
    game.scale.setResizeCallback(Paloquiz.resize, this);
}

Paloquiz.resize = function () {
    var gameScale = Paloquiz.getGameScale();
    Paloquiz.game.scale.setUserScale(gameScale.x, gameScale.y);
    Paloquiz.positionFbButtons();
}

Paloquiz.getGameScale = function() {
    var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    if ((width / height) > Paloquiz.MAX_WIDTH_RATIO) {
        width = Math.round(height * Paloquiz.MAX_WIDTH_RATIO);
    } else if ((height / width) > Paloquiz.MAX_HEIGHT_RATIO) {
        height = Math.round(width * Paloquiz.MAX_HEIGHT_RATIO);
    }
    return {
        x: width / Paloquiz.game.width,
        y: height / Paloquiz.game.height
    };
}

Paloquiz.stateChanged = function() {
    // Overchecking doesn't hurt
    fbInit();

    Paloquiz.resize();
    Paloquiz.setupBackground();
    Paloquiz.enableFbButtons(true);
}

Paloquiz.setupBackground = function() {
    if (!Paloquiz.game.cache.checkImageKey('background')) {
        return;
    }
    if (!Paloquiz.background) {
        Paloquiz.background = new Phaser.Image(Paloquiz.game, 0, 0, 'background');
        Paloquiz.background.anchor.setTo(0, 0);
        Paloquiz.game.stage.addChildAt(Paloquiz.background, 0);
    }
    Paloquiz.background.smoothed = false;
    Paloquiz.background.width = Paloquiz.game.width;
    Paloquiz.background.height = Paloquiz.game.height;
}

Paloquiz.positionFbButtons = function () {
    var top = Paloquiz.game.scale.bounds.y;
    var left = Paloquiz.game.scale.bounds.x;
    var height = Paloquiz.game.scale.bounds.height;
    Paloquiz.fbButtons.style.top = Math.round(top + height * .2) + 'px';
    Paloquiz.fbButtons.style.left = Math.round(left) + 'px';
}

Paloquiz.enableFbButtons = function (show) {
    if (show) {
        Paloquiz.fbButtons.style.display = 'block';
    } else {
        Paloquiz.fbButtons.style.display = 'none';
    }
}
<commit_msg>fb buttons<commit_after>Paloquiz = {};
Paloquiz.states = {};
Paloquiz.orientated = false;
Paloquiz.orientationBlock;
Paloquiz.booted = false;

Paloquiz.MAX_WIDTH_RATIO = 11.0 / 16.0;
Paloquiz.MAX_HEIGHT_RATIO = 16.0 / 9.0;

var GAME_CONTAINER_ID = 'game-container';
var ORIENTATION_BLOCK_ID = 'orientation';
var FB_BUTTONS_ID = 'fb-buttons';

window.onload = function() {

    // Check Facebook status
    fbInit();

    // Game container
    Paloquiz.gameContainer = document.getElementById(GAME_CONTAINER_ID);

    // Element with orientation image
    Paloquiz.orientationBlock = document.getElementById(ORIENTATION_BLOCK_ID);

    // Facebook buttons
    Paloquiz.fbButtons = document.getElementById(FB_BUTTONS_ID);

    // // Get game dimensions
    // var gameSize = Paloquiz.getGameScale();

    var renderer = Phaser.AUTO; // Phaser.CANVAS / Phaser.WEBGL / Phaser.AUTO
    var transparent = true;
    var antialias = true;

    var width = 640;
    var height = 960;
    Paloquiz.game = new Phaser.Game(width, height,
        renderer, GAME_CONTAINER_ID, {}, transparent, antialias);

    // Does this do something?
    PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST;
    if (Paloquiz.game.renderType == Phaser.CANVAS) {
        Phaser.Canvas.setImageRenderingCrisp(game.canvas);
        Phaser.Canvas.setSmoothingEnabled(game.context, false);
    }

    Paloquiz.game.state.add('Boot', Paloquiz.states.Boot);
    Paloquiz.game.state.add('Preloader', Paloquiz.states.Preloader);
    Paloquiz.game.state.add('Router', Paloquiz.states.Router);
    Paloquiz.game.state.add('Start', Paloquiz.states.Start);
    Paloquiz.game.state.add('Main', Paloquiz.states.Main);
    Paloquiz.game.state.add('Highscores', Paloquiz.states.Highscores);
    Paloquiz.game.state.add('Finish', Paloquiz.states.Finish);

    Paloquiz.game.state.start('Boot');
}

// Common game functions

Paloquiz.init = function() {
    Paloquiz.setupLoader();

    // Avoid multiple pointer input
    Paloquiz.game.input.maxPointers = 1;

    // Do not pause when focus is lost
    Paloquiz.game.stage.disableVisibilityChange = true;

    Paloquiz.setupScale();

    Paloquiz.game.state.onStateChange.add(Paloquiz.stateChanged);
}

Paloquiz.setupLoader = function() {
    // Base URL for the loader
    Paloquiz.game.load.baseURL = '/static/';
    // Enable cross-origin image loading
    Paloquiz.game.load.crossOrigin = 'anonymous';
}

Paloquiz.setupScale = function() {
    Paloquiz.orientated = true;

    var game = Paloquiz.game;

    // Stretch
    game.scale.scaleMode = Phaser.ScaleManager.USER_SCALE;

    // Center
    game.scale.pageAlignHorizontally = true;
    game.scale.pageAlignVertically = true;

    // Check device
    if (game.device.desktop) {
        // On desktop
    } else {
        // On mobile
        // Force portrait
        game.scale.forceOrientation(false, true);
        // Game orientation callbacks
        game.scale.enterIncorrectOrientation.add(function() {
            Paloquiz.orientated = false;
            if (Paloquiz.orientationBlock) {
                Paloquiz.orientationBlock.style.display = 'block';
            }
        }, this);
        game.scale.leaveIncorrectOrientation.add(function() {
            Paloquiz.orientated = true;
            if (Paloquiz.orientationBlock) {
                Paloquiz.orientationBlock.style.display = 'none';
            }
        }, this);
    }

    // Game resizing callback
    game.scale.setResizeCallback(Paloquiz.resize, this);
}

Paloquiz.resize = function () {
    var gameScale = Paloquiz.getGameScale();
    Paloquiz.game.scale.setUserScale(gameScale.x, gameScale.y);
    Paloquiz.positionFbButtons();
}

Paloquiz.getGameScale = function() {
    var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    if ((width / height) > Paloquiz.MAX_WIDTH_RATIO) {
        width = Math.round(height * Paloquiz.MAX_WIDTH_RATIO);
    } else if ((height / width) > Paloquiz.MAX_HEIGHT_RATIO) {
        height = Math.round(width * Paloquiz.MAX_HEIGHT_RATIO);
    }
    return {
        x: width / Paloquiz.game.width,
        y: height / Paloquiz.game.height
    };
}

Paloquiz.stateChanged = function() {
    // Overchecking doesn't hurt
    fbInit();

    Paloquiz.resize();
    Paloquiz.setupBackground();
    Paloquiz.enableFbButtons(true);
}

Paloquiz.setupBackground = function() {
    if (!Paloquiz.game.cache.checkImageKey('background')) {
        return;
    }
    if (!Paloquiz.background) {
        Paloquiz.background = new Phaser.Image(Paloquiz.game, 0, 0, 'background');
        Paloquiz.background.anchor.setTo(0, 0);
        Paloquiz.game.stage.addChildAt(Paloquiz.background, 0);
    }
    Paloquiz.background.smoothed = false;
    Paloquiz.background.width = Paloquiz.game.width;
    Paloquiz.background.height = Paloquiz.game.height;
}

Paloquiz.positionFbButtons = function () {
    var top = Paloquiz.game.scale.bounds.y;
    var left = Paloquiz.game.scale.bounds.x;
    var height = Paloquiz.game.scale.bounds.height;
    Paloquiz.fbButtons.style.top = Math.round(top + height * .1) + 'px';
    Paloquiz.fbButtons.style.left = Math.round(left) + 'px';
}

Paloquiz.enableFbButtons = function (show) {
    if (show) {
        Paloquiz.fbButtons.style.display = 'block';
    } else {
        Paloquiz.fbButtons.style.display = 'none';
    }
}
<|endoftext|>


<commit_before>CodeMirror.defineMode("glsl", function(config, parserConfig) {
  var indentUnit = config.indentUnit,
      keywords = parserConfig.keywords || {},
      builtins = parserConfig.builtins || {},
      blockKeywords = parserConfig.blockKeywords || {},
      atoms = parserConfig.atoms || {},
      hooks = parserConfig.hooks || {},
      multiLineStrings = parserConfig.multiLineStrings;
  var isOperatorChar = /[+\-*&%=<>!?|\/]/;

  var curPunc;

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (hooks[ch]) {
      var result = hooks[ch](stream, state);
      if (result !== false) return result;
    }
    if (ch == '"' || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    }
    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
      curPunc = ch;
      return "bracket";
    }
    if (/\d/.test(ch)) {
      stream.eatWhile(/[\w\.]/);
      return "number";
    }
    if (ch == "/") {
      if (stream.eat("*")) {
        state.tokenize = tokenComment;
        return tokenComment(stream, state);
      }
      if (stream.eat("/")) {
        stream.skipToEnd();
        return "comment";
      }
    }
    if (isOperatorChar.test(ch)) {
      stream.eatWhile(isOperatorChar);
      return "operator";
    }
    stream.eatWhile(/[\w\$_]/);
    var cur = stream.current();
    if (keywords.propertyIsEnumerable(cur)) {
      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
      return "keyword";
    }
    if (builtins.propertyIsEnumerable(cur)) {
      return "builtin";
    }
    if (atoms.propertyIsEnumerable(cur)) return "atom";
    return "word";
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) {end = true; break;}
        escaped = !escaped && next == "\\";
      }
      if (end || !(escaped || multiLineStrings))
        state.tokenize = tokenBase;
      return "string";
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return "comment";
  }

  function Context(indented, column, type, align, prev) {
    this.indented = indented;
    this.column = column;
    this.type = type;
    this.align = align;
    this.prev = prev;
  }
  function pushContext(state, col, type) {
    return state.context = new Context(state.indented, col, type, null, state.context);
  }
  function popContext(state) {
    var t = state.context.type;
    if (t == ")" || t == "]" || t == "}")
      state.indented = state.context.indented;
    return state.context = state.context.prev;
  }

  // Interface

  return {
    startState: function(basecolumn) {
      return {
        tokenize: null,
        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
        indented: 0,
        startOfLine: true
      };
    },

    token: function(stream, state) {
      var ctx = state.context;
      if (stream.sol()) {
        if (ctx.align == null) ctx.align = false;
        state.indented = stream.indentation();
        state.startOfLine = true;
      }
      if (stream.eatSpace()) return null;
      curPunc = null;
      var style = (state.tokenize || tokenBase)(stream, state);
      if (style == "comment" || style == "meta") return style;
      if (ctx.align == null) ctx.align = true;

      if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
      else if (curPunc == "{") pushContext(state, stream.column(), "}");
      else if (curPunc == "[") pushContext(state, stream.column(), "]");
      else if (curPunc == "(") pushContext(state, stream.column(), ")");
      else if (curPunc == "}") {
        while (ctx.type == "statement") ctx = popContext(state);
        if (ctx.type == "}") ctx = popContext(state);
        while (ctx.type == "statement") ctx = popContext(state);
      }
      else if (curPunc == ctx.type) popContext(state);
      else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
        pushContext(state, stream.column(), "statement");
      state.startOfLine = false;
      return style;
    },

    indent: function(state, textAfter) {
      if (state.tokenize != tokenBase && state.tokenize != null) return 0;
      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type;
      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
      else return ctx.indented + (closing ? 0 : indentUnit);
    },

    electricChars: "{}"
  };
});

(function() {
  function words(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }
  var glslKeywords = "attribute const uniform varying break continue " +
    "do for while if else in out inout float int void bool true false " +
    "lowp mediump highp precision invariant discard return mat2 mat3 " +
    "mat4 vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 sampler2D " +
    "samplerCube struct";
  var glslBuiltins = "radians degrees sin cos tan asin acos atan " +
    "pow exp log exp2 log2 sqrt inversesqrt abs sign foor trunc " +
    "round ceil fract mod min max clamp mix step smoothstep length " +
    "distance dot cross normalize reflect refract transpose lessThan " +
    "greaterThan equal notEqual any all not dFdx dFdy fwidth texture2D " +
    "textureCube";

  function cppHook(stream, state) {
    if (!state.startOfLine) return false;
    stream.skipToEnd();
    return "meta";
  }

  // C#-style strings where "" escapes a quote.
  function tokenAtString(stream, state) {
    var next;
    while ((next = stream.next()) != null) {
      if (next == '"' && !stream.eat('"')) {
        state.tokenize = null;
        break;
      }
    }
    return "string";
  }

  CodeMirror.defineMIME("text/x-glsl", {
    name: "glsl",
    keywords: words(glslKeywords),
    builtins: words(glslBuiltins),
    blockKeywords: words("case do else for if switch while struct"),
    atoms: words("null"),
    hooks: {"#": cppHook}
  });
}());
<commit_msg>fix glsl builtin-list<commit_after>CodeMirror.defineMode("glsl", function(config, parserConfig) {
  var indentUnit = config.indentUnit,
      keywords = parserConfig.keywords || {},
      builtins = parserConfig.builtins || {},
      blockKeywords = parserConfig.blockKeywords || {},
      atoms = parserConfig.atoms || {},
      hooks = parserConfig.hooks || {},
      multiLineStrings = parserConfig.multiLineStrings;
  var isOperatorChar = /[+\-*&%=<>!?|\/]/;

  var curPunc;

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (hooks[ch]) {
      var result = hooks[ch](stream, state);
      if (result !== false) return result;
    }
    if (ch == '"' || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    }
    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
      curPunc = ch;
      return "bracket";
    }
    if (/\d/.test(ch)) {
      stream.eatWhile(/[\w\.]/);
      return "number";
    }
    if (ch == "/") {
      if (stream.eat("*")) {
        state.tokenize = tokenComment;
        return tokenComment(stream, state);
      }
      if (stream.eat("/")) {
        stream.skipToEnd();
        return "comment";
      }
    }
    if (isOperatorChar.test(ch)) {
      stream.eatWhile(isOperatorChar);
      return "operator";
    }
    stream.eatWhile(/[\w\$_]/);
    var cur = stream.current();
    if (keywords.propertyIsEnumerable(cur)) {
      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
      return "keyword";
    }
    if (builtins.propertyIsEnumerable(cur)) {
      return "builtin";
    }
    if (atoms.propertyIsEnumerable(cur)) return "atom";
    return "word";
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) {end = true; break;}
        escaped = !escaped && next == "\\";
      }
      if (end || !(escaped || multiLineStrings))
        state.tokenize = tokenBase;
      return "string";
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return "comment";
  }

  function Context(indented, column, type, align, prev) {
    this.indented = indented;
    this.column = column;
    this.type = type;
    this.align = align;
    this.prev = prev;
  }
  function pushContext(state, col, type) {
    return state.context = new Context(state.indented, col, type, null, state.context);
  }
  function popContext(state) {
    var t = state.context.type;
    if (t == ")" || t == "]" || t == "}")
      state.indented = state.context.indented;
    return state.context = state.context.prev;
  }

  // Interface

  return {
    startState: function(basecolumn) {
      return {
        tokenize: null,
        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
        indented: 0,
        startOfLine: true
      };
    },

    token: function(stream, state) {
      var ctx = state.context;
      if (stream.sol()) {
        if (ctx.align == null) ctx.align = false;
        state.indented = stream.indentation();
        state.startOfLine = true;
      }
      if (stream.eatSpace()) return null;
      curPunc = null;
      var style = (state.tokenize || tokenBase)(stream, state);
      if (style == "comment" || style == "meta") return style;
      if (ctx.align == null) ctx.align = true;

      if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
      else if (curPunc == "{") pushContext(state, stream.column(), "}");
      else if (curPunc == "[") pushContext(state, stream.column(), "]");
      else if (curPunc == "(") pushContext(state, stream.column(), ")");
      else if (curPunc == "}") {
        while (ctx.type == "statement") ctx = popContext(state);
        if (ctx.type == "}") ctx = popContext(state);
        while (ctx.type == "statement") ctx = popContext(state);
      }
      else if (curPunc == ctx.type) popContext(state);
      else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
        pushContext(state, stream.column(), "statement");
      state.startOfLine = false;
      return style;
    },

    indent: function(state, textAfter) {
      if (state.tokenize != tokenBase && state.tokenize != null) return 0;
      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type;
      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
      else return ctx.indented + (closing ? 0 : indentUnit);
    },

    electricChars: "{}"
  };
});

(function() {
  function words(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }
  var glslKeywords = "attribute const uniform varying break continue " +
    "do for while if else in out inout float int void bool true false " +
    "lowp mediump highp precision invariant discard return mat2 mat3 " +
    "mat4 vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 sampler2D " +
    "samplerCube struct";
  var glslBuiltins = "radians degrees sin cos tan asin acos atan pow " +
    "exp log exp2 log2 sqrt inversesqrt abs sign floor ceil fract mod " +
    "min max clamp mix step smoothstep length distance dot cross " +
    "normalize faceforward reflect refract matrixCompMult lessThan " +
    "lessThanEqual greaterThan greaterThanEqual equal notEqual any all " +
    "not dFdx dFdy fwidth texture2D texture2DProj texture2DLod
    "texture2DProjLod textureCube textureCubeLod";

  function cppHook(stream, state) {
    if (!state.startOfLine) return false;
    stream.skipToEnd();
    return "meta";
  }

  // C#-style strings where "" escapes a quote.
  function tokenAtString(stream, state) {
    var next;
    while ((next = stream.next()) != null) {
      if (next == '"' && !stream.eat('"')) {
        state.tokenize = null;
        break;
      }
    }
    return "string";
  }

  CodeMirror.defineMIME("text/x-glsl", {
    name: "glsl",
    keywords: words(glslKeywords),
    builtins: words(glslBuiltins),
    blockKeywords: words("case do else for if switch while struct"),
    atoms: words("null"),
    hooks: {"#": cppHook}
  });
}());
<|endoftext|>


<commit_before>$(function() {

    write_lists();
    show_tweets("timeline", {}, "overwrite");
    $("#search-text").val("");

    $("button.timeline").on('click', function() {
        show_tweets("timeline", {}, "overwrite");
    });
    $("button.favorites").on('click', function() {
        show_tweets("favorites", {}, "overwrite");
    });
    $("select.lists").change(function() {
        show_tweets(
            "list_status",
            {list_id: $("select.lists option:selected").val()},
            "overwrite"
        );
    });
    $("form[name='search']").submit(function(event) {
        event.preventDefault();
        show_tweets(
            "search",
            { q: $(":text[name='search']").val()},
            "overwrite"
        );
    });

    $(document).on('click', "div.tweet-newer" , function() {
        update_tweets(
            $('div.tweet-content').attr('data-twtype'),
            {since_id: $(this).attr('data-max_id')},
            "prepend"
        );
    });
    $(document).on('click', "div.tweet-older" , function() {
        update_tweets(
            $('div.tweet-content').attr('data-twtype'),
            {max_id: $(this).attr('data-since_id')},
            "append"
        );
    });

    $(document).on('click', "span.retweet-count" , function() {
        var tweet_id = $(this).parent().parent().attr('data-id');
        if ($(this).attr("data-retweeted") == "False")  {
            if (change_status("retweet", tweet_id)) {
                $(this).attr("data-retweeted", "True");
                $(this).css('color', "#00cc00");
            }
        } else if ($(this).attr("data-retweeted") == "True")  {
            if (change_status("unretweet", tweet_id)) {
                $(this).attr("data-retweeted", "False");
                $(this).css('color', "#666666");
            }
        }
    });
    $(document).on('click', "span.favorite-count" , function() {
        var tweet_id = $(this).parent().parent().attr('data-id');
        if ($(this).attr("data-favorited") == "False")  {
            if (change_status("favorite-create", tweet_id)) {
                $(this).attr("data-favorited", "True");
                $(this).css('color', "#ff0000");
            }
        } else if ($(this).attr("data-favorited") == "True")  {
            if (change_status("favorite-destroy", tweet_id)) {
                $(this).attr("data-favorited", "False");
                $(this).css('color', "#666666");
            }
        }
    });

    $(document).on('mouseover',"span.retweet-count", function() {
        if ($(this).attr("data-retweeted") == "False")  {
            $(this).css('color', "#00cc00");
        }
    });
    $(document).on('mouseout',"span.retweet-count", function() {
        if ($(this).attr("data-retweeted") == "False")  {
            $(this).css('color', "#666666");
        }
    });
    $(document).on('mouseover',"span.favorite-count", function() {
        if ($(this).attr("data-favorited") == "False")  {
            $(this).css('color', "#ff0000");
        }
    });
    $(document).on('mouseout',"span.favorite-count" ,function() {
        if ($(this).attr("data-favorited") == "False")  {
            $(this).css('color', "#666666");
        }
    });
    $(document).on('mouseover',"div.tweet-newer", function() {
        $(this).css('background-color', "#f0f0f0");
    });
    $(document).on('mouseout',"div.tweet-newer" ,function() {
        $(this).css('background-color', "#ffffff");
    });
    $(document).on('mouseover',"div.tweet-older", function() {
        $(this).css('background-color', "#f0f0f0");
    });
    $(document).on('mouseout',"div.tweet-older" ,function() {
        $(this).css('background-color', "#ffffff");
    });
});

function update_tweets(twtype, params, mode) {
    if (twtype == "search") {
        params['q'] = $('div.tweet-content').attr('data-q');
    } else if (twtype == "list_status") {
        params['list_id'] = $('div.tweet-content').attr('data-list_id');
    }
    show_tweets(twtype, params, mode);
}

function show_tweets(twtype, params, mode) {
    params['count'] = 100;
    write_tweets({
        twtype: twtype,
        params: params,
        mode: mode
    });
}

function change_status(twtype, id) {
    return request_post({
        twtype: twtype,
        params: {id: id}
    });
}

function disable_button(status) {
    $("button.timeline").prop('disabled', status);
    $("button.favorites").prop('disabled', status);
    $("select.lists").prop('disabled', status);
    $("form.search-form").prop('disabled', status);
}

function request_post(data) {
    return post_tweets(data).done(function(result) {
        console.log(result);
        if (result == "success") {
            return true;
        } else {
            return false;
        }
    }).fail(function(result) {
        console.log("error");
        console.log(result);
        return false;
    });
}

function write_tweets(data) {
    disable_button(true);
    if ($('.error').length > 0) {
        $('.error').remove();
    }
    if (data['mode'] == "overwrite") {
        $('.content').html("");
        $('#lightbox').remove();
        $('#lightboxOverlay').remove();
    }
    get_tweets(data).done(function(result) {
        switch (data['mode']) {
            case "overwrite":
                $('.content').html(result);
                break;
            case "prepend":
                $('.tweet-content').prepend(result);
                if ($('.error').length == 0) {
                    $('.tweet-newer:last').remove();
                    if ($('.tweets').length > 1) {
                        $('.tweets:first').append($('.tweets:last').children());
                        $('.tweets:last').remove();
                        $('.tweet[data-id=]')
                    }
                }
                break;
            case "append":
                $('.tweet-content').append(result);
                if ($('.error').length == 0) {
                    $('.tweet-older:first').remove();
                    if ($('.tweets').length > 1) {
                        $('.tweets:first').append($('.tweets:last').children());
                        $('.tweets:last').remove();
                    }
                }
                break;
        }
    }).fail(function(result) {
        $('.content').html("
" + result.statusText + "
");
        console.log("error");
        console.log(result);
    });
    disable_button(false);
}

function write_lists(){
    data = {
        twtype: "lists",
        params: {}
    }
    get_tweets(data).done(function(result) {
        $("select[name='lists']").append(result);
    }).fail(function(result) {
        console.log(result);
    });
}

function get_tweets(data){
    console.log("get_tweets")
    console.log(data);
    return $.ajax({
        url: '_get_tweets',
        type: 'post',
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'html',
    });
}

function post_tweets(data){
    console.log("post_tweets")
    console.log(data);
    return $.ajax({
        url: '_post_tweets',
        type: 'post',
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'text',
    });
}
<commit_msg>かぶりを修正<commit_after>$(function() {

    write_lists();
    show_tweets("timeline", {}, "overwrite");
    $("#search-text").val("");

    $("button.timeline").on('click', function() {
        show_tweets("timeline", {}, "overwrite");
    });
    $("button.favorites").on('click', function() {
        show_tweets("favorites", {}, "overwrite");
    });
    $("select.lists").change(function() {
        show_tweets(
            "list_status",
            {list_id: $("select.lists option:selected").val()},
            "overwrite"
        );
    });
    $("form[name='search']").submit(function(event) {
        event.preventDefault();
        show_tweets(
            "search",
            { q: $(":text[name='search']").val()},
            "overwrite"
        );
    });

    $(document).on('click', "div.tweet-newer" , function() {
        update_tweets(
            $('div.tweet-content').attr('data-twtype'),
            {since_id: $(this).attr('data-max_id')},
            "prepend"
        );
    });
    $(document).on('click', "div.tweet-older" , function() {
        update_tweets(
            $('div.tweet-content').attr('data-twtype'),
            {max_id: $(this).attr('data-since_id')},
            "append"
        );
    });

    $(document).on('click', "span.retweet-count" , function() {
        var tweet_id = $(this).parent().parent().attr('data-id');
        if ($(this).attr("data-retweeted") == "False")  {
            if (change_status("retweet", tweet_id)) {
                $(this).attr("data-retweeted", "True");
                $(this).css('color', "#00cc00");
            }
        } else if ($(this).attr("data-retweeted") == "True")  {
            if (change_status("unretweet", tweet_id)) {
                $(this).attr("data-retweeted", "False");
                $(this).css('color', "#666666");
            }
        }
    });
    $(document).on('click', "span.favorite-count" , function() {
        var tweet_id = $(this).parent().parent().attr('data-id');
        if ($(this).attr("data-favorited") == "False")  {
            if (change_status("favorite-create", tweet_id)) {
                $(this).attr("data-favorited", "True");
                $(this).css('color', "#ff0000");
            }
        } else if ($(this).attr("data-favorited") == "True")  {
            if (change_status("favorite-destroy", tweet_id)) {
                $(this).attr("data-favorited", "False");
                $(this).css('color', "#666666");
            }
        }
    });

    $(document).on('mouseover',"span.retweet-count", function() {
        if ($(this).attr("data-retweeted") == "False")  {
            $(this).css('color', "#00cc00");
        }
    });
    $(document).on('mouseout',"span.retweet-count", function() {
        if ($(this).attr("data-retweeted") == "False")  {
            $(this).css('color', "#666666");
        }
    });
    $(document).on('mouseover',"span.favorite-count", function() {
        if ($(this).attr("data-favorited") == "False")  {
            $(this).css('color', "#ff0000");
        }
    });
    $(document).on('mouseout',"span.favorite-count" ,function() {
        if ($(this).attr("data-favorited") == "False")  {
            $(this).css('color', "#666666");
        }
    });
    $(document).on('mouseover',"div.tweet-newer", function() {
        $(this).css('background-color', "#f0f0f0");
    });
    $(document).on('mouseout',"div.tweet-newer" ,function() {
        $(this).css('background-color', "#ffffff");
    });
    $(document).on('mouseover',"div.tweet-older", function() {
        $(this).css('background-color', "#f0f0f0");
    });
    $(document).on('mouseout',"div.tweet-older" ,function() {
        $(this).css('background-color', "#ffffff");
    });
});

function update_tweets(twtype, params, mode) {
    if (twtype == "search") {
        params['q'] = $('div.tweet-content').attr('data-q');
    } else if (twtype == "list_status") {
        params['list_id'] = $('div.tweet-content').attr('data-list_id');
    }
    show_tweets(twtype, params, mode);
}

function show_tweets(twtype, params, mode) {
    params['count'] = 100;
    write_tweets({
        twtype: twtype,
        params: params,
        mode: mode
    });
}

function change_status(twtype, id) {
    return request_post({
        twtype: twtype,
        params: {id: id}
    });
}

function disable_button(status) {
    $("button.timeline").prop('disabled', status);
    $("button.favorites").prop('disabled', status);
    $("select.lists").prop('disabled', status);
    $("form.search-form").prop('disabled', status);
}

function request_post(data) {
    return post_tweets(data).done(function(result) {
        console.log(result);
        if (result == "success") {
            return true;
        } else {
            return false;
        }
    }).fail(function(result) {
        console.log("error");
        console.log(result);
        return false;
    });
}

function write_tweets(data) {
    disable_button(true);
    if ($('.error').length > 0) {
        $('.error').remove();
    }
    if (data['mode'] == "overwrite") {
        $('.content').html("");
        $('#lightbox').remove();
        $('#lightboxOverlay').remove();
    }
    get_tweets(data).done(function(result) {
        switch (data['mode']) {
            case "overwrite":
                $('.content').html(result);
                break;
            case "prepend":
                var max_id = $('.tweet-older').attr('data-max_id');
                $('.tweet-content').prepend(result);
                if ($('.error').length == 0) {
                    $('.tweet-newer:last').remove();
                    $('.tweet[data-id='+max_id+']:first').remove();
                    if ($('.tweets').length > 1) {
                        $('.tweets:first').append($('.tweets:last').children());
                        $('.tweets:last').remove();
                        $('.tweet[data-id=]')
                    }
                }
                break;
            case "append":
                var since_id = $('.tweet-older').attr('data-since_id');
                $('.tweet-content').append(result);
                if ($('.error').length == 0) {
                    $('.tweet-older:first').remove();
                    $('.tweet[data-id='+since_id+']:first').remove();
                    if ($('.tweets').length > 1) {
                        $('.tweets:first').append($('.tweets:last').children());
                        $('.tweets:last').remove();
                    }
                }
                break;
        }
    }).fail(function(result) {
        $('.content').html("
" + result.statusText + "
");
        console.log("error");
        console.log(result);
    });
    disable_button(false);
}

function write_lists(){
    data = {
        twtype: "lists",
        params: {}
    }
    get_tweets(data).done(function(result) {
        $("select[name='lists']").append(result);
    }).fail(function(result) {
        console.log(result);
    });
}

function get_tweets(data){
    console.log("get_tweets")
    console.log(data);
    return $.ajax({
        url: '_get_tweets',
        type: 'post',
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'html',
    });
}

function post_tweets(data){
    console.log("post_tweets")
    console.log(data);
    return $.ajax({
        url: '_post_tweets',
        type: 'post',
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'text',
    });
}
<|endoftext|>


<commit_before>$(function() {

	function get_series_data(data) {
		// append value after each label
		for (var i = 0; i < data.signal.length; ++i) {
			data.signal[i].label = data.signal[i].label + " = 0";
		}

		return data.signal;
	}

	var number_of_signal = 200;
	var moving_average_status = false;
	var plot = null;

	function init_draw(data) {

		plot = $.plot('#signal-plot', data, {
			series: {
				lines: { show: true, lineWidth: 1.5 },
				shadowSize: 0 },
			crosshair: { mode: "x" },
			grid: { hoverable: true, autoHighlight: false },
			xaxis: { show: false },
			yaxis: { min: -36000, max: 36000 },
			legend: { position: "sw" }
		});

	}

    // Websocket connection
    var ws = new WebSocket("ws://localhost:8888/ws");

    ws.onmessage = function (evt) {

		if (plot == null) {
			var data = JSON.parse(evt.data);
			data = get_series_data(data);
			init_draw(data);
		}

		var data = JSON.parse(evt.data);
		data = get_series_data(data);
		// set data for plot
		plot.setData(data);
		// redraw graph
		plot.draw();
		// uplate legend
		update_legend();

	};

	var legends = $('#signal-plot .legendLabel');

	var latest_pos = null;
	var update_legend_timeout = null;

	function update_legend() {
		update_legend_timeout = null;
		var pos = latest_pos;

		var axes = plot.getAxes();

		if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
			pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
			return;
		}

		var dataset = plot.getData();

		for (var i = 0; i < dataset.length; ++i) {
			var series = dataset[i];

			var idx = Math.floor(pos.x);

			var p1 = series.data[idx], p2 = series.data[idx + 1];
			var ret = null;

			ret = (p1 == null) ? p2[1] : p1[1];
			var new_label = series.label.replace(/=.*/, "= " + ret);
			legends.eq(i).text(new_label);
		}
	};

	$('#signal-plot').bind("plothover", function (event, pos, iten) {
		latest_pos = pos;
		if (!update_legend_timeout) {
			update_legend_timeout = setTimeout(update_legend, 50);
		}
	});

	$('#clear-btn').click(function () {
		ws.send("clear");
	});

	$('#status-btn').click(function () {
		// close connection
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			$(this).empty();
			$(this).append("");
			ws.send("pause");
		}
		// open connection
		else {
			$(this).addClass('active');
			$(this).empty();
			$(this).append("");
			ws.send("play");
		}
	});

	$('#moving-average-filter').click(function () {
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
            $('#MA-slider').attr('disabled', true);
			moving_average_status = false;
			ws.send("MAF 0");
		}
		else {
			$(this).addClass('active');
            $('#MA-slider').attr('disabled', false);
			moving_average_status = true;
			ws.send("MAF 10");
		}
	});

    $('.ui.checkbox').checkbox();

});
<commit_msg>update MA filter window dynamically<commit_after>var ws = undefined;

function update_MA(value) {
    if (value != '') {
        $('#moving-average-filter label').text('MA Filter (' + value + ')');
        $('#MA-slider').val(value);
        ws.send("MAF " + value);
    }
    else {
        $('#moving-average-filter label').text('MA Filter');
    }
}

$(function() {

	function get_series_data(data) {
		// append value after each label
		for (var i = 0; i < data.signal.length; ++i) {
			data.signal[i].label = data.signal[i].label + " = 0";
		}

		return data.signal;
	}

	var number_of_signal = 200;
	var plot = null;

	function init_draw(data) {

		plot = $.plot('#signal-plot', data, {
			series: {
				lines: { show: true, lineWidth: 1.5 },
				shadowSize: 0 },
			crosshair: { mode: "x" },
			grid: { hoverable: true, autoHighlight: false },
			xaxis: { show: false },
			yaxis: { min: -36000, max: 36000 },
			legend: { position: "sw" }
		});

	}

    // Websocket connection
    ws = new WebSocket("ws://localhost:8888/ws");

    ws.onmessage = function (evt) {

		if (plot == null) {
			var data = JSON.parse(evt.data);
			data = get_series_data(data);
			init_draw(data);
		}

		var data = JSON.parse(evt.data);
		data = get_series_data(data);
		// set data for plot
		plot.setData(data);
		// redraw graph
		plot.draw();
		// uplate legend
		update_legend();

	};

	var legends = $('#signal-plot .legendLabel');

	var latest_pos = null;
	var update_legend_timeout = null;

	function update_legend() {
		update_legend_timeout = null;
		var pos = latest_pos;

		var axes = plot.getAxes();

		if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
			pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
			return;
		}

		var dataset = plot.getData();

		for (var i = 0; i < dataset.length; ++i) {
			var series = dataset[i];

			var idx = Math.floor(pos.x);

			var p1 = series.data[idx], p2 = series.data[idx + 1];
			var ret = null;

			ret = (p1 == null) ? p2[1] : p1[1];
			var new_label = series.label.replace(/=.*/, "= " + ret);
			legends.eq(i).text(new_label);
		}
	};

	$('#signal-plot').bind("plothover", function (event, pos, iten) {
		latest_pos = pos;
		if (!update_legend_timeout) {
			update_legend_timeout = setTimeout(update_legend, 50);
		}
	});

	$('#clear-btn').click(function () {
		ws.send("clear");
	});

	$('#status-btn').click(function () {
		// close connection
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			$(this).empty();
			$(this).append("");
			ws.send("pause");
		}
		// open connection
		else {
			$(this).addClass('active');
			$(this).empty();
			$(this).append("");
			ws.send("play");
		}
	});

	$('#moving-average-filter').click(function () {
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
            $('#MA-slider').attr('disabled', true);
            update_MA('');
			ws.send("MAF 0");
		}
		else {
			$(this).addClass('active');
            update_MA($('#MA-slider').val());
            $('#MA-slider').attr('disabled', false);
		}
	});

    $('.ui.checkbox').checkbox();

});
<|endoftext|>


<commit_before>L.DomUtil = L.DomUtil || {};
L.DistortableImage = L.DistortableImage || {};
L.distortableImage = L.DistortableImage;

L.DistortableImage.Keymapper = L.Handler.extend({

  options: {
    position: 'topright',
  },

  initialize(map, options) {
    this._map = map;
    L.setOptions(this, options);
  },

  addHooks() {
    if (!this._keymapper) {
      this._container = this._buildContainer();
      this._scrollWrapper = this._wrap();
      this._toggler = this._createButton();
      this._setMapper(this._container, this._scrollWrapper, this._toggler);

      L.DomEvent.on(this._toggler, 'click', this._toggleKeymapper, this);

      L.DomEvent.disableClickPropagation(this._container);
      L.DomEvent.disableScrollPropagation(this._container);
    }
  },

  removeHooks() {
    if (this._keymapper) {
      L.DomEvent.off(this._toggler, 'click', this._toggleKeymapper, this);

      L.DomUtil.remove(this._toggler);
      L.DomUtil.remove(this._scrollWrapper);
      L.DomUtil.remove(this._container);
      this._keymapper = false;
    }
  },

  _buildContainer() {
    var container = L.DomUtil.create('div', 'ldi-keymapper-hide');
    container.setAttribute('id', 'ldi-keymapper');

    var divider = L.DomUtil.create('br', 'divider');
    container.appendChild(divider);

    return container;
  },

  _createButton() {
    var toggler = L.DomUtil.create('a', '');
    toggler.innerHTML = L.IconUtil.create('keyboard_open');

    toggler.setAttribute('id', 'toggle-keymapper');
    toggler.setAttribute('href', '#');
    toggler.setAttribute('title', 'Show keymap');
    // Will force screen readers like VoiceOver to read this as "Show keymap - button"
    toggler.setAttribute('role', 'button');
    toggler.setAttribute('aria-label', 'Show keymap');

    return toggler;
  },

  _wrap() {
    var wrap = L.DomUtil.create('div', '');
    wrap.setAttribute('id', 'keymapper-wrapper');
    wrap.style.display = 'none';

    return wrap;
  },

  _setMapper: function(container, wrap, button) {
    this._keymapper = L.control({position: this.options.position});

    this._keymapper.onAdd = function() {
      container.appendChild(wrap);
      wrap.insertAdjacentHTML(
          'beforeend',
          '

' +
          '
' +
          /* eslint-disable */
          '

Rotate Mode

R

' +
          '

RotateScale Mode

r

' +
          '

Scale Mode

s

' +
          '

Distort Mode

d

' +
          '

Drag Mode

D

' +
          '

Lock (Mode) / Unlock Image

l\xa0u

' +
          '

Stack up / down

q\xa0a

' +
          '

Add / Remove Image Border

b

' +
          '

Toggle Opacity

o

' +
          '

Deselect All

esc

' +
          '

Delete Image(s)

delete\xa0backspace

' +
          '

Export Image(s)

e

' +
          '

'
      );
      /* eslint-enable */
      container.appendChild(button);
      return container;
    };

    this._keymapper.addTo(this._map);
  },

  _toggleKeymapper: function(e) {
    e.preventDefault();

    this._container.className = (
      this._container.className === 'ldi-keymapper leaflet-control' ?
        'ldi-keymapper-hide leaflet-control' :
        'ldi-keymapper leaflet-control'
    );

    this._scrollWrapper.style.display = (
      this._scrollWrapper.style.display === 'none' ? 'block' : 'none'
    );

    this._toggler.innerHTML = (
      this._toggler.innerHTML === 'close' ?
        L.IconUtil.create('keyboard_open') :
        'close'
    );

    L.IconUtil.toggleTitle(this._toggler, 'Show keymap', 'Hide keymap');
    L.DomUtil.toggleClass(this._toggler, 'close-icon');
  },

  _injectIconSet: function() {
    if (document.querySelector('#keymapper-iconset')) { return; }

    var el = L.DomUtil.create('div', '');
    el.id = 'keymapper-iconset';
    el.setAttribute('hidden', 'hidden');

    this._iconset = new L.KeymapperIconSet().render();
    el.innerHTML = this._iconset;

    document.querySelector('.leaflet-control-container').appendChild(el);
  },
});

L.DistortableImage.Keymapper.addInitHook(function() {
  L.DistortableImage.Keymapper.prototype._n = (
    L.DistortableImage.Keymapper.prototype._n ?
    L.DistortableImage.Keymapper.prototype._n + 1 :
    1
  );
  // dont enable keymapper for mobile
  if (L.DistortableImage.Keymapper.prototype._n === 1 && !L.Browser.mobile) {
    this.enable();
    this._injectIconSet();
  }
});

L.distortableImage.keymapper = function(map, options) {
  return new L.DistortableImage.Keymapper(map, options);
};
<commit_msg>changed in DistortableImage.Keymapper- by removing the function (#783)<commit_after>L.DomUtil = L.DomUtil || {};
L.DistortableImage = L.DistortableImage || {};
L.distortableImage = L.DistortableImage;

L.DistortableImage.Keymapper = L.Handler.extend({

  options: {
    position: 'topright',
  },

  initialize(map, options) {
    this._map = map;
    L.setOptions(this, options);
  },

  addHooks() {
    if (!this._keymapper) {
      this._container = this._buildContainer();
      this._scrollWrapper = this._wrap();
      this._toggler = this._createButton();
      this._setMapper(this._container, this._scrollWrapper, this._toggler);

      L.DomEvent.on(this._toggler, 'click', this._toggleKeymapper, this);

      L.DomEvent.disableClickPropagation(this._container);
      L.DomEvent.disableScrollPropagation(this._container);
    }
  },

  removeHooks() {
    if (this._keymapper) {
      L.DomEvent.off(this._toggler, 'click', this._toggleKeymapper, this);

      L.DomUtil.remove(this._toggler);
      L.DomUtil.remove(this._scrollWrapper);
      L.DomUtil.remove(this._container);
      this._keymapper = false;
    }
  },

  _buildContainer() {
    var container = L.DomUtil.create('div', 'ldi-keymapper-hide');
    container.setAttribute('id', 'ldi-keymapper');

    var divider = L.DomUtil.create('br', 'divider');
    container.appendChild(divider);

    return container;
  },

  _createButton() {
    var toggler = L.DomUtil.create('a', '');
    toggler.innerHTML = L.IconUtil.create('keyboard_open');

    toggler.setAttribute('id', 'toggle-keymapper');
    toggler.setAttribute('href', '#');
    toggler.setAttribute('title', 'Show keymap');
    // Will force screen readers like VoiceOver to read this as "Show keymap - button"
    toggler.setAttribute('role', 'button');
    toggler.setAttribute('aria-label', 'Show keymap');

    return toggler;
  },

  _wrap() {
    var wrap = L.DomUtil.create('div', '');
    wrap.setAttribute('id', 'keymapper-wrapper');
    wrap.style.display = 'none';

    return wrap;
  },

  _setMapper(container, wrap, button) {
    this._keymapper = L.control({position: this.options.position});

    this._keymapper.onAdd = function() {
      container.appendChild(wrap);
      wrap.insertAdjacentHTML(
          'beforeend',
          '

' +
          '
' +
          /* eslint-disable */
          '

Rotate Mode

R

' +
          '

RotateScale Mode

r

' +
          '

Scale Mode

s

' +
          '

Distort Mode

d

' +
          '

Drag Mode

D

' +
          '

Lock (Mode) / Unlock Image

l\xa0u

' +
          '

Stack up / down

q\xa0a

' +
          '

Add / Remove Image Border

b

' +
          '

Toggle Opacity

o

' +
          '

Deselect All

esc

' +
          '

Delete Image(s)

delete\xa0backspace

' +
          '

Export Image(s)

e

' +
          '

'
      );
      /* eslint-enable */
      container.appendChild(button);
      return container;
    };

    this._keymapper.addTo(this._map);
  },

  _toggleKeymapper(e) {
    e.preventDefault();

    this._container.className = (
      this._container.className === 'ldi-keymapper leaflet-control' ?
        'ldi-keymapper-hide leaflet-control' :
        'ldi-keymapper leaflet-control'
    );

    this._scrollWrapper.style.display = (
      this._scrollWrapper.style.display === 'none' ? 'block' : 'none'
    );

    this._toggler.innerHTML = (
      this._toggler.innerHTML === 'close' ?
        L.IconUtil.create('keyboard_open') :
        'close'
    );

    L.IconUtil.toggleTitle(this._toggler, 'Show keymap', 'Hide keymap');
    L.DomUtil.toggleClass(this._toggler, 'close-icon');
  },

  _injectIconSet() {
    if (document.querySelector('#keymapper-iconset')) { return; }

    var el = L.DomUtil.create('div', '');
    el.id = 'keymapper-iconset';
    el.setAttribute('hidden', 'hidden');

    this._iconset = new L.KeymapperIconSet().render();
    el.innerHTML = this._iconset;

    document.querySelector('.leaflet-control-container').appendChild(el);
  },
});

L.DistortableImage.Keymapper.addInitHook(() => {
  L.DistortableImage.Keymapper.prototype._n = (
    L.DistortableImage.Keymapper.prototype._n ?
    L.DistortableImage.Keymapper.prototype._n + 1 :
    1
  );
  // dont enable keymapper for mobile
  if (L.DistortableImage.Keymapper.prototype._n === 1 && !L.Browser.mobile) {
    this.enable();
    this._injectIconSet();
  }
});

L.distortableImage.keymapper = (map, options) => {
  return new L.DistortableImage.Keymapper(map, options);
};
<|endoftext|>