<commit_before>/*===============================================================================
************   Handle clicks and make them fast (on tap);   ************
===============================================================================*/
app.initClickEvents = function () {
    function handleClicks(e) {
        /*jshint validthis:true */
        var clicked = $(this);
        var url = clicked.attr('href');
        var isLink = clicked[0].nodeName.toLowerCase() === 'a';

        // Str to boolean for data attributes
        function toBoolean(str) {
            if (str === 'false') return false;
            if (str === 'true') return true;
            return undefined;
        }
        // Check if link is external
        if (isLink) {
          if (clicked.is(app.params.extenalLinks) {
            if(clicked.attr('target') === '_system') {
              e.preventDefault();
              window.open(url, '_system');
            }
            return;
          }
        }

        // Smart Select
        if (clicked.hasClass('smart-select')) {
            if (app.smartSelectOpen) app.smartSelectOpen(clicked);
        }

        // Open Panel
        if (clicked.hasClass('open-panel')) {
            if ($('.panel').length === 1) {
                if ($('.panel').hasClass('panel-left')) app.openPanel('left');
                else app.openPanel('right');
            }
            else {
                if (clicked.attr('data-panel') === 'right') app.openPanel('right');
                else app.openPanel('left');
            }
        }
        // Close Panel
        if (clicked.hasClass('close-panel')) {
            app.closePanel();
        }

        if (clicked.hasClass('panel-overlay') && app.params.panelsCloseByOutside) {
            app.closePanel();
        }
        // Popover
        if (clicked.hasClass('open-popover')) {
            var popover;
            if (clicked.attr('data-popover')) {
                popover = clicked.attr('data-popover');
            }
            else popover = '.popover';
            app.popover(popover, clicked);
        }
        if (clicked.hasClass('close-popover')) {
            app.closeModal('.popover.modal-in');
        }
        // Popup
        var popup;
        if (clicked.hasClass('open-popup')) {
            if (clicked.attr('data-popup')) {
                popup = clicked.attr('data-popup');
            }
            else popup = '.popup';
            app.popup(popup);
        }
        if (clicked.hasClass('close-popup')) {
            if (clicked.attr('data-popup')) {
                popup = clicked.attr('data-popup');
            }
            else popup = '.popup.modal-in';
            app.closeModal(popup);
        }
        // Login Screen
        var loginScreen;
        if (clicked.hasClass('open-login-screen')) {
            if (clicked.attr('data-login-screen')) {
                loginScreen = clicked.attr('data-login-screen');
            }
            else loginScreen = '.login-screen';
            app.loginScreen(loginScreen);
        }
        if (clicked.hasClass('close-login-screen')) {
            app.closeModal('.login-screen.modal-in');
        }
        // Close Modal
        if (clicked.hasClass('modal-overlay')) {
            if ($('.modal.modal-in').length > 0 && app.params.modalCloseByOutside)
                app.closeModal('.modal.modal-in');
            if ($('.actions-modal.modal-in').length > 0 && app.params.actionsCloseByOutside)
                app.closeModal('.actions-modal.modal-in');

            if ($('.popover.modal-in').length > 0) app.closeModal('.popover.modal-in');
        }
        if (clicked.hasClass('popup-overlay')) {
            if ($('.popup.modal-in').length > 0 && app.params.popupCloseByOutside)
                app.closeModal('.popup.modal-in');
        }

        // Picker
        if (clicked.hasClass('close-picker')) {
            var pickerToClose = $('.picker-modal.modal-in');
            if (pickerToClose.length > 0) {
                app.closeModal(pickerToClose);
            }
            else {
                pickerToClose = $('.popover.modal-in .picker-modal');
                if (pickerToClose.length > 0) {
                    app.closeModal(pickerToClose.parents('.popover'));
                }
            }
        }
        if (clicked.hasClass('open-picker')) {
            var pickerToOpen;
            if (clicked.attr('data-picker')) {
                pickerToOpen = clicked.attr('data-picker');
            }
            else pickerToOpen = '.picker-modal';
            app.pickerModal(pickerToOpen, clicked);
        }

        // Tabs
        var isTabLink;
        if (clicked.hasClass('tab-link')) {
            isTabLink = true;
            app.showTab(clicked.attr('data-tab') || clicked.attr('href'), clicked);
        }
        // Swipeout Close
        if (clicked.hasClass('swipeout-close')) {
            app.swipeoutClose(clicked.parents('.swipeout-opened'));
        }
        // Swipeout Delete
        if (clicked.hasClass('swipeout-delete')) {
            if (clicked.attr('data-confirm')) {
                var text = clicked.attr('data-confirm');
                var title = clicked.attr('data-confirm-title');
                if (title) {
                    app.confirm(text, title, function () {
                        app.swipeoutDelete(clicked.parents('.swipeout'));
                    });
                }
                else {
                    app.confirm(text, function () {
                        app.swipeoutDelete(clicked.parents('.swipeout'));
                    });
                }
            }
            else {
                app.swipeoutDelete(clicked.parents('.swipeout'));
            }

        }
        // Sortable
        if (clicked.hasClass('toggle-sortable')) {
            app.sortableToggle(clicked.data('sortable'));
        }
        if (clicked.hasClass('open-sortable')) {
            app.sortableOpen(clicked.data('sortable'));
        }
        if (clicked.hasClass('close-sortable')) {
            app.sortableClose(clicked.data('sortable'));
        }
        // Accordion
        if (clicked.hasClass('accordion-item-toggle') || (clicked.hasClass('item-link') && clicked.parent().hasClass('accordion-item'))) {
            var accordionItem = clicked.parent('.accordion-item');
            if (accordionItem.length === 0) accordionItem = clicked.parents('.accordion-item');
            if (accordionItem.length === 0) accordionItem = clicked.parents('li');
            app.accordionToggle(accordionItem);
        }

        // Load Page
        if (app.params.ajaxLinks && !clicked.is(app.params.ajaxLinks) || !isLink || !app.params.router) {
            return;
        }
        if (isLink) {
            e.preventDefault();
        }

        var validUrl = url && url.length > 0 && url !== '#' && !isTabLink;
        var template = clicked.attr('data-template');
        if (validUrl || clicked.hasClass('back') || template) {
            var view;
            if (clicked.attr('data-view')) {
                view = $(clicked.attr('data-view'))[0].f7View;
            }
            else {
                view = clicked.parents('.' + app.params.viewClass)[0] && clicked.parents('.' + app.params.viewClass)[0].f7View;
                if (view && view.params.linksView) {
                    if (typeof view.params.linksView === 'string') view = $(view.params.linksView)[0].f7View;
                    else if (view.params.linksView instanceof View) view = view.params.linksView;
                }
            }
            if (!view) {
                if (app.mainView) view = app.mainView;
            }
            if (!view) return;

            var pageName;
            if (!template) {
                if (url.indexOf('#') === 0 && url !== '#')  {
                    if (view.params.domCache) {
                        pageName = url.split('#')[1];
                        url = undefined;
                    }
                    else return;
                }
                if (url === '#' && !clicked.hasClass('back')) return;
            }
            else {
                url = undefined;
            }

            var animatePages;
            if (clicked.attr('data-animatePages')) {
                animatePages = toBoolean(clicked.attr('data-animatePages'));
            }
            else {
                if (clicked.hasClass('with-animation')) animatePages = true;
                if (clicked.hasClass('no-animation')) animatePages = false;
            }

            var options = {
                animatePages: animatePages,
                ignoreCache: toBoolean(clicked.attr('data-ignoreCache')),
                force: toBoolean(clicked.attr('data-force')),
                reload: toBoolean(clicked.attr('data-reload')),
                reloadPrevious: toBoolean(clicked.attr('data-reloadPrevious')),
                pageName: pageName,
                url: url
            };

            if (app.params.template7Pages) {
                options.contextName = clicked.attr('data-contextName');
                var context = clicked.attr('data-context');
                if (context) {
                    options.context = JSON.parse(context);
                }
            }
            if (template && template in t7.templates) {
                options.template = t7.templates[template];
            }

            if (clicked.hasClass('back')) view.router.back(options);
            else view.router.load(options);
        }
    }
    $(document).on('click', 'a, .open-panel, .close-panel, .panel-overlay, .modal-overlay, .popup-overlay, .swipeout-delete, .swipeout-close, .close-popup, .open-popup, .open-popover, .open-login-screen, .close-login-screen .smart-select, .toggle-sortable, .open-sortable, .close-sortable, .accordion-item-toggle, .close-picker', handleClicks);

    // Prevent scrolling on overlays
    function preventScrolling(e) {
        e.preventDefault();
    }
    if (app.support.touch) {
        $(document).on('touchstart', '.panel-overlay, .modal-overlay, .preloader-indicator-overlay, .popup-overlay, .searchbar-overlay', preventScrolling);
    }
};
<commit_msg>typo fix<commit_after>/*===============================================================================
************   Handle clicks and make them fast (on tap);   ************
===============================================================================*/
app.initClickEvents = function () {
    function handleClicks(e) {
        /*jshint validthis:true */
        var clicked = $(this);
        var url = clicked.attr('href');
        var isLink = clicked[0].nodeName.toLowerCase() === 'a';

        // Str to boolean for data attributes
        function toBoolean(str) {
            if (str === 'false') return false;
            if (str === 'true') return true;
            return undefined;
        }
        // Check if link is external
        if (isLink) {
          if (clicked.is(app.params.extenalLinks)) {
            if(clicked.attr('target') === '_system') {
              e.preventDefault();
              window.open(url, '_system');
            }
            return;
          }
        }

        // Smart Select
        if (clicked.hasClass('smart-select')) {
            if (app.smartSelectOpen) app.smartSelectOpen(clicked);
        }

        // Open Panel
        if (clicked.hasClass('open-panel')) {
            if ($('.panel').length === 1) {
                if ($('.panel').hasClass('panel-left')) app.openPanel('left');
                else app.openPanel('right');
            }
            else {
                if (clicked.attr('data-panel') === 'right') app.openPanel('right');
                else app.openPanel('left');
            }
        }
        // Close Panel
        if (clicked.hasClass('close-panel')) {
            app.closePanel();
        }

        if (clicked.hasClass('panel-overlay') && app.params.panelsCloseByOutside) {
            app.closePanel();
        }
        // Popover
        if (clicked.hasClass('open-popover')) {
            var popover;
            if (clicked.attr('data-popover')) {
                popover = clicked.attr('data-popover');
            }
            else popover = '.popover';
            app.popover(popover, clicked);
        }
        if (clicked.hasClass('close-popover')) {
            app.closeModal('.popover.modal-in');
        }
        // Popup
        var popup;
        if (clicked.hasClass('open-popup')) {
            if (clicked.attr('data-popup')) {
                popup = clicked.attr('data-popup');
            }
            else popup = '.popup';
            app.popup(popup);
        }
        if (clicked.hasClass('close-popup')) {
            if (clicked.attr('data-popup')) {
                popup = clicked.attr('data-popup');
            }
            else popup = '.popup.modal-in';
            app.closeModal(popup);
        }
        // Login Screen
        var loginScreen;
        if (clicked.hasClass('open-login-screen')) {
            if (clicked.attr('data-login-screen')) {
                loginScreen = clicked.attr('data-login-screen');
            }
            else loginScreen = '.login-screen';
            app.loginScreen(loginScreen);
        }
        if (clicked.hasClass('close-login-screen')) {
            app.closeModal('.login-screen.modal-in');
        }
        // Close Modal
        if (clicked.hasClass('modal-overlay')) {
            if ($('.modal.modal-in').length > 0 && app.params.modalCloseByOutside)
                app.closeModal('.modal.modal-in');
            if ($('.actions-modal.modal-in').length > 0 && app.params.actionsCloseByOutside)
                app.closeModal('.actions-modal.modal-in');

            if ($('.popover.modal-in').length > 0) app.closeModal('.popover.modal-in');
        }
        if (clicked.hasClass('popup-overlay')) {
            if ($('.popup.modal-in').length > 0 && app.params.popupCloseByOutside)
                app.closeModal('.popup.modal-in');
        }

        // Picker
        if (clicked.hasClass('close-picker')) {
            var pickerToClose = $('.picker-modal.modal-in');
            if (pickerToClose.length > 0) {
                app.closeModal(pickerToClose);
            }
            else {
                pickerToClose = $('.popover.modal-in .picker-modal');
                if (pickerToClose.length > 0) {
                    app.closeModal(pickerToClose.parents('.popover'));
                }
            }
        }
        if (clicked.hasClass('open-picker')) {
            var pickerToOpen;
            if (clicked.attr('data-picker')) {
                pickerToOpen = clicked.attr('data-picker');
            }
            else pickerToOpen = '.picker-modal';
            app.pickerModal(pickerToOpen, clicked);
        }

        // Tabs
        var isTabLink;
        if (clicked.hasClass('tab-link')) {
            isTabLink = true;
            app.showTab(clicked.attr('data-tab') || clicked.attr('href'), clicked);
        }
        // Swipeout Close
        if (clicked.hasClass('swipeout-close')) {
            app.swipeoutClose(clicked.parents('.swipeout-opened'));
        }
        // Swipeout Delete
        if (clicked.hasClass('swipeout-delete')) {
            if (clicked.attr('data-confirm')) {
                var text = clicked.attr('data-confirm');
                var title = clicked.attr('data-confirm-title');
                if (title) {
                    app.confirm(text, title, function () {
                        app.swipeoutDelete(clicked.parents('.swipeout'));
                    });
                }
                else {
                    app.confirm(text, function () {
                        app.swipeoutDelete(clicked.parents('.swipeout'));
                    });
                }
            }
            else {
                app.swipeoutDelete(clicked.parents('.swipeout'));
            }

        }
        // Sortable
        if (clicked.hasClass('toggle-sortable')) {
            app.sortableToggle(clicked.data('sortable'));
        }
        if (clicked.hasClass('open-sortable')) {
            app.sortableOpen(clicked.data('sortable'));
        }
        if (clicked.hasClass('close-sortable')) {
            app.sortableClose(clicked.data('sortable'));
        }
        // Accordion
        if (clicked.hasClass('accordion-item-toggle') || (clicked.hasClass('item-link') && clicked.parent().hasClass('accordion-item'))) {
            var accordionItem = clicked.parent('.accordion-item');
            if (accordionItem.length === 0) accordionItem = clicked.parents('.accordion-item');
            if (accordionItem.length === 0) accordionItem = clicked.parents('li');
            app.accordionToggle(accordionItem);
        }

        // Load Page
        if (app.params.ajaxLinks && !clicked.is(app.params.ajaxLinks) || !isLink || !app.params.router) {
            return;
        }
        if (isLink) {
            e.preventDefault();
        }

        var validUrl = url && url.length > 0 && url !== '#' && !isTabLink;
        var template = clicked.attr('data-template');
        if (validUrl || clicked.hasClass('back') || template) {
            var view;
            if (clicked.attr('data-view')) {
                view = $(clicked.attr('data-view'))[0].f7View;
            }
            else {
                view = clicked.parents('.' + app.params.viewClass)[0] && clicked.parents('.' + app.params.viewClass)[0].f7View;
                if (view && view.params.linksView) {
                    if (typeof view.params.linksView === 'string') view = $(view.params.linksView)[0].f7View;
                    else if (view.params.linksView instanceof View) view = view.params.linksView;
                }
            }
            if (!view) {
                if (app.mainView) view = app.mainView;
            }
            if (!view) return;

            var pageName;
            if (!template) {
                if (url.indexOf('#') === 0 && url !== '#')  {
                    if (view.params.domCache) {
                        pageName = url.split('#')[1];
                        url = undefined;
                    }
                    else return;
                }
                if (url === '#' && !clicked.hasClass('back')) return;
            }
            else {
                url = undefined;
            }

            var animatePages;
            if (clicked.attr('data-animatePages')) {
                animatePages = toBoolean(clicked.attr('data-animatePages'));
            }
            else {
                if (clicked.hasClass('with-animation')) animatePages = true;
                if (clicked.hasClass('no-animation')) animatePages = false;
            }

            var options = {
                animatePages: animatePages,
                ignoreCache: toBoolean(clicked.attr('data-ignoreCache')),
                force: toBoolean(clicked.attr('data-force')),
                reload: toBoolean(clicked.attr('data-reload')),
                reloadPrevious: toBoolean(clicked.attr('data-reloadPrevious')),
                pageName: pageName,
                url: url
            };

            if (app.params.template7Pages) {
                options.contextName = clicked.attr('data-contextName');
                var context = clicked.attr('data-context');
                if (context) {
                    options.context = JSON.parse(context);
                }
            }
            if (template && template in t7.templates) {
                options.template = t7.templates[template];
            }

            if (clicked.hasClass('back')) view.router.back(options);
            else view.router.load(options);
        }
    }
    $(document).on('click', 'a, .open-panel, .close-panel, .panel-overlay, .modal-overlay, .popup-overlay, .swipeout-delete, .swipeout-close, .close-popup, .open-popup, .open-popover, .open-login-screen, .close-login-screen .smart-select, .toggle-sortable, .open-sortable, .close-sortable, .accordion-item-toggle, .close-picker', handleClicks);

    // Prevent scrolling on overlays
    function preventScrolling(e) {
        e.preventDefault();
    }
    if (app.support.touch) {
        $(document).on('touchstart', '.panel-overlay, .modal-overlay, .preloader-indicator-overlay, .popup-overlay, .searchbar-overlay', preventScrolling);
    }
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

const Layout = () => (

やっていく

);

const app = document.getElementById('app');

ReactDOM.render(<Layout />, app);
<commit_msg>:recycle: Refactor<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

const Layout = () =>
やっていく
;

ReactDOM.render(
  <Layout />,
  document.getElementById('app')
);
<|endoftext|>


<commit_before>var Cell = require("./propagator-cell.js")

function coerceToArray(object) {
    if (!(object instanceof Array)) return [object];
    else return object;
}

function Propagator(func,input,output) {
      var self = this

      assert(func && input && output, "You need to call the propagator constructor with all three of a function, input cell and output cell")
      assert(input instanceof Cell || input instanceof Array,  "Propagators read from cells, not", typeof input)
      assert(output instanceof Cell, "Propagators output to cells, not", typeof output)
      assert(input !== output, "Propagators shouldn't write out to the same cell they read from.")

      this.input = coerceToArray(input);
      this.output = output;

      function applyFuncToInputs() {
          var inputValues = self.input.map((cell) => cell.getContents())

          return func.apply(null,inputValues);

      }

      this.propagate = function propagate() {

          var outputValues = applyFuncToInputs();
          self.output.update(outputValues, self)
      }

      this.input.forEach( (cell) => cell.addListener(self.propagate) )
}

Propagator.makeCell = function makeCell() {return new Cell};
Propagator.prototype.makeCell = Propagator.makeCell;

module.exports = Propagator<commit_msg>fixed missing assert library import<commit_after>var Cell = require("./propagator-cell.js")
var assert = require("assert")

function coerceToArray(object) {
    if (!(object instanceof Array)) return [object];
    else return object;
}

function Propagator(func,input,output) {
      var self = this

      assert(func && input && output, "You need to call the propagator constructor with all three of a function, input cell and output cell")
      assert(input instanceof Cell || input instanceof Array,  "Propagators read from cells, not", typeof input)
      assert(output instanceof Cell, "Propagators output to cells, not", typeof output)
      assert(input !== output, "Propagators shouldn't write out to the same cell they read from.")

      this.input = coerceToArray(input);
      this.output = output;

      function applyFuncToInputs() {
          var inputValues = self.input.map((cell) => cell.getContents())

          return func.apply(null,inputValues);

      }

      this.propagate = function propagate() {

          var outputValues = applyFuncToInputs();
          self.output.update(outputValues, self)
      }

      this.input.forEach( (cell) => cell.addListener(self.propagate) )
}

Propagator.makeCell = function makeCell() {return new Cell};
Propagator.prototype.makeCell = Propagator.makeCell;

module.exports = Propagator<|endoftext|>


<commit_before>var __loader = (function() {

var loader = {};

loader.packages = {};

loader.packagesLinenoOrder = [{ filename: 'loader.js', lineno: 0 }];

loader.extpaths = ['?', '?.js', '?.json', '?/index.js'];

loader.require = function(path) {
  var module;
  var extpaths = loader.extpaths;
  for (var i = 0, ii = extpaths.length; !module && i < ii; ++i) {
    var filepath = extpaths[i].replace('?', path);
    module = loader.packages[filepath];
  }

  if (!module) {
    throw new Error("Cannot find module'" + path + "'");
  }

  if (module.exports) {
    return module.exports;
  }

  module.exports = {};
  module.loader(module, loader.require);
  module.loaded = true;

  return module.exports;
};

loader.define = function(path, lineno, loader) {
  var module = {
    filename: path,
    lineno: lineno,
    loader: loader,
  };

  loader.packages[path] = module;
  loader.packagesLinenoOrder.push(module);
  loader.packagesLinenoOrder.sort(function(a, b) {
    return a.lineno - b.lineno;
  });
};

loader.getPackageByLineno = function(lineno) {
  var packages = loader.packagesLinenoOrder;
  var module;
  for (var i = 0, ii = packages.length; i < ii; ++i) {
    var next = packages[i];
    if (next.lineno > lineno) {
      break;
    }
    module = next;
  }
  return module;
};

return loader;

})();
<commit_msg>Add loader.js paths for attempting to load relative to multiple paths<commit_after>var __loader = (function() {

var loader = {};

loader.packages = {};

loader.packagesLinenoOrder = [{ filename: 'loader.js', lineno: 0 }];

loader.extpaths = ['?', '?.js', '?.json', '?/index.js'];

loader.paths = ['lib', 'vendor'];

loader.require = function(path) {
  var module = loader.getPackage(path);
  if (!module) {
    throw new Error("Cannot find module'" + path + "'");
  }

  if (module.exports) {
    return module.exports;
  }

  module.exports = {};
  module.loader(module, loader.require);
  module.loaded = true;

  return module.exports;
};

var compareLineno = function(a, b) { return a.lineno - b.lineno; };

loader.define = function(path, lineno, loadfun) {
  var module = {
    filename: path,
    lineno: lineno,
    loader: loadfun,
  };

  loader.packages[path] = module;
  loader.packagesLinenoOrder.push(module);
  loader.packagesLinenoOrder.sort(compareLineno);
};

loader.getPackage = function(path) {
  var module = loader.getPackageAtPath(path);
  var paths = loader.paths;
  for (var i = 0, ii = paths.length; !module && i < ii; ++i) {
    var dirpath = paths[i];
    module = loader.getPackageAtPath(dirpath + '/' + path);
  }
  return module;
};

loader.getPackageAtPath = function(path) {
  var module;
  var extpaths = loader.extpaths;
  for (var i = 0, ii = extpaths.length; !module && i < ii; ++i) {
    var filepath = extpaths[i].replace('?', path);
    module = loader.packages[filepath];
  }
  return module;
};

loader.getPackageByLineno = function(lineno) {
  var packages = loader.packagesLinenoOrder;
  var module;
  for (var i = 0, ii = packages.length; i < ii; ++i) {
    var next = packages[i];
    if (next.lineno > lineno) {
      break;
    }
    module = next;
  }
  return module;
};

return loader;

})();
<|endoftext|>


<commit_before>  $.extend(prototype, {
    render: function () {
      this.initContainer();
      this.initCanvas();
      this.initCropBox();

      this.renderCanvas();

      if (this.cropped) {
        this.renderCropBox();
      }
    },

    initContainer: function () {
      var options = this.options;
      var $this = this.$element;
      var $container = this.$container;
      var $cropper = this.$cropper;

      $cropper.addClass(CLASS_HIDDEN);
      $this.removeClass(CLASS_HIDDEN);

      $cropper.css((this.container = {
        width: max($container.width(), num(options.minContainerWidth) || 200),
        height: max($container.height(), num(options.minContainerHeight) || 100)
      }));

      $this.addClass(CLASS_HIDDEN);
      $cropper.removeClass(CLASS_HIDDEN);
    },

    // Canvas (image wrapper)
    initCanvas: function () {
      var container = this.container;
      var containerWidth = container.width;
      var containerHeight = container.height;
      var image = this.image;
      var aspectRatio = image.aspectRatio;
      var canvas = {
            aspectRatio: aspectRatio,
            width: containerWidth,
            height: containerHeight
          };

      if (containerHeight * aspectRatio > containerWidth) {
        canvas.height = containerWidth / aspectRatio;
      } else {
        canvas.width = containerHeight * aspectRatio;
      }

      canvas.oldLeft = canvas.left = (containerWidth - canvas.width) / 2;
      canvas.oldTop = canvas.top = (containerHeight - canvas.height) / 2;

      this.canvas = canvas;
      this.limitCanvas(true, true);
      this.initialImage = $.extend({}, image);
      this.initialCanvas = $.extend({}, canvas);
    },

    limitCanvas: function (size, position) {
      var options = this.options;
      var strict = options.strict;
      var container = this.container;
      var containerWidth = container.width;
      var containerHeight = container.height;
      var canvas = this.canvas;
      var aspectRatio = canvas.aspectRatio;
      var cropBox = this.cropBox;
      var cropped = this.cropped && cropBox;
      var initialCanvas = this.initialCanvas || canvas;
      var minCanvasWidth;
      var minCanvasHeight;

      if (size) {
        minCanvasWidth = num(options.minCanvasWidth) || 0;
        minCanvasHeight = num(options.minCanvasHeight) || 0;

        if (strict) {
          if (minCanvasWidth) {
            minCanvasWidth = max(minCanvasWidth, cropped ? cropBox.width : initialCanvas.width);
          } else if (minCanvasHeight) {
            minCanvasHeight = max(minCanvasHeight, cropped ? cropBox.height : initialCanvas.height);
          } else if (cropped) {
            minCanvasWidth = cropBox.width;
            minCanvasHeight = cropBox.height;

            if (minCanvasHeight * aspectRatio > minCanvasWidth) {
              minCanvasWidth = minCanvasHeight * aspectRatio;
            } else {
              minCanvasHeight = minCanvasWidth / aspectRatio;
            }
          }
        }

        if (minCanvasWidth && minCanvasHeight) {
          if (minCanvasHeight * aspectRatio > minCanvasWidth) {
            minCanvasHeight = minCanvasWidth / aspectRatio;
          } else {
            minCanvasWidth = minCanvasHeight * aspectRatio;
          }
        } else if (minCanvasWidth) {
          minCanvasHeight = minCanvasWidth / aspectRatio;
        } else if (minCanvasHeight) {
          minCanvasWidth = minCanvasHeight * aspectRatio;
        }

        canvas.minWidth = minCanvasWidth;
        canvas.minHeight = minCanvasHeight;
        canvas.maxWidth = Infinity;
        canvas.maxHeight = Infinity;
      }

      if (position) {
        if (strict) {
          canvas.minLeft = cropped ?
            min(cropBox.left, (cropBox.left + cropBox.width) - canvas.width) :
            min(0, containerWidth - canvas.width);
          canvas.minTop = cropped ?
            min(cropBox.top, (cropBox.top + cropBox.height) - canvas.height) :
            min(0, containerHeight - canvas.height);
          canvas.maxLeft = cropped ? cropBox.left : max(0, containerWidth - canvas.width);
          canvas.maxTop = cropped ? cropBox.top : max(0, containerHeight - canvas.height);
        } else {
          canvas.minLeft = -canvas.width;
          canvas.minTop = -canvas.height;
          canvas.maxLeft = containerWidth;
          canvas.maxTop = containerHeight;
        }
      }
    },

    renderCanvas: function (changed) {
      var options = this.options;
      var canvas = this.canvas;
      var image = this.image;
      var aspectRatio;
      var rotated;

      if (this.rotated) {
        this.rotated = false;

        // Computes rotated sizes with image sizes
        rotated = getRotatedSizes({
          width: image.width,
          height: image.height,
          degree: image.rotate
        });

        aspectRatio = rotated.width / rotated.height;

        if (aspectRatio !== canvas.aspectRatio) {
          canvas.left -= (rotated.width - canvas.width) / 2;
          canvas.top -= (rotated.height - canvas.height) / 2;
          canvas.width = rotated.width;
          canvas.height = rotated.height;
          canvas.aspectRatio = aspectRatio;
          this.limitCanvas(true, false);
        }
      }

      if (canvas.width > canvas.maxWidth || canvas.width < canvas.minWidth) {
        canvas.left = canvas.oldLeft;
      }

      if (canvas.height > canvas.maxHeight || canvas.height < canvas.minHeight) {
        canvas.top = canvas.oldTop;
      }

      canvas.width = min(max(canvas.width, canvas.minWidth), canvas.maxWidth);
      canvas.height = min(max(canvas.height, canvas.minHeight), canvas.maxHeight);

      this.limitCanvas(false, true);

      canvas.oldLeft = canvas.left = min(max(canvas.left, canvas.minLeft), canvas.maxLeft);
      canvas.oldTop = canvas.top = min(max(canvas.top, canvas.minTop), canvas.maxTop);

      this.$canvas.css({
        width: canvas.width,
        height: canvas.height,
        left: canvas.left,
        top: canvas.top
      });

      this.renderImage();

      if (this.cropped && options.strict) {
        this.limitCropBox(true, true);
      }

      if (changed) {
        this.output();
      }
    },

    renderImage: function (changed) {
      var canvas = this.canvas;
      var image = this.image;
      var reversed;

      if (image.rotate) {
        reversed = getRotatedSizes({
          width: canvas.width,
          height: canvas.height,
          degree: image.rotate,
          aspectRatio: image.aspectRatio
        }, true);
      }

      $.extend(image, reversed ? {
        width: reversed.width,
        height: reversed.height,
        left: (canvas.width - reversed.width) / 2,
        top: (canvas.height - reversed.height) / 2
      } : {
        width: canvas.width,
        height: canvas.height,
        left: 0,
        top: 0
      });

      this.$clone.css({
        width: image.width,
        height: image.height,
        marginLeft: image.left,
        marginTop: image.top,
        transform: getTransform(image)
      });

      if (changed) {
        this.output();
      }
    },

    initCropBox: function () {
      var options = this.options;
      var canvas = this.canvas;
      var aspectRatio = options.aspectRatio;
      var autoCropArea = num(options.autoCropArea) || 0.8;
      var cropBox = {
            width: canvas.width,
            height: canvas.height
          };

      if (aspectRatio) {
        if (canvas.height * aspectRatio > canvas.width) {
          cropBox.height = cropBox.width / aspectRatio;
        } else {
          cropBox.width = cropBox.height * aspectRatio;
        }
      }

      this.cropBox = cropBox;
      this.limitCropBox(true, true);

      // Initialize auto crop area
      cropBox.width = min(max(cropBox.width, cropBox.minWidth), cropBox.maxWidth);
      cropBox.height = min(max(cropBox.height, cropBox.minHeight), cropBox.maxHeight);

      // The width of auto crop area must large than "minWidth", and the height too. (#164)
      cropBox.width = max(cropBox.minWidth, cropBox.width * autoCropArea);
      cropBox.height = max(cropBox.minHeight, cropBox.height * autoCropArea);
      cropBox.oldLeft = cropBox.left = canvas.left + (canvas.width - cropBox.width) / 2;
      cropBox.oldTop = cropBox.top = canvas.top + (canvas.height - cropBox.height) / 2;

      this.initialCropBox = $.extend({}, cropBox);
    },

    limitCropBox: function (size, position) {
      var options = this.options;
      var strict = options.strict;
      var container = this.container;
      var containerWidth = container.width;
      var containerHeight = container.height;
      var canvas = this.canvas;
      var cropBox = this.cropBox;
      var aspectRatio = options.aspectRatio;
      var minCropBoxWidth;
      var minCropBoxHeight;
      var maxCropBoxWidth;
      var maxCropBoxHeight;

      if (size) {
        minCropBoxWidth = num(options.minCropBoxWidth) || 0;
        minCropBoxHeight = num(options.minCropBoxHeight) || 0;

        // The min/maxCropBoxWidth/Height must be less than containerWidth/Height
        minCropBoxWidth = min(minCropBoxWidth, containerWidth);
        minCropBoxHeight = min(minCropBoxHeight, containerHeight);
        maxCropBoxWidth = min(containerWidth, strict ? canvas.width : containerWidth);
        maxCropBoxHeight = min(containerHeight, strict ? canvas.height : containerHeight);

        if (aspectRatio) {
          if (minCropBoxWidth && minCropBoxHeight) {
            if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {
              minCropBoxHeight = minCropBoxWidth / aspectRatio;
            } else {
              minCropBoxWidth = minCropBoxHeight * aspectRatio;
            }
          } else if (minCropBoxWidth) {
            minCropBoxHeight = minCropBoxWidth / aspectRatio;
          } else if (minCropBoxHeight) {
            minCropBoxWidth = minCropBoxHeight * aspectRatio;
          }

          if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {
            maxCropBoxHeight = maxCropBoxWidth / aspectRatio;
          } else {
            maxCropBoxWidth = maxCropBoxHeight * aspectRatio;
          }
        }

        // The minWidth/Height must be less than maxWidth/Height
        cropBox.minWidth = min(minCropBoxWidth, maxCropBoxWidth);
        cropBox.minHeight = min(minCropBoxHeight, maxCropBoxHeight);
        cropBox.maxWidth = maxCropBoxWidth;
        cropBox.maxHeight = maxCropBoxHeight;
      }

      if (position) {
        if (strict) {
          cropBox.minLeft = max(0, canvas.left);
          cropBox.minTop = max(0, canvas.top);
          cropBox.maxLeft = min(containerWidth, canvas.left + canvas.width) - cropBox.width;
          cropBox.maxTop = min(containerHeight, canvas.top + canvas.height) - cropBox.height;
        } else {
          cropBox.minLeft = 0;
          cropBox.minTop = 0;
          cropBox.maxLeft = containerWidth - cropBox.width;
          cropBox.maxTop = containerHeight - cropBox.height;
        }
      }
    },

    renderCropBox: function () {
      var options = this.options;
      var container = this.container;
      var containerWidth = container.width;
      var containerHeight = container.height;
      var cropBox = this.cropBox;

      if (cropBox.width > cropBox.maxWidth || cropBox.width < cropBox.minWidth) {
        cropBox.left = cropBox.oldLeft;
      }

      if (cropBox.height > cropBox.maxHeight || cropBox.height < cropBox.minHeight) {
        cropBox.top = cropBox.oldTop;
      }

      cropBox.width = min(max(cropBox.width, cropBox.minWidth), cropBox.maxWidth);
      cropBox.height = min(max(cropBox.height, cropBox.minHeight), cropBox.maxHeight);

      this.limitCropBox(false, true);

      cropBox.oldLeft = cropBox.left = min(max(cropBox.left, cropBox.minLeft), cropBox.maxLeft);
      cropBox.oldTop = cropBox.top = min(max(cropBox.top, cropBox.minTop), cropBox.maxTop);

      if (options.movable && options.cropBoxMovable) {

        // Turn to move the canvas when the crop box is equal to the container
        this.$face.data(DATA_ACTION, (cropBox.width === containerWidth && cropBox.height === containerHeight) ? ACTION_MOVE : ACTION_ALL);
      }

      this.$cropBox.css({
        width: cropBox.width,
        height: cropBox.height,
        left: cropBox.left,
        top: cropBox.top
      });

      if (this.cropped && options.strict) {
        this.limitCanvas(true, true);
      }

      if (!this.disabled) {
        this.output();
      }
    },

    output: function () {
      this.preview();

      if (this.complete) {
        this.trigger(EVENT_CROP, this.getData());
      } else if (!this.built) {

        // Only trigger one crop event before complete
        this.$element.one(EVENT_BUILT, $.proxy(function () {
          this.trigger(EVENT_CROP, this.getData());
        }, this));
      }
    }
  });
<commit_msg>Added `naturalWidth/Height` to `canvasData`<commit_after>  $.extend(prototype, {
    render: function () {
      this.initContainer();
      this.initCanvas();
      this.initCropBox();

      this.renderCanvas();

      if (this.cropped) {
        this.renderCropBox();
      }
    },

    initContainer: function () {
      var options = this.options;
      var $this = this.$element;
      var $container = this.$container;
      var $cropper = this.$cropper;

      $cropper.addClass(CLASS_HIDDEN);
      $this.removeClass(CLASS_HIDDEN);

      $cropper.css((this.container = {
        width: max($container.width(), num(options.minContainerWidth) || 200),
        height: max($container.height(), num(options.minContainerHeight) || 100)
      }));

      $this.addClass(CLASS_HIDDEN);
      $cropper.removeClass(CLASS_HIDDEN);
    },

    // Canvas (image wrapper)
    initCanvas: function () {
      var container = this.container;
      var containerWidth = container.width;
      var containerHeight = container.height;
      var image = this.image;
      var aspectRatio = image.aspectRatio;
      var canvas = {
            naturalWidth: image.naturalWidth,
            naturalHeight: image.naturalHeight,
            aspectRatio: aspectRatio,
            width: containerWidth,
            height: containerHeight
          };

      if (containerHeight * aspectRatio > containerWidth) {
        canvas.height = containerWidth / aspectRatio;
      } else {
        canvas.width = containerHeight * aspectRatio;
      }

      canvas.oldLeft = canvas.left = (containerWidth - canvas.width) / 2;
      canvas.oldTop = canvas.top = (containerHeight - canvas.height) / 2;

      this.canvas = canvas;
      this.limitCanvas(true, true);
      this.initialImage = $.extend({}, image);
      this.initialCanvas = $.extend({}, canvas);
    },

    limitCanvas: function (size, position) {
      var options = this.options;
      var strict = options.strict;
      var container = this.container;
      var containerWidth = container.width;
      var containerHeight = container.height;
      var canvas = this.canvas;
      var aspectRatio = canvas.aspectRatio;
      var cropBox = this.cropBox;
      var cropped = this.cropped && cropBox;
      var initialCanvas = this.initialCanvas || canvas;
      var minCanvasWidth;
      var minCanvasHeight;

      if (size) {
        minCanvasWidth = num(options.minCanvasWidth) || 0;
        minCanvasHeight = num(options.minCanvasHeight) || 0;

        if (strict) {
          if (minCanvasWidth) {
            minCanvasWidth = max(minCanvasWidth, cropped ? cropBox.width : initialCanvas.width);
          } else if (minCanvasHeight) {
            minCanvasHeight = max(minCanvasHeight, cropped ? cropBox.height : initialCanvas.height);
          } else if (cropped) {
            minCanvasWidth = cropBox.width;
            minCanvasHeight = cropBox.height;

            if (minCanvasHeight * aspectRatio > minCanvasWidth) {
              minCanvasWidth = minCanvasHeight * aspectRatio;
            } else {
              minCanvasHeight = minCanvasWidth / aspectRatio;
            }
          }
        }

        if (minCanvasWidth && minCanvasHeight) {
          if (minCanvasHeight * aspectRatio > minCanvasWidth) {
            minCanvasHeight = minCanvasWidth / aspectRatio;
          } else {
            minCanvasWidth = minCanvasHeight * aspectRatio;
          }
        } else if (minCanvasWidth) {
          minCanvasHeight = minCanvasWidth / aspectRatio;
        } else if (minCanvasHeight) {
          minCanvasWidth = minCanvasHeight * aspectRatio;
        }

        canvas.minWidth = minCanvasWidth;
        canvas.minHeight = minCanvasHeight;
        canvas.maxWidth = Infinity;
        canvas.maxHeight = Infinity;
      }

      if (position) {
        if (strict) {
          canvas.minLeft = cropped ?
            min(cropBox.left, (cropBox.left + cropBox.width) - canvas.width) :
            min(0, containerWidth - canvas.width);
          canvas.minTop = cropped ?
            min(cropBox.top, (cropBox.top + cropBox.height) - canvas.height) :
            min(0, containerHeight - canvas.height);
          canvas.maxLeft = cropped ? cropBox.left : max(0, containerWidth - canvas.width);
          canvas.maxTop = cropped ? cropBox.top : max(0, containerHeight - canvas.height);
        } else {
          canvas.minLeft = -canvas.width;
          canvas.minTop = -canvas.height;
          canvas.maxLeft = containerWidth;
          canvas.maxTop = containerHeight;
        }
      }
    },

    renderCanvas: function (changed) {
      var options = this.options;
      var canvas = this.canvas;
      var image = this.image;
      var rotate = image.rotate;
      var naturalWidth = image.naturalWidth;
      var naturalHeight = image.naturalHeight;
      var aspectRatio;
      var rotated;

      if (this.rotated) {
        this.rotated = false;

        // Computes rotated sizes with image sizes
        rotated = getRotatedSizes({
          width: image.width,
          height: image.height,
          degree: rotate
        });

        aspectRatio = rotated.width / rotated.height;

        if (aspectRatio !== canvas.aspectRatio) {
          canvas.left -= (rotated.width - canvas.width) / 2;
          canvas.top -= (rotated.height - canvas.height) / 2;
          canvas.width = rotated.width;
          canvas.height = rotated.height;
          canvas.aspectRatio = aspectRatio;
          canvas.naturalWidth = naturalWidth;
          canvas.naturalHeight = naturalHeight;

          // Computes rotated sizes with natural image sizes
          if (rotate % 180) {
            rotated = getRotatedSizes({
              width: naturalWidth,
              height: naturalHeight,
              degree: rotate
            });

            canvas.naturalWidth = rotated.width;
            canvas.naturalHeight = rotated.height;
          }

          this.limitCanvas(true, false);
        }
      }

      if (canvas.width > canvas.maxWidth || canvas.width < canvas.minWidth) {
        canvas.left = canvas.oldLeft;
      }

      if (canvas.height > canvas.maxHeight || canvas.height < canvas.minHeight) {
        canvas.top = canvas.oldTop;
      }

      canvas.width = min(max(canvas.width, canvas.minWidth), canvas.maxWidth);
      canvas.height = min(max(canvas.height, canvas.minHeight), canvas.maxHeight);

      this.limitCanvas(false, true);

      canvas.oldLeft = canvas.left = min(max(canvas.left, canvas.minLeft), canvas.maxLeft);
      canvas.oldTop = canvas.top = min(max(canvas.top, canvas.minTop), canvas.maxTop);

      this.$canvas.css({
        width: canvas.width,
        height: canvas.height,
        left: canvas.left,
        top: canvas.top
      });

      this.renderImage();

      if (this.cropped && options.strict) {
        this.limitCropBox(true, true);
      }

      if (changed) {
        this.output();
      }
    },

    renderImage: function (changed) {
      var canvas = this.canvas;
      var image = this.image;
      var reversed;

      if (image.rotate) {
        reversed = getRotatedSizes({
          width: canvas.width,
          height: canvas.height,
          degree: image.rotate,
          aspectRatio: image.aspectRatio
        }, true);
      }

      $.extend(image, reversed ? {
        width: reversed.width,
        height: reversed.height,
        left: (canvas.width - reversed.width) / 2,
        top: (canvas.height - reversed.height) / 2
      } : {
        width: canvas.width,
        height: canvas.height,
        left: 0,
        top: 0
      });

      this.$clone.css({
        width: image.width,
        height: image.height,
        marginLeft: image.left,
        marginTop: image.top,
        transform: getTransform(image)
      });

      if (changed) {
        this.output();
      }
    },

    initCropBox: function () {
      var options = this.options;
      var canvas = this.canvas;
      var aspectRatio = options.aspectRatio;
      var autoCropArea = num(options.autoCropArea) || 0.8;
      var cropBox = {
            width: canvas.width,
            height: canvas.height
          };

      if (aspectRatio) {
        if (canvas.height * aspectRatio > canvas.width) {
          cropBox.height = cropBox.width / aspectRatio;
        } else {
          cropBox.width = cropBox.height * aspectRatio;
        }
      }

      this.cropBox = cropBox;
      this.limitCropBox(true, true);

      // Initialize auto crop area
      cropBox.width = min(max(cropBox.width, cropBox.minWidth), cropBox.maxWidth);
      cropBox.height = min(max(cropBox.height, cropBox.minHeight), cropBox.maxHeight);

      // The width of auto crop area must large than "minWidth", and the height too. (#164)
      cropBox.width = max(cropBox.minWidth, cropBox.width * autoCropArea);
      cropBox.height = max(cropBox.minHeight, cropBox.height * autoCropArea);
      cropBox.oldLeft = cropBox.left = canvas.left + (canvas.width - cropBox.width) / 2;
      cropBox.oldTop = cropBox.top = canvas.top + (canvas.height - cropBox.height) / 2;

      this.initialCropBox = $.extend({}, cropBox);
    },

    limitCropBox: function (size, position) {
      var options = this.options;
      var strict = options.strict;
      var container = this.container;
      var containerWidth = container.width;
      var containerHeight = container.height;
      var canvas = this.canvas;
      var cropBox = this.cropBox;
      var aspectRatio = options.aspectRatio;
      var minCropBoxWidth;
      var minCropBoxHeight;
      var maxCropBoxWidth;
      var maxCropBoxHeight;

      if (size) {
        minCropBoxWidth = num(options.minCropBoxWidth) || 0;
        minCropBoxHeight = num(options.minCropBoxHeight) || 0;

        // The min/maxCropBoxWidth/Height must be less than containerWidth/Height
        minCropBoxWidth = min(minCropBoxWidth, containerWidth);
        minCropBoxHeight = min(minCropBoxHeight, containerHeight);
        maxCropBoxWidth = min(containerWidth, strict ? canvas.width : containerWidth);
        maxCropBoxHeight = min(containerHeight, strict ? canvas.height : containerHeight);

        if (aspectRatio) {
          if (minCropBoxWidth && minCropBoxHeight) {
            if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {
              minCropBoxHeight = minCropBoxWidth / aspectRatio;
            } else {
              minCropBoxWidth = minCropBoxHeight * aspectRatio;
            }
          } else if (minCropBoxWidth) {
            minCropBoxHeight = minCropBoxWidth / aspectRatio;
          } else if (minCropBoxHeight) {
            minCropBoxWidth = minCropBoxHeight * aspectRatio;
          }

          if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {
            maxCropBoxHeight = maxCropBoxWidth / aspectRatio;
          } else {
            maxCropBoxWidth = maxCropBoxHeight * aspectRatio;
          }
        }

        // The minWidth/Height must be less than maxWidth/Height
        cropBox.minWidth = min(minCropBoxWidth, maxCropBoxWidth);
        cropBox.minHeight = min(minCropBoxHeight, maxCropBoxHeight);
        cropBox.maxWidth = maxCropBoxWidth;
        cropBox.maxHeight = maxCropBoxHeight;
      }

      if (position) {
        if (strict) {
          cropBox.minLeft = max(0, canvas.left);
          cropBox.minTop = max(0, canvas.top);
          cropBox.maxLeft = min(containerWidth, canvas.left + canvas.width) - cropBox.width;
          cropBox.maxTop = min(containerHeight, canvas.top + canvas.height) - cropBox.height;
        } else {
          cropBox.minLeft = 0;
          cropBox.minTop = 0;
          cropBox.maxLeft = containerWidth - cropBox.width;
          cropBox.maxTop = containerHeight - cropBox.height;
        }
      }
    },

    renderCropBox: function () {
      var options = this.options;
      var container = this.container;
      var containerWidth = container.width;
      var containerHeight = container.height;
      var cropBox = this.cropBox;

      if (cropBox.width > cropBox.maxWidth || cropBox.width < cropBox.minWidth) {
        cropBox.left = cropBox.oldLeft;
      }

      if (cropBox.height > cropBox.maxHeight || cropBox.height < cropBox.minHeight) {
        cropBox.top = cropBox.oldTop;
      }

      cropBox.width = min(max(cropBox.width, cropBox.minWidth), cropBox.maxWidth);
      cropBox.height = min(max(cropBox.height, cropBox.minHeight), cropBox.maxHeight);

      this.limitCropBox(false, true);

      cropBox.oldLeft = cropBox.left = min(max(cropBox.left, cropBox.minLeft), cropBox.maxLeft);
      cropBox.oldTop = cropBox.top = min(max(cropBox.top, cropBox.minTop), cropBox.maxTop);

      if (options.movable && options.cropBoxMovable) {

        // Turn to move the canvas when the crop box is equal to the container
        this.$face.data(DATA_ACTION, (cropBox.width === containerWidth && cropBox.height === containerHeight) ? ACTION_MOVE : ACTION_ALL);
      }

      this.$cropBox.css({
        width: cropBox.width,
        height: cropBox.height,
        left: cropBox.left,
        top: cropBox.top
      });

      if (this.cropped && options.strict) {
        this.limitCanvas(true, true);
      }

      if (!this.disabled) {
        this.output();
      }
    },

    output: function () {
      this.preview();

      if (this.complete) {
        this.trigger(EVENT_CROP, this.getData());
      } else if (!this.built) {

        // Only trigger one crop event before complete
        this.$element.one(EVENT_BUILT, $.proxy(function () {
          this.trigger(EVENT_CROP, this.getData());
        }, this));
      }
    }
  });
<|endoftext|>


<commit_before>var app = new Vue({
  el: '#app',
  data: {
	crypto_amount: 0,
	cryptoPrices: {},
	currencies: [],
	currentCrypto: "BTC",
	exchangeRates: {
	rates: {}
	},
	fiat: {
		AUD: "$",
		BRL: "R$",
		CAD: "C$",
		CHF: "Fr.",
		CNY: "¥",
		EUR: "€",
		GBP: "£",
		HKD: "HK$",
		IDR: "Rp",
		INR: "₹",
		JPY: "¥",
		KRW: "₩",
		MXN: "M$",
		RUB: "₽",
		USD: "$"
	},
	fiat_amount: 0,
	investment: {
		currentPrice: 0,
		target: 0,
		amount: 0
	},
	settings: {
		currency: "USD",
		darkMode: false,
		numDisplay: 100,
		removeUnmineable: false
	},
	shifts: {},
	state: "calculator",
	stats: {},
	topGains: [],
	topLosses: []
  },
  methods: {
	calculate: function (type) {
		var crypto = $('.ui.dropdown').dropdown('get value')[0] ? $('.ui.dropdown').dropdown('get value')[0].toUpperCase() : "BTC";
		var fiat = $('.ui.dropdown').dropdown('get value')[1] ? $('.ui.dropdown').dropdown('get value')[1].toUpperCase() : "USD";
		var rate = (fiat != "USD" ? this.exchangeRates.rates[fiat] : 1);
		if (type == "fiat") {
			this.crypto_amount = Number($('#crypto-amount')[0].value);
			this.fiat_amount = this.crypto_amount * this.cryptoPrices[crypto] * rate;
		} else {
			this.fiat_amount = Number($('#fiat-amount')[0].value);
			this.crypto_amount = ((this.fiat_amount / this.cryptoPrices[crypto]) * rate).toFixed(8);
		}
	},
	changeState: function (state) {
		this.state = state;
	},
	checkMineable: function () {
		if (!app.settings.removeUnmineable) {return this.currencies};
		return this.currencies.filter(function(currency){
		  return (mineable[currency.symbol] == "m" || mineable[currency.symbol] == "p" || mineable[currency.symbol] == "i" || mineable[currency.symbol] == "s");
		});
	},
	currentInvestmentPrice: function () {
		var crypto = $('.ui.dropdown').dropdown('get value')[2] ? $('.ui.dropdown').dropdown('get value')[2].toUpperCase() : "BTC";
		var fiat = $('.ui.dropdown').dropdown('get value')[3] ? $('.ui.dropdown').dropdown('get value')[3].toUpperCase() : "USD";
		var rate = (fiat != "USD" ? this.exchangeRates.rates[fiat] : 1);

		this.investment.currentPrice = this.cryptoPrices[crypto] * rate;
		return (this.investment.currentPrice * this.investment.amount * rate).toLocaleString();
	},
	format: function (amount) {
		return parseFloat(amount).toLocaleString();
	},
	getImgID: function (name) {
		return cmcid[name];
	},
	getMarketcap: function (currency) {
		return app.format(currency['market_cap_' + app.settings.currency.toLowerCase()]);
	},
	getPrice: function (currency) {
		return app.format(currency['price_' + app.settings.currency.toLowerCase()]);
	},
	mineable: function (symbol) {
		return mineable[symbol];
	},
	updateData: function () {
		var _this = this;

		url = 'https://api.coinmarketcap.com/v1/ticker/?limit=' + app.settings.numDisplay;
		if (app.settings.currency != "BTC" && app.settings.currency != "USD") {
			url += "&convert=" + app.settings.currency;
		};

		this.$http.get(url).then(function (response) {
			_this.currencies = response.body;
			var coins = _this.currencies.slice();
			coins.sort(function (a, b) {
				return Number(a.percent_change_24h) - Number(b.percent_change_24h);
			});
			_this.topLosses = [jQuery.extend({}, coins[0]), jQuery.extend({}, coins[1]), jQuery.extend({}, coins[2])];
			coins.sort(function (a, b) {
				return Number(b.percent_change_24h) - Number(a.percent_change_24h);
			});
			_this.topGains = [jQuery.extend({}, coins[0]), jQuery.extend({}, coins[1]), jQuery.extend({}, coins[2])];

			var _iteratorNormalCompletion = true;
			var _didIteratorError = false;
			var _iteratorError = undefined;

			try {
				for (var _iterator = _this.currencies[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
					var currency = _step.value;

					_this.cryptoPrices[currency.symbol] = Number(currency.price_usd);
				}
			} catch (err) {
				_didIteratorError = true;
				_iteratorError = err;
			} finally {
				try {
					if (!_iteratorNormalCompletion && _iterator.return) {
						_iterator.return();
					}
				} finally {
					if (_didIteratorError) {
						throw _iteratorError;
					}
				}
			}

			;

			_this.$http.get('https://shapeshift.io/getcoins').then(function (res) {
				app.shifts = res.body;
				_this.currencies.forEach(function (currency, idx) {
					if (app.shifts[currency.symbol] && app.shifts[currency.symbol].status == "available") {
						// using the 'last_updated' property for canShift
						// something about reactivity, so I'll just use a small hack :)
						app.currencies[idx].last_updated = true;
					} else {
						app.currencies[idx].last_updated = false;
					}
				});
			});
			_this.$http.get('https://api.fixer.io/latest?base=USD').then(function (response) {
				_this.exchangeRates = response.body;
				$('#crypto-dropdown').dropdown('setting', 'onChange', function () {
					app.calculate('fiat');
				});
				$('#fiat-dropdown').dropdown('setting', 'onChange', function () {
					app.calculate('crypto');
				});
				$('#investment-crypto').dropdown('setting', 'onChange', function (val) {
					app.currentInvestmentPrice();
				});
				$('#target-fiat').dropdown('setting', 'onChange', function () {
					app.currentInvestmentPrice();
				});
			});
		});
		this.$http.get('https://api.coinmarketcap.com/v1/global/').then(function (response) {
			_this.stats = response.body;
		});
	},
	wallet: function (symbol) {
		return wallets[symbol];
	}
  },
  computed: {
	current: function () {
		return this.fiat[this.settings.currency];
	},
	currencyList: function () {
		var list = [];
		var _iteratorNormalCompletion = true;
		var _didIteratorError = false;
		var _iteratorError = undefined;

		try {
				for (var _iterator = this.currencies[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
						var currency = _step.value;

						list.push(currency.symbol);
				}
		} catch (err) {
				_didIteratorError = true;
				_iteratorError = err;
		} finally {
				try {
						if (!_iteratorNormalCompletion && _iterator.return) {
								_iterator.return();
						}
				} finally {
						if (_didIteratorError) {
								throw _iteratorError;
						}
				}
		}

		return list.sort();
	},
	profit: function () {
		return ((Number(this.investment.target) - Number(this.investment.currentPrice)) * this.investment.amount).toFixed(2).toLocaleString();
	},
	rates: function () {
		var c = Object.keys(this.exchangeRates.rates)
		c.push("USD");
		return c.sort();
	}
  }
})

$(document).ready(function() {
	if (window.location.hash.match(/[A-Z]{3}-\d{2,4}-[tf]-[tf]/)) {
		var bits = window.location.hash.split('-');
		var arr = Object.keys(app.fiat);
		bits[0] = bits[0].substring(1);
		if (arr.indexOf(bits[0]) || bits[0] == "BTC") {
			app.settings.currency = bits[0];
		}
		if (Number(bits[1]) >= 10) {
			app.settings.numDisplay = bits[1];
		}
		app.settings.darkMode = (bits[2] == "t" ? true : false);
		app.settings.removeUnmineable = (bits[3] == "t" ? true : false);
	}
	app.updateData();
	setInterval(app.updateData, 300 * 1000);
});

function showModal(symbol) {
	app.currentCrypto = symbol;
	$('.ui.modal').modal('show');
};

function generateURL() {
	var base = $("#base-currency")[0].value ? $("#base-currency")[0].value : "USD";
	var darkMode = $("#dark")[0].checked ? "t" : "f";
	var numDisplay = $("#num-display")[0].value;
	var unmineable = $("#unmineable")[0].checked ? "t" : "f";

	window.location.hash = "#" + base + "-" + numDisplay + "-" + darkMode + "-" + unmineable;
	window.location.reload();
};<commit_msg>fix js variables<commit_after>var app = new Vue({
  el: '#app',
  data: {
	crypto_amount: 0,
	cryptoPrices: {},
	currencies: [],
	currentCrypto: "BTC",
	exchangeRates: {
	rates: {}
	},
	fiat: {
		AUD: "$",
		BRL: "R$",
		CAD: "C$",
		CHF: "Fr.",
		CNY: "¥",
		EUR: "€",
		GBP: "£",
		HKD: "HK$",
		IDR: "Rp",
		INR: "₹",
		JPY: "¥",
		KRW: "₩",
		MXN: "M$",
		RUB: "₽",
		USD: "$"
	},
	fiat_amount: 0,
	investment: {
		currentPrice: 0,
		target: 0,
		amount: 0
	},
	settings: {
		currency: "USD",
		darkMode: false,
		numDisplay: 100,
		removeUnmineable: false
	},
	shifts: {},
	state: "calculator",
	stats: {},
	topGains: [],
	topLosses: []
  },
  methods: {
	calculate: function (type) {
		var crypto = $('.ui.dropdown').dropdown('get value')[0] ? $('.ui.dropdown').dropdown('get value')[0].toUpperCase() : "BTC";
		var fiat = $('.ui.dropdown').dropdown('get value')[1] ? $('.ui.dropdown').dropdown('get value')[1].toUpperCase() : "USD";
		var rate = (fiat != "USD" ? this.exchangeRates.rates[fiat] : 1);
		if (type == "fiat") {
			this.crypto_amount = Number($('#crypto-amount')[0].value);
			this.fiat_amount = this.crypto_amount * this.cryptoPrices[crypto] * rate;
		} else {
			this.fiat_amount = Number($('#fiat-amount')[0].value);
			this.crypto_amount = ((this.fiat_amount / this.cryptoPrices[crypto]) * rate).toFixed(8);
		}
	},
	changeState: function (state) {
		this.state = state;
	},
	checkMineable: function () {
		if (!this.settings.removeUnmineable) {return this.currencies};
		return this.currencies.filter(function(currency){
		  return (mineable[currency.symbol] == "m" || mineable[currency.symbol] == "p" || mineable[currency.symbol] == "i" || mineable[currency.symbol] == "s");
		});
	},
	currentInvestmentPrice: function () {
		var crypto = $('.ui.dropdown').dropdown('get value')[2] ? $('.ui.dropdown').dropdown('get value')[2].toUpperCase() : "BTC";
		var fiat = $('.ui.dropdown').dropdown('get value')[3] ? $('.ui.dropdown').dropdown('get value')[3].toUpperCase() : "USD";
		var rate = (fiat != "USD" ? this.exchangeRates.rates[fiat] : 1);

		this.investment.currentPrice = this.cryptoPrices[crypto] * rate;
		return (this.investment.currentPrice * this.investment.amount * rate).toLocaleString();
	},
	format: function (amount) {
		return parseFloat(amount).toLocaleString();
	},
	getImgID: function (name) {
		return cmcid[name];
	},
	getMarketcap: function (currency) {
		return app.format(currency['market_cap_' + app.settings.currency.toLowerCase()]);
	},
	getPrice: function (currency) {
		return app.format(currency['price_' + app.settings.currency.toLowerCase()]);
	},
	mineable: function (symbol) {
		return mineable[symbol];
	},
	updateData: function () {
		var _this = this;

		url = 'https://api.coinmarketcap.com/v1/ticker/?limit=' + app.settings.numDisplay;
		if (this.settings.currency != "BTC" && this.settings.currency != "USD") {
			url += "&convert=" + this.settings.currency;
		};

		this.$http.get(url).then(function (response) {
			_this.currencies = response.body;
			var coins = _this.currencies.slice();
			coins.sort(function (a, b) {
				return Number(a.percent_change_24h) - Number(b.percent_change_24h);
			});
			_this.topLosses = [jQuery.extend({}, coins[0]), jQuery.extend({}, coins[1]), jQuery.extend({}, coins[2])];
			coins.sort(function (a, b) {
				return Number(b.percent_change_24h) - Number(a.percent_change_24h);
			});
			_this.topGains = [jQuery.extend({}, coins[0]), jQuery.extend({}, coins[1]), jQuery.extend({}, coins[2])];

			var _iteratorNormalCompletion = true;
			var _didIteratorError = false;
			var _iteratorError = undefined;

			try {
				for (var _iterator = _this.currencies[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
					var currency = _step.value;

					_this.cryptoPrices[currency.symbol] = Number(currency.price_usd);
				}
			} catch (err) {
				_didIteratorError = true;
				_iteratorError = err;
			} finally {
				try {
					if (!_iteratorNormalCompletion && _iterator.return) {
						_iterator.return();
					}
				} finally {
					if (_didIteratorError) {
						throw _iteratorError;
					}
				}
			}

			;

			_this.$http.get('https://shapeshift.io/getcoins').then(function (res) {
				app.shifts = res.body;
				_this.currencies.forEach(function (currency, idx) {
					if (app.shifts[currency.symbol] && app.shifts[currency.symbol].status == "available") {
						// using the 'last_updated' property for canShift
						// something about reactivity, so I'll just use a small hack :)
						app.currencies[idx].last_updated = true;
					} else {
						app.currencies[idx].last_updated = false;
					}
				});
			});
			_this.$http.get('https://api.fixer.io/latest?base=USD').then(function (response) {
				_this.exchangeRates = response.body;
				$('#crypto-dropdown').dropdown('setting', 'onChange', function () {
					app.calculate('fiat');
				});
				$('#fiat-dropdown').dropdown('setting', 'onChange', function () {
					app.calculate('crypto');
				});
				$('#investment-crypto').dropdown('setting', 'onChange', function (val) {
					app.currentInvestmentPrice();
				});
				$('#target-fiat').dropdown('setting', 'onChange', function () {
					app.currentInvestmentPrice();
				});
			});
		});
		this.$http.get('https://api.coinmarketcap.com/v1/global/').then(function (response) {
			_this.stats = response.body;
		});
	},
	wallet: function (symbol) {
		return wallets[symbol];
	}
  },
  computed: {
	current: function () {
		return this.fiat[this.settings.currency];
	},
	currencyList: function () {
		var list = [];
		var _iteratorNormalCompletion = true;
		var _didIteratorError = false;
		var _iteratorError = undefined;

		try {
				for (var _iterator = this.currencies[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
						var currency = _step.value;

						list.push(currency.symbol);
				}
		} catch (err) {
				_didIteratorError = true;
				_iteratorError = err;
		} finally {
				try {
						if (!_iteratorNormalCompletion && _iterator.return) {
								_iterator.return();
						}
				} finally {
						if (_didIteratorError) {
								throw _iteratorError;
						}
				}
		}

		return list.sort();
	},
	profit: function () {
		return ((Number(this.investment.target) - Number(this.investment.currentPrice)) * this.investment.amount).toFixed(2).toLocaleString();
	},
	rates: function () {
		var c = Object.keys(this.exchangeRates.rates)
		c.push("USD");
		return c.sort();
	}
  }
})

$(document).ready(function() {
	if (window.location.hash.match(/[A-Z]{3}-\d{2,4}-[tf]-[tf]/)) {
		var bits = window.location.hash.split('-');
		var arr = Object.keys(app.fiat);
		bits[0] = bits[0].substring(1);
		if (arr.indexOf(bits[0]) || bits[0] == "BTC") {
			app.settings.currency = bits[0];
		}
		if (Number(bits[1]) >= 10) {
			app.settings.numDisplay = bits[1];
		}
		app.settings.darkMode = (bits[2] == "t" ? true : false);
		app.settings.removeUnmineable = (bits[3] == "t" ? true : false);
	}
	app.updateData();
	setInterval(app.updateData, 300 * 1000);
});

function showModal(symbol) {
	app.currentCrypto = symbol;
	$('.ui.modal').modal('show');
};

function generateURL() {
	var base = $("#base-currency")[0].value ? $("#base-currency")[0].value : "USD";
	var darkMode = $("#dark")[0].checked ? "t" : "f";
	var numDisplay = $("#num-display")[0].value;
	var unmineable = $("#unmineable")[0].checked ? "t" : "f";

	window.location.hash = "#" + base + "-" + numDisplay + "-" + darkMode + "-" + unmineable;
	window.location.reload();
};<|endoftext|>


<commit_before>'use strict';

const github = require('../../lib/github');
// const User = require('./model').User;

module.exports = function authMiddleware(req, res, next) {
  if (!req.session.auth
      && !/^\/login/.test(req.originalUrl)
      && !/^\/page\//.test(req.originalUrl)
      && !/^\/app(\/[^\/]+){2}\/(webhook|[0-9a-f]{40})\/?$/.test(req.originalUrl)
  ) {
    return res.redirect('/login');
  }

  if (req.session.auth) {
    if (!req.session.auth.accessToken) {
      throw new Error(`Missing accessToken for user ${req.session.auth.userName}`);
    }

    req.github = github.client(req.session.auth);
  }

  next();
};
<commit_msg>fix(auth): cannot read property 'auth' of undefined<commit_after>'use strict';

const github = require('../../lib/github');
// const User = require('./model').User;

module.exports = function authMiddleware(req, res, next) {
  if (!req.session || !req.session.auth
      && !/^\/login/.test(req.originalUrl)
      && !/^\/page\//.test(req.originalUrl)
      && !/^\/app(\/[^\/]+){2}\/(webhook|[0-9a-f]{40})\/?$/.test(req.originalUrl)
  ) {
    return res.redirect('/login');
  }

  if (req.session.auth) {
    if (!req.session.auth.accessToken) {
      throw new Error(`Missing accessToken for user ${req.session.auth.userName}`);
    }

    req.github = github.client(req.session.auth);
  }

  next();
};
<|endoftext|>


<commit_before>$(window).load(function () {

  $(document).on('change', '.btn-file :file', function () {
    var input = $(this)
    var numFiles = input.get(0).files ? input.get(0).files.length : 1
    var label = input.val().replace(/\\/g, '/').replace(/.*\//, '')

    input.trigger('fileselect', [numFiles, label])
  })

  $(document).ready(function () {
    $('.btn-file :file').on('fileselect', function (event, numFiles, label) {
      //console.log(numFiles)
      //console.log(label)
    })
  })

  $('[data-toggle="tooltip"]').tooltip()
})

$(function () {
  $('a').click(function (event) { // Load links in-app
    event.preventDefault()
    if (!($(this).attr('href') === undefined)) {
      window.location = $(this).attr('href')
    }
  })

  $('.toggle-dropdown').on('click', function () {
    $('ul.active').removeClass('active') // Reset active class
    var parent = $(this).parent() // Select parent of clicked element
    parent.children('ul').addClass('active') // Set class 'active' to parent's child
  })

  $('.searchForm').keyup(function () {
    if ($('.searchForm').val() === '') {
      $('#searchForm-btn-default').html('')
      $('#textReceiver').slideUp(600)
      $('#results').hide()
      if ($('#searchEngine-noResults').css('display') === 'block') {
        $('#searchEngine-noResults').slideUp('fast')
      }
      if ($('#heroSearch').hasClass('contracted')) {
        $('#heroSearch').removeClass('contracted')
      }
    } else {
      $('#heroSearch').addClass('contracted')
      $('html, body').animate({ scrollTop: 0 }, 'fast')
      $('#searchForm-btn-default').html('')
    }
  })

  var typingTimer
  $('.searchForm').on('keyup', function () {
    clearTimeout(typingTimer)
    typingTimer = setTimeout(doTrigger, 150)
  })

  $('.searchForm').on('keydown', function () {
    clearTimeout(typingTimer)
  })

  function doTrigger() {
    if ($('.searchForm').val().length > 2) {
      $('#searchResultsContainer').html('')
      $.getJSON('/ajax/search/?s=' + $('.searchForm').val(), function (data) {
        if (data[0] !== undefined) {
          if ($('#searchEngine-noResults').css('display') === 'block') {
            $('#searchEngine-noResults').show()
          }
          $('#searchFor').html('
Sökresultat för ' + $('.searchForm').val() + '
')
          $('#results').show()
          $('#searchResult').append('

')

          $('#searchResultsContainer').show('fast')
          for (var i = 0, result = data; i < result.length; i++) {
            var id = result[i]._id
            var content = '
'
            content += '
'
            content += '

'
            content += '
'
            content += '
' + result[i].title + '
'
            content += '
' + result[i].post.content + '

'
            content += '
'
            content += 'Status'
            content += 'Läs mer

'
            $('#searchResultsContainer').append(content)
            $('#searchResult-' + id).show()
            $('#searchForm-btn-default').html('')
          }
        } else { // No results
          $('#searchForm-btn-default').html('')
          $('#searchEngine-noResults').show()
          $('#results').show()
          $('#searchFor').html('')
          $('#searchResultsContainer').show()
        }
      })
    }
  }
})<commit_msg>Change elements<commit_after>$(window).load(function () {

  $(document).on('change', '.btn-file :file', function () {
    var input = $(this)
    var numFiles = input.get(0).files ? input.get(0).files.length : 1
    var label = input.val().replace(/\\/g, '/').replace(/.*\//, '')

    input.trigger('fileselect', [numFiles, label])
  })

  $(document).ready(function () {
    $('.btn-file :file').on('fileselect', function (event, numFiles, label) {
      //console.log(numFiles)
      //console.log(label)
    })
  })

  $('[data-toggle="tooltip"]').tooltip()
})

$(function () {
  $('a').click(function (event) { // Load links in-app
    event.preventDefault()
    if (!($(this).attr('href') === undefined)) {
      window.location = $(this).attr('href')
    }
  })

  $('.toggle-dropdown').on('click', function () {
    $('li.active').removeClass('active') // Reset active class
    var parent = $(this).parent() // Select parent of clicked element
    parent.children('li').addClass('active') // Set class 'active' to parent's child
  })

  $('.searchForm').keyup(function () {
    if ($('.searchForm').val() === '') {
      $('#searchForm-btn-default').html('')
      $('#textReceiver').slideUp(600)
      $('#results').hide()
      if ($('#searchEngine-noResults').css('display') === 'block') {
        $('#searchEngine-noResults').slideUp('fast')
      }
      if ($('#heroSearch').hasClass('contracted')) {
        $('#heroSearch').removeClass('contracted')
      }
    } else {
      $('#heroSearch').addClass('contracted')
      $('html, body').animate({ scrollTop: 0 }, 'fast')
      $('#searchForm-btn-default').html('')
    }
  })

  var typingTimer
  $('.searchForm').on('keyup', function () {
    clearTimeout(typingTimer)
    typingTimer = setTimeout(doTrigger, 150)
  })

  $('.searchForm').on('keydown', function () {
    clearTimeout(typingTimer)
  })

  function doTrigger() {
    if ($('.searchForm').val().length > 2) {
      $('#searchResultsContainer').html('')
      $.getJSON('/ajax/search/?s=' + $('.searchForm').val(), function (data) {
        if (data[0] !== undefined) {
          if ($('#searchEngine-noResults').css('display') === 'block') {
            $('#searchEngine-noResults').show()
          }
          $('#searchFor').html('
Sökresultat för ' + $('.searchForm').val() + '
')
          $('#results').show()
          $('#searchResult').append('

')

          $('#searchResultsContainer').show('fast')
          for (var i = 0, result = data; i < result.length; i++) {
            var id = result[i]._id
            var content = '
'
            content += '
'
            content += '

'
            content += '
'
            content += '
' + result[i].title + '
'
            content += '
' + result[i].post.content + '

'
            content += '
'
            content += 'Status'
            content += 'Läs mer

'
            $('#searchResultsContainer').append(content)
            $('#searchResult-' + id).show()
            $('#searchForm-btn-default').html('')
          }
        } else { // No results
          $('#searchForm-btn-default').html('')
          $('#searchEngine-noResults').show()
          $('#results').show()
          $('#searchFor').html('')
          $('#searchResultsContainer').show()
        }
      })
    }
  }
})<|endoftext|>


<commit_before>'use strict';
require("style/keyboard.css");
//var kana = require('./kana.js');

var debug = true;
function setAttribute(parentElement, name, key, value){
    if(! parentElement) {
        return;
    }
    var elements = parentElement.getElementsByTagName(name);
    if(elements){
        for(var i=0; i<elements.length;i++){elements[i].setAttribute(key, value);}
    }else{
        parentElement.setAttribute(key, value);
    }
}

function removeAllChildrenNode(element){
    while(element.hasChildNodes()){
        element.removeChild(element.lastChild);
    }
}

function TextSource(){
    this.index = -1;
    this.src = ["hogehoge","abcdefg", "AAABBBCCC", "Japanese Touch-typing Practice"];

    this.getNextText = function(){
        this.index++;
        if(this.index == this.src.length) {
            this.index = 0;
        }
        return this.src[this.index];
    };
}

function MainPanel(document, element, callback){
    this.document = document;
    this.element = element;
    this._isEnabled = false;

    this.setEnabled = function(isEnabled){
        if(isEnabled){
            this.element.setAttribute('style', 'background-color: #fff');
        }else{
            this.element.setAttribute('style', 'background-color: #bbb;');
        }
        this._isEnabled = isEnabled;
    };

    this.isEnabled = function(){
        return this._isEnabled;
    };

    this.setSVGDocument = function(svgDocument){
        this.svgDocument = svgDocument;
    };

    this.setKeyFocused = function(code, fillColor){
        if(this.svgDocument){
            setAttribute(this.svgDocument.getElementById("code-"+code), 'path', 'fill', fillColor);
        }
    };

    this.initialize = function(callback){
        this.setEnabled(false);
        this.objectElement = this.document.createElement('object');
        this.objectElement.setAttribute('tabindex','0');
        this.objectElement.setAttribute('type','image/svg+xml');
        this.objectElement.setAttribute('width','1190');
        this.objectElement.setAttribute('height','348');
        this.objectElement.setAttribute('data', 'img/keyboard_ja.svg');

        this.document.getElementById('keyboard').appendChild(this.objectElement);

        var _this = this;
        this.objectElement.addEventListener("load", function(){
            _this.setSVGDocument(_this.objectElement.getSVGDocument());
            callback();
        });
    };

    this.initialize(callback);
}

function PromptField(document, element){
    this.element = element;
    this._isEnabled = false;

    this.clearText = function(){
        removeAllChildrenNode(this.element);
    };

    this.setText = function(text){
        this.clearText();
        text.split('').forEach(function(c){
            var span1 = document.createElement('span');
            var span2 = document.createElement('span');
            span1.appendChild(span2);
            span2.appendChild(document.createTextNode(c));
            element.appendChild(span1);
        });
    };

    this.setEnabled = function(isEnabled){
        this._isEnabled = isEnabled;
        setAttribute(this.element, 'span', 'style', 'border-left-color:'+(isEnabled?'#fff':'#bbb'));
    };

    this.isEnabled = function(){
        return this._isEnabled;
    };

    this.setEnabled(false);
}

function InputField(document, element){
    this.element = element;

    this.clearCursor = function(){
        for(var i = 0; i < this.element.childElementCount; i++){
            var item = this.element.childNodes.item(i);
            if(item.hasAttribute('class')){
                item.removeAttribute('class');
            }
        }
    };

    this.setCursor = function(cursor) {
        if(cursor < this.element.childNodes.length){
            this.element.childNodes.item(cursor).setAttribute('class', 'cursor');
        }
    };

    this.setCursorBlink = function(cursorBlink){
        for(var i = 0; i < this.element.childElementCount; i++){
            var item = this.element.childNodes.item(i);
            var clazz = item.getAttribute('class');
            if(clazz){
                if(cursorBlink){
                    item.setAttribute('class', 'cursor');
                }else{
                    item.setAttribute('class', '_cursor');
                }
            }
        }
    };

    this.clearText = function(){
        while(1 < this.element.childElementCount){
            this.element.removeChild(this.element.firstElementChild);
        }
    };

    this.removeTextAfter = function(cursor){
        var count = this.element.childElementCount - 1;
        for(var i = cursor ; i < count; i++){
            this.element.removeChild(this.element.childNodes.item(cursor));
        }
    };

    this.removeCharAt = function(cursor){
        var target = this.element.childNodes.item(cursor);
        this.element.removeChild(target);
    };

    this.length = function(){
        return this.element.childElementCount - 1;
    };

    this.appendChar = function(cursor, ch){
        var span1 = document.createElement('span');
        var span2 = document.createElement('span');
        span1.appendChild(span2);
        span2.appendChild(document.createTextNode(ch));
        var target = this.element.childNodes.item(cursor);
        this.element.insertBefore(span1, target);
    };

    this.setEnabled = function(isEnabled){
        setAttribute(this.element, 'span', 'style', 'border-left-color:'+(isEnabled?'#fff':'#bbb'));
    };

    this.setEnabled(false);
    this.setCursorBlink(false);

}

function setupTypingPracticeElement(document, src){

    var mainPanel = new MainPanel(document, document.getElementById("main"), function(){
        var promptField = new PromptField(document, document.getElementById('prompt'));
        var inputField = new InputField(document, document.getElementById('typed'));
        promptField.setText(src.getNextText());

        var cursor = 0;
        mainPanel.setEnabled(false);
        promptField.setEnabled(false);
        inputField.setEnabled(false);
        inputField.setCursorBlink(false);

        document.addEventListener("mousedown", function (){
            mainPanel.setEnabled(true);
            promptField.setEnabled(true);
            inputField.setEnabled(true);
            inputField.setCursorBlink(true);
        }, false);

        document.addEventListener("mouseleave", function (){
            mainPanel.setEnabled(false);
            promptField.setEnabled(false);
            inputField.setEnabled(false);
            inputField.setCursorBlink(false);
        }, false);

        document.addEventListener("keydown", function (e) {
            if(! mainPanel.isEnabled()){
                return;
            }

            var code = e.keyCode ? e.keyCode : e.which;
            if(debug){
                console.log(code);
            }

            if(code == 9){//tab
                return;
            }

            mainPanel.setKeyFocused(code, (e.key.length == 1)?'red':'yellow');

            inputField.clearCursor();

            if(code == 13){//Enter
                inputField.clearText();
                promptField.clearText();
                promptField.setText(src.getNextText());
                cursor = 0;
            } if(code == 75/*'k'*/ && e.ctrlKey){
                inputField.removeTextAfter(cursor);
            }else if(code == 8 || (code == 72/*'h'*/ && e.ctrlKey)){ // backspace
                if(0 < cursor){
                    cursor -= 1;
                    inputField.removeCharAt(cursor);
                }
            }else if(code == 37 || (code == 66 /*'b'*/ && e.ctrlKey)){ // backward
                if(0 < cursor){
                    cursor -= 1;
                }
            }else if(code == 39 || (code == 70 /*'f'*/ && e.ctrlKey)){ // forward
                if(cursor < inputField.length()) {
                    cursor += 1;
                }
            }else if(code == 65 /*'a'*/ && e.ctrlKey){ // ahead
                cursor = 0;
            }else if(code == 69 /*'e'*/ && e.ctrlKey){ // end
                cursor = inputField.length();
            }else if(e.key.length == 1){
                inputField.appendChar(cursor, e.key);
                cursor += 1;
            }
            inputField.setCursor(cursor);
        }, false);

        document.addEventListener("keyup", function (e) {
            if(! mainPanel.isEnabled()){
                return;
            }
            var code = e.keyCode ? e.keyCode : e.which;
            mainPanel.setKeyFocused(code, 'none');
        }, false);

    });

}

setupTypingPracticeElement(document, new TextSource());

module.exports = {
    setupTypingPracticeElement:setupTypingPracticeElement
};
<commit_msg>refactor hardcoded colors<commit_after>'use strict';
require("style/keyboard.css");
//var kana = require('./kana.js');

var debug = true;
var Colors = {
    enabled: '#fff',
    disabled: '#bbb',
    focusedKey: '#f88',
    focusedSpecialKey:'#aaa'
};

function setAttribute(parentElement, name, key, value){
    if(! parentElement) {
        return;
    }
    var elements = parentElement.getElementsByTagName(name);
    if(elements){
        for(var i=0; i<elements.length;i++){elements[i].setAttribute(key, value);}
    }else{
        parentElement.setAttribute(key, value);
    }
}

function removeAllChildrenNode(element){
    while(element.hasChildNodes()){
        element.removeChild(element.lastChild);
    }
}

function TextSource(){
    this.index = -1;
    this.src = ["hogehoge","abcdefg", "AAABBBCCC", "Japanese Touch-typing Practice"];

    this.getNextText = function(){
        this.index++;
        if(this.index == this.src.length) {
            this.index = 0;
        }
        return this.src[this.index];
    };
}

function MainPanel(document, element, callback){
    this.document = document;
    this.element = element;
    this._isEnabled = false;

    this.setEnabled = function(isEnabled){
        if(isEnabled){
            this.element.setAttribute('style', 'background-color: '+Colors.enabled);
        }else{
            this.element.setAttribute('style', 'background-color: '+Colors.disabled);
        }
        this._isEnabled = isEnabled;
    };

    this.isEnabled = function(){
        return this._isEnabled;
    };

    this.setSVGDocument = function(svgDocument){
        this.svgDocument = svgDocument;
    };

    this.setKeyFocused = function(code, fillColor){
        if(this.svgDocument){
            setAttribute(this.svgDocument.getElementById("code-"+code), 'path', 'fill', fillColor);
        }
    };

    this.initialize = function(callback){
        this.setEnabled(false);
        this.objectElement = this.document.createElement('object');
        this.objectElement.setAttribute('tabindex','0');
        this.objectElement.setAttribute('type','image/svg+xml');
        this.objectElement.setAttribute('width','1190');
        this.objectElement.setAttribute('height','348');
        this.objectElement.setAttribute('data', 'img/keyboard_ja.svg');

        this.document.getElementById('keyboard').appendChild(this.objectElement);

        var _this = this;
        this.objectElement.addEventListener("load", function(){
            _this.setSVGDocument(_this.objectElement.getSVGDocument());
            callback();
        });
    };

    this.initialize(callback);
}

function PromptField(document, element){
    this.element = element;
    this._isEnabled = false;

    this.clearText = function(){
        removeAllChildrenNode(this.element);
    };

    this.setText = function(text){
        this.clearText();
        text.split('').forEach(function(c){
            var span1 = document.createElement('span');
            var span2 = document.createElement('span');
            span1.appendChild(span2);
            span2.appendChild(document.createTextNode(c));
            element.appendChild(span1);
        });
    };

    this.setEnabled = function(isEnabled){
        this._isEnabled = isEnabled;
        setAttribute(this.element, 'span', 'style', 'border-left-color:'+(isEnabled?Colors.enabled:Colors.disabled));
    };

    this.isEnabled = function(){
        return this._isEnabled;
    };

    this.setEnabled(false);
}

function InputField(document, element){
    this.element = element;

    this.clearCursor = function(){
        for(var i = 0; i < this.element.childElementCount; i++){
            var item = this.element.childNodes.item(i);
            if(item.hasAttribute('class')){
                item.removeAttribute('class');
            }
        }
    };

    this.setCursor = function(cursor) {
        if(cursor < this.element.childNodes.length){
            this.element.childNodes.item(cursor).setAttribute('class', 'cursor');
        }
    };

    this.setCursorBlink = function(cursorBlink){
        for(var i = 0; i < this.element.childElementCount; i++){
            var item = this.element.childNodes.item(i);
            var clazz = item.getAttribute('class');
            if(clazz){
                if(cursorBlink){
                    item.setAttribute('class', 'cursor');
                }else{
                    item.setAttribute('class', '_cursor');
                }
            }
        }
    };

    this.clearText = function(){
        while(1 < this.element.childElementCount){
            this.element.removeChild(this.element.firstElementChild);
        }
    };

    this.removeTextAfter = function(cursor){
        var count = this.element.childElementCount - 1;
        for(var i = cursor ; i < count; i++){
            this.element.removeChild(this.element.childNodes.item(cursor));
        }
    };

    this.removeCharAt = function(cursor){
        var target = this.element.childNodes.item(cursor);
        this.element.removeChild(target);
    };

    this.length = function(){
        return this.element.childElementCount - 1;
    };

    this.appendChar = function(cursor, ch){
        var span1 = document.createElement('span');
        var span2 = document.createElement('span');
        span1.appendChild(span2);
        span2.appendChild(document.createTextNode(ch));
        var target = this.element.childNodes.item(cursor);
        this.element.insertBefore(span1, target);
    };

    this.setEnabled = function(isEnabled){
        setAttribute(this.element, 'span', 'style', 'border-left-color:'+(isEnabled?Colors.enabled:Colors.disabled));
    };

    this.setEnabled(false);
    this.setCursorBlink(false);

}

function setupTypingPracticeElement(document, src){

    var mainPanel = new MainPanel(document, document.getElementById("main"), function(){
        var promptField = new PromptField(document, document.getElementById('prompt'));
        var inputField = new InputField(document, document.getElementById('typed'));
        promptField.setText(src.getNextText());

        var cursor = 0;
        mainPanel.setEnabled(false);
        promptField.setEnabled(false);
        inputField.setEnabled(false);
        inputField.setCursorBlink(false);

        document.addEventListener("mousedown", function (){
            mainPanel.setEnabled(true);
            promptField.setEnabled(true);
            inputField.setEnabled(true);
            inputField.setCursorBlink(true);
        }, false);

        document.addEventListener("mouseleave", function (){
            mainPanel.setEnabled(false);
            promptField.setEnabled(false);
            inputField.setEnabled(false);
            inputField.setCursorBlink(false);
        }, false);

        document.addEventListener("keydown", function (e) {
            if(! mainPanel.isEnabled()){
                return;
            }

            var code = e.keyCode ? e.keyCode : e.which;
            if(debug){
                console.log(code);
            }

            if(code == 9){//tab
                return;
            }

            mainPanel.setKeyFocused(code, (e.key.length == 1)?Colors.focusedKey:Colors.focusedSpecialKey);

            inputField.clearCursor();

            if(code == 13){//Enter
                inputField.clearText();
                promptField.clearText();
                promptField.setText(src.getNextText());
                cursor = 0;
            } if(code == 75/*'k'*/ && e.ctrlKey){
                inputField.removeTextAfter(cursor);
            }else if(code == 8 || (code == 72/*'h'*/ && e.ctrlKey)){ // backspace
                if(0 < cursor){
                    cursor -= 1;
                    inputField.removeCharAt(cursor);
                }
            }else if(code == 37 || (code == 66 /*'b'*/ && e.ctrlKey)){ // backward
                if(0 < cursor){
                    cursor -= 1;
                }
            }else if(code == 39 || (code == 70 /*'f'*/ && e.ctrlKey)){ // forward
                if(cursor < inputField.length()) {
                    cursor += 1;
                }
            }else if(code == 65 /*'a'*/ && e.ctrlKey){ // ahead
                cursor = 0;
            }else if(code == 69 /*'e'*/ && e.ctrlKey){ // end
                cursor = inputField.length();
            }else if(e.key.length == 1){
                inputField.appendChar(cursor, e.key);
                cursor += 1;
            }
            inputField.setCursor(cursor);
        }, false);

        document.addEventListener("keyup", function (e) {
            if(! mainPanel.isEnabled()){
                return;
            }
            var code = e.keyCode ? e.keyCode : e.which;
            mainPanel.setKeyFocused(code, 'none');
        }, false);

    });

}

setupTypingPracticeElement(document, new TextSource());

module.exports = {
    setupTypingPracticeElement:setupTypingPracticeElement
};
<|endoftext|>


<commit_before>'use strict';

  Darwinator.Weapon = function(game, coolDown, bulletSpeed, bullets, damage, owner) {
    this.game         = game;
    var baseCoolDown  = Darwinator.PLAYER_RANGE_WEAPON_BASE_COOLDOWN - game.player.attributes.intellect * 20;
    this.coolDown     = baseCoolDown > 200 ? baseCoolDown : 100;
    this.nextFire     = 0;
    this.bullets      = bullets;
    this.bulletSpeed  = bulletSpeed;
    this.damage       = damage;
    this.owner        = owner;
  };

  Darwinator.Weapon.prototype.fire = function (x, y) {
    if (this.game.time.now > this.nextFire && this.bullets.countDead() > 0) {
        this.nextFire = this.game.time.now + this.coolDown;
        var bullet    = this.bullets.getFirstDead();
        bullet.reset(this.owner.x, this.owner.y); // resets sprite and body
        bullet.target = { x: x, y: y };
        var angle = this.takeAim(bullet.target.x, bullet.target.y);
        bullet.rotation = angle;
        this.game.physics.arcade.velocityFromRotation(angle, this.bulletSpeed, bullet.body.velocity);
        console.log(bullet);
    }
  };

  Darwinator.Weapon.prototype.takeAim = function(x, y) {
    var perfAngle = this.game.physics.arcade.angleToXY(this.owner, x, y);
    console.log(perfAngle);
    perfAngle += (Math.random() - 0.5) / (Math.round(this.owner.attributes.intellect / 5) + 1);
    console.log(perfAngle);
    return perfAngle;
  };
<commit_msg>Remove unused prints<commit_after>'use strict';

  Darwinator.Weapon = function(game, coolDown, bulletSpeed, bullets, damage, owner) {
    this.game         = game;
    var baseCoolDown  = Darwinator.PLAYER_RANGE_WEAPON_BASE_COOLDOWN - game.player.attributes.intellect * 20;
    this.coolDown     = baseCoolDown > 200 ? baseCoolDown : 100;
    this.nextFire     = 0;
    this.bullets      = bullets;
    this.bulletSpeed  = bulletSpeed;
    this.damage       = damage;
    this.owner        = owner;
  };

  Darwinator.Weapon.prototype.fire = function (x, y) {
    if (this.game.time.now > this.nextFire && this.bullets.countDead() > 0) {
        this.nextFire = this.game.time.now + this.coolDown;
        var bullet    = this.bullets.getFirstDead();
        bullet.reset(this.owner.x, this.owner.y); // resets sprite and body
        bullet.target = { x: x, y: y };
        var angle = this.takeAim(bullet.target.x, bullet.target.y);
        bullet.rotation = angle;
        this.game.physics.arcade.velocityFromRotation(angle, this.bulletSpeed, bullet.body.velocity);
    }
  };

  Darwinator.Weapon.prototype.takeAim = function(x, y) {
    var perfAngle = this.game.physics.arcade.angleToXY(this.owner, x, y);
    perfAngle += (Math.random() - 0.5) / (Math.round(this.owner.attributes.intellect / 5) + 1);
    return perfAngle;
  };
<|endoftext|>