<commit_before>// ui module
// Handles displaying data to UI, user interaction events and changing views,
// basically any interaction with the page should run through UI

// Calling ui.help("<function name>") will give parameter information
// the help will also be displayed if the parameters are given incorrectly

// The UI will get updates to it's data from TODO (external module), update it's
// data object, then calls update(data); on all views.

// Example UI Data Format
/*
{
    "miner": {
        "State": "On",
        "Threads": 2,
        "RunningThreads": 1,
        "Address": [
        126,
        66,
        "...",
        173,
        53
        ],
        "AccountName": "Personal",
        "Balance": 1,
        "USDBalance": 2,
        "IncomeRate": "20.345 SC/h"
    },
    "wallet": {
        "Balance": 0,
        "USDBalance": 0,
        "FullBalance": 0,
        "NumAddresses": 2392,
        "DefaultAccount": "Personal",
        "Accounts": [
    {
        "Name": "Personal",
        "Balance": 1,
        "USDBalance": 2,
        "FullBalance": 0,
        "NumAddresses": 231,
        "Addresses": [
    {
        "Address": "aaaaaaaaaaaaaaaaaaaaaa",
        "Balance": 2.13
    },
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Balance": 0.001
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Balance": 1.32
}
],
"Transactions": [
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
},
{
    "Date": "01/02/2015",
    "Amount": "3.14",
    "USDAmount": "3.90",
    "Deposit": false
}
]
},
{
    "Name": "Work",
    "Balance": 0,
    "USDBalance": 0,
    "FullBalance": 0,
    "NumAddresses": 101,
    "Addresses": [
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 2.13
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 0.001
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 1.32
}
],
"Transactions": [
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
},
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
}
]
}
]
},
"status": {
    "StateInfo": {
        "CurrentBlock": [
        231,
        83,
        "...",
        114,
        111,
        159
        ],
        "Height": 0,
        "Target": [
        0,
        0,
        "...",
        0,
        0
        ],
        "Depth": [
        255,
        255,
        "...",
        255,
        255
        ],
        "EarliestLegalTimestamp": 1417070299
    },
    "RenterFiles": null,
    "IPAddress": ":9988",
    "HostSettings": {
        "IPAddress": ":9988",
        "TotalStorage": 0,
        "MinFilesize": 0,
        "MaxFilesize": 0,
        "MinDuration": 0,
        "MaxDuration": 0,
        "MinChallengeWindow": 0,
        "MaxChallengeWindow": 0,
        "MinTolerance": 0,
        "Price": 0,
        "Burn": 0,
        "CoinAddress": [
        0,
        0,
        "...",
        0,
        0
        ],
        "SpendConditions": {
            "TimeLock": 0,
            "NumSignatures": 0,
            "PublicKeys": null
        },
        "FreezeIndex": 0
    },
    "HostSpaceRemaining": 0,
    "HostContractCount": 0
}
}*/

var ui = (function(){

    var currentView = "overview";
    var viewNames = ["overview", "money", "manage-account", "files", "hosting", "mining", "transfer-funds"];
    var transitionTypes = {
        "money->manage-account": "slideleft",
        "manage-account->money": "slideright",
        "manage-account->transfer-funds": "slideleft",
        "transfer-funds->manage-account": "slideright"
    };
    var lastData;
    var eTooltip;
    var eventListeners = {};

    function switchView(newView){
        // Check that parameter is specified
        if (!newView){
            console.error(help("switchView"));
            return;
        }
        // Check if view is valid
        if (viewNames.indexOf(newView) === -1){
            console.error(newView + " is not a valid view");
            return;
        }

        // Refresh the new view's data
        ui["_" + newView].update(lastData);

        // Call the view onViewOpened event
        if (ui["_" + newView].onViewOpened) ui["_" + newView].onViewOpened();

        // Make the currently selected button greyed
        $("#sidebar .current").removeClass("current");
        $("." + newView + "-button").addClass("current");

        // Get the animation for the change
        var transitionType = transitionTypes[currentView + "->" + newView] || "load";

        if (transitionType == "load"){
            // Play a dummy loading animation (we may need the time later)
            startLoadingAnimation();
            setTimeout(function(){
                stopLoadingAnimation(newView);
            },400);
        }else if (transitionType == "slideright"){
            slideAnimation(newView, "right");
        }else if (transitionType == "slideleft"){
            slideAnimation(newView, "left");
        }else{
            console.error("Invalid transition type specified");
        }

    }

    function startLoadingAnimation(){
        // Position rotating loader icon in center of content
        $("#loader").css({
            "left": $("#content").width()/2 - $("#loader").width()/2,
            "top": "250px"
        });

        // Animate the loader in
        $("#loader").stop().fadeIn();

        // Make all content (excluding the loader) non-visible
        $("#content").children().filter(function(i){
            return this != $("#loader")[0];
        }).fadeOut();
    }

    function stopLoadingAnimation(newView){
        currentView = newView;
        $("#loader").stop().fadeOut();
        $("#" + newView).fadeIn();
    }

    function slideAnimation(newView, directionString){

        // Utility functions
        function setTranslate(element, x, y){
            element.css({
                "-webkit-transform": "translate(" + x + "px," + y + "px)"
            });
        }

        function clearTransform(element){
            element.css({
                "-webkit-transform": ""
            });
        }

        // Show the new view (off to the side)
        $("#" + newView).show();

        var newElement = $("#" + newView);
        var oldElement = $("#" + currentView);

        // To avoid movement upon removal
        newElement.before(oldElement);

        var slideDistance = oldElement.width();
        var heightDifference = oldElement.offset().top - newElement.offset().top;

        newElement.css({"animationProgress":0});
        newElement.animate({animationProgress:1},{
            duration:400,
            step: function(v){
                // Prevent tooltips from being spawned
                eTooltip.stop().hide();
                clearTimeout(tooltipTimeout);

                // Translate views
                if (directionString == "right"){
                    setTranslate(newElement, slideDistance * (v- 1),heightDifference);
                    setTranslate(oldElement, slideDistance * v, 0);
                }else{
                    setTranslate(newElement, slideDistance * (1-v), heightDifference);
                    setTranslate(oldElement, slideDistance * -v,0);
                }
            },
            complete:function(){
                // When the animation is done, clear the transformations and
                // make the current view the primary view
                clearTransform(oldElement);
                clearTransform(newElement);
                oldElement.hide();
                currentView = newView;
            }
        });
    }

    function help(functionName){
        if (!functionName) console.error("help(<function name>)");
        return {
            "switchView": "switchView(<string newView>) \
            \nPossible Views: " + viewNames.join(", "),
            "update": "update(<json data object>) \
            \nData object generated from requests from server, see top of ui.js",
            "addListener": "addListener(<string event>, <function callback>)\
            \nAdd listener when a ui event occurs"
        }[functionName];
    }

    function init(){
        // Hide everything but the "overview" view
        $("#content").children().filter(function(i){
            return this != $("#overview")[0];
        }).hide();

        // Add click listeners to buttons
        viewNames.forEach(function(view){
            $("." + view + "-button").click(function(){
                switchView(view);
            });
        });

        eTooltip = $("#tooltip");

        initViews();
    }

    function initViews(){
        viewNames.forEach(function(view){
            ui["_" + view].init();
        });
    }

    function update(data){
        viewNames.forEach(function(view){
            ui["_" + view].update(data);
        });
        lastData = data;
    }

    // Triggers an event, many ui actions cause triggers
    function _trigger(event){
        console.log("Event Triggered:",event);
        var callbacks = eventListeners[event] || [];
        for (var i = 0;i < callbacks.length;i++){
            callbacks[i].apply(this, Array.prototype.slice.call(arguments).slice(1,arguments.length));
        }
    }

    // Shows tooltip with content on given element
    var tooltipTimeout,tooltipVisible;
    function _tooltip(element, content, offset){
        offset = offset || {top:0,left:0};
        element = $(element);
        eTooltip.show();
        eTooltip.html(content);
        var middleX = element.offset().left + element.width()/2;
        var topY = element.offset().top - element.height();
        eTooltip.offset({
            top: topY - eTooltip.height() + offset.top,
            left: middleX - eTooltip.width()/2 + offset.left
        });
        if (!tooltipVisible){
            eTooltip.stop();
            eTooltip.css({"opacity":0});
            tooltipVisible = true;
            eTooltip.animate({
                "opacity":1
            },400);
        }else{
            eTooltip.stop();
            eTooltip.show();
            eTooltip.css({"opacity":1});
        }
        clearTimeout(tooltipTimeout);
        tooltipTimeout = setTimeout(function(){
            // eTooltip.hide();
            eTooltip.animate({
                "opacity":"0"
            },400,function(){
                tooltipVisible = false;
                eTooltip.hide();
            });
        },1400);
    }

    function addListener(event, callback){
        eventListeners[event] = eventListeners[event] || [];
        eventListeners[event].push(callback);
    }

    return {
        "switchView": switchView,
        "update": update,
        "addListener": addListener,
        "_tooltip": _tooltip,
        "_trigger": _trigger,
        "help": help,
        "init": init
    };
})();
<commit_msg>removed onViewOpened event and added _data property to ui<commit_after>// ui module
// Handles displaying data to UI, user interaction events and changing views,
// basically any interaction with the page should run through UI

// Calling ui.help("<function name>") will give parameter information
// the help will also be displayed if the parameters are given incorrectly

// The UI will get updates to it's data from TODO (external module), update it's
// data object, then calls update(data); on all views.

// Example UI Data Format
/*
{
    "miner": {
        "State": "On",
        "Threads": 2,
        "RunningThreads": 1,
        "Address": [
        126,
        66,
        "...",
        173,
        53
        ],
        "AccountName": "Personal",
        "Balance": 1,
        "USDBalance": 2,
        "IncomeRate": "20.345 SC/h"
    },
    "wallet": {
        "Balance": 0,
        "USDBalance": 0,
        "FullBalance": 0,
        "NumAddresses": 2392,
        "DefaultAccount": "Personal",
        "Accounts": [
    {
        "Name": "Personal",
        "Balance": 1,
        "USDBalance": 2,
        "FullBalance": 0,
        "NumAddresses": 231,
        "Addresses": [
    {
        "Address": "aaaaaaaaaaaaaaaaaaaaaa",
        "Balance": 2.13
    },
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Balance": 0.001
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Balance": 1.32
}
],
"Transactions": [
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
},
{
    "Date": "01/02/2015",
    "Amount": "3.14",
    "USDAmount": "3.90",
    "Deposit": false
}
]
},
{
    "Name": "Work",
    "Balance": 0,
    "USDBalance": 0,
    "FullBalance": 0,
    "NumAddresses": 101,
    "Addresses": [
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 2.13
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 0.001
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 1.32
}
],
"Transactions": [
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
},
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
}
]
}
]
},
"status": {
    "StateInfo": {
        "CurrentBlock": [
        231,
        83,
        "...",
        114,
        111,
        159
        ],
        "Height": 0,
        "Target": [
        0,
        0,
        "...",
        0,
        0
        ],
        "Depth": [
        255,
        255,
        "...",
        255,
        255
        ],
        "EarliestLegalTimestamp": 1417070299
    },
    "RenterFiles": null,
    "IPAddress": ":9988",
    "HostSettings": {
        "IPAddress": ":9988",
        "TotalStorage": 0,
        "MinFilesize": 0,
        "MaxFilesize": 0,
        "MinDuration": 0,
        "MaxDuration": 0,
        "MinChallengeWindow": 0,
        "MaxChallengeWindow": 0,
        "MinTolerance": 0,
        "Price": 0,
        "Burn": 0,
        "CoinAddress": [
        0,
        0,
        "...",
        0,
        0
        ],
        "SpendConditions": {
            "TimeLock": 0,
            "NumSignatures": 0,
            "PublicKeys": null
        },
        "FreezeIndex": 0
    },
    "HostSpaceRemaining": 0,
    "HostContractCount": 0
}
}*/

var ui = (function(){

    var currentView = "overview";
    var viewNames = ["overview", "money", "manage-account", "files", "hosting", "mining", "transfer-funds"];
    var transitionTypes = {
        "money->manage-account": "slideleft",
        "manage-account->money": "slideright",
        "manage-account->transfer-funds": "slideleft",
        "transfer-funds->manage-account": "slideright"
    };
    var eTooltip;
    var eventListeners = {};

    function switchView(newView){
        // Check that parameter is specified
        if (!newView){
            console.error(help("switchView"));
            return;
        }
        // Check if view is valid
        if (viewNames.indexOf(newView) === -1){
            console.error(newView + " is not a valid view");
            return;
        }

        // Refresh the new view's data
        ui["_" + newView].update(ui._data);

        // Make the currently selected button greyed
        $("#sidebar .current").removeClass("current");
        $("." + newView + "-button").addClass("current");

        // Get the animation for the change
        var transitionType = transitionTypes[currentView + "->" + newView] || "load";

        if (transitionType == "load"){
            // Play a dummy loading animation (we may need the time later)
            startLoadingAnimation();
            setTimeout(function(){
                stopLoadingAnimation(newView);
            },400);
        }else if (transitionType == "slideright"){
            slideAnimation(newView, "right");
        }else if (transitionType == "slideleft"){
            slideAnimation(newView, "left");
        }else{
            console.error("Invalid transition type specified");
        }

    }

    function startLoadingAnimation(){
        // Position rotating loader icon in center of content
        $("#loader").css({
            "left": $("#content").width()/2 - $("#loader").width()/2,
            "top": "250px"
        });

        // Animate the loader in
        $("#loader").stop().fadeIn();

        // Make all content (excluding the loader) non-visible
        $("#content").children().filter(function(i){
            return this != $("#loader")[0];
        }).fadeOut();
    }

    function stopLoadingAnimation(newView){
        currentView = newView;
        $("#loader").stop().fadeOut();
        $("#" + newView).fadeIn();
    }

    function slideAnimation(newView, directionString){

        // Utility functions
        function setTranslate(element, x, y){
            element.css({
                "-webkit-transform": "translate(" + x + "px," + y + "px)"
            });
        }

        function clearTransform(element){
            element.css({
                "-webkit-transform": ""
            });
        }

        // Show the new view (off to the side)
        $("#" + newView).show();

        var newElement = $("#" + newView);
        var oldElement = $("#" + currentView);

        // To avoid movement upon removal
        newElement.before(oldElement);

        var slideDistance = oldElement.width();
        var heightDifference = oldElement.offset().top - newElement.offset().top;

        newElement.css({"animationProgress":0});
        newElement.animate({animationProgress:1},{
            duration:400,
            step: function(v){
                // Prevent tooltips from being spawned
                eTooltip.stop().hide();
                clearTimeout(tooltipTimeout);

                // Translate views
                if (directionString == "right"){
                    setTranslate(newElement, slideDistance * (v- 1),heightDifference);
                    setTranslate(oldElement, slideDistance * v, 0);
                }else{
                    setTranslate(newElement, slideDistance * (1-v), heightDifference);
                    setTranslate(oldElement, slideDistance * -v,0);
                }
            },
            complete:function(){
                // When the animation is done, clear the transformations and
                // make the current view the primary view
                clearTransform(oldElement);
                clearTransform(newElement);
                oldElement.hide();
                currentView = newView;
            }
        });
    }

    function help(functionName){
        if (!functionName) console.error("help(<function name>)");
        return {
            "switchView": "switchView(<string newView>) \
            \nPossible Views: " + viewNames.join(", "),
            "update": "update(<json data object>) \
            \nData object generated from requests from server, see top of ui.js",
            "addListener": "addListener(<string event>, <function callback>)\
            \nAdd listener when a ui event occurs"
        }[functionName];
    }

    function init(){
        // Hide everything but the "overview" view
        $("#content").children().filter(function(i){
            return this != $("#overview")[0];
        }).hide();

        // Add click listeners to buttons
        viewNames.forEach(function(view){
            $("." + view + "-button").click(function(){
                switchView(view);
            });
        });

        eTooltip = $("#tooltip");

        initViews();
    }

    function initViews(){
        viewNames.forEach(function(view){
            ui["_" + view].init();
        });
    }

    function update(data){
        viewNames.forEach(function(view){
            ui["_" + view].update(data);
        });
        ui._data = data;
    }

    // Triggers an event, many ui actions cause triggers
    function _trigger(event){
        console.log("Event Triggered:",event);
        var callbacks = eventListeners[event] || [];
        for (var i = 0;i < callbacks.length;i++){
            callbacks[i].apply(this, Array.prototype.slice.call(arguments).slice(1,arguments.length));
        }
    }

    // Shows tooltip with content on given element
    var tooltipTimeout,tooltipVisible;
    function _tooltip(element, content, offset){
        offset = offset || {top:0,left:0};
        element = $(element);
        eTooltip.show();
        eTooltip.html(content);
        var middleX = element.offset().left + element.width()/2;
        var topY = element.offset().top - element.height();
        eTooltip.offset({
            top: topY - eTooltip.height() + offset.top,
            left: middleX - eTooltip.width()/2 + offset.left
        });
        if (!tooltipVisible){
            eTooltip.stop();
            eTooltip.css({"opacity":0});
            tooltipVisible = true;
            eTooltip.animate({
                "opacity":1
            },400);
        }else{
            eTooltip.stop();
            eTooltip.show();
            eTooltip.css({"opacity":1});
        }
        clearTimeout(tooltipTimeout);
        tooltipTimeout = setTimeout(function(){
            // eTooltip.hide();
            eTooltip.animate({
                "opacity":"0"
            },400,function(){
                tooltipVisible = false;
                eTooltip.hide();
            });
        },1400);
    }

    function addListener(event, callback){
        eventListeners[event] = eventListeners[event] || [];
        eventListeners[event].push(callback);
    }

    return {
        "switchView": switchView,
        "update": update,
        "addListener": addListener,
        "_tooltip": _tooltip,
        "_trigger": _trigger,
        "_data": null,
        "help": help,
        "init": init
    };
})();
<|endoftext|>


<commit_before>/**
 * # Ashigaru
 *
 * Copyright (c)2011, by Branko Vukelic <branko@herdhound.com>
 *
 * jQuery plugin for making requests to Samurai payment gateway via a hidden
 * iframe.
 *
 * Ashigaru is part of Daimyo (https//github.com/HerdHound/Daimyo).
 *
 * ## About the JSON parser
 *
 * Ashigaru requires either a native JSON parser, or a 3rd party solution.
 *
 * If your environment (browser(s) you intend to support) does not provide the
 * native JSON object, you can use the Crockford's implementation found on
 * [on Github](https://github.com/douglascrockford/JSON-js/blob/master/json2.js).
 *
 * ## Preparing the server
 *
 * Before you can use this plugin, you must make sure that a valid redirect URL
 * is handled on your server. Once Samurai gateway receives data from this
 * plugin, it will redirect the user to the redirect URL. The redirect URL will
 * have an URL parameter called `payment_method_token` which should be a
 * 24-digit hexdigest. That token identifies the payment method created by the
 * user. (See the documentation for the `daimyo` module for more information
 * on how to use this token.)
 *
 * Once you have performed any operations you want, you can respond to the
 * request that was made to the redirect URL. The response should be text/html,
 * and it should contain at least the `<body>` tag, and a single `<script>` tag
 * that contains the JSON response. A typical success response may look like
 * this:
 *
 *
 *
 * There is no need to add standard HTML markup because this response will
 * never be rendered. Once you have set up the server-side handler to work this
 * way, you are ready to start using Ashigaru.
 *
 * ## Basic usage
 *
 * Generally, it is expected that you will take care of the user-facing form
 * yourself, validate the input, and extract the data into an object. The
 * object should have the following properties:
 *
 *  + _firstName_: cardholder's first name (optional)
 *  + _lastName_: cardholder's last name (optional)
 *  + _address1_: cardholder's address line 1 (optional)
 *  + _address2_: cardholder's address line 2 (optional)
 *  + _city_: city (optional)
 *  + _state_: state or region (optional)
 *  + _country_: country (optional)
 *  + _zip_: zip/postal code (optional)
 *  + _number_: card number (required)
 *  + _csc_: card security code, CCV, CVV, CVC, etc (required)
 *  + _year_: expiration year (optional)
 *  + _month_: expiration month (optional)
 *
 * As you can see, only card number and CSC (a.k.a CCV, CVC, CVV) are required,
 * and other fields are optional. To increase the chance of transactions
 * actually clearing, and minimize your liability in case of trouble, you
 * should try to collect as much data as possible, but cardholder name, zip,
 * and address line 1 are probably bare minimum.
 *
 * Once you have created the object containing the cardholder data, you can
 * call Ashigaru like this:
 *
 *     $.ashigaru(cardData, merchantKey, redirectURL, function(err, data) {
 *       // err means there was an error parsing the JSON or no data
 *       // was ever returned. If all went fine, err should be null.
 *       // data will contain a fully parsed JSON response.
 *     });
 *
 * Ashigaru currently has no mechanisms for retrying a failed connection. You
 * should make sure you handle such unforeseen problems yourself.
 *
 * @version 0.0.1
 * @author Branko Vurkelic <branko@herdhound.com>
 * @license MIT (see LICENSE)
 */

(function($, window) {

  var originalDomain = window.document.domain;
  var samuraiURI = 'https://samurai.feefighters.com/v1/payment_methods';

  /**
   * ## Remove the hidden form
   */
  function removeForm() {
    $('#samurai-form').remove();
    removeIframe();
  }

  /**
   * ## onResultLoad(iFrame, callback)
   * *Processes data loaded into the iframe*
   *
   * This is triggered when iFrame is loadded with results. This method will
   * use the JSON object to parse the loaded JSON data. If such an object is
   * not available in your environment, you can load Crockfords json2.js
   * found [on Github](https://github.com/douglascrockford/JSON-js/blob/master/json2.js).
   *
   * @param {jQuery} iFrame The iframe that contians the loaded data
   * @param {Function} callback Callback function that will handle the data
   * @private
   */
  function onResultLoad(iFrame, callback) {
    var resultDocument = $(iFrame).contents();
    var jsonData;

    // Remove the form
    removeForm();

    // The result document should contain JSON data in a
 *
 * There is no need to add standard HTML markup because this response will
 * never be rendered. Once you have set up the server-side handler to work this
 * way, you are ready to start using Ashigaru.
 *
 * ## Basic usage
 *
 * Generally, it is expected that you will take care of the user-facing form
 * yourself, validate the input, and extract the data into an object. The
 * object should have the following properties:
 *
 *  + _firstName_: cardholder's first name (optional)
 *  + _lastName_: cardholder's last name (optional)
 *  + _address1_: cardholder's address line 1 (optional)
 *  + _address2_: cardholder's address line 2 (optional)
 *  + _city_: city (optional)
 *  + _state_: state or region (optional)
 *  + _country_: country (optional)
 *  + _zip_: zip/postal code (optional)
 *  + _number_: card number (required)
 *  + _csc_: card security code, CCV, CVV, CVC, etc (required)
 *  + _year_: expiration year (optional)
 *  + _month_: expiration month (optional)
 *
 * As you can see, only card number and CSC (a.k.a CCV, CVC, CVV) are required,
 * and other fields are optional. To increase the chance of transactions
 * actually clearing, and minimize your liability in case of trouble, you
 * should try to collect as much data as possible, but cardholder name, zip,
 * and address line 1 are probably bare minimum.
 *
 * Once you have created the object containing the cardholder data, you can
 * call Ashigaru like this:
 *
 *     $.ashigaru(cardData, merchantKey, redirectURL, function(err, data) {
 *       // err means there was an error parsing the JSON or no data
 *       // was ever returned. If all went fine, err should be null.
 *       // data will contain a fully parsed JSON response.
 *     });
 *
 * Ashigaru currently has no mechanisms for retrying a failed connection. You
 * should make sure you handle such unforeseen problems yourself.
 *
 * @version 0.0.1
 * @author Branko Vurkelic <branko@herdhound.com>
 * @license MIT (see LICENSE)
 */

(function($, window) {

  var originalDomain = window.document.domain;
  var samuraiURI = 'https://samurai.feefighters.com/v1/payment_methods';

  /**
   * ## Remove the hidden form
   */
  function removeForm() {
    $('#samurai-form').remove();
    removeIframe();
  }

  /**
   * ## onResultLoad(iFrame, callback)
   * *Processes data loaded into the iframe*
   *
   * This is triggered when iFrame is loadded with results. This method will
   * use the JSON object to parse the loaded JSON data. If such an object is
   * not available in your environment, you can load Crockfords json2.js
   * found [on Github](https://github.com/douglascrockford/JSON-js/blob/master/json2.js).
   *
   * @param {jQuery} iFrame The iframe that contians the loaded data
   * @param {Function} callback Callback function that will handle the data
   * @private
   */
  function onResultLoad(iFrame, callback) {
    var resultDocument = $(iFrame).contents();
    var jsonData;

    // Remove the form
    removeForm();

    // The result document should contain JSON data in a


<commit_before>const app = require('../app-quick');
const expect = require('chai').expect;

const version = process.env.QB_VERSION;

describe('run docker with version', function () {
    it('should have benchmark results', async () => {
        var request = {
            options: {
                compiler: version,
                optim: 3,
                cppVersion: 17,
                isAnnotated: "true",
                lib: "gnu"
            },
            force: "true"
        };
        expect(version).to.be.ok;
        process.env.BENCH_ROOT = __dirname;
        const done = await app.execute('system-test/testfile/test', request);
        const parsed = JSON.parse(done.res);
        expect(parsed.benchmarks).to.have.length(2);
        expect(done.annotation).to.be.ok;
        expect(done.annotation.split('\n')).to.have.lengthOf.above(7);
        expect(done.annotation).to.have.string('BM_StringCreation');
        expect(done.annotation).to.have.string('BM_StringCopy');
        //	expect(done.stdout).to.be.empty; // Removed because of a Docker message on my Ubuntu version.
        console.log(done.stdout);
        expect(done.annotation).to.be.ok;
    }).timeout(120000);
});

describe('check compiler version inside docker', function () {
    it('should have the same version', async () => {
        const exec = require('child_process').exec;
        let options = {
            timeout: 60000,
            killSignal: 'SIGKILL'
        };
        console.log(`${__dirname}/testfile/version.cpp`);
        const result = await new Promise(resolve => exec(`docker run --rm -v ${__dirname}/testfile/version.cpp:/home/builder/bench-file.cpp -t fredtingaud/quick-bench:${version} /bin/bash -c "./build && ./run"`, options, (error, stdout, stderr) => {
            resolve(stdout + stderr);
        }));
        expect(result).to.eql(version);
    }).timeout(60000);
});
<commit_msg>Fix system-test.<commit_after>const app = require('../app-quick');
const expect = require('chai').expect;

const version = process.env.QB_VERSION;

describe('run docker with version', function () {
    before(function () {
        const execSync = require('child_process').execSync;
        execSync(`rm -rf ${process.cwd()}/system-test/testfile/test/test.lock`);
    });

    it('should have benchmark results', async () => {
        var request = {
            options: {
                compiler: version,
                optim: 3,
                cppVersion: 17,
                lib: "gnu"
            },
            isAnnotated: "true",
            force: "true"
        };
        expect(version).to.be.ok;
        process.env.BENCH_ROOT = process.cwd();
        const done = await app.execute('system-test/testfile/test', request);
        const parsed = JSON.parse(done.res);
        expect(parsed.benchmarks).to.have.length(2);
        expect(done.annotation).to.be.ok;
        expect(done.annotation.split('\n')).to.have.lengthOf.above(7);
        expect(done.annotation).to.have.string('BM_StringCreation');
        expect(done.annotation).to.have.string('BM_StringCopy');
        //	expect(done.stdout).to.be.empty; // Removed because of a Docker message on my Ubuntu version.
        console.log(done.stdout);
        expect(done.annotation).to.be.ok;
    }).timeout(120000);
});

describe('check compiler version inside docker', function () {
    it('should have the same version', async () => {
        const exec = require('child_process').exec;
        let options = {
            timeout: 60000,
            killSignal: 'SIGKILL'
        };
        console.log(`${__dirname}/testfile/version.cpp`);
        const result = await new Promise(resolve => exec(`docker run --rm -v ${__dirname}/testfile/version.cpp:/home/builder/bench-file.cpp -t fredtingaud/quick-bench:${version} /bin/bash -c "./build && ./run"`, options, (error, stdout, stderr) => {
            resolve(stdout + stderr);
        }));
        expect(result).to.eql(version);
    }).timeout(60000);
});
<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : index.js
* Module : SystemTest
* Location : /SystemTest
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-06-27   Filippo Rampado    Initial code
* =========================================================
*/
var Helper=require('./helper.js');

console.log('Hello Norris');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);

// Includo e creo l'ustanza di Norris
var Norris = require('../norris-nrti.js');
var norris = new Norris(app,io,'/norris','http://norris-nrti-dev.herokuapp.com');

var page1=Helper.newPage(norris, 'page1', 'Pagina creazione grafici');
var page2=Helper.newPage(norris, 'page2', 'Pagina aggiornamento grafici');

var barChart=Helper.newBarChart(page2, 'Test aggiornamento dati Bar Chart');
var lineChart=Helper.newLineChart(page2, 'Test aggiornamento dati Line Chart');
//var mapChart=Helper.newMapChart(page2, 'Test aggiornamento dati Map Chart');
//var table=Helper.newTable(page2, 'Test aggiornamento dati Table');

var TS1 = require('./TS1.js');
var TS2 = require('./TS2.js');
var TS3 = require('./TS3.js');
var TS4 = require('./TS4.js');
var TS5 = require('./TS5.js');
var TS6 = require('./TS6.js');
var TS7 = require('./TS7.js');
//var TS8 = require('./TS8.js');
//var TS9 = require('./TS9.js');

TS1(norris);
TS2(page1);
TS3(page1);
TS4(page1);
TS5(page1);
TS6(barChart);
TS7(lineChart);
//TS8(mapChart);
//TS9(table);

/////////////////////////////////////////////
app.get('/', function (req, res) {
	var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
	console.log(' Test di sistema '+ fullUrl);
	res.send(' Test di sistema '+ fullUrl);
});

var port = process.env.PORT || 3000;
server.listen(port);<commit_msg>let only barChart<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : index.js
* Module : SystemTest
* Location : /SystemTest
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-06-27   Filippo Rampado    Initial code
* =========================================================
*/
var Helper=require('./helper.js');

console.log('Hello Norris');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);

// Includo e creo l'ustanza di Norris
var Norris = require('../norris-nrti.js');
var norris = new Norris(app,io,'/norris','http://norris-nrti-dev.herokuapp.com');

var page1=Helper.newPage(norris, 'page1', 'Pagina creazione grafici');
var page2=Helper.newPage(norris, 'page2', 'Pagina aggiornamento grafici');

var barChart=Helper.newBarChart(page2, 'Test aggiornamento dati Bar Chart');
//var lineChart=Helper.newLineChart(page2, 'Test aggiornamento dati Line Chart');
//var mapChart=Helper.newMapChart(page2, 'Test aggiornamento dati Map Chart');
//var table=Helper.newTable(page2, 'Test aggiornamento dati Table');

var TS1 = require('./TS1.js');
var TS2 = require('./TS2.js');
var TS3 = require('./TS3.js');
var TS4 = require('./TS4.js');
var TS5 = require('./TS5.js');
var TS6 = require('./TS6.js');
var TS7 = require('./TS7.js');
//var TS8 = require('./TS8.js');
//var TS9 = require('./TS9.js');

TS1(norris);
TS2(page1);
TS3(page1);
TS4(page1);
TS5(page1);
TS6(barChart);
//TS7(lineChart);
//TS8(mapChart);
//TS9(table);

/////////////////////////////////////////////
app.get('/', function (req, res) {
	var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
	console.log(' Test di sistema '+ fullUrl);
	res.send(' Test di sistema '+ fullUrl);
});

var port = process.env.PORT || 3000;
server.listen(port);<|endoftext|>


<commit_before>#!/usr/bin/env node

/*
    ___ usage: en_US ___
    usage: basic [options] [files]
        -c, --config <key=value> @
            --longonly
    ___ strings ___
    badness: A bad thing happened.
    ordered(2, 1): First %s then %s.
    unordered: First %s then %s.
    ___ usage ___
*/

var stream = require('stream'),
    path = require('path'),
    cadence = require('cadence')

require('proof')(16, cadence(function (async, assert) {
    var usage = 'usage: basic [options] [files]\n' +
                '    -c, --config <key=value>\n' +
                '        --longonly\n' +
                ''
    var run = require('../../run'), io
    run(path.join(__dirname, 'endless.js'), {}, [], {}, cadence(function (async, options) {
    }), function (error, code) {
        assert(error.message, 'no usage found', 'no usage found')
    })
    run(__filename, {}, [], {}, cadence(function (async, options) {
    }), function (error, code) {
        if (error) throw error
        assert(code, 0, 'exit zero')
    })
    run(__filename, {}, [], {}, cadence(function (async, options) {
        throw new Error('raw')
    }), function (error) {
        assert(error.message, 'raw', 'raw exception')
    })
    run(__filename, {}, [], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
        options.abend('badness')
    }), function (error, code) {
        if (error) throw error
        assert(io.stderr.read().toString(), 'A bad thing happened.\n', 'error')
        assert(code, 1, 'error code')
    })
    run(__filename, {}, [], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
        options.abend('nogoodness')
    }), function (error, code) {
        if (error) throw error
        assert(io.stderr.read().toString(), 'nogoodness\n', 'error string missing')
        assert(code, 1, 'error string missing code')
    })
    run(__filename, {}, [ '-x' ], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
        options.abend('nogoodness')
    }), function (error, code) {
        assert(io.stderr.read().toString(), 'unknown argument\n', 'unknown argument')
        assert(code, 1, 'unknown argument code')
    })
    run(__filename, {}, [], io = {
    }, cadence(function (async, options) {
        options.exit(0)
    }), function (error, code) {
        if (error) throw error
        assert(code, 0, 'normal exit')
    })
    run(__filename, {}, [], io = {
        stdout: new stream.PassThrough
    }, cadence(function (async, options) {
        options.help()
    }), function (error) {
        assert(io.stdout.read().toString(), usage, 'help')
    })
    run(path.join(__dirname, 'sub.js'), {}, [], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
    }), function (error, code) {
        assert(io.stderr.read().toString(), 'command required\n', 'command missing')
    })
    run(path.join(__dirname, 'sub.js'), {}, [ 'run', '-p', 3 ],  {
    }, cadence(function (async, options) {
        assert(options.params.processes, 3, 'correct sub command arguments pattern')
    }), function (error, code) {
        if (error) throw error
        assert(code, 0, 'sub command normal exit')
    })
    run(__filename, {}, [],  {
    }, cadence(function (async, options) {
        assert(options.format('ordered', 'this', 'that'), 'First that then this.', 'ordered format')
        assert(options.format('unordered', 'this', 'that'), 'First this then that.', 'unordered format')
    }), function (error, code) {
        if (error) throw error
    })
}))
<commit_msg>Test abend with code.<commit_after>#!/usr/bin/env node

/*
    ___ usage: en_US ___
    usage: basic [options] [files]
        -c, --config <key=value> @
            --longonly
    ___ strings ___
    badness: A bad thing happened.
    ordered(2, 1): First %s then %s.
    unordered: First %s then %s.
    ___ usage ___
*/

var stream = require('stream'),
    path = require('path'),
    cadence = require('cadence')

require('proof')(18, cadence(function (async, assert) {
    var usage = 'usage: basic [options] [files]\n' +
                '    -c, --config <key=value>\n' +
                '        --longonly\n' +
                ''
    var run = require('../../run'), io
    run(path.join(__dirname, 'endless.js'), {}, [], {}, cadence(function (async, options) {
    }), function (error, code) {
        assert(error.message, 'no usage found', 'no usage found')
    })
    run(__filename, {}, [], {}, cadence(function (async, options) {
    }), function (error, code) {
        if (error) throw error
        assert(code, 0, 'exit zero')
    })
    run(__filename, {}, [], {}, cadence(function (async, options) {
        throw new Error('raw')
    }), function (error) {
        assert(error.message, 'raw', 'raw exception')
    })
    run(__filename, {}, [], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
        options.abend('badness')
    }), function (error, code) {
        if (error) throw error
        assert(io.stderr.read().toString(), 'A bad thing happened.\n', 'error')
        assert(code, 1, 'error code')
    })
    run(__filename, {}, [], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
        options.abend(127, 'badness')
    }), function (error, code) {
        if (error) throw error
        assert(io.stderr.read().toString(), 'A bad thing happened.\n', 'error with code')
        assert(code, 127, 'code for error with code')
    })
    run(__filename, {}, [], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
        options.abend('nogoodness')
    }), function (error, code) {
        if (error) throw error
        assert(io.stderr.read().toString(), 'nogoodness\n', 'error string missing')
        assert(code, 1, 'error string missing code')
    })
    run(__filename, {}, [ '-x' ], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
        options.abend('nogoodness')
    }), function (error, code) {
        assert(io.stderr.read().toString(), 'unknown argument\n', 'unknown argument')
        assert(code, 1, 'unknown argument code')
    })
    run(__filename, {}, [], io = {
    }, cadence(function (async, options) {
        options.exit(0)
    }), function (error, code) {
        if (error) throw error
        assert(code, 0, 'normal exit')
    })
    run(__filename, {}, [], io = {
        stdout: new stream.PassThrough
    }, cadence(function (async, options) {
        options.help()
    }), function (error) {
        assert(io.stdout.read().toString(), usage, 'help')
    })
    run(path.join(__dirname, 'sub.js'), {}, [], io = {
        stderr: new stream.PassThrough
    }, cadence(function (async, options) {
    }), function (error, code) {
        assert(io.stderr.read().toString(), 'command required\n', 'command missing')
    })
    run(path.join(__dirname, 'sub.js'), {}, [ 'run', '-p', 3 ],  {
    }, cadence(function (async, options) {
        assert(options.params.processes, 3, 'correct sub command arguments pattern')
    }), function (error, code) {
        if (error) throw error
        assert(code, 0, 'sub command normal exit')
    })
    run(__filename, {}, [],  {
    }, cadence(function (async, options) {
        assert(options.format('ordered', 'this', 'that'), 'First that then this.', 'ordered format')
        assert(options.format('unordered', 'this', 'that'), 'First this then that.', 'unordered format')
    }), function (error, code) {
        if (error) throw error
    })
}))
<|endoftext|>


<commit_before>const argv = require('yargs').argv;
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync');
const browserify = require('browserify');
const buffer = require('vinyl-buffer');
const csso = require('gulp-csso');
const gulp = require('gulp');
const gulpif = require('gulp-if');
const imagemin = require('gulp-imagemin');
const plumber = require('gulp-plumber');
const sass = require('gulp-sass');
const sassGlob = require('gulp-sass-glob');
const source = require('vinyl-source-stream');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const watchify = require('watchify');

function plumbing() {
  return plumber({
    errorHandler: function (error) {
      console.log(error.message);
      this.emit('end');
    }
  });
}

gulp.task('browser-sync', function () {
  browserSync({
    proxy: 'http://127.0.0.1:8000',
  });
});

gulp.task('bs-reload', function () {
  browserSync.reload();
});

gulp.task('copy', function () {
  return gulp.src(['static/img/**/*', 'static/favicon/**/*'], {base: './static'})
    .pipe(gulp.dest('_build'));
});

gulp.task('images', function () {
  return gulp.src('static/images/**/*.{jpg,png}')
    .pipe(gulpif(argv.prod, imagemin({optimizationLevel: 3, progressive: true, interlaced: true})))
    .pipe(gulp.dest('_build/images/'));
});

gulp.task('svg', function () {
  return gulp.src('static/svg/**/*.svg')
    .pipe(imagemin({optimizationLevel: 3, progressive: true, interlaced: true}))
    .pipe(gulp.dest('_build/svg/'));
});

gulp.task('styles', function () {
  return gulp.src(['static/styles/**/*.scss'])
    .pipe(plumbing())
    .pipe(sassGlob())
    .pipe(gulpif(!argv.prod, sourcemaps.init()))
    .pipe(sass({
      includePaths: ['node_modules'],
    }))
    .pipe(autoprefixer('last 2 versions'))
    .pipe(gulpif(argv.prod, csso()))
    .pipe(gulpif(!argv.prod, sourcemaps.write()))
    .pipe(gulp.dest('_build/styles/'))
    .pipe(gulpif(!argv.prod, browserSync.reload({stream: true})));
});

const bundler = browserify({
  entries: ['static/scripts/main.js'],
  debug: !argv.prod,
  cache: {},
  packageCache: {},
});

bundler.transform('babelify');
bundler.transform('envify', {global: true});
if (argv.prod) {
  bundler.transform('uglifyify', {global: true});
}
bundler.transform('browserify-shim', {global: true});

function bundle() {
  return bundler.bundle()
    .on('error', function (error) {
      console.log(error.message);
    })
    .pipe(plumbing())
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest('_build/scripts/'))
    .pipe(gulpif(!argv.prod, browserSync.reload({stream: true})));
}

gulp.task('scripts', bundle);

gulp.task('build', ['styles', 'scripts', 'images', 'svg', 'copy']);

gulp.task('default', ['browser-sync'], function () {
  bundler.plugin(watchify);
  bundler.on('update', bundle);
  gulp.watch('static/styles/**/*.scss', ['styles']);
  gulp.watch('static/scripts/**/*.js', ['scripts']);
  gulp.watch('static/images/**/*.{jpg,png}', ['images']);
  gulp.watch('static/svg/**/*.svg', ['svg']);
  gulp.watch('**/*.html', ['bs-reload']);
});
<commit_msg>Update template gulpfile.js<commit_after>const argv = require('yargs').argv
const autoprefixer = require('gulp-autoprefixer')
const browserSync = require('browser-sync')
const browserify = require('browserify')
const buffer = require('vinyl-buffer')
const csso = require('gulp-csso')
const gulp = require('gulp')
const gulpif = require('gulp-if')
const imagemin = require('gulp-imagemin')
const plumber = require('gulp-plumber')
const sass = require('gulp-sass')
const sassGlob = require('gulp-sass-glob')
const source = require('vinyl-source-stream')
const sourcemaps = require('gulp-sourcemaps')
const uglify = require('gulp-uglify')
const watchify = require('watchify')

function plumbing() {
  return plumber({
    errorHandler: function (error) {
      console.log(error.message)
      this.emit('end')
    }
  })
}

gulp.task('browser-sync', function () {
  browserSync({
    proxy: 'http://127.0.0.1:8000',
  })
})

gulp.task('bs-reload', function () {
  browserSync.reload()
})

gulp.task('copy', function () {
  return gulp.src([], {base: './static'})
    .pipe(gulp.dest('_build'))
})

gulp.task('images', function () {
  return gulp.src('static/images/**/*.{gif,jpg,png}')
    .pipe(gulpif(argv.prod, imagemin({optimizationLevel: 3, progressive: true, interlaced: true})))
    .pipe(gulp.dest('_build/images/'))
})

gulp.task('svg', function () {
  return gulp.src('static/svg/**/*.svg')
    .pipe(imagemin({optimizationLevel: 3, progressive: true, interlaced: true}))
    .pipe(gulp.dest('_build/svg/'))
})

gulp.task('styles', function () {
  return gulp.src(['static/styles/**/*.scss'])
    .pipe(plumbing())
    .pipe(sassGlob())
    .pipe(gulpif(!argv.prod, sourcemaps.init()))
    .pipe(sass({
      includePaths: ['node_modules'],
    }))
    .pipe(autoprefixer('last 2 versions'))
    .pipe(gulpif(argv.prod, csso()))
    .pipe(gulpif(!argv.prod, sourcemaps.write()))
    .pipe(gulp.dest('_build/styles/'))
    .pipe(gulpif(!argv.prod, browserSync.reload({stream: true})))
})

const bundler = browserify({
  entries: ['static/scripts/main.js'],
  debug: !argv.prod,
  cache: {},
  packageCache: {},
})

bundler.transform('babelify')
bundler.transform('envify', {global: true})
if (argv.prod) {
  bundler.transform('uglifyify', {global: true})
}
bundler.transform('browserify-shim', {global: true})

function bundle() {
  return bundler.bundle()
    .on('error', function (error) {
      console.log(error.message)
    })
    .pipe(plumbing())
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest('_build/scripts/'))
    .pipe(gulpif(!argv.prod, browserSync.reload({stream: true})))
}

gulp.task('scripts', bundle)

gulp.task('build', ['styles', 'scripts', 'images', 'svg', 'copy'])

gulp.task('default', ['browser-sync'], function () {
  bundler.plugin(watchify)
  bundler.on('update', bundle)
  gulp.watch('static/styles/**/*.scss', ['styles'])
  gulp.watch('static/scripts/**/*.js', ['scripts'])
  gulp.watch('static/images/**/*.{jpg,png}', ['images'])
  gulp.watch('static/svg/**/*.svg', ['svg'])
  gulp.watch('**/*.html', ['bs-reload'])
})
<|endoftext|>


<commit_before>import Modifier from 'ember-modifier';
import {action} from '@ember/object';
import {guidFor} from '@ember/object/internals';

export default class MovableModifier extends Modifier {
    moveThreshold = 3;

    active = false;
    currentX = undefined;
    currentY = undefined;
    initialX = undefined;
    initialY = undefined;
    xOffset = 0;
    yOffset = 0;

    // Lifecycle hooks ---------------------------------------------------------

    didInstall() {
        this.addStartEventListeners();
    }

    willDestroy() {
        this.removeEventListeners();
        this.enableSelection();
    }

    // Custom methods -----------------------------------------------------------

    addStartEventListeners() {
        this.element.addEventListener('touchstart', this.dragStart, false);
        this.element.addEventListener('mousedown', this.dragStart, false);
    }

    removeStartEventListeners() {
        this.element.removeEventListener('touchstart', this.dragStart, false);
        this.element.removeEventListener('mousedown', this.dragStart, false);
    }

    addActiveEventListeners() {
        window.addEventListener('touchend', this.dragEnd, {capture: true, passive: false});
        window.addEventListener('touchmove', this.drag, {capture: true, passive: false});
        window.addEventListener('mouseup', this.dragEnd, {capture: true, passive: false});
        window.addEventListener('mousemove', this.drag, {capture: true, passive: false});
    }

    removeActiveEventListeners() {
        window.removeEventListener('touchend', this.dragEnd, {capture: true, passive: false});
        window.removeEventListener('touchmove', this.drag, {capture: true, passive: false});
        window.removeEventListener('mouseup', this.dragEnd, {capture: true, passive: false});
        window.removeEventListener('mousemove', this.drag, {capture: true, passive: false});
        window.removeEventListener('click', this.cancelClick, {capture: true, passive: false});
    }

    removeEventListeners() {
        this.removeStartEventListeners();
        this.removeActiveEventListeners();
    }

    @action
    dragStart(e) {
        if (e.type === 'touchstart' || e.button === 0) {
            if (e.type === 'touchstart') {
                this.initialX = e.touches[0].clientX - this.xOffset;
                this.initialY = e.touches[0].clientY - this.yOffset;
            } else {
                this.initialX = e.clientX - this.xOffset;
                this.initialY = e.clientY - this.yOffset;
            }

            for (const elem of (e.path || e.composedPath())) {
                if (elem.matches('input, .ember-basic-dropdown-trigger')) {
                    break;
                }

                if (elem === this.element) {
                    this.addActiveEventListeners();
                    break;
                }
            }
        }
    }

    @action
    drag(e) {
        e.preventDefault();

        let eventX, eventY;

        if (e.type === 'touchmove') {
            eventX = e.touches[0].clientX;
            eventY = e.touches[0].clientY;
        } else {
            eventX = e.clientX;
            eventY = e.clientY;
        }

        if (!this.active) {
            if (
                Math.abs(Math.abs(this.initialX - eventX) - Math.abs(this.xOffset)) > this.moveThreshold ||
                Math.abs(Math.abs(this.initialY - eventY) - Math.abs(this.yOffset)) > this.moveThreshold
            ) {
                this.disableScroll();
                this.disableSelection();
                this.disablePointerEvents();
                this.active = true;
            }
        }

        if (this.active) {
            this.currentX = eventX - this.initialX;
            this.currentY = eventY - this.initialY;
            this.xOffset = this.currentX;
            this.yOffset = this.currentY;

            this.setTranslate(this.currentX, this.currentY);
        }
    }

    @action
    dragEnd(e) {
        e.preventDefault();
        e.stopPropagation();

        this.active = false;

        this.initialX = this.currentX;
        this.initialY = this.currentY;

        this.removeActiveEventListeners();
        this.enableScroll();
        this.enableSelection();

        // timeout required so immediate events blocked until the dragEnd has fully realised
        setTimeout(() => {
            this.enablePointerEvents();
        }, 5);
    }

    @action
    cancelClick(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    setTranslate(xPos, yPos) {
        this.element.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
    }

    disableScroll() {
        this.originalOverflow = this.element.style.overflow;
        this.element.style.overflow = 'hidden';
    }

    enableScroll() {
        this.element.style.overflow = this.originalOverflow;
    }

    disableSelection() {
        window.getSelection().removeAllRanges();

        const stylesheet = document.createElement('style');
        stylesheet.id = `stylesheet-${guidFor(this)}`;

        document.head.appendChild(stylesheet);

        stylesheet.sheet.insertRule('* { user-select: none !important; }', 0);
    }

    enableSelection() {
        const stylesheet = document.getElementById(`stylesheet-${guidFor(this)}`);
        stylesheet?.remove();
    }

    // disabling pointer events prevents inputs being activated when drag finishes,
    // preventing clicks stops any event handlers that may otherwise result in the
    // movable element being closed when the drag finishes
    disablePointerEvents() {
        this.element.style.pointerEvents = 'none';
        window.addEventListener('click', this.cancelClick, {capture: true, passive: false});
    }

    enablePointerEvents() {
        this.element.style.pointerEvents = '';
        window.removeEventListener('click', this.cancelClick, {capture: true, passive: false});
    }
}
<commit_msg>Fixed card settings panel drag outside of central editor canvas closing panel<commit_after>import Modifier from 'ember-modifier';
import {action} from '@ember/object';
import {guidFor} from '@ember/object/internals';

export default class MovableModifier extends Modifier {
    moveThreshold = 3;

    active = false;
    currentX = undefined;
    currentY = undefined;
    initialX = undefined;
    initialY = undefined;
    xOffset = 0;
    yOffset = 0;

    // Lifecycle hooks ---------------------------------------------------------

    didInstall() {
        this.addStartEventListeners();
    }

    willDestroy() {
        this.removeEventListeners();
        this.enableSelection();
    }

    // Custom methods -----------------------------------------------------------

    addStartEventListeners() {
        this.element.addEventListener('touchstart', this.dragStart, false);
        this.element.addEventListener('mousedown', this.dragStart, false);
    }

    removeStartEventListeners() {
        this.element.removeEventListener('touchstart', this.dragStart, false);
        this.element.removeEventListener('mousedown', this.dragStart, false);
    }

    addActiveEventListeners() {
        window.addEventListener('touchend', this.dragEnd, {capture: true, passive: false});
        window.addEventListener('touchmove', this.drag, {capture: true, passive: false});
        window.addEventListener('mouseup', this.dragEnd, {capture: true, passive: false});
        window.addEventListener('mousemove', this.drag, {capture: true, passive: false});
    }

    removeActiveEventListeners() {
        window.removeEventListener('touchend', this.dragEnd, {capture: true, passive: false});
        window.removeEventListener('touchmove', this.drag, {capture: true, passive: false});
        window.removeEventListener('mouseup', this.dragEnd, {capture: true, passive: false});
        window.removeEventListener('mousemove', this.drag, {capture: true, passive: false});

        // Removing this immediately results in the click event behind re-enabled in the same
        // event loop meaning that it doesn't have the desired effect when dragging out of the canvas.
        // Putting in the next tick stops the immediate click event firing when finishing drag
        setTimeout(() => {
            window.removeEventListener('click', this.cancelClick, {capture: true, passive: false});
        }, 1);
    }

    removeEventListeners() {
        this.removeStartEventListeners();
        this.removeActiveEventListeners();
    }

    @action
    dragStart(e) {
        if (e.type === 'touchstart' || e.button === 0) {
            if (e.type === 'touchstart') {
                this.initialX = e.touches[0].clientX - this.xOffset;
                this.initialY = e.touches[0].clientY - this.yOffset;
            } else {
                this.initialX = e.clientX - this.xOffset;
                this.initialY = e.clientY - this.yOffset;
            }

            for (const elem of (e.path || e.composedPath())) {
                if (elem.matches('input, .ember-basic-dropdown-trigger')) {
                    break;
                }

                if (elem === this.element) {
                    this.addActiveEventListeners();
                    break;
                }
            }
        }
    }

    @action
    drag(e) {
        e.preventDefault();

        let eventX, eventY;

        if (e.type === 'touchmove') {
            eventX = e.touches[0].clientX;
            eventY = e.touches[0].clientY;
        } else {
            eventX = e.clientX;
            eventY = e.clientY;
        }

        if (!this.active) {
            if (
                Math.abs(Math.abs(this.initialX - eventX) - Math.abs(this.xOffset)) > this.moveThreshold ||
                Math.abs(Math.abs(this.initialY - eventY) - Math.abs(this.yOffset)) > this.moveThreshold
            ) {
                this.disableScroll();
                this.disableSelection();
                this.disablePointerEvents();
                this.active = true;
            }
        }

        if (this.active) {
            this.currentX = eventX - this.initialX;
            this.currentY = eventY - this.initialY;
            this.xOffset = this.currentX;
            this.yOffset = this.currentY;

            this.setTranslate(this.currentX, this.currentY);
        }
    }

    @action
    dragEnd(e) {
        e.preventDefault();
        e.stopPropagation();

        this.active = false;

        this.initialX = this.currentX;
        this.initialY = this.currentY;

        this.removeActiveEventListeners();
        this.enableScroll();
        this.enableSelection();

        // timeout required so immediate events blocked until the dragEnd has fully realised
        setTimeout(() => {
            this.enablePointerEvents();
        }, 5);
    }

    @action
    cancelClick(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    setTranslate(xPos, yPos) {
        this.element.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
    }

    disableScroll() {
        this.originalOverflow = this.element.style.overflow;
        this.element.style.overflow = 'hidden';
    }

    enableScroll() {
        this.element.style.overflow = this.originalOverflow;
    }

    disableSelection() {
        window.getSelection().removeAllRanges();

        const stylesheet = document.createElement('style');
        stylesheet.id = `stylesheet-${guidFor(this)}`;

        document.head.appendChild(stylesheet);

        stylesheet.sheet.insertRule('* { user-select: none !important; }', 0);
    }

    enableSelection() {
        const stylesheet = document.getElementById(`stylesheet-${guidFor(this)}`);
        stylesheet?.remove();
    }

    // disabling pointer events prevents inputs being activated when drag finishes,
    // preventing clicks stops any event handlers that may otherwise result in the
    // movable element being closed when the drag finishes
    disablePointerEvents() {
        this.element.style.pointerEvents = 'none';
        window.addEventListener('click', this.cancelClick, {capture: true, passive: false});
    }

    enablePointerEvents() {
        this.element.style.pointerEvents = '';
        window.removeEventListener('click', this.cancelClick, {capture: true, passive: false});
    }
}
<|endoftext|>


<commit_before>import { fatal, logIfDebug, warnIfDebug, warnOnceIfDebug, welcome } from 'utils/log';
import { missingPlugin } from 'config/errors';
import { magic as magicSupported } from 'config/environment';
import { ensureArray } from 'utils/array';
import { findInViewHierarchy } from 'shared/registry';
import arrayAdaptor from 'Ractive/static/adaptors/array/index';
import magicAdaptor from 'Ractive/static/adaptors/magic';
import magicArrayAdaptor from 'Ractive/static/adaptors/magicArray';
import { getElement } from 'utils/dom';
import { create, extend } from 'utils/object';
import runloop from 'global/runloop';
import config from 'Ractive/config/config';
import dataConfigurator from 'Ractive/config/custom/data';
import Fragment from 'virtualdom/Fragment';
import Viewmodel from 'viewmodel/Viewmodel';
import Hook from './prototype/shared/hooks/Hook';
import HookQueue from './prototype/shared/hooks/HookQueue';
import getComputationSignatures from './helpers/getComputationSignatures';
import Ractive from '../Ractive';

let constructHook = new Hook( 'construct' );
let configHook = new Hook( 'config' );
let initHook = new HookQueue( 'init' );
let uid = 0;

let registryNames = [
	'adaptors',
	'components',
	'decorators',
	'easing',
	'events',
	'interpolators',
	'partials',
	'transitions'
];

export default initialiseRactiveInstance;

function initialiseRactiveInstance ( ractive, userOptions = {}, options = {} ) {
	var el, viewmodel;

	if ( Ractive.DEBUG ) {
		welcome();
	}

	initialiseProperties( ractive, options );

	// TODO remove this, eventually
	Object.defineProperty( ractive, 'data', { get: deprecateRactiveData });

	// TODO don't allow `onconstruct` with `new Ractive()`, there's no need for it
	constructHook.fire( ractive, userOptions );

	// Add registries
	registryNames.forEach( name => {
		ractive[ name ] = extend( create( ractive.constructor[ name ] || null ), userOptions[ name ] );
	});

	// Create a viewmodel
	viewmodel = new Viewmodel({
		adapt: getAdaptors( ractive, ractive.adapt, userOptions ),
		data: dataConfigurator.init( ractive.constructor, ractive, userOptions ),
		computed: getComputationSignatures( ractive, extend( create( ractive.constructor.prototype.computed ), userOptions.computed ) ),
		mappings: options.mappings,
		ractive: ractive,
		onchange: () => runloop.addRactive( ractive )
	});

	ractive.viewmodel = viewmodel;

	// This can't happen earlier, because computed properties may call `ractive.get()`, etc
	viewmodel.init();

	// init config from Parent and options
	config.init( ractive.constructor, ractive, userOptions );

	configHook.fire( ractive );
	initHook.begin( ractive );

	// // If this is a component with a function `data` property, call the function
	// // with `ractive` as context (unless the child was also a function)
	// if ( typeof ractive.constructor.prototype.data === 'function' && typeof userOptions.data !== 'function' ) {
	// 	viewmodel.reset( ractive.constructor.prototype.data.call( ractive ) || fatal( '`data` functions must return a data object' ) );
	// }

	// Render virtual DOM
	if ( ractive.template ) {
		let cssIds;

		if ( options.cssIds || ractive.cssId ) {
			cssIds = options.cssIds ? options.cssIds.slice() : [];

			if ( ractive.cssId ) {
				cssIds.push( ractive.cssId );
			}
		}

		ractive.fragment = new Fragment({
			template: ractive.template,
			root: ractive,
			owner: ractive, // saves doing `if ( this.parent ) { /*...*/ }` later on
			cssIds
		});
	}

	initHook.end( ractive );

	// render automatically ( if `el` is specified )
	if ( el = getElement( ractive.el ) ) {
		let promise = ractive.render( el, ractive.append );

		if ( Ractive.DEBUG_PROMISES ) {
			promise.catch( err => {
				warnOnceIfDebug( 'Promise debugging is enabled, to help solve errors that happen asynchronously. Some browsers will log unhandled promise rejections, in which case you can safely disable promise debugging:\n  Ractive.DEBUG_PROMISES = false;' );
				warnIfDebug( 'An error happened during rendering', { ractive });
				err.stack && logIfDebug( err.stack );

				throw err;
			});
		}
	}
}

function getAdaptors ( ractive, protoAdapt, userOptions ) {
	var adapt, magic, modifyArrays;

	protoAdapt = protoAdapt.map( lookup );
	adapt = ensureArray( userOptions.adapt ).map( lookup );

	adapt = combine( protoAdapt, adapt );

	magic = 'magic' in userOptions ? userOptions.magic : ractive.magic;
	modifyArrays = 'modifyArrays' in userOptions ? userOptions.modifyArrays : ractive.modifyArrays;

	if ( magic ) {
		if ( !magicSupported ) {
			throw new Error( 'Getters and setters (magic mode) are not supported in this browser' );
		}

		if ( modifyArrays ) {
			adapt.push( magicArrayAdaptor );
		}

		adapt.push( magicAdaptor );
	}

	if ( modifyArrays ) {
		adapt.push( arrayAdaptor );
	}

	return adapt;

	function lookup ( adaptor ) {
		if ( typeof adaptor === 'string' ) {
			adaptor = findInViewHierarchy( 'adaptors', ractive, adaptor );

			if ( !adaptor ) {
				fatal( missingPlugin( adaptor, 'adaptor' ) );
			}
		}

		return adaptor;
	}
}

function combine ( a, b ) {
	var c = a.slice(), i = b.length;

	while ( i-- ) {
		if ( !~c.indexOf( b[i] ) ) {
			c.push( b[i] );
		}
	}

	return c;
}

function initialiseProperties ( ractive, options ) {
	// Generate a unique identifier, for places where you'd use a weak map if it
	// existed
	ractive._guid = 'r-' + uid++;

	// events
	ractive._subs = create( null );

	// storage for item configuration from instantiation to reset,
	// like dynamic functions or original values
	ractive._config = {};

	// two-way bindings
	ractive._twowayBindings = create( null );

	// animations (so we can stop any in progress at teardown)
	ractive._animations = [];

	// nodes registry
	ractive.nodes = {};

	// live queries
	ractive._liveQueries = [];
	ractive._liveComponentQueries = [];

	// bound data functions
	ractive._boundFunctions = [];

	// properties specific to inline components
	if ( options.component ) {
		ractive.parent = options.parent;
		ractive.container = options.container || null;
		ractive.root = ractive.parent.root;

		ractive.component = options.component;
		options.component.instance = ractive;

		// for hackability, this could be an open option
		// for any ractive instance, but for now, just
		// for components and just for ractive...
		ractive._inlinePartials = options.inlinePartials;
	} else {
		ractive.root = ractive;
		ractive.parent = ractive.container = null;
	}
}

function deprecateRactiveData () {
	throw new Error( 'Using `ractive.data` is no longer supported - you must use the `ractive.get()` API instead' );
}
<commit_msg>use internal defineProperty sham (fails gracefully in IE8)<commit_after>import { fatal, logIfDebug, warnIfDebug, warnOnceIfDebug, welcome } from 'utils/log';
import { missingPlugin } from 'config/errors';
import { magic as magicSupported } from 'config/environment';
import { ensureArray } from 'utils/array';
import { findInViewHierarchy } from 'shared/registry';
import arrayAdaptor from 'Ractive/static/adaptors/array/index';
import magicAdaptor from 'Ractive/static/adaptors/magic';
import magicArrayAdaptor from 'Ractive/static/adaptors/magicArray';
import { getElement } from 'utils/dom';
import { create, defineProperty, extend } from 'utils/object';
import runloop from 'global/runloop';
import config from 'Ractive/config/config';
import dataConfigurator from 'Ractive/config/custom/data';
import Fragment from 'virtualdom/Fragment';
import Viewmodel from 'viewmodel/Viewmodel';
import Hook from './prototype/shared/hooks/Hook';
import HookQueue from './prototype/shared/hooks/HookQueue';
import getComputationSignatures from './helpers/getComputationSignatures';
import Ractive from '../Ractive';

let constructHook = new Hook( 'construct' );
let configHook = new Hook( 'config' );
let initHook = new HookQueue( 'init' );
let uid = 0;

let registryNames = [
	'adaptors',
	'components',
	'decorators',
	'easing',
	'events',
	'interpolators',
	'partials',
	'transitions'
];

export default initialiseRactiveInstance;

function initialiseRactiveInstance ( ractive, userOptions = {}, options = {} ) {
	var el, viewmodel;

	if ( Ractive.DEBUG ) {
		welcome();
	}

	initialiseProperties( ractive, options );

	// TODO remove this, eventually
	defineProperty( ractive, 'data', { get: deprecateRactiveData });

	// TODO don't allow `onconstruct` with `new Ractive()`, there's no need for it
	constructHook.fire( ractive, userOptions );

	// Add registries
	registryNames.forEach( name => {
		ractive[ name ] = extend( create( ractive.constructor[ name ] || null ), userOptions[ name ] );
	});

	// Create a viewmodel
	viewmodel = new Viewmodel({
		adapt: getAdaptors( ractive, ractive.adapt, userOptions ),
		data: dataConfigurator.init( ractive.constructor, ractive, userOptions ),
		computed: getComputationSignatures( ractive, extend( create( ractive.constructor.prototype.computed ), userOptions.computed ) ),
		mappings: options.mappings,
		ractive: ractive,
		onchange: () => runloop.addRactive( ractive )
	});

	ractive.viewmodel = viewmodel;

	// This can't happen earlier, because computed properties may call `ractive.get()`, etc
	viewmodel.init();

	// init config from Parent and options
	config.init( ractive.constructor, ractive, userOptions );

	configHook.fire( ractive );
	initHook.begin( ractive );

	// // If this is a component with a function `data` property, call the function
	// // with `ractive` as context (unless the child was also a function)
	// if ( typeof ractive.constructor.prototype.data === 'function' && typeof userOptions.data !== 'function' ) {
	// 	viewmodel.reset( ractive.constructor.prototype.data.call( ractive ) || fatal( '`data` functions must return a data object' ) );
	// }

	// Render virtual DOM
	if ( ractive.template ) {
		let cssIds;

		if ( options.cssIds || ractive.cssId ) {
			cssIds = options.cssIds ? options.cssIds.slice() : [];

			if ( ractive.cssId ) {
				cssIds.push( ractive.cssId );
			}
		}

		ractive.fragment = new Fragment({
			template: ractive.template,
			root: ractive,
			owner: ractive, // saves doing `if ( this.parent ) { /*...*/ }` later on
			cssIds
		});
	}

	initHook.end( ractive );

	// render automatically ( if `el` is specified )
	if ( el = getElement( ractive.el ) ) {
		let promise = ractive.render( el, ractive.append );

		if ( Ractive.DEBUG_PROMISES ) {
			promise.catch( err => {
				warnOnceIfDebug( 'Promise debugging is enabled, to help solve errors that happen asynchronously. Some browsers will log unhandled promise rejections, in which case you can safely disable promise debugging:\n  Ractive.DEBUG_PROMISES = false;' );
				warnIfDebug( 'An error happened during rendering', { ractive });
				err.stack && logIfDebug( err.stack );

				throw err;
			});
		}
	}
}

function getAdaptors ( ractive, protoAdapt, userOptions ) {
	var adapt, magic, modifyArrays;

	protoAdapt = protoAdapt.map( lookup );
	adapt = ensureArray( userOptions.adapt ).map( lookup );

	adapt = combine( protoAdapt, adapt );

	magic = 'magic' in userOptions ? userOptions.magic : ractive.magic;
	modifyArrays = 'modifyArrays' in userOptions ? userOptions.modifyArrays : ractive.modifyArrays;

	if ( magic ) {
		if ( !magicSupported ) {
			throw new Error( 'Getters and setters (magic mode) are not supported in this browser' );
		}

		if ( modifyArrays ) {
			adapt.push( magicArrayAdaptor );
		}

		adapt.push( magicAdaptor );
	}

	if ( modifyArrays ) {
		adapt.push( arrayAdaptor );
	}

	return adapt;

	function lookup ( adaptor ) {
		if ( typeof adaptor === 'string' ) {
			adaptor = findInViewHierarchy( 'adaptors', ractive, adaptor );

			if ( !adaptor ) {
				fatal( missingPlugin( adaptor, 'adaptor' ) );
			}
		}

		return adaptor;
	}
}

function combine ( a, b ) {
	var c = a.slice(), i = b.length;

	while ( i-- ) {
		if ( !~c.indexOf( b[i] ) ) {
			c.push( b[i] );
		}
	}

	return c;
}

function initialiseProperties ( ractive, options ) {
	// Generate a unique identifier, for places where you'd use a weak map if it
	// existed
	ractive._guid = 'r-' + uid++;

	// events
	ractive._subs = create( null );

	// storage for item configuration from instantiation to reset,
	// like dynamic functions or original values
	ractive._config = {};

	// two-way bindings
	ractive._twowayBindings = create( null );

	// animations (so we can stop any in progress at teardown)
	ractive._animations = [];

	// nodes registry
	ractive.nodes = {};

	// live queries
	ractive._liveQueries = [];
	ractive._liveComponentQueries = [];

	// bound data functions
	ractive._boundFunctions = [];

	// properties specific to inline components
	if ( options.component ) {
		ractive.parent = options.parent;
		ractive.container = options.container || null;
		ractive.root = ractive.parent.root;

		ractive.component = options.component;
		options.component.instance = ractive;

		// for hackability, this could be an open option
		// for any ractive instance, but for now, just
		// for components and just for ractive...
		ractive._inlinePartials = options.inlinePartials;
	} else {
		ractive.root = ractive;
		ractive.parent = ractive.container = null;
	}
}

function deprecateRactiveData () {
	throw new Error( 'Using `ractive.data` is no longer supported - you must use the `ractive.get()` API instead' );
}
<|endoftext|>


<commit_before>/* @flow */

import fastGlob from 'fast-glob'

import Rule from '../Rule'

import type { Command, Phase } from '../types'

export default class FindLogFiles extends Rule {
  static commands: Set<Command> = new Set(['build', 'report'])
  static phases: Set<Phase> = new Set(['initialize'])
  static alwaysEvaluate: boolean = true
  static description: string = 'Find preexisting log files.'

  async run () {
    const filePattern = this.resolvePath('.@(log|*lg)')
    await this.getFiles(await fastGlob(filePattern), { cwd: this.rootPath, bashNative: [] })
    return true
  }
}
<commit_msg>Fix fastGlob call<commit_after>/* @flow */

import fastGlob from 'fast-glob'

import Rule from '../Rule'

import type { Command, Phase } from '../types'

export default class FindLogFiles extends Rule {
  static commands: Set<Command> = new Set(['build', 'report'])
  static phases: Set<Phase> = new Set(['initialize'])
  static alwaysEvaluate: boolean = true
  static description: string = 'Find preexisting log files.'

  async run () {
    const filePattern = this.resolvePath('.@(log|*lg)')
    await this.getFiles(await fastGlob(filePattern, { cwd: this.rootPath, bashNative: [] }))
    return true
  }
}
<|endoftext|>


<commit_before>var ScreenLayer = (function ScreenLayer() {

    var that = {};
    var my   = {};

    that.init = function init(mapName) {

        var screenLayer = new Group();
        screenLayer.y = poipoi.SCREEN.OFFSET_Y;

        // weather
        var user = User.init();
        var defaultWeather = StageManager.getDefaultWeather(user.get('currentDifficulty'), user.get('currentStageIndex'));
        var weatherLayer = WeatherLayer.init(0, -screenLayer.y, defaultWeather);
        screenLayer.addChild(weatherLayer);

		// map
		var map = MapManager.createMap(mapName);
		screenLayer.addChild(map);

        // charactor
        var playerLayer = PlayerLayer.init(map.objectData);
        screenLayer.addChild(playerLayer);

        var enemyLayer = EnemyLayer.init(map.objectData);
        screenLayer.addChild(enemyLayer);

        var goal = Goal.initByObjectData('goal', map.objectData);
        screenLayer.addChild(goal);

        return _.extend(screenLayer, {
            map          : map,
            playerLayer  : playerLayer,
            enemyLayer   : enemyLayer,
            goal         : goal,

            doAction     : _.bind(my.doAction, screenLayer),
            notClear     : _.bind(my.notClear, screenLayer),
            clear        : _.bind(my.clear   , screenLayer),
        });
    };

    my.doAction = function doAction(job) {
        var collision = Collision.init(this);
        var actionList = collision.getActionList(job);
        this.playerLayer.doActionList(actionList);
    };

    my.notClear = function notClear() {
        this.playerLayer.notClear(this.enemyLayer);
    };

    my.clear = function clear() {
        this.playerLayer.clear();
    };

    return that;
}());
<commit_msg>display clear and fail panel in surface<commit_after>var ScreenLayer = (function ScreenLayer() {

    var that = {};
    var my   = {};

    that.init = function init(mapName) {

        var screenLayer = new Group();
        screenLayer.y = poipoi.SCREEN.OFFSET_Y;

        // weather
        var user = User.init();
        var defaultWeather = StageManager.getDefaultWeather(user.get('currentDifficulty'), user.get('currentStageIndex'));
        var weatherLayer = WeatherLayer.init(0, -screenLayer.y, defaultWeather);
        screenLayer.addChild(weatherLayer);

		// map
		var map = MapManager.createMap(mapName);
		screenLayer.addChild(map);

        var goal = Goal.initByObjectData('goal', map.objectData);
        screenLayer.addChild(goal);

        var enemyLayer = EnemyLayer.init(map.objectData);
        screenLayer.addChild(enemyLayer);

        // charactor
        var playerLayer = PlayerLayer.init(map.objectData);
        screenLayer.addChild(playerLayer);

        return _.extend(screenLayer, {
            map          : map,
            playerLayer  : playerLayer,
            enemyLayer   : enemyLayer,
            goal         : goal,

            doAction     : _.bind(my.doAction, screenLayer),
            notClear     : _.bind(my.notClear, screenLayer),
            clear        : _.bind(my.clear   , screenLayer),
        });
    };

    my.doAction = function doAction(job) {
        var collision = Collision.init(this);
        var actionList = collision.getActionList(job);
        this.playerLayer.doActionList(actionList);
    };

    my.notClear = function notClear() {
        this.playerLayer.notClear(this.enemyLayer);
    };

    my.clear = function clear() {
        this.playerLayer.clear();
    };

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


<commit_before>import {get, cloneDeep, isNil, isFunction, isString, isArray, isEqual, isEmpty} from 'lodash';

import {
    InsufficientDataError,
    WrongInterfaceError,
    InvalidParamsError,
    DuplicateError,
} from '../lib/baseErrors';

let isStoreLinked = false;
export function linkStore(globalStore) {
  if (isStoreLinked) {
    throw new DuplicateError('Attempt to link store twice');
  }

  isStoreLinked = true;

  for (const module of modulesList) {
    module.__initializeMdl(globalStore);
  }
}

export function unlinkStore() {
  if (!isStoreLinked) {
    throw new InsufficientDataError("Attempt to unlink not linked store")
  }

  isStoreLinked = false;

  for (const module of modulesList) {
    module.deinitialize();
  }
}

export class RMCCtl {
    constructor() {
        if (!isFunction(this._stateDidUpdate)) {
            throw new WrongInterfaceError('A controller must have `_stateDidUpdate` method');
        }
    }

    __initializeCtl(store, path) {
        this.__storeCtl = store;
        this.__pathCtl = path;
        this.ownState = this.__getOwnStateCtl();

        this.__unsubscribeStoreCtl = this.__storeCtl.subscribe(() => {
            const state = this.__storeCtl.getState();

            this.__stateUpdateListenerCtl(state);
        });
    }

    __deinitializeCtl() {
        this.__unsubscribeStoreCtl();
    }

    __getOwnStateCtl(outerState = this.__storeCtl.getState()) {
        return get(outerState, this.__pathCtl);
    }

    __stateUpdateListenerCtl = (nextOuterState) => {
        const prevOwnState = this.ownState;

        this.ownState = this.__getOwnStateCtl(nextOuterState);

        if (!isEqual(this.ownState, prevOwnState)) {
            this._stateDidUpdate(cloneDeep(prevOwnState));
        }
    };

    dispatch(action) {
        this.__storeCtl.dispatch(action);
    }
}

const deprecatedMethodsForCtl = [
  '__validateControllerMdl',
  '__initializeMdl',
  '__pathMdl',
  '__reducerMdl',
  '__controllerMdl',
];
const warnMethodsForCtl = [
  'deinitialize',
  'integrator',
];
class Module {
    constructor(reducer, CtlClass) {
        if (!isFunction(reducer)) {
          const msg = 'Attempt to create a module, but reducer is not a function';

          throw new InvalidParamsError(msg);
        }

        if (!(CtlClass.prototype instanceof RMCCtl)) {
          const msg = `Attempt to create a module with a wrong ctl class "${CtlClass.name}"`;

          throw new InvalidParamsError(msg);
        }

        this.__pathMdl = undefined;
        this.__reducerMdl = reducer;
        this.__controllerMdl = new CtlClass();

        this.__validateControllerMdl(this.__controllerMdl);
    }

    __validateControllerMdl(ctl) {
      let ctlName = Object.getPrototypeOf(ctl).constructor.name;

      for (const methodName of deprecatedMethodsForCtl) {
        if (methodName in ctl) {
          const msg = `A "${ctlName}" contains a deprecated for a controller method/property "${methodName}"`;

          throw new DuplicateError(msg);
        }
      }

      for (const methodName of warnMethodsForCtl) {
        if (methodName in ctl) {
          const msg = `A "${ctlName}" contains a method/property "${methodName}" that exists in the module. You will not have access to the controllers method.`;

          console.warn(msg);
        }
      }
    }

    __initializeMdl(store) {
      this.__controllerMdl.__initializeCtl(store, this.__pathMdl);
    }

    deinitialize() {
        this.__controllerMdl.__deinitializeCtl();
    }

    integrator(path) {
        if (
            (!isString(path) || path === '') &&
            (!isArray(path) || isEmpty(path) || path.some(pathPart => !isString(pathPart)))
        ) {
            throw new InvalidParamsError(`Attempt to integrate bad path: "${path}"`);
        }

        if (!isNil(this.__pathMdl) && !isEqual(this.__pathMdl, path)) {
            const msg = `Attempt to change a path of integration: "${this.__pathMdl}" -> "${path}"`;

            throw new InvalidParamsError(msg);
        }

        this.__pathMdl = path;

        return this.__reducerMdl;
    };
}

const modulesList = [];

export function createModule(reducer, Controller) {
  const module = new Module(reducer, Controller);

  modulesList.push(module);

  return new Proxy(module, {
    get(target, propName) {
      const isProtected = propName[0] === '_';
      const isPrivate = isProtected && propName[1] === '_';

      if (isPrivate && propName in target) {
        return target[propName];
      }

      if (!isProtected && propName in target) {
        return target[propName];
      }

      return target.__controllerMdl[propName];
    }
  });
}
<commit_msg>Optimize integrator a little.<commit_after>import {get, cloneDeep, isNil, isFunction, isString, isArray, isEqual, isEmpty} from 'lodash';

import {
    InsufficientDataError,
    WrongInterfaceError,
    InvalidParamsError,
    DuplicateError,
} from '../lib/baseErrors';

let isStoreLinked = false;
export function linkStore(globalStore) {
  if (isStoreLinked) {
    throw new DuplicateError('Attempt to link store twice');
  }

  isStoreLinked = true;

  for (const module of modulesList) {
    module.__initializeMdl(globalStore);
  }
}

export function unlinkStore() {
  if (!isStoreLinked) {
    throw new InsufficientDataError("Attempt to unlink not linked store")
  }

  isStoreLinked = false;

  for (const module of modulesList) {
    module.deinitialize();
  }
}

export class RMCCtl {
    constructor() {
        if (!isFunction(this._stateDidUpdate)) {
            throw new WrongInterfaceError('A controller must have `_stateDidUpdate` method');
        }
    }

    __initializeCtl(store, path) {
        this.__storeCtl = store;
        this.__pathCtl = path;
        this.ownState = this.__getOwnStateCtl();

        this.__unsubscribeStoreCtl = this.__storeCtl.subscribe(() => {
            const state = this.__storeCtl.getState();

            this.__stateUpdateListenerCtl(state);
        });
    }

    __deinitializeCtl() {
        this.__unsubscribeStoreCtl();
    }

    __getOwnStateCtl(outerState = this.__storeCtl.getState()) {
        return get(outerState, this.__pathCtl);
    }

    __stateUpdateListenerCtl = (nextOuterState) => {
        const prevOwnState = this.ownState;

        this.ownState = this.__getOwnStateCtl(nextOuterState);

        if (!isEqual(this.ownState, prevOwnState)) {
            this._stateDidUpdate(cloneDeep(prevOwnState));
        }
    };

    dispatch(action) {
        this.__storeCtl.dispatch(action);
    }
}

const deprecatedMethodsForCtl = [
  '__validateControllerMdl',
  '__initializeMdl',
  '__pathMdl',
  '__reducerMdl',
  '__controllerMdl',
];
const warnMethodsForCtl = [
  'deinitialize',
  'integrator',
];
class Module {
    constructor(reducer, CtlClass) {
        if (!isFunction(reducer)) {
          const msg = 'Attempt to create a module, but reducer is not a function';

          throw new InvalidParamsError(msg);
        }

        if (!(CtlClass.prototype instanceof RMCCtl)) {
          const msg = `Attempt to create a module with a wrong ctl class "${CtlClass.name}"`;

          throw new InvalidParamsError(msg);
        }

        this.__pathMdl = undefined;
        this.__reducerMdl = reducer;
        this.__controllerMdl = new CtlClass();

        this.__validateControllerMdl(this.__controllerMdl);
    }

    __validateControllerMdl(ctl) {
      let ctlName = Object.getPrototypeOf(ctl).constructor.name;

      for (const methodName of deprecatedMethodsForCtl) {
        if (methodName in ctl) {
          const msg = `A "${ctlName}" contains a deprecated for a controller method/property "${methodName}"`;

          throw new DuplicateError(msg);
        }
      }

      for (const methodName of warnMethodsForCtl) {
        if (methodName in ctl) {
          const msg = `A "${ctlName}" contains a method/property "${methodName}" that exists in the module. You will not have access to the controllers method.`;

          console.warn(msg);
        }
      }
    }

    __initializeMdl(store) {
      this.__controllerMdl.__initializeCtl(store, this.__pathMdl);
    }

    deinitialize() {
        this.__controllerMdl.__deinitializeCtl();
    }

    integrator(path) {
        const prevPath = this.__pathMdl;

        if (isNil(prevPath)) {
          if (
            (!isString(path) || path === '') &&
            (!isArray(path) || isEmpty(path) || path.some(pathPart => !isString(pathPart)))
          ) {
            throw new InvalidParamsError(`Attempt to integrate bad path: "${path}"`);
          }

          this.__pathMdl = path;
        } else if (!isEqual(prevPath, path)) {
          const msg = `Attempt to change a path of integration: "${prevPath}" -> "${path}"`;

          throw new InvalidParamsError(msg);
        }

        return this.__reducerMdl;
    };
}

const modulesList = [];

export function createModule(reducer, Controller) {
  const module = new Module(reducer, Controller);

  modulesList.push(module);

  return new Proxy(module, {
    get(target, propName) {
      const isProtected = propName[0] === '_';
      const isPrivate = isProtected && propName[1] === '_';

      if (isPrivate && propName in target) {
        return target[propName];
      }

      if (!isProtected && propName in target) {
        return target[propName];
      }

      return target.__controllerMdl[propName];
    }
  });
}
<|endoftext|>


<commit_before>define([
  'jquery',
  'backbone',
  'underscore',
  'models/event',
  'models/client',
  'collections/events',
  'text!templates/events.tmpl',
  'views/events/list_table',
  'views/events/list_counts',
  'views/events/details',
], function($,
            Backbone,
            _,
            EventModel,
            ClientModel,
            EventsCollection,
            template,
            ListTableView,
            ListCountsView,
            DetailsView) {
  var View = Backbone.View.extend({
    template: _.template(template),
    el: '#main',
    events: {
      'click #toggle-checkboxes': 'toggleSelected',
      'click #select-all': 'selectAll',
      'click #select-none': 'selectNone',
      'click #select-critical': 'selectCritical',
      'click #select-unknown': 'selectUnknown',
      'click #select-warning': 'selectWarning',
      'click #resolve-selected': 'resolveSelected',
      'click #silence-selected': 'silenceSelected',
      'click #unsilence-selected': 'unsilenceSelected',
      'click tr': 'showDetails',
    },
    initialize: function() {
      this.collection = new EventsCollection();
      this.collection.bind('reset', this.renderSubViews, this);
      this.collection.fetch({
        success: function(collection, response) {
        },
        error: function(collection, response) {
          alert('Unable to fetch events from the Sensu API.\n'
            + 'Error ' + response['status'] + ': '
            + response['statusText']);
        }
      });
    },
    render: function() {
      $(this.el).html(this.template);
      this.renderSubViews();
      this.detailView = new DetailsView({eventModel: new EventModel(), clientModel: new ClientModel()});
      return this;
    },
    renderSubViews: function() {
      // TODO: this is currently being called twice on page load; although
      // there does not seem to be a performance hit, we should look into
      // a method to load it only once
      console.log('rendering subviews');
      var eventsView = new ListTableView({
        collection: this.collection
      });

      var countsView = new ListCountsView({
        collection: this.collection
      });

      eventsView.render();
      countsView.render();
    },
    toggleSelected: function() {
      this.collection.toggleSelected();
    },
    selectAll: function() {
      this.collection.selectAll();
    },
    selectNone: function() {
      this.collection.selectNone();
    },
    selectCritical: function () {
      this.collection.selectCritical();
    },
    selectUnknown: function() {
      this.collection.selectUnknown();
    },
    selectWarning: function() {
      this.collection.selectWarning();
    },
    resolveSelected: function() {
      this.collection.resolveSelected();
    },
    silenceSelected: function() {
      this.collection.silenceSelected();
    },
    unsilenceSelected: function() {
      this.collection.unsilenceSelected();
    },
    showDetails: function(e) {
      e.preventDefault();
      var id = $(e.currentTarget).data('id');
      this.detailView.options.eventModel = this.collection.getByCid(id);
      this.detailView.options.clientModel.set({id: this.detailView.options.eventModel.get('client')});

      this.detailView.options.clientModel.fetch({
        success: function(user) {
          console.log(user.toJSON());
        }
      });
      this.detailView.render();
      $('#event_modal').modal();
    },
  });

  return new View;
});
<commit_msg>alert user if unable to fetch client data<commit_after>define([
  'jquery',
  'backbone',
  'underscore',
  'models/event',
  'models/client',
  'collections/events',
  'text!templates/events.tmpl',
  'views/events/list_table',
  'views/events/list_counts',
  'views/events/details',
], function($,
            Backbone,
            _,
            EventModel,
            ClientModel,
            EventsCollection,
            template,
            ListTableView,
            ListCountsView,
            DetailsView) {
  var View = Backbone.View.extend({
    template: _.template(template),
    el: '#main',
    events: {
      'click #toggle-checkboxes': 'toggleSelected',
      'click #select-all': 'selectAll',
      'click #select-none': 'selectNone',
      'click #select-critical': 'selectCritical',
      'click #select-unknown': 'selectUnknown',
      'click #select-warning': 'selectWarning',
      'click #resolve-selected': 'resolveSelected',
      'click #silence-selected': 'silenceSelected',
      'click #unsilence-selected': 'unsilenceSelected',
      'click tr': 'showDetails',
    },
    initialize: function() {
      this.collection = new EventsCollection();
      this.collection.bind('reset', this.renderSubViews, this);
      this.collection.fetch({
        success: function(collection, response) {
        },
        error: function(collection, response) {
          alert('Unable to fetch events from the Sensu API.\n'
            + 'Error ' + response['status'] + ': '
            + response['statusText']);
        }
      });
    },
    render: function() {
      $(this.el).html(this.template);
      this.renderSubViews();
      this.detailView = new DetailsView({eventModel: new EventModel(), clientModel: new ClientModel()});
      return this;
    },
    renderSubViews: function() {
      // TODO: this is currently being called twice on page load; although
      // there does not seem to be a performance hit, we should look into
      // a method to load it only once
      console.log('rendering subviews');
      var eventsView = new ListTableView({
        collection: this.collection
      });

      var countsView = new ListCountsView({
        collection: this.collection
      });

      eventsView.render();
      countsView.render();
    },
    toggleSelected: function() {
      this.collection.toggleSelected();
    },
    selectAll: function() {
      this.collection.selectAll();
    },
    selectNone: function() {
      this.collection.selectNone();
    },
    selectCritical: function () {
      this.collection.selectCritical();
    },
    selectUnknown: function() {
      this.collection.selectUnknown();
    },
    selectWarning: function() {
      this.collection.selectWarning();
    },
    resolveSelected: function() {
      this.collection.resolveSelected();
    },
    silenceSelected: function() {
      this.collection.silenceSelected();
    },
    unsilenceSelected: function() {
      this.collection.unsilenceSelected();
    },
    showDetails: function(e) {
      e.preventDefault();
      var id = $(e.currentTarget).data('id');
      this.detailView.options.eventModel = this.collection.getByCid(id);
      this.detailView.options.clientModel.set({id: this.detailView.options.eventModel.get('client')});

      this.detailView.options.clientModel.fetch({
        success: function(user, response) {
          console.log(user.toJSON());
        },
        error: function(user, response) {
          alert('Unable to fetch client from the Sensu API.\n'
            + 'Error ' + response['status'] + ': '
            + response['statusText']);
        }
      });
      this.detailView.render();
      $('#event_modal').modal();
    },
  });

  return new View;
});
<|endoftext|>