<commit_before>const Cookies          = require('js-cookie');
const moment           = require('moment');
const ClientBase       = require('./client_base');
const Login            = require('./login');
const ServerTime       = require('./server_time');
const BinarySocket     = require('./socket_base');
const getElementById   = require('../common_functions').getElementById;
const isVisible        = require('../common_functions').isVisible;
const getLanguage      = require('../language').get;
const State            = require('../storage').State;
const getPropertyValue = require('../utility').getPropertyValue;
const getAppId         = require('../../config').getAppId;

const GTM = (() => {
    const isGtmApplicable = () => (/^(1|1098|14473|15284|15760)$/.test(getAppId()));

    const getCommonVariables = () => ({
        language : getLanguage(),
        pageTitle: pageTitle(),
        pjax     : State.get('is_loaded_by_pjax'),
        url      : document.URL,
        ...ClientBase.isLoggedIn() && {
            visitorId: ClientBase.get('loginid'),
            bom_email: ClientBase.get('email'),
        },
    });

    const pushDataLayer = (data) => {
        if (isGtmApplicable() && !Login.isLoginPages()) {
            dataLayer.push({
                ...getCommonVariables(),
                ...data,
            });
        }
    };

    const pageTitle = () => {
        const t = /^.+[:-]\s*(.+)$/.exec(document.title);
        return t && t[1] ? t[1] : document.title;
    };

    const eventHandler = (get_settings) => {
        if (!isGtmApplicable()) return;
        const login_event       = localStorage.getItem('GTM_login');
        const is_new_account    = localStorage.getItem('GTM_new_account') === '1';

        localStorage.removeItem('GTM_login');
        localStorage.removeItem('GTM_new_account');

        const affiliate_token = Cookies.getJSON('affiliate_tracking');
        if (affiliate_token) {
            pushDataLayer({ bom_affiliate_token: affiliate_token.t });
        }

        // Get current time (moment, set by server), else fallback to client time
        const moment_now = window.time || moment().utc();
        const data = {
            visitorId         : ClientBase.get('loginid'),
            bom_account_type  : ClientBase.getAccountType(),
            bom_currency      : ClientBase.get('currency'),
            bom_country       : get_settings.country,
            bom_country_abbrev: get_settings.country_code,
            bom_email         : get_settings.email,
            url               : window.location.href,
            bom_today         : moment_now.unix(),
        };

        if (is_new_account) {
            data.event = 'new_account';
            data.bom_date_joined = data.bom_today;
        }

        if (!ClientBase.get('is_virtual')) {
            data.bom_age       = moment_now.diff(moment.unix(get_settings.date_of_birth).utc(), 'year');
            data.bom_firstname = get_settings.first_name;
            data.bom_lastname  = get_settings.last_name;
            data.bom_phone     = get_settings.phone;
        }

        if (login_event) {
            data.event = login_event;
            BinarySocket.wait('mt5_login_list').then((response) => {
                (response.mt5_login_list || []).forEach((obj) => {
                    const acc_type = (ClientBase.getMT5AccountType(obj.group) || '')
                        .replace('real_vanuatu', 'financial').replace('vanuatu_', '').replace('costarica', 'gaming'); // i.e. financial_cent, demo_cent, demo_gaming, real_gaming
                    if (acc_type) {
                        data[`mt5_${acc_type}_id`] = obj.login;
                    }
                });
                pushDataLayer(data);
            });
        } else {
            pushDataLayer(data);
        }

        // check if there are any transactions in the last 30 days for UX interview selection
        BinarySocket.send({ statement: 1, limit: 1 }).then((response) => {
            const last_transaction_timestamp = getPropertyValue(response, ['statement', 'transactions', '0', 'transaction_time']);
            pushDataLayer({
                bom_transaction_in_last_30d: !!last_transaction_timestamp && moment(last_transaction_timestamp * 1000).isAfter(ServerTime.get().subtract(30, 'days')),
            });
        });
    };

    const pushPurchaseData = (response) => {
        if (!isGtmApplicable() || ClientBase.get('is_virtual')) return;
        const buy = response.buy;
        if (!buy) return;
        const req  = response.echo_req.passthrough;
        const data = {
            event             : 'buy_contract',
            bom_ui            : 'legacy',
            bom_symbol        : req.symbol,
            bom_market        : getElementById('contract_markets').value,
            bom_currency      : req.currency,
            bom_contract_type : req.contract_type,
            bom_contract_id   : buy.contract_id,
            bom_transaction_id: buy.transaction_id,
            bom_buy_price     : buy.buy_price,
            bom_payout        : buy.payout,
        };
        Object.assign(data, {
            bom_amount     : req.amount,
            bom_basis      : req.basis,
            bom_expiry_type: getElementById('expiry_type').value,
        });
        if (data.bom_expiry_type === 'duration') {
            Object.assign(data, {
                bom_duration     : req.duration,
                bom_duration_unit: req.duration_unit,
            });
        }
        if (isVisible(getElementById('barrier'))) {
            data.bom_barrier = req.barrier;
        } else if (isVisible(getElementById('barrier_high'))) {
            data.bom_barrier_high = req.barrier;
            data.bom_barrier_low  = req.barrier2;
        }
        if (isVisible(getElementById('prediction'))) {
            data.bom_prediction = req.barrier;
        }

        pushDataLayer(data);
    };

    const mt5NewAccount = (response) => {
        const acc_type = response.mt5_new_account.mt5_account_type ?
            `${response.mt5_new_account.account_type}_${response.mt5_new_account.mt5_account_type}` : // financial_cent, demo_cent, ...
            `${response.mt5_new_account.account_type === 'demo' ? 'demo' : 'real'}_gaming`;           // demo_gaming, real_gaming

        const gtm_data = {
            event          : 'mt5_new_account',
            bom_email      : ClientBase.get('email'),
            bom_country    : State.getResponse('get_settings.country'),
            mt5_last_signup: acc_type,
        };

        gtm_data[`mt5_${acc_type}_id`] = response.mt5_new_account.login;

        if (/demo/.test(acc_type) && !ClientBase.get('is_virtual')) {
            gtm_data.visitorId = ClientBase.getAccountOfType('virtual').loginid;
        }

        pushDataLayer(gtm_data);
    };

    // Pushes deposit & withdrawal data from transaction-stream to GTM
    const pushTransactionData = (response, extra_data = {}) => {
        if (!isGtmApplicable() || ClientBase.get('is_virtual')) return;
        if (!response.transaction || !response.transaction.action) return;
        if (!['deposit', 'withdrawal'].includes(response.transaction.action)) return;

        const moment_now  = window.time || moment().utc();
        const storage_key = 'GTM_transactions';

        // Remove values from prev days so localStorage doesn't grow to infinity
        let gtm_transactions  = JSON.parse(localStorage.getItem(storage_key)) || {};
        if (Object.prototype.hasOwnProperty.call(gtm_transactions, 'timestamp')) {
            if (moment_now.isAfter(moment.utc().unix(gtm_transactions.timestamp), 'day')) {
                localStorage.removeItem(storage_key);
                gtm_transactions = { timestamp: moment_now.unix() };
            }
        }
        const transactions_arr = gtm_transactions.transactions || [];
        if (!transactions_arr.includes(response.transaction.transaction_id)) {
            const data = {
                event           : 'transaction',
                bom_account_type: ClientBase.getAccountType(),
                bom_today       : moment_now.unix(),
                transaction     : {
                    id      : response.transaction.transaction_id,
                    type    : response.transaction.action,
                    time    : response.transaction.transaction_time,
                    amount  : response.transaction.amount,
                    balance : response.transaction.balance,
                },
            };
            Object.assign(data, extra_data);
            pushDataLayer(data);

            transactions_arr.push(response.transaction.transaction_id);
            gtm_transactions.transactions = transactions_arr;
            gtm_transactions.timestamp    = gtm_transactions.timestamp || moment_now.unix();

            localStorage.setItem(storage_key, JSON.stringify(gtm_transactions));
        }
    };

    return {
        pushDataLayer,
        eventHandler,
        pushPurchaseData,
        pushTransactionData,
        mt5NewAccount,
        setLoginFlag: (event_name) => { if (isGtmApplicable()) localStorage.setItem('GTM_login', event_name); },
    };
})();

module.exports = GTM;
<commit_msg>Revert changes in 4d3d03f4863b5acaa3bce54704451df51356c0ba<commit_after>const Cookies          = require('js-cookie');
const moment           = require('moment');
const ClientBase       = require('./client_base');
const Login            = require('./login');
const ServerTime       = require('./server_time');
const BinarySocket     = require('./socket_base');
const getElementById   = require('../common_functions').getElementById;
const isVisible        = require('../common_functions').isVisible;
const getLanguage      = require('../language').get;
const State            = require('../storage').State;
const getPropertyValue = require('../utility').getPropertyValue;
const getAppId         = require('../../config').getAppId;

const GTM = (() => {
    const isGtmApplicable = () => (/^(1|1098|14473|15284)$/.test(getAppId()));

    const getCommonVariables = () => ({
        language : getLanguage(),
        pageTitle: pageTitle(),
        pjax     : State.get('is_loaded_by_pjax'),
        url      : document.URL,
        ...ClientBase.isLoggedIn() && {
            visitorId: ClientBase.get('loginid'),
            bom_email: ClientBase.get('email'),
        },
    });

    const pushDataLayer = (data) => {
        if (isGtmApplicable() && !Login.isLoginPages()) {
            dataLayer.push({
                ...getCommonVariables(),
                ...data,
            });
        }
    };

    const pageTitle = () => {
        const t = /^.+[:-]\s*(.+)$/.exec(document.title);
        return t && t[1] ? t[1] : document.title;
    };

    const eventHandler = (get_settings) => {
        if (!isGtmApplicable()) return;
        const login_event       = localStorage.getItem('GTM_login');
        const is_new_account    = localStorage.getItem('GTM_new_account') === '1';

        localStorage.removeItem('GTM_login');
        localStorage.removeItem('GTM_new_account');

        const affiliate_token = Cookies.getJSON('affiliate_tracking');
        if (affiliate_token) {
            pushDataLayer({ bom_affiliate_token: affiliate_token.t });
        }

        // Get current time (moment, set by server), else fallback to client time
        const moment_now = window.time || moment().utc();
        const data = {
            visitorId         : ClientBase.get('loginid'),
            bom_account_type  : ClientBase.getAccountType(),
            bom_currency      : ClientBase.get('currency'),
            bom_country       : get_settings.country,
            bom_country_abbrev: get_settings.country_code,
            bom_email         : get_settings.email,
            url               : window.location.href,
            bom_today         : moment_now.unix(),
        };

        if (is_new_account) {
            data.event = 'new_account';
            data.bom_date_joined = data.bom_today;
        }

        if (!ClientBase.get('is_virtual')) {
            data.bom_age       = moment_now.diff(moment.unix(get_settings.date_of_birth).utc(), 'year');
            data.bom_firstname = get_settings.first_name;
            data.bom_lastname  = get_settings.last_name;
            data.bom_phone     = get_settings.phone;
        }

        if (login_event) {
            data.event = login_event;
            BinarySocket.wait('mt5_login_list').then((response) => {
                (response.mt5_login_list || []).forEach((obj) => {
                    const acc_type = (ClientBase.getMT5AccountType(obj.group) || '')
                        .replace('real_vanuatu', 'financial').replace('vanuatu_', '').replace('costarica', 'gaming'); // i.e. financial_cent, demo_cent, demo_gaming, real_gaming
                    if (acc_type) {
                        data[`mt5_${acc_type}_id`] = obj.login;
                    }
                });
                pushDataLayer(data);
            });
        } else {
            pushDataLayer(data);
        }

        // check if there are any transactions in the last 30 days for UX interview selection
        BinarySocket.send({ statement: 1, limit: 1 }).then((response) => {
            const last_transaction_timestamp = getPropertyValue(response, ['statement', 'transactions', '0', 'transaction_time']);
            pushDataLayer({
                bom_transaction_in_last_30d: !!last_transaction_timestamp && moment(last_transaction_timestamp * 1000).isAfter(ServerTime.get().subtract(30, 'days')),
            });
        });
    };

    const pushPurchaseData = (response) => {
        if (!isGtmApplicable() || ClientBase.get('is_virtual')) return;
        const buy = response.buy;
        if (!buy) return;
        const req  = response.echo_req.passthrough;
        const data = {
            event             : 'buy_contract',
            bom_ui            : 'legacy',
            bom_symbol        : req.symbol,
            bom_market        : getElementById('contract_markets').value,
            bom_currency      : req.currency,
            bom_contract_type : req.contract_type,
            bom_contract_id   : buy.contract_id,
            bom_transaction_id: buy.transaction_id,
            bom_buy_price     : buy.buy_price,
            bom_payout        : buy.payout,
        };
        Object.assign(data, {
            bom_amount     : req.amount,
            bom_basis      : req.basis,
            bom_expiry_type: getElementById('expiry_type').value,
        });
        if (data.bom_expiry_type === 'duration') {
            Object.assign(data, {
                bom_duration     : req.duration,
                bom_duration_unit: req.duration_unit,
            });
        }
        if (isVisible(getElementById('barrier'))) {
            data.bom_barrier = req.barrier;
        } else if (isVisible(getElementById('barrier_high'))) {
            data.bom_barrier_high = req.barrier;
            data.bom_barrier_low  = req.barrier2;
        }
        if (isVisible(getElementById('prediction'))) {
            data.bom_prediction = req.barrier;
        }

        pushDataLayer(data);
    };

    const mt5NewAccount = (response) => {
        const acc_type = response.mt5_new_account.mt5_account_type ?
            `${response.mt5_new_account.account_type}_${response.mt5_new_account.mt5_account_type}` : // financial_cent, demo_cent, ...
            `${response.mt5_new_account.account_type === 'demo' ? 'demo' : 'real'}_gaming`;           // demo_gaming, real_gaming

        const gtm_data = {
            event          : 'mt5_new_account',
            bom_email      : ClientBase.get('email'),
            bom_country    : State.getResponse('get_settings.country'),
            mt5_last_signup: acc_type,
        };

        gtm_data[`mt5_${acc_type}_id`] = response.mt5_new_account.login;

        if (/demo/.test(acc_type) && !ClientBase.get('is_virtual')) {
            gtm_data.visitorId = ClientBase.getAccountOfType('virtual').loginid;
        }

        pushDataLayer(gtm_data);
    };

    // Pushes deposit & withdrawal data from transaction-stream to GTM
    const pushTransactionData = (response, extra_data = {}) => {
        if (!isGtmApplicable() || ClientBase.get('is_virtual')) return;
        if (!response.transaction || !response.transaction.action) return;
        if (!['deposit', 'withdrawal'].includes(response.transaction.action)) return;

        const moment_now  = window.time || moment().utc();
        const storage_key = 'GTM_transactions';

        // Remove values from prev days so localStorage doesn't grow to infinity
        let gtm_transactions  = JSON.parse(localStorage.getItem(storage_key)) || {};
        if (Object.prototype.hasOwnProperty.call(gtm_transactions, 'timestamp')) {
            if (moment_now.isAfter(moment.utc().unix(gtm_transactions.timestamp), 'day')) {
                localStorage.removeItem(storage_key);
                gtm_transactions = { timestamp: moment_now.unix() };
            }
        }
        const transactions_arr = gtm_transactions.transactions || [];
        if (!transactions_arr.includes(response.transaction.transaction_id)) {
            const data = {
                event           : 'transaction',
                bom_account_type: ClientBase.getAccountType(),
                bom_today       : moment_now.unix(),
                transaction     : {
                    id      : response.transaction.transaction_id,
                    type    : response.transaction.action,
                    time    : response.transaction.transaction_time,
                    amount  : response.transaction.amount,
                    balance : response.transaction.balance,
                },
            };
            Object.assign(data, extra_data);
            pushDataLayer(data);

            transactions_arr.push(response.transaction.transaction_id);
            gtm_transactions.transactions = transactions_arr;
            gtm_transactions.timestamp    = gtm_transactions.timestamp || moment_now.unix();

            localStorage.setItem(storage_key, JSON.stringify(gtm_transactions));
        }
    };

    return {
        pushDataLayer,
        eventHandler,
        pushPurchaseData,
        pushTransactionData,
        mt5NewAccount,
        setLoginFlag: (event_name) => { if (isGtmApplicable()) localStorage.setItem('GTM_login', event_name); },
    };
})();

module.exports = GTM;
<|endoftext|>


<commit_before>;(function(window) {
  'use strict';

  var angular = window.angular;

  angular
    .module('tuchong-daily')
    .controller('home', [
      '$scope',
      'Store',
      '$ionicLoading',
      '$timeout',
      'imageLoader',
      'share',
      '$ionicModal',
      '$rootScope',
      '$cordovaDialogs',
      home
    ]);

  function home(scope, Store, $ionicLoading, $timeout, imageLoader, share, $ionicModal, $rootScope, $cordovaDialogs) {
    // When Push Received,
    // Render this notified post as first post.
    $rootScope.$on('pushNotificationReceived', pushNotificationReceived);

    scope.share = share.popup;
    scope.makeCssUri = makeCssUri;
    scope.openZoom = openZoom;
    scope.hideZoom = hideZoom;

    var slides = null;
    var childrenSlides = {};

    var backgrounds = scope.backgrounds = [];
    var childrens = scope.childrens = {};

    // Show loading
    $ionicLoading.show();

    // Read local cache from localStorage
    if (Store.cache.collections)
      return setup(Store.cache.collections);

    // Open a request
    fetch();

    // Fetch fresh data from API server
    function fetch(id) {
      var query = {};

      if (id)
        query.postId = id;

      Store[id ? 'post' : 'hot'].get(query, success, fail);

      function success(data) {
        if (id) {
          data.postId = id;
          return setup([data]);
        }

        if (!data.collections)
          return fail();

        // Setup a few slides
        setup(data.collections);

        // Save all data to cache
        Store.save('collections', data);
      }

      function fail(err) {
        $ionicLoading.show({
          template: ' 网络连接失败...请稍后再试'
        });
        return false;
      }
    }

    // Setup slides view
    function setup(data) {
      var rendered = scope.collections && scope.collections.length > 0;

      scope.collections = rendered ?
        scope.collections.concat(data) :
        data;

      // Show befor init slides
      if (!scope.slidesReady)
        scope.slidesReady = true;

      // Hide loading
      $ionicLoading.hide();

      var targetIndex = rendered && data.length === 1 ?
        findIndex(data[0].postId, scope.collections) :
        0;

      // Load cover image
      loadCover(targetIndex, {
        setupChildrenSwiper: true
      });

      if (targetIndex === 0)
        loadCover(1);

      // Init the slides on next tick
      $timeout(function() {
        // When Push Received
        if (rendered && slides) {
          slides.updateSlidesSize();

          if (targetIndex !== 0)
            slides.slideTo(targetIndex);

          return;
        }

        slides = new Swiper('.swiper-container-collection', {
          onSlideChangeStart: function() {
            loadCover(slides.activeIndex + 1, {
              setupChildrenSwiper: true,
              loadFirstChild: true
            });
          }
        });
      }, 10);
    }

    // Lazy loading the cover image of a slide
    function loadCover(index, opts) {
      // If this collection have on one picture
      if (scope.collections[index].images.length === 1)
        return loadImage(index);

      loadChildImage(index, 0);

      // Load its first child if required
      if (opts && opts.loadFirstChild)
        loadChildImage(index, 1);

      if (!opts || !opts.setupChildrenSwiper)
        return;

      if ('undefined' !== typeof(childrenSlides[index]))
        return;

      // Then setup its children slides
      $timeout(function() {
        setupChildrenSwiper(index);
      }, 10);
    }

    function findIndex(id, arr) {
      var target;
      angular.forEach(arr, function(item, index){
        if (item.postId === id)
          target = index;
      });
      return target;
    }

    function setupChildrenSwiper(index) {
      childrenSlides[index] = new Swiper('#children-' + index, {
        direction: 'vertical',
        onSlideChangeStart: function() {
          loadChildImage(index, childrenSlides[index].activeIndex);
          loadChildImage(index, childrenSlides[index].activeIndex + 1);
        }
      });
    }

    // Update slides async
    function loadImage(index) {
      if (backgrounds[index])
        return scope.$apply();

      if (!scope.collections[index])
        return;

      imageLoader.load(
        scope.collections[index].images[0].uri + '.jpg',
        function(localImage) {
          scope.backgrounds[index] = localImage;
          scope.$apply();
        }
      );
    }

    function loadChildImage(parentIndex, index) {
      if (Array.isArray(scope.childrens[parentIndex]) && scope.childrens[parentIndex][index])
        return scope.$apply();

      if (!Array.isArray(scope.childrens[parentIndex]))
        scope.childrens[parentIndex] = [];

      if (!scope.collections[parentIndex])
        return;

      if (!scope.collections[parentIndex].images[index])
        return;

      imageLoader.load(
        scope.collections[parentIndex].images[index].uri + '.jpg',
        function(localImage) {
          scope.childrens[parentIndex][index] = localImage;
          scope.$apply();
        }
      );
    }

    function openZoom(uri) {
      scope.zoomImage = uri;

      $ionicLoading.show({
        scope: scope,
        templateUrl: 'zoom-modal',
        hideOnStateChange: true
      });
    }

    function hideZoom() {
      $ionicLoading.hide();
    }

    function makeCssUri(str) {
      if (!str)
        return 'none';

      return 'url(' + str + ')';
    }

    function pushNotificationReceived(event, notification) {
      if (notification.collectionId)
        return fetch(notification.collectionId);

      $cordovaDialogs.alert(
        notification.alert, // message
        '收到通知', // title,
        '知道了' // button
      )
    }
  }
})(this);<commit_msg>Add a blank check when quick jump to push notify slide<commit_after>;(function(window) {
  'use strict';

  var angular = window.angular;

  angular
    .module('tuchong-daily')
    .controller('home', [
      '$scope',
      'Store',
      '$ionicLoading',
      '$timeout',
      'imageLoader',
      'share',
      '$ionicModal',
      '$rootScope',
      '$cordovaDialogs',
      home
    ]);

  function home(scope, Store, $ionicLoading, $timeout, imageLoader, share, $ionicModal, $rootScope, $cordovaDialogs) {
    // When Push Received,
    // Render this notified post as first post.
    $rootScope.$on('pushNotificationReceived', pushNotificationReceived);

    scope.share = share.popup;
    scope.makeCssUri = makeCssUri;
    scope.openZoom = openZoom;
    scope.hideZoom = hideZoom;

    var slides = null;
    var childrenSlides = {};

    var backgrounds = scope.backgrounds = [];
    var childrens = scope.childrens = {};

    // Show loading
    $ionicLoading.show();

    // Read local cache from localStorage
    if (Store.cache.collections)
      return setup(Store.cache.collections);

    // Open a request
    fetch();

    // Fetch fresh data from API server
    function fetch(id) {
      var query = {};

      if (id)
        query.postId = id;

      Store[id ? 'post' : 'hot'].get(query, success, fail);

      function success(data) {
        if (id) {
          data.postId = id;
          return setup([data]);
        }

        if (!data.collections)
          return fail();

        // Setup a few slides
        setup(data.collections);

        // Save all data to cache
        Store.save('collections', data);
      }

      function fail(err) {
        $ionicLoading.show({
          template: ' 网络连接失败...请稍后再试'
        });
        return false;
      }
    }

    // Setup slides view
    function setup(data) {
      var rendered = scope.collections && scope.collections.length > 0;

      scope.collections = rendered ?
        scope.collections.concat(data) :
        data;

      // Show befor init slides
      if (!scope.slidesReady)
        scope.slidesReady = true;

      // Hide loading
      $ionicLoading.hide();

      var targetIndex = rendered && data.length === 1 ?
        findIndex(data[0].postId, scope.collections) :
        0;

      // Load cover image
      loadCover(targetIndex, {
        setupChildrenSwiper: true
      });

      if (targetIndex === 0)
        loadCover(1);

      // Init the slides on next tick
      $timeout(function() {
        // When Push Received
        if (rendered && slides) {
          slides.updateSlidesSize();

          if (targetIndex !== 0)
            slides.slideTo(targetIndex);

          return;
        }

        slides = new Swiper('.swiper-container-collection', {
          onSlideChangeStart: function() {
            loadCover(slides.activeIndex + 1, {
              setupChildrenSwiper: true,
              loadFirstChild: true
            });
          }
        });
      }, 10);
    }

    // Lazy loading the cover image of a slide
    function loadCover(index, opts) {
      // If this collection have on one picture
      if (scope.collections[index].images.length === 1)
        return loadImage(index);

      loadChildImage(index, 0);

      // Load its first child if required
      if (opts && opts.loadFirstChild)
        loadChildImage(index, 1);

      if (!opts || !opts.setupChildrenSwiper)
        return;

      if ('undefined' !== typeof(childrenSlides[index]))
        return;

      // Then setup its children slides
      $timeout(function() {
        setupChildrenSwiper(index);
      }, 10);
    }

    function findIndex(id, arr) {
      var target;
      angular.forEach(arr, function(item, index){
        if (item.postId === id)
          target = index;
      });
      return target;
    }

    function setupChildrenSwiper(index) {
      childrenSlides[index] = new Swiper('#children-' + index, {
        direction: 'vertical',
        onSlideChangeStart: function() {
          loadChildImage(index, childrenSlides[index].activeIndex + 1);
        }
      });
    }

    // Update slides async
    function loadImage(index) {
      if (backgrounds[index])
        return scope.$apply();

      if (!scope.collections[index])
        index -= 1;

      imageLoader.load(
        scope.collections[index].images[0].uri + '.jpg',
        function(localImage) {
          scope.backgrounds[index] = localImage;
          scope.$apply();
        }
      );
    }

    function loadChildImage(parentIndex, index) {
      if (Array.isArray(scope.childrens[parentIndex]) && scope.childrens[parentIndex][index])
        return scope.$apply();

      if (!Array.isArray(scope.childrens[parentIndex]))
        scope.childrens[parentIndex] = [];

      if (!scope.collections[parentIndex])
        return;

      if (!scope.collections[parentIndex].images[index])
        return;

      imageLoader.load(
        scope.collections[parentIndex].images[index].uri + '.jpg',
        function(localImage) {
          scope.childrens[parentIndex][index] = localImage;
          scope.$apply();
        }
      );
    }

    function openZoom(uri) {
      scope.zoomImage = uri;

      $ionicLoading.show({
        scope: scope,
        templateUrl: 'zoom-modal',
        hideOnStateChange: true
      });
    }

    function hideZoom() {
      $ionicLoading.hide();
    }

    function makeCssUri(str) {
      if (!str)
        return 'none';

      return 'url(' + str + ')';
    }

    function pushNotificationReceived(event, notification) {
      if (notification.collectionId)
        return fetch(notification.collectionId);

      $cordovaDialogs.alert(
        notification.alert, // message
        '收到通知', // title,
        '知道了' // button
      )
    }
  }
})(this);<|endoftext|>


<commit_before>ngapp.controller('helpModalController', function($timeout, $scope, helpService, errorService) {
    // helper functions
    let selectTopic = function(topic) {
        if ($scope.topic) $scope.topic.selected = false;
        $scope.topic = topic;
        topic.selected = true;
    };

    let expandTopic = function(topic) {
        $scope.$broadcast('expandTreeNode', topic);
    };

    // scope functions
    $scope.closeModal = function() {
        $scope.topic.selected = false;
        $scope.$broadcast('collapseTree');
        $timeout(() => $scope.$emit('closeModal'));
    };

    $scope.navigateTo = function(path) {
        selectTopic(helpService.getTopic(path, expandTopic));
        // TODO: scroll to top
    };

    // redirect help links internally
    $scope.$on("helpNavigateTo", function(e, path) {
        errorService.try(function() {
            $scope.$applyAsync(() => $scope.navigateTo(path));
        });
    });

    $scope.$on('navigateToChild', function(e, child) {
        $scope.$broadcast('expandTreeNode', $scope.topic);
        selectTopic(child);
        e.stopPropagation && e.stopPropagation();
    });

    // initialization
    $scope.xelib = xelib;
    $scope.topics = helpService.getTopics();
    selectTopic($scope.topics[0]);
});
<commit_msg>help modal now scrolls to the top of the modal whenever the topic is changed<commit_after>ngapp.controller('helpModalController', function($scope, $element, $timeout, helpService, errorService) {
    let modalContainerElement = $element[0].firstElementChild;

    // helper functions
    let selectTopic = function(topic) {
        if ($scope.topic) $scope.topic.selected = false;
        $scope.topic = topic;
        topic.selected = true;
    };

    let expandTopic = function(topic) {
        $scope.$broadcast('expandTreeNode', topic);
    };

    // scope functions
    $scope.closeModal = function() {
        $scope.topic.selected = false;
        $scope.$broadcast('collapseTree');
        $timeout(() => $scope.$emit('closeModal'));
    };

    $scope.navigateTo = function(path) {
        selectTopic(helpService.getTopic(path, expandTopic));
        // TODO: scroll to top
    };

    // event listeners
    $scope.$on("helpNavigateTo", function(e, path) {
        errorService.try(function() {
            $scope.$applyAsync(() => $scope.navigateTo(path));
        });
    });

    $scope.$on('navigateToChild', function(e, child) {
        $scope.$broadcast('expandTreeNode', $scope.topic);
        selectTopic(child);
        e.stopPropagation && e.stopPropagation();
    });

    $scope.$watch('topic', () => modalContainerElement.scrollTop = 0);

    // initialization
    $scope.xelib = xelib;
    $scope.topics = helpService.getTopics();
    selectTopic($scope.topics[0]);
});
<|endoftext|>


<commit_before>var _$_decorated=function(e){var t=e._$.bind(e);return t.api=e.api,t.routes=e.routes,t.here=function(n,o){parent_component_name=e.scope.split('"')[1];var r=function(e){return e.dataset.component==parent_component_name?e:(parentScope=e.parentNode,r(parentScope))};return e.nodeScope=r(n),t.call(e,o)},t};"undefined"==typeof jQuery&&(window.$=function(e){return[].slice.call(document.querySelectorAll(e))}.bind(this)),String.prototype.interpolate=function(e){return this.replace(/#\{(.+?)\}/g,function(t,n){var o=e[n];return"string"==typeof o||"number"==typeof o?o:t})},Object.deepExtend=function(e,t){for(var n in t)t[n]&&t[n].constructor&&t[n].constructor===Object?(e[n]=e[n]||{},arguments.callee(e[n],t[n])):e[n]=t[n];return e},window.m$={};var Mozart=function(){this.scope=void 0,this.nodeScope=void 0};Mozart.prototype._$=function(e){if(e instanceof Mozart)return $(this.scope);var t=e?" "+e:"";return this.nodeScope?"undefined"==typeof jQuery?this.nodeScope.querySelectorAll(e):$(e).find(e):$(this.scope+t)},Mozart.prototype.api=function(e){for(var t in e){var n=this;this.api[t]=function(e){return this.api_fn.call(n,_$_decorated(n),e)}.bind({api_fn:e[t]})}},Mozart.prototype.routes=function(e){for(var t in e){var n=JSON.parse(JSON.stringify(e[t]));this.routes[t]=function(){var e=Array.prototype.slice.call(arguments),t=e[1],n=e[0],o={};return o.url=n.url.interpolate(t),o.data=n.data||{},o.method=n.method,o.data=Object.deepExtend(o.data,t.data),o}.bind(this,n)}},Mozart.prototype.events=function(e){this.events=e},Mozart.init=function(){var e=[];for(var t in window.m$){var n=m$[t],o=_$_decorated(n);if(!n instanceof Mozart)return;n.scope='[data-component~="'+t+'"]',e.push([n,o])}e.forEach(function(e){e[0].events.call(e[0],e[1])})},Mozart.clone=function(e){var t=new DOMParser,n=document.createElement("div");if(!e)return console.error("No <template> element provided");if("object"!=typeof e)return console.error("Element to clone expected to be a <template> element. Was a "+typeof e);n.append(document.importNode(e.content,!0));var o=t.parseFromString(n.innerHTML,"text/xml").documentElement,r=document.createElement("div");return r.appendChild(o),o=r.childNodes[0],"undefined"==typeof jQuery?o:$(o)};
<commit_msg>Adding minified version<commit_after>var _$_decorated=function(e){var t;return t=e._$.bind(e),t.api=e._api,t.routes=e.routes,t.here=function(n,o){parent_component_name=e.scope.split('"')[1];var r=function(e){return e.dataset.component==parent_component_name?e:(parentScope=e.parentNode,r(parentScope))};return e.nodeScope=r(n),t.call(e,o)},t};"undefined"==typeof jQuery&&(window.$=function(e){return[].slice.call(document.querySelectorAll(e))}.bind(this)),String.prototype.interpolate=function(e){return this.replace(/#\{(.+?)\}/g,function(t,n){var o=e[n];return"string"==typeof o||"number"==typeof o?o:t})},Object.deepExtend=function(e,t){for(var n in t)t[n]&&t[n].constructor&&t[n].constructor===Object?(e[n]=e[n]||{},arguments.callee(e[n],t[n])):e[n]=t[n];return e},window.m$={};var Mozart=function(){this.scope=void 0,this.nodeScope=void 0,this._api={}};Mozart.prototype._$=function(e){if(e instanceof Mozart)return $(this.scope);var t=e?" "+e:"";return this.nodeScope?"undefined"==typeof jQuery?this.nodeScope.querySelectorAll(e):$(e).find(e):$(this.scope+t)},Mozart.prototype.api=function(e){for(var t in e)!function(e,t,n){n._api[t]=function(o){return e[t].call(n,_$_decorated(n),o)}}(e,t,this)},Mozart.prototype.routes=function(e){for(var t in e){var n=JSON.parse(JSON.stringify(e[t]));this.routes[t]=function(){var e=Array.prototype.slice.call(arguments),t=e[1],n=e[0],o={};return o.url=n.url.interpolate(t),o.data=n.data||{},o.method=n.method,o.data=Object.deepExtend(o.data,t.data),o}.bind(this,n)}},Mozart.prototype.events=function(e){this.events=e},Mozart.init=function(){var e=[];for(var t in window.m$){var n=m$[t];if(!n instanceof Mozart)return;n.scope='[data-component~="'+t+'"]';var o=_$_decorated(n);e.push([n,o])}e.forEach(function(e){e[0].events.call(e[0],e[1])})},Mozart.clone=function(e){var t=new DOMParser,n=document.createElement("div");if(!e)return console.error("No <template> element provided");if("object"!=typeof e)return console.error("Element to clone expected to be a <template> element. Was a "+typeof e);n.append(document.importNode(e.content,!0));var o=t.parseFromString(n.innerHTML,"text/xml").documentElement,r=document.createElement("div");return r.appendChild(o),o=r.childNodes[0],"undefined"==typeof jQuery?o:$(o)};
<|endoftext|>


<commit_before>const Search = require('../Search');

const _names = require('../../internal/names');

/**
 * An api adapter that provides functions for accessing constellation
 * information via the
 * [universe](https://esi.tech.ccp.is/latest/#/Universe) and
 * [search](https://esi.tech.ccp.is/latest/#/Search) ESI end points.
 * You should not usually instantiate this directly as its constructor requires
 * an internal api instance.
 */
class Constellations {
  /**
   * Create a new Constellations instance using the given `api`.
   *
   * @param api {ApiProvider} The api provider
   * @constructor
   */
  constructor(api) {
    this._api = api;

    this._search = null;
  }

  /**
   * A Search module instance configured to search over the `'constellation'`
   * type.
   *
   * @returns {Search}
   */
  get search() {
    if (!this._search) {
      this._search = new Search(this._api, ['constellation']);
    }
    return this._search;
  }

  /**
   * Get the names for a list of constellation ids from the ESI endpoint. This
   * makes an HTTP POST request to
   * [`universe/names/`](https://esi.tech.ccp.is/latest/#!/Universe/post_universe_names).
   * The request is returned as an asynchronous Promise that resolves to an
   * array parsed from the response JSON model. An example value looks like:
   *
   * ```
   * [
   *   {
   *     "id": 1000171,
   *     "name": "Republic University"
   *   }
   * ]
   * ```
   *
   * Note that this has the category field stripped from the response and will
   * only include matches with the constellation category.
   *
   * @param {Array.<Number>} ids The constellation ids to look up.
   * @return {Promise} A Promise that resolves to the response of
   *   the request
   * @esi_link UniverseApi.postUniverseNames
   */
  names(ids) {
    return _names(this._api, 'constellation', ids);
  }
}

module.exports = Constellations;
<commit_msg>Add new constellation end points<commit_after>const Search = require('../Search');

const ExtendableFunction = require('../../internal/ExtendableFunction');
const _names = require('../../internal/names');

/**
 * An api adapter that provides functions for accessing various details for a
 * constellation specified by id, via functions in the
 * [universe](https://esi.tech.ccp.is/latest/#/Universe) ESI endpoints. You
 * should not usually instantiate this directly as its constructor requires an
 * internal api instance.
 */
class Constellation {
  /**
   * Create a new Constellation for the given `api` provider and specific
   * `constellationId`.
   *
   * @param api {ApiProvider} The api provider used to generate web requests
   * @param constellationId {Number} The constellation id that is used for all
   *     requests
   * @constructor
   */
  constructor(api, constellationId) {
    this._api = api;
    this._id = constellationId;
  }

  /**
   * Get information on the constellation from the ESI endpoint. This makes an
   * HTTP GET request to
   * [`universe/constellations/{id}/`](https://esi.tech.ccp.is/dev/?datasource=tranquility#!/Universe/get_universe_constellations_constellation_id).
   * The request is returned as an asynchronous Promise that resolves to an
   * object parsed from the response JSON model. An example value looks like:
   *
   * ```
   * {
   *   "constellation_id": 20000009,
   *   "name": "Mekashtad",
   *   "position": {
   *     "x": 67796138757472320,
   *     "y": -70591121348560960,
   *     "z": -59587016159270070
   *   },
   *   "region_id": 10000001,
   *   "systems": [
   *     20000302,
   *     20000303
   *   ]
   * }
   * ```
   *
   * @returns {Promise}
   * @esi_link UniverseApi.getUniverseConstellationsConstellationId
   */
  info() {
    return this._api.universe()
    .newRequest('getUniverseConstellationsConstellationId', [this._id]);
  }
}

/**
 * An api adapter that provides functions for accessing constellation
 * information via the
 * [universe](https://esi.tech.ccp.is/latest/#/Universe) and
 * [search](https://esi.tech.ccp.is/latest/#/Search) ESI end points.
 * You should not usually instantiate this directly as its constructor requires
 * an internal api instance.
 *
 * This is a function class so instances of `Constellations` are functions and
 * can be invoked directly, besides accessing its members. Its default function
 * action is equivalent to {@link Constellations#get get} or {@link
 * Constellations#all all} if no id is provided.
 */
class Constellations extends ExtendableFunction {
  /**
   * Create a new Constellations instance using the given `api`.
   *
   * @param api {ApiProvider} The api provider
   * @constructor
   */
  constructor(api) {
    super(id => (id ? this.get(id) : this.all()));
    this._api = api;

    this._search = null;
  }

  /**
   * A Search module instance configured to search over the `'constellation'`
   * type.
   *
   * @returns {Search}
   */
  get search() {
    if (!this._search) {
      this._search = new Search(this._api, ['constellation']);
    }
    return this._search;
  }

  /**
   * Create a new Constellation end point targeting the particular constellation
   * by `id`.
   *
   * @param id {Number} The constellation id
   * @returns {Constellation}
   */
  get(id) {
    return new Constellation(this._api, id);
  }

  /**
   * Get all constellation ids from the ESI endpoint. This makes an HTTP GET
   * request to
   * [`universe/constellations/`](https://esi.tech.ccp.is/dev/?datasource=tranquility#!/Universe/get_universe_constellations).
   * The request is returned as an asynchronous Promise that resolves to an
   * array parsed from the response JSON model. An example value looks like:
   *
   * ```
   * [
   *   20000001,
   *   20000002
   * ]
   * ```
   *
   * @returns {Promise}
   * @esi_link UniverseApi.getUniverseConstellations
   */
  all() {
    return this._api.universe().newRequest('getUniverseConstellations', []);
  }

  /**
   * Get the names for a list of constellation ids from the ESI endpoint. This
   * makes an HTTP POST request to
   * [`universe/names/`](https://esi.tech.ccp.is/latest/#!/Universe/post_universe_names).
   * The request is returned as an asynchronous Promise that resolves to an
   * array parsed from the response JSON model. An example value looks like:
   *
   * ```
   * [
   *   {
   *     "id": 1000171,
   *     "name": "Republic University"
   *   }
   * ]
   * ```
   *
   * Note that this has the category field stripped from the response and will
   * only include matches with the constellation category.
   *
   * @param {Array.<Number>} ids Optional; the constellation ids to look up. If
   *     not provided then the names of all constellations will be returned.
   * @return {Promise} A Promise that resolves to the response of
   *     the request
   * @esi_link UniverseApi.postUniverseNames
   */
  names(ids = []) {
    if (!ids || ids.length == 0) {
      return this.all().then(allIds => this.names(allIds));
    } else {
      return _names(this._api, 'constellation', ids);
    }
  }
}

module.exports = Constellations;
<|endoftext|>


<commit_before>/*

  ## filtering

*/
define([
  'angular',
  'app',
  'underscore'
],
function (angular, app, _) {
  'use strict';

  var module = angular.module('kibana.panels.filtering', []);
  app.useModule(module);

  module.controller('filtering', function($scope, filterSrv, datasourceSrv, $rootScope, dashboard) {

    $scope.panelMeta = {
      status  : "Stable",
      description : "graphite target filters"
    };

    // Set and populate defaults
    var _d = {
    };
    _.defaults($scope.panel,_d);

    $scope.init = function() {
      $scope.filterSrv = filterSrv;
      _.each(filterSrv.list, function(filter) {
        $scope.applyFilter(filter);
      });
    };

    $scope.remove = function(filter) {
      filterSrv.remove(filter);
    };

    $scope.filterOptionSelected = function(filter, option) {
      filterSrv.filterOptionSelected(filter, option);
      $scope.applyFilterToOtherFilters(filter);
    };

    $scope.applyFilterToOtherFilters = function(updatedFilter) {
      _.each(filterSrv.list, function(filter) {
        if (filter === updatedFilter) {
          return;
        }
        if (filter.query.indexOf(updatedFilter.name) !== -1) {
          $scope.applyFilter(filter);
        }
      });
    };

    $scope.applyFilter = function(filter) {
      var query = filterSrv.applyFilterToTarget(filter.query);

      datasourceSrv.default.metricFindQuery(query)
        .then(function (results) {
          filter.editing=undefined;
          filter.options = _.map(results, function(node) {
            return { text: node.text, value: node.text };
          });

          if (filter.includeAll) {
            if(endsWithWildcard(filter.query)) {
              filter.options.unshift({text: 'All', value: '*'});
            }
            else {
              var allExpr = '{';
              _.each(filter.options, function(option) {
                allExpr += option.text + ',';
              });
              allExpr = allExpr.substring(0, allExpr.length - 1) + '}';
              filter.options.unshift({text: 'All', value: allExpr});
            }
          }

          filterSrv.filterOptionSelected(filter, filter.options[0]);
        });
    };

    $scope.add = function() {
      filterSrv.add({
        type      : 'filter',
        name      : 'filter name',
        editing   : true,
        query     : 'metric.path.query.*',
      });
    };

    $scope.refresh = function() {
      dashboard.refresh();
    };

    $scope.render = function() {
      $rootScope.$broadcast('render');
    };

    function endsWithWildcard(query) {
      if (query.length === 0) {
        return false;
      }

      return query[query.length - 1] === '*';
    }

  });
});<commit_msg>Revert "Merge pull request #310 from roidelapluie/master"<commit_after>/*

  ## filtering

*/
define([
  'angular',
  'app',
  'underscore'
],
function (angular, app, _) {
  'use strict';

  var module = angular.module('kibana.panels.filtering', []);
  app.useModule(module);

  module.controller('filtering', function($scope, filterSrv, datasourceSrv, $rootScope, dashboard) {

    $scope.panelMeta = {
      status  : "Stable",
      description : "graphite target filters"
    };

    // Set and populate defaults
    var _d = {
    };
    _.defaults($scope.panel,_d);

    $scope.init = function() {
      $scope.filterSrv = filterSrv;
    };

    $scope.remove = function(filter) {
      filterSrv.remove(filter);
    };

    $scope.filterOptionSelected = function(filter, option) {
      filterSrv.filterOptionSelected(filter, option);
      $scope.applyFilterToOtherFilters(filter);
    };

    $scope.applyFilterToOtherFilters = function(updatedFilter) {
      _.each(filterSrv.list, function(filter) {
        if (filter === updatedFilter) {
          return;
        }
        if (filter.query.indexOf(updatedFilter.name) !== -1) {
          $scope.applyFilter(filter);
        }
      });
    };

    $scope.applyFilter = function(filter) {
      var query = filterSrv.applyFilterToTarget(filter.query);

      datasourceSrv.default.metricFindQuery(query)
        .then(function (results) {
          filter.editing=undefined;
          filter.options = _.map(results, function(node) {
            return { text: node.text, value: node.text };
          });

          if (filter.includeAll) {
            if(endsWithWildcard(filter.query)) {
              filter.options.unshift({text: 'All', value: '*'});
            }
            else {
              var allExpr = '{';
              _.each(filter.options, function(option) {
                allExpr += option.text + ',';
              });
              allExpr = allExpr.substring(0, allExpr.length - 1) + '}';
              filter.options.unshift({text: 'All', value: allExpr});
            }
          }

          filterSrv.filterOptionSelected(filter, filter.options[0]);
        });
    };

    $scope.add = function() {
      filterSrv.add({
        type      : 'filter',
        name      : 'filter name',
        editing   : true,
        query     : 'metric.path.query.*',
      });
    };

    $scope.refresh = function() {
      dashboard.refresh();
    };

    $scope.render = function() {
      $rootScope.$broadcast('render');
    };

    function endsWithWildcard(query) {
      if (query.length === 0) {
        return false;
      }

      return query[query.length - 1] === '*';
    }

  });
});<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular
    .module('permission')
    .service('Authorization', function ($q, PermissionMap, PermissionStore, RoleStore) {
      this.authorize = authorize;

      /**
       * Checks if provided permissions are acceptable
       *
       * @param permissionsMap {PermissionMap} Map of permission names
       * @param [toParams] {Object} UI-Router params object
       * @returns {promise} $q.promise object
       */
      function authorize(permissionsMap, toParams) {
        return handleAuthorization(permissionsMap, toParams);
      }

      /**
       * Handles authorization based on provided permissions map
       * @private
       *
       * @param permissionsMap {Object} Map of permission names
       * @param toParams {Object} UI-Router params object
       * @returns {promise} $q.promise object
       */
      function handleAuthorization(permissionsMap, toParams) {
        var deferred = $q.defer();

        var exceptPromises = findMatchingPermissions(permissionsMap.except, toParams);

        allSettled(exceptPromises)
          .then(function (rejectedPermissions) {
            if (rejectedPermissions.length) {
              deferred.reject(rejectedPermissions[0]);
            }

            return $q.reject(null);
          })
          .catch(function () {
            if (!permissionsMap.only.length) {
              deferred.resolve(null);
            }
            var onlyPromises = findMatchingPermissions(permissionsMap.only, toParams);

            allSettled(onlyPromises)
              .then(function (resolvedPermissions) {
                deferred.resolve(resolvedPermissions[0]);
              })
              .catch(function (rejectedPermission) {

                var resolved = onlyPromises.filter(function (promise) {
                  return promise.$$state.status === 1;
                });

                if (resolved.length) {
                  deferred.resolve(resolved);
                } else {
                  deferred.reject(rejectedPermission);
                }
              });
          });

        return deferred.promise;
      }

      /**
       * Waits for all promises to be settled
       * @private
       *
       * @param promises {Array|promise} Set of promises
       * @returns {Promise} Rejected or fulfilled promise collection
       */
      function allSettled(promises) {
        var wrapped = angular.isArray(promises) ? [] : {};
        angular.forEach(promises, function (promise, key) {
          if (!wrapped.hasOwnProperty(key)) {
            wrapped[key] = wrap(promise);
          }
        });
        return $q.all(wrapped);
      }

      function wrap(promise) {
        return $q.when(promise)
          .then(function (value) {
            return $q.resolve(value);
          }, function (reason) {
            return $q.reject(reason);
          });
      }

      /**
       * Performs iteration over list of defined permissions looking for matching roles
       * @private
       *
       * @param permissionNames {Array} Set of permission names
       * @param toParams {Object} UI-Router params object
       * @returns {Array} Promise collection
       */
      function findMatchingPermissions(permissionNames, toParams) {
        return permissionNames.map(function (permissionName) {
          if (RoleStore.hasRoleDefinition(permissionName)) {
            return handleRoleValidation(permissionName, toParams);
          }

          if (PermissionStore.hasPermissionDefinition(permissionName)) {
            return handlePermissionValidation(permissionName, toParams);
          }

          if (permissionName) {
            return $q.reject(permissionName);
          }
        });
      }

      /**
       * Executes role validation checking
       * @private
       *
       * @param roleName {String} Store permission key
       * @param toParams {Object} UI-Router params object
       * @returns {Promise}
       */
      function handleRoleValidation(roleName, toParams) {
        var role = RoleStore.getRoleDefinition(roleName);
        return role.validateRole(toParams);
      }

      /**
       * Executes permission validation checking
       * @private
       *
       * @param permissionName {String} Store permission key
       * @param toParams {Object} UI-Router params object
       * @returns {Promise}
       */
      function handlePermissionValidation(permissionName, toParams) {
        var permission = PermissionStore.getPermissionDefinition(permissionName);
        return permission.validatePermission(toParams);
      }
    });
})();
<commit_msg>wip(Authorization) : #148 - except not accepting multiple permissions<commit_after>(function () {
  'use strict';

  angular
    .module('permission')
    .service('Authorization', function ($q, PermissionMap, PermissionStore, RoleStore) {
      this.authorize = authorize;

      /**
       * Checks if provided permissions are acceptable
       *
       * @param permissionsMap {PermissionMap} Map of permission names
       * @param [toParams] {Object} UI-Router params object
       * @returns {promise} $q.promise object
       */
      function authorize(permissionsMap, toParams) {
        return handleAuthorization(permissionsMap, toParams);
      }

      /**
       * Handles authorization based on provided permissions map
       * @private
       *
       * @param permissionsMap {Object} Map of permission names
       * @param toParams {Object} UI-Router params object
       * @returns {promise} $q.promise object
       */
      function handleAuthorization(permissionsMap, toParams) {
        var deferred = $q.defer();

        var exceptPromises = findMatchingPermissions(permissionsMap.except, toParams);

        allSettled(exceptPromises)
          .then(function (rejectedPermissions) {
            if (rejectedPermissions.length) {
              deferred.reject(rejectedPermissions[0]);
            }

            return $q.reject(null);
          })
          .catch(function () {
            if (!permissionsMap.only.length) {
              deferred.resolve(null);
            }
            var onlyPromises = findMatchingPermissions(permissionsMap.only, toParams);

            allSettled(onlyPromises)
              .then(function (resolvedPermissions) {
                deferred.resolve(resolvedPermissions[0]);
              })
              .catch(function (rejectedPermission) {

                var resolved = onlyPromises.filter(function (promise) {
                  return promise.$$state.status === 1;
                });

                if (resolved.length) {
                  deferred.resolve(resolved);
                } else {
                  deferred.reject(rejectedPermission);
                }
              });
          });

        return deferred.promise;
      }

      /**
       * Waits for all promises to be settled
       * @private
       *
       * @param promises {Array|promise} Set of promises
       * @returns {Promise} Rejected or fulfilled promise collection
       */
      function allSettled(promises) {
        var results = angular.isArray(promises) ? [] : {};

        angular.forEach(promises, function (promise, key) {
          if (results.hasOwnProperty(key)) {
            return;
          }

          results[key] = $q.when(promise)
            .then(function (value) {
              return $q.resolve(value);
            }, function (reason) {
              return $q.reject(reason);
            });
        });

        return $q.all(results);
      }

      /**
       * Performs iteration over list of defined permissions looking for matching roles
       * @private
       *
       * @param permissionNames {Array} Set of permission names
       * @param toParams {Object} UI-Router params object
       * @returns {Array} Promise collection
       */
      function findMatchingPermissions(permissionNames, toParams) {
        return permissionNames.map(function (permissionName) {
          if (RoleStore.hasRoleDefinition(permissionName)) {
            return handleRoleValidation(permissionName, toParams);
          }

          if (PermissionStore.hasPermissionDefinition(permissionName)) {
            return handlePermissionValidation(permissionName, toParams);
          }

          if (permissionName) {
            return $q.reject(permissionName);
          }
        });
      }

      /**
       * Executes role validation checking
       * @private
       *
       * @param roleName {String} Store permission key
       * @param toParams {Object} UI-Router params object
       * @returns {Promise}
       */
      function handleRoleValidation(roleName, toParams) {
        var role = RoleStore.getRoleDefinition(roleName);
        return role.validateRole(toParams);
      }

      /**
       * Executes permission validation checking
       * @private
       *
       * @param permissionName {String} Store permission key
       * @param toParams {Object} UI-Router params object
       * @returns {Promise}
       */
      function handlePermissionValidation(permissionName, toParams) {
        var permission = PermissionStore.getPermissionDefinition(permissionName);
        return permission.validatePermission(toParams);
      }
    });
})();
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Ambris
 *
 * Project : Very simple PDF viewer jQuery plugin
 * Version : 0.1
 * author: Richard Stefan (richard.stefan@ambris.com)
 *
 * Licensed under the Apache License, Version 2.0(the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http: //www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function($) {
    $.pdfviewer = function(element, options) {

        var defaults = {
            href: '', // for demonstration purpose
            scale: 1.0,
            autoFit: false,
            toolbar_template: '
' +
                '<button id="pdf-prev">Previous</button>' +
                '<button id="pdf-next">Next</button>' +
                'Page:/' +
                '<button id="pdf-autofit-height">Adjust Height</button>' +
                '<button id="pdf-autofit-width">Adjust Width</button>' +
                '<button id="pdf-autofit">Auto fit</button>' +
                '
',
            viewer_template: '
<canvas id="pdf-the-canvas"></canvas>
',

            onPrevPage: function() {
                return true;
            },
            onNextPage: function() {
                return true;
            },
            onDocumentLoaded: function() {},
            onBeforeRenderPage: function(num) {
                return true;
            },
            onRenderedPage: function(num) {}
        }

        var plugin = this;

        plugin.settings = {};

        var $element = $(element), // reference to the jQuery version of DOM element
            element = element, // reference to the actual DOM element
            elt_width = $element.innerWidth(),
            elt_heigth = $element.innerHeight();

        var pdfDoc = null,
            pageNum = 1,
            pageRendering = false,
            pageNumPending = null,
            scale = 1.0,
            canvas = null,
            ctx = null;

        plugin.init = function() {

            options = options || {};
            options.href = options.href || $element.data('href');

            plugin.settings = $.extend({}, defaults, options);

            $element.html(build());

            if (!PDFJS) {
                console.log('pdf.js not loaded. Add "pdf.js" to your page.');
                return this;
            }

            PDFJS.disableWorker = true;

            scale = plugin.settings.scale;
            canvas = $('#pdf-the-canvas', element).get(0);
            ctx = canvas.getContext('2d');

            $('#pdf-prev', element).on('click', plugin.prevPage);
            $('#pdf-next', element).on('click', plugin.nextPage);
            $('#pdf-autofit-height', element).on('click', plugin.autoFitScaleByHeight);
            $('#pdf-autofit-width', element).on('click', plugin.autoFitScaleByWidth);
            $('#pdf-autofit', element).on('click', plugin.autoFit);

            /**
             * Asynchronously downloads PDF.
             */
            PDFJS.getDocument(plugin.settings.href).then(function(pdfDoc_) {
                pdfDoc = pdfDoc_;
                plugin.settings.onDocumentLoaded.call(element);

                $('#pdf-page-count', element).text(pdfDoc.numPages);

                // Initial/first page rendering
                plugin.renderPage(pageNum);
            });
        };

        // public methods
        /**
         * Get page info from document, resize canvas accordingly, and render page.
         * @param num Page number.
         */
        plugin.renderPage = function(num) {

            if (!plugin.settings.onBeforeRenderPage.call(element, num)) return;

            pageRendering = true;
            // Using promise to fetch the page
            pdfDoc.getPage(num).then(function(page) {
                var viewport = page.getViewport(scale);
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                if (canvas.width < $(canvas).parent().width() - 20)
                    $(canvas).css('left', (($(canvas).parent().width() - canvas.width) / 2));
                else
                    $(canvas).css('left', 0);

                // Render PDF page into canvas context
                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };
                var renderTask = page.render(renderContext);

                // Wait for rendering to finish
                renderTask.promise.then(function() {
                    pageRendering = false;

                    plugin.settings.onRenderedPage.call(element, num);

                    if (pageNumPending !== null) {
                        // New page rendering is pending
                        renderPage(pageNumPending);
                        pageNumPending = null;
                    }
                });
            });

            // Update page counters
            $('#pdf-page-num', element).text(pageNum);
        };

        plugin.currentPage = function() {
            return pageNum;
        };

        plugin.pages = function() {
            return pdfDoc.numPages;
        };

        /**
         * Displays previous page.
         */
        plugin.prevPage = function() {
            if (!plugin.settings.onPrevPage.call(element)) return;

            if (pageNum <= 1) {
                return;
            }
            pageNum--;
            queueRenderPage(pageNum);
        };

        /**
         * Displays next page.
         */
        plugin.nextPage = function() {
            if (!plugin.settings.onNextPage.call(element)) return;

            if (pageNum >= pdfDoc.numPages) {
                return;
            }
            pageNum++;
            queueRenderPage(pageNum);
        }

        plugin.autoFit = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentHeight = $(canvas).parent().height() - 5;
                var parentWidth = $(canvas).parent().width() - 20;
                var viewport = page.getViewport(1.0);

                if (parentHeight <= parentWidth)
                    plugin.autoFitScaleByHeight();
                else
                    plugin.autoFitScaleByWidth();
            });
        }

        plugin.autoFitScaleByHeight = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentHeight = $(canvas).parent().height() - 5;

                var viewport = page.getViewport(1.0);
                scale = parentHeight / viewport.height;

                queueRenderPage(pageNum);
            });
        }

        plugin.autoFitScaleByWidth = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentWidth = $(canvas).parent().width() - 20;

                var viewport = page.getViewport(1.0);
                scale = parentWidth / viewport.width;

                queueRenderPage(pageNum);
            });
        }

        // private methods
        // these methods can be called only from inside the plugin like:
        // methodName(arg1, arg2, ... argn)
        var build = function() {
            return plugin.settings.toolbar_template + plugin.settings.viewer_template;
        }

        /**
         * If another page rendering in progress, waits until the rendering is
         * finised. Otherwise, executes rendering immediately.
         */
        var queueRenderPage = function(num) {
            if (pageRendering) {
                pageNumPending = num;
            } else {
                plugin.renderPage(num);
            }
        }

        // fire up the plugin!
        // call the "constructor" method
        plugin.init();
    }

    // add the plugin to the jQuery.fn object
    $.fn.pdfviewer = function(options) {

        // iterate through the DOM elements we are attaching the plugin to
        return this.each(function() {

            // if plugin has not already been attached to the element
            if (undefined == $(this).data('pdfviewer')) {

                // create a new instance of the plugin
                // pass the DOM element and the user-provided options as arguments
                var plugin = new $.pdfviewer(this, options);

                // in the jQuery version of the element
                // store a reference to the plugin object
                // you can later access the plugin and its methods and properties like
                // element.data('pdfviewer').publicMethod(arg1, arg2, ... argn) or
                // element.data('pdfviewer').settings.propertyName
                $(this).data('pdfviewer', plugin);

            }

        });

    }

})(jQuery);<commit_msg>clearing comments<commit_after>/*
 * Copyright 2014 Ambris
 *
 * Project : Very simple PDF viewer jQuery plugin
 * Version : 0.1
 * author: Richard Stefan (richard.stefan@ambris.com)
 *
 * Licensed under the Apache License, Version 2.0(the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http: //www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function($) {
    $.pdfviewer = function(element, options) {

        var defaults = {
            href: '', // for demonstration purpose
            scale: 1.0,
            autoFit: false,
            toolbar_template: '
' +
                '<button id="pdf-prev">Previous</button>' +
                '<button id="pdf-next">Next</button>' +
                'Page:/' +
                '<button id="pdf-autofit-height">Adjust Height</button>' +
                '<button id="pdf-autofit-width">Adjust Width</button>' +
                '<button id="pdf-autofit">Auto fit</button>' +
                '
',
            viewer_template: '
<canvas id="pdf-the-canvas"></canvas>
',

            onPrevPage: function() {
                return true;
            },
            onNextPage: function() {
                return true;
            },
            onDocumentLoaded: function() {},
            onBeforeRenderPage: function(num) {
                return true;
            },
            onRenderedPage: function(num) {}
        }

        var plugin = this;

        plugin.settings = {};

        var $element = $(element), // reference to the jQuery version of DOM element
            element = element, // reference to the actual DOM element
            elt_width = $element.innerWidth(),
            elt_heigth = $element.innerHeight();

        var pdfDoc = null,
            pageNum = 1,
            pageRendering = false,
            pageNumPending = null,
            scale = 1.0,
            canvas = null,
            ctx = null;

        plugin.init = function() {

            options = options || {};
            options.href = options.href || $element.data('href');

            plugin.settings = $.extend({}, defaults, options);

            $element.html(build());

            if (!PDFJS) {
                console.log('pdf.js not loaded. Add "pdf.js" to your page.');
                return this;
            }

            PDFJS.disableWorker = true;

            scale = plugin.settings.scale;
            canvas = $('#pdf-the-canvas', element).get(0);
            ctx = canvas.getContext('2d');

            $('#pdf-prev', element).on('click', plugin.prevPage);
            $('#pdf-next', element).on('click', plugin.nextPage);
            $('#pdf-autofit-height', element).on('click', plugin.autoFitScaleByHeight);
            $('#pdf-autofit-width', element).on('click', plugin.autoFitScaleByWidth);
            $('#pdf-autofit', element).on('click', plugin.autoFit);

            /**
             * Asynchronously downloads PDF.
             */
            PDFJS.getDocument(plugin.settings.href).then(function(pdfDoc_) {
                pdfDoc = pdfDoc_;
                plugin.settings.onDocumentLoaded.call(element);

                $('#pdf-page-count', element).text(pdfDoc.numPages);

                // Initial/first page rendering
                plugin.renderPage(pageNum);
            });
        };

        // public methods
        /**
         * Get page info from document, resize canvas accordingly, and render page.
         * @param num Page number.
         */
        plugin.renderPage = function(num) {

            if (!plugin.settings.onBeforeRenderPage.call(element, num)) return;

            pageRendering = true;
            // Using promise to fetch the page
            pdfDoc.getPage(num).then(function(page) {
                var viewport = page.getViewport(scale);
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                if (canvas.width < $(canvas).parent().width() - 20)
                    $(canvas).css('left', (($(canvas).parent().width() - canvas.width) / 2));
                else
                    $(canvas).css('left', 0);

                // Render PDF page into canvas context
                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };
                var renderTask = page.render(renderContext);

                // Wait for rendering to finish
                renderTask.promise.then(function() {
                    pageRendering = false;

                    plugin.settings.onRenderedPage.call(element, num);

                    if (pageNumPending !== null) {
                        // New page rendering is pending
                        renderPage(pageNumPending);
                        pageNumPending = null;
                    }
                });
            });

            // Update page counters
            $('#pdf-page-num', element).text(pageNum);
        };

        plugin.currentPage = function() {
            return pageNum;
        };

        plugin.pages = function() {
            return pdfDoc.numPages;
        };

        /**
         * Displays previous page.
         */
        plugin.prevPage = function() {
            if (!plugin.settings.onPrevPage.call(element)) return;

            if (pageNum <= 1) {
                return;
            }
            pageNum--;
            queueRenderPage(pageNum);
        };

        /**
         * Displays next page.
         */
        plugin.nextPage = function() {
            if (!plugin.settings.onNextPage.call(element)) return;

            if (pageNum >= pdfDoc.numPages) {
                return;
            }
            pageNum++;
            queueRenderPage(pageNum);
        }

        plugin.autoFit = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentHeight = $(canvas).parent().height() - 5;
                var parentWidth = $(canvas).parent().width() - 20;
                var viewport = page.getViewport(1.0);

                if (parentHeight <= parentWidth)
                    plugin.autoFitScaleByHeight();
                else
                    plugin.autoFitScaleByWidth();
            });
        }

        plugin.autoFitScaleByHeight = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentHeight = $(canvas).parent().height() - 5;

                var viewport = page.getViewport(1.0);
                scale = parentHeight / viewport.height;

                queueRenderPage(pageNum);
            });
        }

        plugin.autoFitScaleByWidth = function() {
            pdfDoc.getPage(pageNum).then(function(page) {
                var parentWidth = $(canvas).parent().width() - 20;

                var viewport = page.getViewport(1.0);
                scale = parentWidth / viewport.width;

                queueRenderPage(pageNum);
            });
        }

        // private methods
        var build = function() {
            return plugin.settings.toolbar_template + plugin.settings.viewer_template;
        }

        /**
         * If another page rendering in progress, waits until the rendering is
         * finised. Otherwise, executes rendering immediately.
         */
        var queueRenderPage = function(num) {
            if (pageRendering) {
                pageNumPending = num;
            } else {
                plugin.renderPage(num);
            }
        }

        plugin.init();
    }

    $.fn.pdfviewer = function(options) {

        return this.each(function() {

            if (undefined == $(this).data('pdfviewer')) {

                var plugin = new $.pdfviewer(this, options);

                // in the jQuery version of the element
                // store a reference to the plugin object
                // you can later access the plugin and its methods and properties like
                // element.data('pdfviewer').publicMethod(arg1, arg2, ... argn) or
                // element.data('pdfviewer').settings.propertyName
                $(this).data('pdfviewer', plugin);

            }

        });

    }

})(jQuery);<|endoftext|>


<commit_before>describe('ax5.util.param TEST', function() {
    it('ax5.util.param({a: 1, b: \'123\'"2&\'}, "param") expect "a=1&b=123%27%222%26"', function() {
        var actual = ax5.util.param({a: 1, b: '123\'"2&'}, 'param');

        actual.should.equal('a=1&b=123%27%222%26');
    });
    it('ax5.util.param("a=1&b=12\'"32", "param") expect "a=1&b=12\'"32"', function() {
        var actual = ax5.util.param("a=1&b=12'\"32", 'param');

        actual.should.equal('a=1&b=12\'"32');
    });
    it('ax5.util.param("a=1&b=1232") expect {"a":"1","b":"1232"}', function() {
        var actual = ax5.util.param("a=1&b=1232");

        should.deepEqual(actual, {"a":"1","b":"1232"});
    });
});

describe('ax5.util.parseJson TEST', function() {
    it('ax5.util.util.parseJson("[{"a":"99"},"2","3"]") expect [{"a":"99"},"2","3"]', function() {
        var actual = ax5.util.parseJson('[{"a":"99"},"2","3"]');

        actual.should.deepEqual([{"a":"99"},"2","3"]);
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", false) expect {"error": 500, "msg": "syntax error"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', false);

        actual.should.deepEqual({"error": 500, "msg": "syntax error"});
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", true) expect {"a": 1, "b": "{Function}"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', true);

        actual.a.should.equal(1);
        actual.b.should.Function();
    });
});

describe('ax5.util.toJson TEST', function() {
    var testCases = [
        {
            args: 1,
            expect: 1
        },
        {
            args: "A",
            expect: '"A"'
        },
        {
            args: [1, 2, 3, "A"],
            expect: '[1,2,3,"A"]'
        },
        {
            args: {a: "a", x: "x"},
            expect: '{"a": "a", "x": "x"}'
        },
        {
            args: [1,{"a": "a", "x": "x"}],
            expect: '[1,{"a": "a", "x": "x"}]'
        },
        {
            args: {"a": "a", "x": "x", "list": [1,2,3]},
            expect: '{"a": "a", "x": "x", "list": [1,2,3]}'
        },
        {
            args: function func() {},
            expect: '"{Function}"'
        },
        {
            args: [true, false, true],
            expect: '[true,false,true]'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + (JSON.stringify(testCase.args) || testCase.args.toString()) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.toJson(testCase.args);

            actual.should.deepEqual(testCase.expect);
        });
    });
});

describe('ax5.util.alert TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.toArray TEST', function() {
    it('ax5.util.toArray converts [Array-like objects] to [Array]', function() {
        function something() {
            return ax5.util.toArray(arguments);
        }
        var actual = something("A", "X", "I", "S", "J");

        actual.should.deepEqual(["A", "X", "I", "S", "J"]);
    });
});

describe('ax5.util.xxxCookie TEST', function() {

    describe('ax5.util.setCookie TEST', function() {
        it('ax5.util.setCookie("ax5-cookie", "eng+한글")', function() {
            ax5.util.setCookie('ax5-cookie', 'eng+한글');

            document.cookie.indexOf('ax5-cookie=eng+%uD55C%uAE00').should.above(-1);
        });
    });

    describe('ax5.util.getCookie TEST', function() {
        it('ax5.util.getCookie("ax5-cookie") expect "eng+한글"', function() {
            var actual = ax5.util.getCookie('ax5-cookie');

            actual.should.equal('eng+한글');
        });
    });

});

describe('ax5.util.findParentNode TEST', function() {
    it('ax5.util.findParentNode($(".first").get(0), { tagname: "div", clazz: "test-mockup-1" }) expect $("div.test-mockup-1").get(0)', function() {
        var actual = ax5.util.findParentNode($('.first').get(0), { tagname: 'div', clazz: 'test-mockup-1' });
        var expect = $('div.test-mockup-1').get(0);

        should.equal(actual, expect);
    });
});

describe('ax5.util.cssNumber TEST', function() {
    var testCases = [
        {
            args: '100px',
            expect: '100px'
        },
        {
            args: 100,
            expect: '100px'
        },
        {
            args: '100%',
            expect: '100%'
        },
        {
            args: '##100@',
            expect: '100px'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + JSON.stringify(testCase.args) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.cssNumber(testCase.args);

            should.equal(actual, testCase.expect);
        });
    });
});

describe('ax5.util.css TEST', function() {

    it('ax5.util.css({background:"#ccc",padding:"50px",width:"100px" }) expect background:#ccc;padding:50px;width:100px;', function() {
        var actual = ax5.util.css({background:"#ccc",padding:"50px",width:"100px" });

        should.equal(actual, 'background:#ccc;padding:50px;width:100px;');
    });

    it('ax5.util.css("width:100px;padding: 50px; background: #ccc") expect {width: "100px", padding: "50px", background: "#ccc"}', function() {
        var actual = ax5.util.css('width:100px;padding: 50px; background: #ccc');

        should.deepEqual(actual, {width: "100px", padding: "50px", background: "#ccc"});
    });

});

describe('ax5.util.stopEvent TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.selectRange TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.debounce TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});
<commit_msg>update test code<commit_after>describe('ax5.util.param TEST', function() {
    it('ax5.util.param({a: 1, b: \'123\'"2&\'}, "param") expect "a=1&b=123%27%222%26"', function() {
        var actual = ax5.util.param({a: 1, b: '123\'"2&'}, 'param');

        actual.should.equal('a=1&b=123%27%222%26');
    });
    it('ax5.util.param("a=1&b=12\'"32", "param") expect "a=1&b=12\'"32"', function() {
        var actual = ax5.util.param("a=1&b=12'\"32", 'param');

        actual.should.equal('a=1&b=12\'"32');
    });
    it('ax5.util.param("a=1&b=1232") expect {"a":"1","b":"1232"}', function() {
        var actual = ax5.util.param("a=1&b=1232");

        should.deepEqual(actual, {"a":"1","b":"1232"});
    });
});

describe('ax5.util.parseJson TEST', function() {
    it('ax5.util.util.parseJson("[{"a":"99"},"2","3"]") expect [{"a":"99"},"2","3"]', function() {
        var actual = ax5.util.parseJson('[{"a":"99"},"2","3"]');

        actual.should.deepEqual([{"a":"99"},"2","3"]);
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", false) expect {"error": 500, "msg": "syntax error"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', false);

        actual.should.deepEqual({"error": 500, "msg": "syntax error"});
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", true) expect {"a": 1, "b": "{Function}"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', true);

        actual.a.should.equal(1);
        actual.b.should.Function();
    });

    it('ax5.util.parseJson("{"key": [true, false, true, false], "fn": function(){return "fn";}}", true);', function() {
        var actual = ax5.util.parseJson('{"key": [true, false, true, false], "fn": function(){return "fn";}}', true);

        actual.key.should.deepEqual([true, false, true, false]);
        actual.fn.should.Function();
    });
});

describe('ax5.util.toJson TEST', function() {
    var testCases = [
        {
            args: 1,
            expect: 1
        },
        {
            args: "A",
            expect: '"A"'
        },
        {
            args: [1, 2, 3, "A"],
            expect: '[1,2,3,"A"]'
        },
        {
            args: {a: "a", x: "x"},
            expect: '{"a": "a", "x": "x"}'
        },
        {
            args: [1,{"a": "a", "x": "x"}],
            expect: '[1,{"a": "a", "x": "x"}]'
        },
        {
            args: {"a": "a", "x": "x", "list": [1,2,3]},
            expect: '{"a": "a", "x": "x", "list": [1,2,3]}'
        },
        {
            args: function func() {},
            expect: '"{Function}"'
        },
        {
            args: [true, false, true],
            expect: '[true,false,true]'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + (JSON.stringify(testCase.args) || testCase.args.toString()) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.toJson(testCase.args);

            actual.should.deepEqual(testCase.expect);
        });
    });
});

describe('ax5.util.alert TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.toArray TEST', function() {
    it('ax5.util.toArray converts [Array-like objects] to [Array]', function() {
        function something() {
            return ax5.util.toArray(arguments);
        }
        var actual = something("A", "X", "I", "S", "J");

        actual.should.deepEqual(["A", "X", "I", "S", "J"]);
    });
});

describe('ax5.util.xxxCookie TEST', function() {

    describe('ax5.util.setCookie TEST', function() {
        it('ax5.util.setCookie("ax5-cookie", "eng+한글")', function() {
            ax5.util.setCookie('ax5-cookie', 'eng+한글');

            document.cookie.indexOf('ax5-cookie=eng+%uD55C%uAE00').should.above(-1);
        });
    });

    describe('ax5.util.getCookie TEST', function() {
        it('ax5.util.getCookie("ax5-cookie") expect "eng+한글"', function() {
            var actual = ax5.util.getCookie('ax5-cookie');

            actual.should.equal('eng+한글');
        });
    });

});

describe('ax5.util.findParentNode TEST', function() {
    it('ax5.util.findParentNode($(".first").get(0), { tagname: "div", clazz: "test-mockup-1" }) expect $("div.test-mockup-1").get(0)', function() {
        var actual = ax5.util.findParentNode($('.first').get(0), { tagname: 'div', clazz: 'test-mockup-1' });
        var expect = $('div.test-mockup-1').get(0);

        should.equal(actual, expect);
    });
});

describe('ax5.util.cssNumber TEST', function() {
    var testCases = [
        {
            args: '100px',
            expect: '100px'
        },
        {
            args: 100,
            expect: '100px'
        },
        {
            args: '100%',
            expect: '100%'
        },
        {
            args: '##100@',
            expect: '100px'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + JSON.stringify(testCase.args) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.cssNumber(testCase.args);

            should.equal(actual, testCase.expect);
        });
    });
});

describe('ax5.util.css TEST', function() {

    it('ax5.util.css({background:"#ccc",padding:"50px",width:"100px" }) expect background:#ccc;padding:50px;width:100px;', function() {
        var actual = ax5.util.css({background:"#ccc",padding:"50px",width:"100px" });

        should.equal(actual, 'background:#ccc;padding:50px;width:100px;');
    });

    it('ax5.util.css("width:100px;padding: 50px; background: #ccc") expect {width: "100px", padding: "50px", background: "#ccc"}', function() {
        var actual = ax5.util.css('width:100px;padding: 50px; background: #ccc');

        should.deepEqual(actual, {width: "100px", padding: "50px", background: "#ccc"});
    });

});

describe('ax5.util.stopEvent TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.selectRange TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.debounce TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});
<|endoftext|>