<commit_before>'use strict';
var moment = require('camunda-commons-ui/vendor/moment'),
    angular = require('camunda-commons-ui/vendor/angular');

module.exports = function(ngModule, appRoot, appName) {
  ngModule.factory('localeLoader', ['$q', '$http', 'Notifications', 'configuration',
      function($q, $http, Notifications, configuration) {
        return function(options) {

          if (!options || (!angular.isString(options.prefix) || !angular.isString(options.suffix))) {
            throw new Error('Couldn\'t load static files, no prefix or suffix specified!');
          }

          var deferred = $q.defer();
          var cacheKey = options.prefix+'_locales_data_'+options.key;
          var cachedLocalesData = configuration.get(cacheKey);

          if(cachedLocalesData) {
            cachedLocalesData = JSON.parse((cachedLocalesData));
            if(typeof options.callback === 'function') {
              options.callback(null, cachedLocalesData, options.key);
            }
            deferred.resolve(cachedLocalesData.labels);
          }
          else {
            $http(angular.extend({
              url: [
                options.prefix,
                options.key,
                options.suffix
              ].join(''),
              method: 'GET',
              params: ''
            }, options.$http))
              .success(function(data) {
                configuration.set(cacheKey, JSON.stringify(data));
                if(typeof options.callback === 'function') {
                  options.callback(null, data, options.key);
                }
                deferred.resolve(data.labels);
              })
              .error(function(data) {
                if(typeof options.callback === 'function') {
                  options.callback(data, null, options.key);
                }
                // error notification
                Notifications.addError({
                  status: 'Error in localization configuration',
                  message: '"' + options.key + '" is declared as available locale, but no such locale file exists.'
                });
                deferred.reject(options.key);
              });
          }

          return deferred.promise;
        };
      }]);

  ngModule.config([
    '$translateProvider',
    'configurationProvider',
    function(
      $translateProvider,
       configurationProvider
      ) {
      var avail = configurationProvider.getAvailableLocales();
      var fallback = configurationProvider.getFallbackLocale();

      $translateProvider.useLoader('localeLoader', {
        prefix: appRoot + '/app/'+ appName +'/locales/',
        suffix: '.json',
        callback: function(err, data, locale) {
          if(!err && data && data.dateLocales) {
              // Deprecation warning: moment.lang is deprecated. Use moment.locale instead.
            moment.locale(locale || fallback, data.dateLocales);
          }
        }
      });

      $translateProvider.registerAvailableLanguageKeys(avail);
      $translateProvider.fallbackLanguage(fallback);

      $translateProvider.determinePreferredLanguage(function() {
        var nav = window.navigator;
        var browserLang = ((angular.isArray(nav.languages) ? nav.languages[0] :
                              nav.language ||
                              nav.browserLanguage ||
                              nav.systemLanguage ||
                              nav.userLanguage
                            ) || '').split('-');
        var idx = avail.indexOf(angular.lowercase(browserLang[0]));
        if (idx > -1) {
          return avail[idx];
        } else {
          return fallback;
        }
      });
    }]);
};
<commit_msg>fix(locales): always get latest locales and overwrite in localstorage<commit_after>'use strict';
var moment = require('camunda-commons-ui/vendor/moment'),
    angular = require('camunda-commons-ui/vendor/angular');

module.exports = function(ngModule, appRoot, appName) {
  ngModule.factory('localeLoader', ['$q', '$http', 'Notifications', 'configuration',
      function($q, $http, Notifications, configuration) {
        return function(options) {

          if (!options || (!angular.isString(options.prefix) || !angular.isString(options.suffix))) {
            throw new Error('Couldn\'t load static files, no prefix or suffix specified!');
          }

          var deferred = $q.defer();
          var cacheKey = options.prefix+'_locales_data_'+options.key;
          var cachedLocalesData = configuration.get(cacheKey);

          if(cachedLocalesData) {
            cachedLocalesData = JSON.parse((cachedLocalesData));
            if(typeof options.callback === 'function') {
              options.callback(null, cachedLocalesData, options.key);
            }
            deferred.resolve(cachedLocalesData.labels);
          }

          $http(angular.extend({
            url: [
              options.prefix,
              options.key,
              options.suffix
            ].join(''),
            method: 'GET',
            params: ''
          }, options.$http))
            .success(function(data) {
              configuration.set(cacheKey, JSON.stringify(data));
              if (!cachedLocalesData) {

                if(typeof options.callback === 'function') {
                  options.callback(null, data, options.key);
                }

                deferred.resolve(data.labels);
              }
            })
            .error(function(data) {
              // error notification
              Notifications.addError({
                status: 'Error in localization configuration',
                message: '"' + options.key + '" is declared as available locale, but no such locale file exists.'
              });

              if (!cachedLocalesData) {

                if(typeof options.callback === 'function') {
                  options.callback(data, null, options.key);
                }

                deferred.reject(options.key);
              }
            });

          return deferred.promise;
        };
      }]);

  ngModule.config([
    '$translateProvider',
    'configurationProvider',
    function(
      $translateProvider,
       configurationProvider
      ) {
      var avail = configurationProvider.getAvailableLocales();
      var fallback = configurationProvider.getFallbackLocale();

      $translateProvider.useLoader('localeLoader', {
        prefix: appRoot + '/app/'+ appName +'/locales/',
        suffix: '.json',
        callback: function(err, data, locale) {
          if(!err && data && data.dateLocales) {
              // Deprecation warning: moment.lang is deprecated. Use moment.locale instead.
            moment.locale(locale || fallback, data.dateLocales);
          }
        }
      });

      $translateProvider.registerAvailableLanguageKeys(avail);
      $translateProvider.fallbackLanguage(fallback);

      $translateProvider.determinePreferredLanguage(function() {
        var nav = window.navigator;
        var browserLang = ((angular.isArray(nav.languages) ? nav.languages[0] :
                              nav.language ||
                              nav.browserLanguage ||
                              nav.systemLanguage ||
                              nav.userLanguage
                            ) || '').split('-');
        var idx = avail.indexOf(angular.lowercase(browserLang[0]));
        if (idx > -1) {
          return avail[idx];
        } else {
          return fallback;
        }
      });
    }]);
};
<|endoftext|>


<commit_before>'use strict';
const Confidence = require('confidence');
const Config = require('./config.js');

const criteria = {
    env: process.env.NODE_ENV
};

const manifest = {
    $meta: 'This file defines the plot device.',
    server: {
        debug: {
            request: ['error']
        },
        connections: {
            routes: {
                security: true
            }
        }
    },
    connections: [{
        port: Config.get('/port/web'),
        labels: ['web'],
        state: {
            isHttpOnly: false,
            isSecure: {
                $filter: 'env',
                production: true,
                $default: false
            }
        }
    }],
    registrations: [
        {
            plugin: 'inert'
        },
        {
            plugin: 'hapi-auth-cookie'
        },
        {
            plugin: {
                register: 'crumb',
                options: {
                    restful: true
                }
            }
        },
        {
            plugin: 'vision'
        },
        {
            plugin: {
                register: 'visionary',
                options: {
                    engines: { jsx: 'hapi-react-views' },
                    relativeTo: __dirname,
                    path: './server/web'
                }
            }
        },/*
        {
            plugin: {
                register: 'hapi-console',
                options: {

                    // ignore /ignore/me route
                    ignore: ['/ignore/me'],

                    // show custom data about the request
                    custom: {
                        // shows custom data about auth.credentials.uid as 'uid: <>'
                        'auth.credentials.uid': true,

                        // shows a JSON.stringify version of query
                        'query': true,

                        // executes the function and uses the output where x is request.headers
                        'headers': (x) => JSON.stringify(x).replace(/"/g, '')
                    },

                    // if true it uses the full path of the key to display the data
                    // if false it uses just the last property key to display data
                    customFullLengthKey: false
                }
            }
        },*/
        {
            plugin: {
                register: 'tv',
                options: { endpoint: '/console' }
            }
        },/*
        {
            plugin: 'hapi-recaptcha'
        },
        {
            plugin: {
                register: 'hapi-mongo-models',
                options: {
                    mongodb: Config.get('/hapiMongoModels/mongodb'),
                    models: {
                        Account: './server/models/account',
                        AdminGroup: './server/models/admin-group',
                        Admin: './server/models/admin',
                        AuthAttempt: './server/models/auth-attempt',
                        Session: './server/models/session',
                        Status: './server/models/status',
                        User: './server/models/user'
                    },
                    autoIndex: Config.get('/hapiMongoModels/autoIndex')
                }
            }
        },*/
        {
            plugin: './server/auth'
        },
        {
            plugin: './server/mailer'
        },/*
        {
            plugin: './server/api/accounts',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/admin-groups',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/admins',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/auth-attempts',
            options: {
                routes: { prefix: '/api' }
            }
        },*/
        {
            plugin: './server/api/contact',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/index',
            options: {
                routes: { prefix: '/api' }
            }
        },/*
        {
            plugin: './server/api/login',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/logout',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/sessions',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/signup',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/statuses',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/users',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/web/about'
        },
        {
            plugin: './server/web/account'
        },
        {
            plugin: './server/web/admin'
        },
        {
            plugin: './server/web/contact'
        },
        {
            plugin: './server/web/home'
        },*/
        {
            plugin: './server/web/landing'
        },
        /*
        {
            plugin: './server/web/login'
        },*/
        {
            plugin: './server/web/public'
        }/*,
        {
            plugin: './server/web/signup'
        }
        */
    ]
};

const store = new Confidence.Store(manifest);

exports.get = function (key) {

    return store.get(key, criteria);
};

exports.meta = function (key) {

    return store.meta(key, criteria);
};
<commit_msg>remove crumb<commit_after>'use strict';
const Confidence = require('confidence');
const Config = require('./config.js');

const criteria = {
    env: process.env.NODE_ENV
};

const manifest = {
    $meta: 'This file defines the plot device.',
    server: {
        debug: {
            request: ['error']
        },
        connections: {
            routes: {
                security: true
            }
        }
    },
    connections: [{
        port: Config.get('/port/web'),
        labels: ['web'],
        state: {
            isHttpOnly: false,
            isSecure: {
                $filter: 'env',
                production: true,
                $default: false
            }
        }
    }],
    registrations: [
        {
            plugin: 'inert'
        },
        {
            plugin: 'hapi-auth-cookie'
        },/*
        {
            plugin: {
                register: 'crumb',
                options: {
                    restful: true
                }
            }
        },*/
        {
            plugin: 'vision'
        },
        {
            plugin: {
                register: 'visionary',
                options: {
                    engines: { jsx: 'hapi-react-views' },
                    relativeTo: __dirname,
                    path: './server/web'
                }
            }
        },/*
        {
            plugin: {
                register: 'hapi-console',
                options: {

                    // ignore /ignore/me route
                    ignore: ['/ignore/me'],

                    // show custom data about the request
                    custom: {
                        // shows custom data about auth.credentials.uid as 'uid: <>'
                        'auth.credentials.uid': true,

                        // shows a JSON.stringify version of query
                        'query': true,

                        // executes the function and uses the output where x is request.headers
                        'headers': (x) => JSON.stringify(x).replace(/"/g, '')
                    },

                    // if true it uses the full path of the key to display the data
                    // if false it uses just the last property key to display data
                    customFullLengthKey: false
                }
            }
        },*/
        {
            plugin: {
                register: 'tv',
                options: { endpoint: '/console' }
            }
        },/*
        {
            plugin: 'hapi-recaptcha'
        },
        {
            plugin: {
                register: 'hapi-mongo-models',
                options: {
                    mongodb: Config.get('/hapiMongoModels/mongodb'),
                    models: {
                        Account: './server/models/account',
                        AdminGroup: './server/models/admin-group',
                        Admin: './server/models/admin',
                        AuthAttempt: './server/models/auth-attempt',
                        Session: './server/models/session',
                        Status: './server/models/status',
                        User: './server/models/user'
                    },
                    autoIndex: Config.get('/hapiMongoModels/autoIndex')
                }
            }
        },*/
        {
            plugin: './server/auth'
        },
        {
            plugin: './server/mailer'
        },/*
        {
            plugin: './server/api/accounts',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/admin-groups',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/admins',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/auth-attempts',
            options: {
                routes: { prefix: '/api' }
            }
        },*/
        {
            plugin: './server/api/contact',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/index',
            options: {
                routes: { prefix: '/api' }
            }
        },/*
        {
            plugin: './server/api/login',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/logout',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/sessions',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/signup',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/statuses',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/api/users',
            options: {
                routes: { prefix: '/api' }
            }
        },
        {
            plugin: './server/web/about'
        },
        {
            plugin: './server/web/account'
        },
        {
            plugin: './server/web/admin'
        },
        {
            plugin: './server/web/contact'
        },
        {
            plugin: './server/web/home'
        },*/
        {
            plugin: './server/web/landing'
        },
        /*
        {
            plugin: './server/web/login'
        },*/
        {
            plugin: './server/web/public'
        }/*,
        {
            plugin: './server/web/signup'
        }
        */
    ]
};

const store = new Confidence.Store(manifest);

exports.get = function (key) {

    return store.get(key, criteria);
};

exports.meta = function (key) {

    return store.meta(key, criteria);
};
<|endoftext|>


<commit_before>Template.existing_block.rendered = function() {
  $('.preview-block').click(function() {
  	$('.existingBlockPreview').html($(this).find('.block-preview').html());
  });
}

Template.existing_block.events = {
  'click .add-existing-block': function(e) {
  	e.preventDefault();
    var page = utils.getCurrentPage();

    var label = Template[this.template].label || 'Single Block';
    //find the block by the (block)-id of the insert button
    block = Azimuth.collections.Blocks.findOne(e.target.id);
    // Attach the block to the page
    if (!page.notFound) {
      Azimuth.collections.PageBlocks.insert({page_id: page._id, block_id: block._id, label: label, zone: Session.get('block-zone'), added: Date.now()});
    }

    utils.closeModal('#existingBlockModal');
    noty({text: label + ' added to page.', type: 'success'});
  }
};

Template.existing_block.allBlocks = function() {
  return Azimuth.collections.Blocks.find();
}<commit_msg>Variable scoping for existing block<commit_after>Template.existing_block.rendered = function() {
  $('.preview-block').click(function() {
  	$('.existingBlockPreview').html($(this).find('.block-preview').html());
  });
}

Template.existing_block.events = {
  'click .add-existing-block': function(e) {
  	e.preventDefault();
    var page = utils.getCurrentPage();

    var label = Template[this.template].label || 'Single Block';
    //find the block by the (block)-id of the insert button
    var block = Azimuth.collections.Blocks.findOne(e.target.id);
    // Attach the block to the page
    if (!page.notFound) {
      Azimuth.collections.PageBlocks.insert({page_id: page._id, block_id: block._id, label: label, zone: Session.get('block-zone'), added: Date.now()});
    }

    utils.closeModal('#existingBlockModal');
    noty({text: label + ' added to page.', type: 'success'});
  }
};

Template.existing_block.allBlocks = function() {
  return Azimuth.collections.Blocks.find();
}<|endoftext|>


<commit_before>/* Initialization of the change_form page - this script is run once everything is ready. */

$(function() {
    // Hide form rows containing only hidden inputs
    $('.form-row').each(function() {
        if (!$('p, label, select, input:not([type=hidden])', this).length) {
            $(this).hide();
        }
    });

    // Focus the title
    $('#id_title').focus();

    // Automatically update the slug when typing the title
    var slug_auto = true;
    var slug = $("#id_slug").change(function() {
        slug_auto && (slug_auto = false);
    });
    $("#id_title").keyup(function() {
        slug_auto && slug.val(URLify(this.value, 64));
    });

    // Set the publication status
    var select = $('#id_status');
    var opt = ({ 0: 'draft', 1: 'published', 2: 'expired', 3: 'hidden' })[select.val()];
    var img = $('').insertAfter(select);
    // disable ajax post if page not already created (add view)
    var change_status = (typeof(add_form) !== 'undefined' && add_form) ? 0 : 1;

    select.change(function(e) {
        pages.update_published_icon('', select, img, change_status);
    });

    // Translation helper
    $('#translation-helper-select').change(function() {
        var index = this.selectedIndex;
        if (index) {
            $.get(window.location.href.split('?')[0]+'traduction/'+this.options[index].value+'/', function(html) {
                $('#translation-helper-content').html(html).show();
            });
        } else {
            $('#translation-helper-content').hide();
        }
    });

    // Confirm language and template change if page is not saved
    // this code doesn't work with languages
    $.each(['language', 'template'], function(i, label) {
        var select = $('#id_'+label);
        if (select.length) {
            var orig_ = select.val();
            select.change(function() {
                if(confirm(gettext('You will loose any changes you have done to the page. Are you sure?')))
                    $('input[name=_continue]').click();
            });
        };
    });

    // Disable the page content if the page is a redirection
    /*
    // To fix if we use placeholder in templates for META or extra content

    var redirect = $('#id_redirect_to').change(update_redirect);
    var affected = $('.form-row:has(#id_language), .form-row:has(#id_template), .module-content .form-row')
        .css('position', 'relative');
    var overlay = $('

').css({
            'display': 'none',
            'position': 'absolute',
            'z-index': '1000',
            'top': '0',
            'left': '0',
            'height': '100%',
            'width': '100%',
            'opacity': '0.66',
            'background': 'white'
        }).appendTo(affected);
    function update_redirect() {
        redirect.val() ? overlay.show() : overlay.hide();
    }
    update_redirect();
    */

    // Content revision selector
    $('.revisions').change(function () {
        var select = $(this);
        var val = select.val();
        if (val) {
            $.get(val, function (html) {
                var formrow = select.closest('.form-row');
                if ($('a.disable', formrow).length) {
                    $('iframe', formrow)[0].contentWindow.document.getElementsByTagName("body")[0].innerHTML = html;
                } else {
                	// support for TextInput
                	$('input', formrow).val(html);
                	// support for TextArea
                    var formrow_textarea = $('textarea', formrow).val(html);
                    // support for WYMeditor
                    if (window.WYMeditor !== undefined) {
                        $(WYMeditor.INSTANCES).each(function (i, wym) {
                            if (formrow_textarea.attr('id') === wym._element.attr('id')) {
                                wym.html(html);
                            }
                        });
                    }
                    // support for TinyMCE
                    if (window.tinyMCE !== undefined) {
                    	var editor = tinyMCE.get(formrow_textarea.attr('id'));
                    	if (editor !== undefined) {
                    		editor.setContent(html);
                    	}
                    }
                }
            });
        }
        return false;
    });

    $('.js-confirm-delete').click(function() {
        return confirm(gettext('Are you sure you want to delete this content?'));
    });
});
<commit_msg>Fix a typo<commit_after>/* Initialization of the change_form page - this script is run once everything is ready. */

$(function() {
    // Hide form rows containing only hidden inputs
    $('.form-row').each(function() {
        if (!$('p, label, select, input:not([type=hidden])', this).length) {
            $(this).hide();
        }
    });

    // Focus the title
    $('#id_title').focus();

    // Automatically update the slug when typing the title
    var slug_auto = true;
    var slug = $("#id_slug").change(function() {
        slug_auto && (slug_auto = false);
    });
    $("#id_title").keyup(function() {
        slug_auto && slug.val(URLify(this.value, 64));
    });

    // Set the publication status
    var select = $('#id_status');
    var opt = ({ 0: 'draft', 1: 'published', 2: 'expired', 3: 'hidden' })[select.val()];
    var img = $('').insertAfter(select);
    // disable ajax post if page not already created (add view)
    var change_status = (typeof(add_form) !== 'undefined' && add_form) ? 0 : 1;

    select.change(function(e) {
        pages.update_published_icon('', select, img, change_status);
    });

    // Translation helper
    $('#translation-helper-select').change(function() {
        var index = this.selectedIndex;
        if (index) {
            $.get(window.location.href.split('?')[0]+'traduction/'+this.options[index].value+'/', function(html) {
                $('#translation-helper-content').html(html).show();
            });
        } else {
            $('#translation-helper-content').hide();
        }
    });

    // Confirm language and template change if page is not saved
    // this code doesn't work with languages
    $.each(['language', 'template'], function(i, label) {
        var select = $('#id_'+label);
        if (select.length) {
            var orig_ = select.val();
            select.change(function() {
                if(confirm(gettext('You may lose any changes you have done to the page. Are you sure?')))
                    $('input[name=_continue]').click();
            });
        };
    });

    // Disable the page content if the page is a redirection
    /*
    // To fix if we use placeholder in templates for META or extra content

    var redirect = $('#id_redirect_to').change(update_redirect);
    var affected = $('.form-row:has(#id_language), .form-row:has(#id_template), .module-content .form-row')
        .css('position', 'relative');
    var overlay = $('

').css({
            'display': 'none',
            'position': 'absolute',
            'z-index': '1000',
            'top': '0',
            'left': '0',
            'height': '100%',
            'width': '100%',
            'opacity': '0.66',
            'background': 'white'
        }).appendTo(affected);
    function update_redirect() {
        redirect.val() ? overlay.show() : overlay.hide();
    }
    update_redirect();
    */

    // Content revision selector
    $('.revisions').change(function () {
        var select = $(this);
        var val = select.val();
        if (val) {
            $.get(val, function (html) {
                var formrow = select.closest('.form-row');
                if ($('a.disable', formrow).length) {
                    $('iframe', formrow)[0].contentWindow.document.getElementsByTagName("body")[0].innerHTML = html;
                } else {
                	// support for TextInput
                	$('input', formrow).val(html);
                	// support for TextArea
                    var formrow_textarea = $('textarea', formrow).val(html);
                    // support for WYMeditor
                    if (window.WYMeditor !== undefined) {
                        $(WYMeditor.INSTANCES).each(function (i, wym) {
                            if (formrow_textarea.attr('id') === wym._element.attr('id')) {
                                wym.html(html);
                            }
                        });
                    }
                    // support for TinyMCE
                    if (window.tinyMCE !== undefined) {
                    	var editor = tinyMCE.get(formrow_textarea.attr('id'));
                    	if (editor !== undefined) {
                    		editor.setContent(html);
                    	}
                    }
                }
            });
        }
        return false;
    });

    $('.js-confirm-delete').click(function() {
        return confirm(gettext('Are you sure you want to delete this content?'));
    });
});
<|endoftext|>


<commit_before>var async = require('async');
var json_rpc = require('caf_transport').json_rpc;

var hello = require('./hello/main.js');

exports.helloworld = function (test) {
    test.expect(27);
    var ca1;
    var meta = {"hello":["msg","cb"],"helloFail":["msg","cb"],
                "helloException":["msg","cb"],
                "helloDelayException":["msg","cb"],
                "getLastMessage":["cb"],"getQueueLength":["cb"]};
    hello.load(null, {name: 'ca1'}, 'ca.json', null, function(err, $) {
                   test.ifError(err);
                   test.equal(typeof($.ca1), 'object',
                              'Cannot create CA');
                   async.series([
                                    function(cb) {
                                        $.ca1.__ca_pulse__(cb);
                                    },
                                    function(cb) {
                                        test.ok($.ca1.__ca_progress__());
                                        test.equals($.ca1.__ca_getName__(),
                                                   'ca1');
                                        cb(null);
                                    },
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            test.equals(resp, 'Bye:hi');
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1', 'hello' ,
                                                           'hi');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            console.log(JSON.stringify(resp));
                                            test.deepEqual(meta, resp);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1',
                                                           '__external_ca_touch__');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },

                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyError(data);
                                            console.log(JSON.stringify(resp));
                                            test.ok(resp.stack);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1', 'helloFail' ,
                                                           'ignore');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // no state change
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            test.equals(resp, 'hi');
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                           .systemRequest('ca1',
                                                          'getLastMessage');

                                       $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // exception thrown
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc
                                                .getSystemErrorCode(data);
                                            console.log(JSON.stringify(resp));
                                            test.equals(resp,
                                                        json_rpc.ERROR_CODES.
                                                        exceptionThrown);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1',
                                                           'helloException' ,
                                                           'ignore');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // no state change
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            test.equals(resp, 'hi');
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                           .systemRequest('ca1',
                                                          'getLastMessage');

                                       $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // exception thrown background
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc
                                                .getSystemErrorCode(data);
                                            console.log(JSON.stringify(resp));
                                            test.equals(resp,
                                                        json_rpc.ERROR_CODES.
                                                        exceptionThrown);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1',
                                                           'helloDelayException' ,
                                                           'ignore');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // no state change
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            test.equals(resp, 'hi');
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                           .systemRequest('ca1',
                                                          'getLastMessage');

                                       $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // queue
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc
                                                .getAppReplyData(data);
                                            console.log(JSON.stringify(resp));
                                            test.equals(resp, 0);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1',
                                                           'getQueueLength');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    //destroy
                                    function(cb) {
                                        ca1 = $.ca1;
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            test.ok(ca1.__ca_isShutdown__);
                                            cb(null);
                                        };
                                        $.ca1.__ca_destroy__(null, cb1);
                                    },
                                    // fail on shutdown
                                     function(cb) {
                                         var cb1 = function(err, data) {
                                             test.ifError(err);
                                             var resp =
                                                 json_rpc
                                                 .getSystemErrorCode(data);
                                             console.log(JSON.stringify(resp));
                                             test.equals(resp,
                                                         json_rpc.ERROR_CODES.
                                                         shutdownCA);
                                             cb(null);
                                         };
                                         var msg = json_rpc
                                             .systemRequest('ca1',
                                                            'getQueueLength');

                                         ca1.__ca_process__(msg, cb1);
                                     }

                                ], function(err, res) {
                                    test.ifError(err);
                                    test.done();
                                });
                  });
};
<commit_msg>Fix test'<commit_after>var async = require('async');
var json_rpc = require('caf_transport').json_rpc;

var hello = require('./hello/main.js');

exports.helloworld = function (test) {
    test.expect(27);
    var ca1;
    var meta = {"hello":["msg","cb"],"helloFail":["msg","cb"],
                "helloException":["msg","cb"],
                "helloDelayException":["msg","cb"],
                "getLastMessage":["cb"],"getQueueLength":["cb"],
                "__external_ca_touch__": [ 'cb' ]};
    hello.load(null, {name: 'ca1'}, 'ca.json', null, function(err, $) {
                   test.ifError(err);
                   test.equal(typeof($.ca1), 'object',
                              'Cannot create CA');
                   async.series([
                                    function(cb) {
                                        $.ca1.__ca_pulse__(cb);
                                    },
                                    function(cb) {
                                        test.ok($.ca1.__ca_progress__());
                                        test.equals($.ca1.__ca_getName__(),
                                                   'ca1');
                                        cb(null);
                                    },
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            test.equals(resp, 'Bye:hi');
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1', 'hello' ,
                                                           'hi');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            console.log(JSON.stringify(resp));
                                            test.deepEqual(meta, resp);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1',
                                                           '__external_ca_touch__');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },

                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyError(data);
                                            console.log(JSON.stringify(resp));
                                            test.ok(resp.stack);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1', 'helloFail' ,
                                                           'ignore');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // no state change
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            test.equals(resp, 'hi');
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                           .systemRequest('ca1',
                                                          'getLastMessage');

                                       $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // exception thrown
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc
                                                .getSystemErrorCode(data);
                                            console.log(JSON.stringify(resp));
                                            test.equals(resp,
                                                        json_rpc.ERROR_CODES.
                                                        exceptionThrown);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1',
                                                           'helloException' ,
                                                           'ignore');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // no state change
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            test.equals(resp, 'hi');
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                           .systemRequest('ca1',
                                                          'getLastMessage');

                                       $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // exception thrown background
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc
                                                .getSystemErrorCode(data);
                                            console.log(JSON.stringify(resp));
                                            test.equals(resp,
                                                        json_rpc.ERROR_CODES.
                                                        exceptionThrown);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1',
                                                           'helloDelayException' ,
                                                           'ignore');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // no state change
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc.getAppReplyData(data);
                                            test.equals(resp, 'hi');
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                           .systemRequest('ca1',
                                                          'getLastMessage');

                                       $.ca1.__ca_process__(msg, cb1);
                                    },
                                    // queue
                                    function(cb) {
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            var resp =
                                                json_rpc
                                                .getAppReplyData(data);
                                            console.log(JSON.stringify(resp));
                                            test.equals(resp, 0);
                                            cb(null);
                                        };
                                        var msg = json_rpc
                                            .systemRequest('ca1',
                                                           'getQueueLength');

                                        $.ca1.__ca_process__(msg, cb1);
                                    },
                                    //destroy
                                    function(cb) {
                                        ca1 = $.ca1;
                                        var cb1 = function(err, data) {
                                            test.ifError(err);
                                            test.ok(ca1.__ca_isShutdown__);
                                            cb(null);
                                        };
                                        $.ca1.__ca_destroy__(null, cb1);
                                    },
                                    // fail on shutdown
                                     function(cb) {
                                         var cb1 = function(err, data) {
                                             test.ifError(err);
                                             var resp =
                                                 json_rpc
                                                 .getSystemErrorCode(data);
                                             console.log(JSON.stringify(resp));
                                             test.equals(resp,
                                                         json_rpc.ERROR_CODES.
                                                         shutdownCA);
                                             cb(null);
                                         };
                                         var msg = json_rpc
                                             .systemRequest('ca1',
                                                            'getQueueLength');

                                         ca1.__ca_process__(msg, cb1);
                                     }

                                ], function(err, res) {
                                    test.ifError(err);
                                    test.done();
                                });
                  });
};
<|endoftext|>


<commit_before>import { Component, PropTypes } from "react";
import ReactMixin from "react-mixin";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import SwipeViews from "react-swipe-views";
import Meta from "../../components/meta";

import Loading from "../../components/loading";

import Likeable from "../../mixins/mixins.Likeable";
import Shareable from "../../mixins/mixins.Shareable";

import {
  nav as navActions,
  header as headerActions,
  live as liveActions,
} from "../../store";

// can we use the core toggle here? Is it ready @jbaxleyiii?
import DevotionsSingleContent from "./devotions.SingleContent";
import DevotionsSingleScripture from "./devotions.SingleScripture";

const DEVOTIONAL_QUERY = gql`
  query getDevotional($id: ID!) {
    content: node(id: $id) {
      id
      ... on Content {
        entryId: id
        title
        status
        channelName
        meta {
          urlTitle
          siteId
          date
          channelId
        }
        content {
          body
          tags
          scripture {
            book
            passage
          }
          images(sizes: ["large"]) {
            fileName
            fileType
            fileLabel
            url
          }
        }
      }
    }
  }
`;

const withDevotional = graphql(DEVOTIONAL_QUERY, {
  name: "devotion",
  options: ownProps => ({
    variables: { id: ownProps.params.id },
  }),
});

const mapStateToProps = state => ({
  modal: { visible: state.modal.visible },
  live: state.live,
});

@connect(mapStateToProps)
@withDevotional
@ReactMixin.decorate(Likeable)
@ReactMixin.decorate(Shareable)
export default class SeriesSingle extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    live: PropTypes.object.isRequired,
    devotion: PropTypes.object.isRequired,
  }

  state = { selectedIndex: 0 }

  componentWillMount() {
    if (process.env.WEB) return;

    // hide the live bar and then bring it back
    // after the view has faded in. this prevents
    // an issue with the z-index and the arrow
    // from the header.
    this.props.dispatch(liveActions.hide());
    // for cached data
    this.handleLiveBar(this.props, this.state);

    this.props.dispatch(navActions.setLevel("CONTENT"));
    this.props.dispatch(navActions.setAction("CONTENT", {
      id: 2,
      action: this.likeableAction,
    }));

    this.props.dispatch(headerActions.set({}));
    this.props.dispatch(headerActions.hide());
  }

  componentWillUpdate(nextProps, nextState) {
    this.handleLiveBar(nextProps, nextState);
  }

  componentWillUnmount() {
    if (process.env.WEB) return;
    this.props.dispatch(liveActions.unfloat());
  }

  onClickLink = (event) => {
    event.preventDefault();
    this.setState({
      selectedIndex: 1,
      liveSet: false,
      livePush: false,
    });
  }

  getLiveClasses = () => {
    const classes = [];
    if (this.props.live.live && this.state.livePush) {
      classes.push("push-double-top");
    }

    return classes;
  }

  // if has scripture and live re-enabled
  // the live bar
  // else apply float styles to the bar so it
  // will display below the fixed header
  handleLiveBar = (props, state) => {
    const { liveSet } = state;
    const { content } = props.devotion;
    const { live } = props.live;

    if (liveSet || !live || !content) return;

    this.setState({
      liveSet: true,
    });

    if (content.content.scripture) {
      this.props.dispatch(liveActions.float());
      setTimeout(() => {
        this.setState({
          livePush: true,
        });
        this.props.dispatch(liveActions.show());
      }, 1000);
    } else {
      setTimeout(() => {
        this.props.dispatch(liveActions.show());
      }, 1000);
    }
  }

  renderContent = (devotion) => {
    if (!devotion.content.scripture) {
      return (

          <DevotionsSingleContent
            devotion={devotion}
            onClickLink={this.onClickLink}
            classes={this.getLiveClasses()}
          />

      );
    }

    return (
      <SwipeViews
        selectedIndex={this.state.selectedIndex}
        disableSwipe
      >

          <DevotionsSingleContent
            devotion={devotion}
            onClickLink={this.onClickLink}
            classes={this.getLiveClasses()}
          />

          <DevotionsSingleScripture
            devotion={devotion}
            classes={this.getLiveClasses()}
          />

      </SwipeViews>
    );
  }

  render() {
    const { content } = this.props.devotion;
    if (!content) {
      return (

            <Loading />

      );
    }

    const devotion = content;
    return (

        <Meta
          title={devotion.title}
          id={devotion.id}
          image={
              devotion.content.images && devotion.content.images.length > 0
                ? devotion.content.images[0].url
                : null
          }
          meta={[
            { property: "og:type", content: "article" },
          ]}
        />
        {this.renderContent(devotion)}

    );
  }

}
<commit_msg>Closes 1331, fixing devotional bounce<commit_after>import { Component, PropTypes } from "react";
import ReactMixin from "react-mixin";
import { connect } from "react-redux";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import SwipeViews from "react-swipe-views";
import Meta from "../../components/meta";

import Loading from "../../components/loading";

import Likeable from "../../mixins/mixins.Likeable";
import Shareable from "../../mixins/mixins.Shareable";

import {
  nav as navActions,
  header as headerActions,
  live as liveActions,
} from "../../store";

// can we use the core toggle here? Is it ready @jbaxleyiii?
import DevotionsSingleContent from "./devotions.SingleContent";
import DevotionsSingleScripture from "./devotions.SingleScripture";

const DEVOTIONAL_QUERY = gql`
  query getDevotional($id: ID!) {
    content: node(id: $id) {
      id
      ... on Content {
        entryId: id
        title
        status
        channelName
        meta {
          urlTitle
          siteId
          date
          channelId
        }
        content {
          body
          tags
          scripture {
            book
            passage
          }
          images(sizes: ["large"]) {
            fileName
            fileType
            fileLabel
            url
          }
        }
      }
    }
  }
`;

const withDevotional = graphql(DEVOTIONAL_QUERY, {
  name: "devotion",
  options: ownProps => ({
    variables: { id: ownProps.params.id },
  }),
});

const mapStateToProps = state => ({
  modal: { visible: state.modal.visible },
  live: state.live,
});

@connect(mapStateToProps)
@withDevotional
@ReactMixin.decorate(Likeable)
@ReactMixin.decorate(Shareable)
export default class SeriesSingle extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    live: PropTypes.object.isRequired,
    devotion: PropTypes.object.isRequired,
  }

  state = { selectedIndex: 0 }

  componentWillMount() {
    if (process.env.WEB) return;

    // hide the live bar and then bring it back
    // after the view has faded in. this prevents
    // an issue with the z-index and the arrow
    // from the header.
    this.props.dispatch(liveActions.hide());
    // for cached data
    this.handleLiveBar(this.props, this.state);

    this.props.dispatch(navActions.setLevel("CONTENT"));
    this.props.dispatch(navActions.setAction("CONTENT", {
      id: 2,
      action: this.likeableAction,
    }));

    this.props.dispatch(headerActions.set({}));
    this.props.dispatch(headerActions.hide());
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.state.selectedIndex !== nextState.selectedIndex) return true;
    if (nextProps.devotion.content && this.props.devotion.content) {
      if (nextProps.devotion.content.id === this.props.devotion.content.id) return false;
      return true;
    }
    return true;
  }

  componentWillUpdate(nextProps, nextState) {
    this.handleLiveBar(nextProps, nextState);
  }

  componentWillUnmount() {
    if (process.env.WEB) return;
    this.props.dispatch(liveActions.unfloat());
  }

  onClickLink = (event) => {
    event.preventDefault();
    this.setState({
      selectedIndex: 1,
      liveSet: false,
      livePush: false,
    });
  }

  getLiveClasses = () => {
    const classes = [];
    if (this.props.live.live && this.state.livePush) {
      classes.push("push-double-top");
    }

    return classes;
  }

  // if has scripture and live re-enabled
  // the live bar
  // else apply float styles to the bar so it
  // will display below the fixed header
  handleLiveBar = (props, state) => {
    const { liveSet } = state;
    const { content } = props.devotion;
    const { live } = props.live;

    if (liveSet || !live || !content) return;

    this.setState({
      liveSet: true,
    });

    if (content.content.scripture) {
      this.props.dispatch(liveActions.float());
      setTimeout(() => {
        this.setState({
          livePush: true,
        });
        this.props.dispatch(liveActions.show());
      }, 1000);
    } else {
      setTimeout(() => {
        this.props.dispatch(liveActions.show());
      }, 1000);
    }
  }

  renderContent = (devotion) => {
    if (!devotion.content.scripture) {
      return (

          <DevotionsSingleContent
            devotion={devotion}
            onClickLink={this.onClickLink}
            classes={this.getLiveClasses()}
          />

      );
    }

    return (
      <SwipeViews
        selectedIndex={this.state.selectedIndex}
        disableSwipe
      >

          <DevotionsSingleContent
            devotion={devotion}
            onClickLink={this.onClickLink}
            classes={this.getLiveClasses()}
          />

          <DevotionsSingleScripture
            devotion={devotion}
            classes={this.getLiveClasses()}
          />

      </SwipeViews>
    );
  }

  render() {
    const { content } = this.props.devotion;
    if (!content) {
      return (

            <Loading />

      );
    }

    const devotion = content;
    return (

        <Meta
          title={devotion.title}
          id={devotion.id}
          image={
              devotion.content.images && devotion.content.images.length > 0
                ? devotion.content.images[0].url
                : null
          }
          meta={[
            { property: "og:type", content: "article" },
          ]}
        />
        {this.renderContent(devotion)}

    );
  }

}
<|endoftext|>


<commit_before>/*eslint no-console:0 */
const request = require('request');
const monk = require('monk');
const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');

const CardService = require('../services/CardService.js');

function apiRequest(path) {
    const apiUrl = 'https://api.fiveringsdb.com/';

    return new Promise((resolve, reject) => {
        request.get(apiUrl + path, function(error, res, body) {
            if(error) {
                return reject(error);
            }

            resolve(JSON.parse(body));
        });
    });
}

function fetchImage(url, id, imagePath, timeout) {
    setTimeout(function() {
        console.log('Downloading image for ' + id);
        request(url).pipe(fs.createWriteStream(imagePath));
    }, timeout);
}

let db = monk('mongodb://127.0.0.1:27017/ringteki');
let cardService = new CardService(db);

let fetchCards = apiRequest('cards')
    .then(cards => cardService.replaceCards(cards.records))
    .then(cards => {
        console.info(cards.length + ' cards fetched');

        let imageDir = path.join(__dirname, '..', '..', 'public', 'img', 'cards');
        mkdirp(imageDir);

        var i = 0;

        cards.forEach(function(card) {
            var imagePath = path.join(imageDir, card.id + '.jpg');

            if(card.pack_cards.length > 0 && card.pack_cards[0].image_url) {
                var imagesrc = card.pack_cards[0].image_url;

                if(imagesrc && !fs.existsSync(imagePath)) {
                    fetchImage(imagesrc, card.id, imagePath, i++ * 200);
                }
            }
        });

        return cards;
    })
    .catch(() => {
        console.error('Unable to fetch cards');
    });

let fetchPacks = apiRequest('packs')
    .then(packs => cardService.replacePacks(packs.records))
    .then(packs => {
        console.info(packs.length + ' packs fetched');
    })
    .catch(() => {
        console.error('Unable to fetch packs');
    });

Promise.all([fetchCards, fetchPacks])
    .then(() => db.close())
    .catch(() => db.close());

<commit_msg>Fix fetch script (promo cards) (#2220)<commit_after>/*eslint no-console:0 */
const request = require('request');
const monk = require('monk');
const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');

const CardService = require('../services/CardService.js');

function apiRequest(path) {
    const apiUrl = 'https://api.fiveringsdb.com/';

    return new Promise((resolve, reject) => {
        request.get(apiUrl + path, function(error, res, body) {
            if(error) {
                return reject(error);
            }

            resolve(JSON.parse(body));
        });
    });
}

function fetchImage(url, id, imagePath, timeout) {
    setTimeout(function() {
        console.log('Downloading image for ' + id);
        request(url).pipe(fs.createWriteStream(imagePath));
    }, timeout);
}

let db = monk('mongodb://127.0.0.1:27017/ringteki');
let cardService = new CardService(db);

let fetchCards = apiRequest('cards')
    .then(cards => cardService.replaceCards(cards.records))
    .then(cards => {
        console.info(cards.length + ' cards fetched');

        let imageDir = path.join(__dirname, '..', '..', 'public', 'img', 'cards');
        mkdirp(imageDir);

        var i = 0;

        cards.forEach(function(card) {
            var imagePath = path.join(imageDir, card.id + '.jpg');
            let imagesrc;

            if(card.pack_cards.length === 1 && card.pack_cards[0].image_url) {
                imagesrc = card.pack_cards[0].image_url;

                if(imagesrc && !fs.existsSync(imagePath)) {
                    fetchImage(imagesrc, card.id, imagePath, i++ * 200);
                }
            }

	    if(card.pack_cards.length === 2 && card.pack_cards[1].image_url) {
                imagesrc = card.pack_cards[1].image_url;

                if(imagesrc && !fs.existsSync(imagePath)) {
                    fetchImage(imagesrc, card.id, imagePath, i++ * 200);
                }
            }
        });

        return cards;
    })
    .catch(() => {
        console.error('Unable to fetch cards');
    });

let fetchPacks = apiRequest('packs')
    .then(packs => cardService.replacePacks(packs.records))
    .then(packs => {
        console.info(packs.length + ' packs fetched');
    })
    .catch(() => {
        console.error('Unable to fetch packs');
    });

Promise.all([fetchCards, fetchPacks])
    .then(() => db.close())
    .catch(() => db.close());

<|endoftext|>


<commit_before>var util2 = require('util2');
var myutil = require('myutil');
var Emitter = require('emitter');
var Platform = require('platform');
var WindowStack = require('ui/windowstack');
var Window = require('ui/window');
var simply = require('ui/simply');

var defaults = {
  backgroundColor: 'white',
  textColor: 'black',
  highlightBackgroundColor: 'black',
  highlightTextColor: 'white',
  fullscreen: false,
};

var Menu = function(menuDef) {
  Window.call(this, myutil.shadow(defaults, menuDef || {}));
  this._dynamic = false;
  this._sections = {};
  this._selection = { sectionIndex: 0, itemIndex: 0 };
  this._selections = [];
};

Menu._codeName = 'menu';

util2.inherit(Menu, Window);

util2.copy(Emitter.prototype, Menu.prototype);

Menu.prototype._show = function() {
  Window.prototype._show.apply(this, arguments);
  this._select();
};

Menu.prototype._select = function() {
  if (this === WindowStack.top()) {
    var select = this._selection;
    simply.impl.menuSelection(select.sectionIndex, select.itemIndex);
  }
};

Menu.prototype._numPreloadItems = (Platform.version() === 'aplite' ? 5 : 50);

Menu.prototype._prop = function(state, clear, pushing) {
  if (this === WindowStack.top()) {
    this._resolveMenu(clear, pushing);
    this._resolveSection(this._selection);
  }
};

Menu.prototype.action = function() {
  throw new Error("Menus don't support action bars.");
};

Menu.prototype.buttonConfig = function() {
  throw new Error("Menus don't support changing button configurations.");
};

Menu.prototype._buttonAutoConfig = function() {};

Menu.prototype._getMetaSection = function(sectionIndex) {
  return (this._sections[sectionIndex] || ( this._sections[sectionIndex] = {} ));
};

Menu.prototype._getSections = function() {
  var sections = this.state.sections;
  if (sections instanceof Array) {
    return sections;
  }
  if (typeof sections === 'number') {
    sections = new Array(sections);
    return (this.state.sections = sections);
  }
  if (typeof sections === 'function') {
    this.sectionsProvider = this.state.sections;
    delete this.state.sections;
  }
  if (this.sectionsProvider) {
    sections = this.sectionsProvider.call(this);
    if (sections) {
      this.state.sections = sections;
      return this._getSections();
    }
  }
  return (this.state.sections = []);
};

Menu.prototype._getSection = function(e, create) {
  var sections = this._getSections();
  var section = sections[e.sectionIndex];
  if (section) {
    return section;
  }
  if (this.sectionProvider) {
    section = this.sectionProvider.call(this, e);
    if (section) {
      return (sections[e.sectionIndex] = section);
    }
  }
  if (!create) { return; }
  return (sections[e.sectionIndex] = {});
};

Menu.prototype._getItems = function(e, create) {
  var section = this._getSection(e, create);
  if (!section) {
    if (e.sectionIndex > 0) { return; }
    section = this.state.sections[0] = {};
  }
  if (section.items instanceof Array) {
    return section.items;
  }
  if (typeof section.items === 'number') {
    return (section.items = new Array(section.items));
  }
  if (typeof section.items === 'function') {
    this._sections[e.sectionIndex] = section.items;
    delete section.items;
  }
  var itemsProvider = this._getMetaSection(e.sectionIndex).items || this.itemsProvider;
  if (itemsProvider) {
    var items = itemsProvider.call(this, e);
    if (items) {
      section.items = items;
      return this._getItems(e, create);
    }
  }
  return (section.items = []);
};

Menu.prototype._getItem = function(e, create) {
  var items = this._getItems(e, create);
  var item = items[e.itemIndex];
  if (item) {
    return item;
  }
  var itemProvider = this._getMetaSection(e.sectionIndex).item || this.itemProvider;
  if (itemProvider) {
    item = itemProvider.call(this, e);
    if (item) {
      return (items[e.itemIndex] = item);
    }
  }
  if (!create) { return; }
  return (items[e.itemIndex] = {});
};

Menu.prototype._resolveMenu = function(clear, pushing) {
  var sections = this._getSections(this);
  if (this === WindowStack.top()) {
    simply.impl.menu(this.state, clear, pushing);
    return true;
  }
};

Menu.prototype._resolveSection = function(e, clear) {
  var section = this._getSection(e);
  if (!section) { return; }
  section.items = this._getItems(e);
  if (this === WindowStack.top()) {
    simply.impl.menuSection.call(this, e.sectionIndex, section, clear);
    var select = this._selection;
    if (select.sectionIndex === e.sectionIndex) {
      this._preloadItems(select);
    }
    return true;
  }
};

Menu.prototype._resolveItem = function(e) {
  var item = this._getItem(e);
  if (!item) { return; }
  if (this === WindowStack.top()) {
    simply.impl.menuItem.call(this, e.sectionIndex, e.itemIndex, item);
    return true;
  }
};

Menu.prototype._preloadItems = function(e) {
  var select = util2.copy(e);
  select.itemIndex = Math.max(0, select.itemIndex - Math.floor(this._numPreloadItems / 2));
  for (var i = 0; i < this._numPreloadItems; ++i) {
    this._resolveItem(select);
    select.itemIndex++;
  }
};

Menu.prototype._emitSelect = function(e) {
  this._selection = e;
  var item = this._getItem(e);
  switch (e.type) {
    case 'select':
      if (item && typeof item.select === 'function') {
        if (item.select(e) === false) {
          return false;
        }
      }
      break;
    case 'longSelect':
      if (item && typeof item.longSelect === 'function') {
        if (item.longSelect(e) === false) {
          return false;
        }
      }
      break;
    case 'selection':
      var handlers = this._selections;
      this._selections = [];
      if (item && typeof item.selected === 'function') {
        if (item.selected(e) === false) {
          return false;
        }
      }
      for (var i = 0, ii = handlers.length; i < ii; ++i) {
        if (handlers[i](e) === false) {
          break;
        }
      }
      break;
  }
};

Menu.prototype.sections = function(sections) {
  if (typeof sections === 'function') {
    delete this.state.sections;
    this.sectionsProvider = sections;
    this._resolveMenu();
    return this;
  }
  this.state.sections = sections;
  this._resolveMenu();
  return this;
};

Menu.prototype.section = function(sectionIndex, section) {
  if (typeof sectionIndex === 'object') {
    sectionIndex = sectionIndex.sectionIndex || 0;
  } else if (typeof sectionIndex === 'function') {
    this.sectionProvider = sectionIndex;
    return this;
  }
  var menuIndex = { sectionIndex: sectionIndex };
  if (!section) {
    return this._getSection(menuIndex);
  }
  var sections = this._getSections();
  var prevLength = sections.length;
  sections[sectionIndex] = util2.copy(section, sections[sectionIndex]);
  if (sections.length !== prevLength) {
    this._resolveMenu();
  }
  this._resolveSection(menuIndex, typeof section.items !== 'undefined');
  return this;
};

Menu.prototype.items = function(sectionIndex, items) {
  if (typeof sectionIndex === 'object') {
    sectionIndex = sectionIndex.sectionIndex || 0;
  } else if (typeof sectionIndex === 'function') {
    this.itemsProvider = sectionIndex;
    return this;
  }
  if (typeof items === 'function') {
    this._getMetaSection(sectionIndex).items = items;
    return this;
  }
  var menuIndex = { sectionIndex: sectionIndex };
  if (!items) {
    return this._getItems(menuIndex);
  }
  var section = this._getSection(menuIndex, true);
  section.items = items;
  this._resolveSection(menuIndex, true);
  return this;
};

Menu.prototype.item = function(sectionIndex, itemIndex, item) {
  if (typeof sectionIndex === 'object') {
    item = itemIndex || item;
    itemIndex = sectionIndex.itemIndex;
    sectionIndex = sectionIndex.sectionIndex || 0;
  } else if (typeof sectionIndex === 'function') {
    this.itemProvider = sectionIndex;
    return this;
  }
  if (typeof itemIndex === 'function') {
    item = itemIndex;
    itemIndex = null;
  }
  if (typeof item === 'function') {
    this._getMetaSection(sectionIndex).item = item;
    return this;
  }
  var menuIndex = { sectionIndex: sectionIndex, itemIndex: itemIndex };
  if (!item) {
    return this._getItem(menuIndex);
  }
  var items = this._getItems(menuIndex, true);
  var prevLength = items.length;
  items[itemIndex] = util2.copy(item, items[itemIndex]);
  if (items.length !== prevLength) {
    this._resolveSection(menuIndex);
  }
  this._resolveItem(menuIndex);
  return this;
};

Menu.prototype.selection = function(callback_or_sectionIndex, itemIndex) {
  if (typeof callback_or_sectionIndex === 'function') {
    this._selections.push(callback);
    simply.impl.menuSelection();
  } else {
    this._selection = {
      sectionIndex: callback_or_sectionIndex,
      itemIndex: itemIndex
    };
    this._select();
  }
};

Menu.emit = Window.emit;

Menu.emitSection = function(sectionIndex) {
  var menu = WindowStack.top();
  if (!(menu instanceof Menu)) { return; }
  var e = {
    menu: menu,
    sectionIndex: sectionIndex
  };
  e.section = menu._getSection(e);
  if (Menu.emit('section', null, e) === false) {
    return false;
  }
  menu._resolveSection(e);
};

Menu.emitItem = function(sectionIndex, itemIndex) {
  var menu = WindowStack.top();
  if (!(menu instanceof Menu)) { return; }
  var e = {
    menu: menu,
    sectionIndex: sectionIndex,
    itemIndex: itemIndex,
  };
  e.section = menu._getSection(e);
  e.item = menu._getItem(e);
  if (Menu.emit('item', null, e) === false) {
    return false;
  }
  menu._resolveItem(e);
};

Menu.emitSelect = function(type, sectionIndex, itemIndex) {
  var menu = WindowStack.top();
  if (!(menu instanceof Menu)) { return; }
  var e = {
    menu: menu,
    sectionIndex: sectionIndex,
    itemIndex: itemIndex,
  };
  e.section = menu._getSection(e);
  e.item = menu._getItem(e);
  switch (type) {
    case 'menuSelect': type = 'select'; break;
    case 'menuLongSelect': type = 'longSelect'; break;
    case 'menuSelection': type = 'selection'; break;
  }
  if (Menu.emit(type, null, e) === false) {
    return false;
  }
  menu._emitSelect(e);
};

module.exports = Menu;
<commit_msg>Fix ReferenceError when using callback.<commit_after>var util2 = require('util2');
var myutil = require('myutil');
var Emitter = require('emitter');
var Platform = require('platform');
var WindowStack = require('ui/windowstack');
var Window = require('ui/window');
var simply = require('ui/simply');

var defaults = {
  backgroundColor: 'white',
  textColor: 'black',
  highlightBackgroundColor: 'black',
  highlightTextColor: 'white',
  fullscreen: false,
};

var Menu = function(menuDef) {
  Window.call(this, myutil.shadow(defaults, menuDef || {}));
  this._dynamic = false;
  this._sections = {};
  this._selection = { sectionIndex: 0, itemIndex: 0 };
  this._selections = [];
};

Menu._codeName = 'menu';

util2.inherit(Menu, Window);

util2.copy(Emitter.prototype, Menu.prototype);

Menu.prototype._show = function() {
  Window.prototype._show.apply(this, arguments);
  this._select();
};

Menu.prototype._select = function() {
  if (this === WindowStack.top()) {
    var select = this._selection;
    simply.impl.menuSelection(select.sectionIndex, select.itemIndex);
  }
};

Menu.prototype._numPreloadItems = (Platform.version() === 'aplite' ? 5 : 50);

Menu.prototype._prop = function(state, clear, pushing) {
  if (this === WindowStack.top()) {
    this._resolveMenu(clear, pushing);
    this._resolveSection(this._selection);
  }
};

Menu.prototype.action = function() {
  throw new Error("Menus don't support action bars.");
};

Menu.prototype.buttonConfig = function() {
  throw new Error("Menus don't support changing button configurations.");
};

Menu.prototype._buttonAutoConfig = function() {};

Menu.prototype._getMetaSection = function(sectionIndex) {
  return (this._sections[sectionIndex] || ( this._sections[sectionIndex] = {} ));
};

Menu.prototype._getSections = function() {
  var sections = this.state.sections;
  if (sections instanceof Array) {
    return sections;
  }
  if (typeof sections === 'number') {
    sections = new Array(sections);
    return (this.state.sections = sections);
  }
  if (typeof sections === 'function') {
    this.sectionsProvider = this.state.sections;
    delete this.state.sections;
  }
  if (this.sectionsProvider) {
    sections = this.sectionsProvider.call(this);
    if (sections) {
      this.state.sections = sections;
      return this._getSections();
    }
  }
  return (this.state.sections = []);
};

Menu.prototype._getSection = function(e, create) {
  var sections = this._getSections();
  var section = sections[e.sectionIndex];
  if (section) {
    return section;
  }
  if (this.sectionProvider) {
    section = this.sectionProvider.call(this, e);
    if (section) {
      return (sections[e.sectionIndex] = section);
    }
  }
  if (!create) { return; }
  return (sections[e.sectionIndex] = {});
};

Menu.prototype._getItems = function(e, create) {
  var section = this._getSection(e, create);
  if (!section) {
    if (e.sectionIndex > 0) { return; }
    section = this.state.sections[0] = {};
  }
  if (section.items instanceof Array) {
    return section.items;
  }
  if (typeof section.items === 'number') {
    return (section.items = new Array(section.items));
  }
  if (typeof section.items === 'function') {
    this._sections[e.sectionIndex] = section.items;
    delete section.items;
  }
  var itemsProvider = this._getMetaSection(e.sectionIndex).items || this.itemsProvider;
  if (itemsProvider) {
    var items = itemsProvider.call(this, e);
    if (items) {
      section.items = items;
      return this._getItems(e, create);
    }
  }
  return (section.items = []);
};

Menu.prototype._getItem = function(e, create) {
  var items = this._getItems(e, create);
  var item = items[e.itemIndex];
  if (item) {
    return item;
  }
  var itemProvider = this._getMetaSection(e.sectionIndex).item || this.itemProvider;
  if (itemProvider) {
    item = itemProvider.call(this, e);
    if (item) {
      return (items[e.itemIndex] = item);
    }
  }
  if (!create) { return; }
  return (items[e.itemIndex] = {});
};

Menu.prototype._resolveMenu = function(clear, pushing) {
  var sections = this._getSections(this);
  if (this === WindowStack.top()) {
    simply.impl.menu(this.state, clear, pushing);
    return true;
  }
};

Menu.prototype._resolveSection = function(e, clear) {
  var section = this._getSection(e);
  if (!section) { return; }
  section.items = this._getItems(e);
  if (this === WindowStack.top()) {
    simply.impl.menuSection.call(this, e.sectionIndex, section, clear);
    var select = this._selection;
    if (select.sectionIndex === e.sectionIndex) {
      this._preloadItems(select);
    }
    return true;
  }
};

Menu.prototype._resolveItem = function(e) {
  var item = this._getItem(e);
  if (!item) { return; }
  if (this === WindowStack.top()) {
    simply.impl.menuItem.call(this, e.sectionIndex, e.itemIndex, item);
    return true;
  }
};

Menu.prototype._preloadItems = function(e) {
  var select = util2.copy(e);
  select.itemIndex = Math.max(0, select.itemIndex - Math.floor(this._numPreloadItems / 2));
  for (var i = 0; i < this._numPreloadItems; ++i) {
    this._resolveItem(select);
    select.itemIndex++;
  }
};

Menu.prototype._emitSelect = function(e) {
  this._selection = e;
  var item = this._getItem(e);
  switch (e.type) {
    case 'select':
      if (item && typeof item.select === 'function') {
        if (item.select(e) === false) {
          return false;
        }
      }
      break;
    case 'longSelect':
      if (item && typeof item.longSelect === 'function') {
        if (item.longSelect(e) === false) {
          return false;
        }
      }
      break;
    case 'selection':
      var handlers = this._selections;
      this._selections = [];
      if (item && typeof item.selected === 'function') {
        if (item.selected(e) === false) {
          return false;
        }
      }
      for (var i = 0, ii = handlers.length; i < ii; ++i) {
        if (handlers[i](e) === false) {
          break;
        }
      }
      break;
  }
};

Menu.prototype.sections = function(sections) {
  if (typeof sections === 'function') {
    delete this.state.sections;
    this.sectionsProvider = sections;
    this._resolveMenu();
    return this;
  }
  this.state.sections = sections;
  this._resolveMenu();
  return this;
};

Menu.prototype.section = function(sectionIndex, section) {
  if (typeof sectionIndex === 'object') {
    sectionIndex = sectionIndex.sectionIndex || 0;
  } else if (typeof sectionIndex === 'function') {
    this.sectionProvider = sectionIndex;
    return this;
  }
  var menuIndex = { sectionIndex: sectionIndex };
  if (!section) {
    return this._getSection(menuIndex);
  }
  var sections = this._getSections();
  var prevLength = sections.length;
  sections[sectionIndex] = util2.copy(section, sections[sectionIndex]);
  if (sections.length !== prevLength) {
    this._resolveMenu();
  }
  this._resolveSection(menuIndex, typeof section.items !== 'undefined');
  return this;
};

Menu.prototype.items = function(sectionIndex, items) {
  if (typeof sectionIndex === 'object') {
    sectionIndex = sectionIndex.sectionIndex || 0;
  } else if (typeof sectionIndex === 'function') {
    this.itemsProvider = sectionIndex;
    return this;
  }
  if (typeof items === 'function') {
    this._getMetaSection(sectionIndex).items = items;
    return this;
  }
  var menuIndex = { sectionIndex: sectionIndex };
  if (!items) {
    return this._getItems(menuIndex);
  }
  var section = this._getSection(menuIndex, true);
  section.items = items;
  this._resolveSection(menuIndex, true);
  return this;
};

Menu.prototype.item = function(sectionIndex, itemIndex, item) {
  if (typeof sectionIndex === 'object') {
    item = itemIndex || item;
    itemIndex = sectionIndex.itemIndex;
    sectionIndex = sectionIndex.sectionIndex || 0;
  } else if (typeof sectionIndex === 'function') {
    this.itemProvider = sectionIndex;
    return this;
  }
  if (typeof itemIndex === 'function') {
    item = itemIndex;
    itemIndex = null;
  }
  if (typeof item === 'function') {
    this._getMetaSection(sectionIndex).item = item;
    return this;
  }
  var menuIndex = { sectionIndex: sectionIndex, itemIndex: itemIndex };
  if (!item) {
    return this._getItem(menuIndex);
  }
  var items = this._getItems(menuIndex, true);
  var prevLength = items.length;
  items[itemIndex] = util2.copy(item, items[itemIndex]);
  if (items.length !== prevLength) {
    this._resolveSection(menuIndex);
  }
  this._resolveItem(menuIndex);
  return this;
};

Menu.prototype.selection = function(callback_or_sectionIndex, itemIndex) {
  if (typeof callback_or_sectionIndex === 'function') {
    this._selections.push(callback_or_sectionIndex);
    simply.impl.menuSelection();
  } else {
    this._selection = {
      sectionIndex: callback_or_sectionIndex,
      itemIndex: itemIndex
    };
    this._select();
  }
};

Menu.emit = Window.emit;

Menu.emitSection = function(sectionIndex) {
  var menu = WindowStack.top();
  if (!(menu instanceof Menu)) { return; }
  var e = {
    menu: menu,
    sectionIndex: sectionIndex
  };
  e.section = menu._getSection(e);
  if (Menu.emit('section', null, e) === false) {
    return false;
  }
  menu._resolveSection(e);
};

Menu.emitItem = function(sectionIndex, itemIndex) {
  var menu = WindowStack.top();
  if (!(menu instanceof Menu)) { return; }
  var e = {
    menu: menu,
    sectionIndex: sectionIndex,
    itemIndex: itemIndex,
  };
  e.section = menu._getSection(e);
  e.item = menu._getItem(e);
  if (Menu.emit('item', null, e) === false) {
    return false;
  }
  menu._resolveItem(e);
};

Menu.emitSelect = function(type, sectionIndex, itemIndex) {
  var menu = WindowStack.top();
  if (!(menu instanceof Menu)) { return; }
  var e = {
    menu: menu,
    sectionIndex: sectionIndex,
    itemIndex: itemIndex,
  };
  e.section = menu._getSection(e);
  e.item = menu._getItem(e);
  switch (type) {
    case 'menuSelect': type = 'select'; break;
    case 'menuLongSelect': type = 'longSelect'; break;
    case 'menuSelection': type = 'selection'; break;
  }
  if (Menu.emit(type, null, e) === false) {
    return false;
  }
  menu._emitSelect(e);
};

module.exports = Menu;
<|endoftext|>


<commit_before>import $ from 'cash-dom';
import {
	observer
} from '@ember/object';
import {
	isEmpty
} from '@ember/utils';
import {
	htmlSafe
} from '@ember/template';
import {
	next,
	schedule
} from '@ember/runloop';
import {
	alias
} from '@ember/object/computed';
import Component from '@ember/component';
import layout from '../templates/components/notification-message';
import configuration from '../configuration';
import velocity from 'velocity-animate';

export const MESSAGE_ID_ATTRIBUTE_NAME = 'data-embernotifyme-message-id';

export default Component.extend({
	classNames: ['notification-message'],
	classNameBindings: ['message.type'],
	attributeBindings: ['messageId:' + MESSAGE_ID_ATTRIBUTE_NAME],

	layout,

	message: null,
	animationDurationCss: null,
	cssAnimationPlayProperty: null,

	removeMe: false,
	closeIconHTML: null,
	messageIcon: null,
	clickable: alias('message.onClick'),

	_handleMouseEnterFn: null,
	_handleMouseLeaveFn: null,

	didInsertElement() {
		this._super(...arguments);

		this.set('messageId', `${this.message.id}-${this.message.timestamp}`);

		this.set('_handleMouseEnterFn', this.handleMouseEnter.bind(this));
		this.set('_handleMouseLeaveFn', this.handleMouseLeave.bind(this));

		this.element.addEventListener('mouseenter', this.get('_handleMouseEnterFn'));
		this.element.addEventListener('mouseleave', this.get('_handleMouseLeaveFn'));

		next(() => {

			if (this.get('isDestroyed') || this.get('isDestroying')) {
				return;
			}

			this.startCountdown();

			let message = this.get('message');
			let timeout = message.get('timeout');

			let sticky = message.get('sticky');
			if (!sticky) {
				let animationDurationCss = `animation-duration: ${timeout}ms; -webkit-animation-duration: ${timeout}ms;`;
				this.set('animationDurationCss', htmlSafe(animationDurationCss));
			}

			let messageIconSafe = message.get('icon');
			if (isEmpty(messageIconSafe)) {
				messageIconSafe = configuration.getMessageIcon(this.get('message.type'));
			}
			messageIconSafe = htmlSafe(messageIconSafe);
			this.set('messageIcon', messageIconSafe);

			this.set('closeIconHTML', configuration.getCloseIconHTML());

			if (message.get('htmlContent')) {
				message.set('message', htmlSafe(message.get('message')));
			}

		});
	},

	willDestroyElement() {
		this._super(...arguments);

		this.element.removeEventListener('mouseenter', this.get('_handleMouseEnterFn'));
		this.element.removeEventListener('mouseleave', this.get('_handleMouseLeaveFn'));

	},

	removeMeObserver: observer('message.removeMe', function() {
		if (this.get('message.removeMe') === true) {
			this.animateRemoval(() => {
				this.notifications.removeMessageFromList(this.get('message'));
			});
		}
	}),

	handleMouseEnter() {
		if (!this.get('message.sticky')) {
			this.stopCountdown();
			this.notifications.pauseMessageTimeout(this.get('message'));
		}
	},

	handleMouseLeave() {
		if (!this.get('message.sticky')) {
			this.startCountdown();
			this.notifications.startMessageTimer(this.get('message'));
		}
	},

	animateRemoval(onAnimationDone) {
		velocity(this.element, {
			scale: 1.05
		}, {
			duration: 200
		});

		velocity(this.element, {
			scale: 0
		}, {
			duration: 500,
			complete: onAnimationDone
		});
	},

	stopCountdown() {
		velocity($(this.element).find(".countdown")[0], "stop", true);
	},

	startCountdown() {
		if (this.get('message.sticky') === true) {
			return;
		}
		schedule('afterRender', this, function() {
			let $element = $(this.element);
			velocity($element.find(".countdown")[0], {
				width: $element.width()
			}, {
				duration: this.get('message.timeout'),
				easing: "linear"
			});
		});
	},

	actions: {

		messageClicked() {
			let message = this.get('message');
			let onClick = message.get('onClick');
			onClick(message);

			if (message.get('closeOnClick') === true) {
				this.notifications.removeMessage(message);
			}
		},

		messageClosed() {
			let message = this.get('message');
			let onClose = message.get('onClose');
			onClose(message);
			this.notifications.removeMessage(message);
		}

	}
});
<commit_msg>fixed animation issue<commit_after>import $ from 'cash-dom';
import {
	observer
} from '@ember/object';
import {
	isEmpty
} from '@ember/utils';
import {
	htmlSafe
} from '@ember/template';
import {
	next,
	schedule
} from '@ember/runloop';
import {
	alias
} from '@ember/object/computed';
import Component from '@ember/component';
import layout from '../templates/components/notification-message';
import configuration from '../configuration';
import velocity from 'velocity-animate';

export const MESSAGE_ID_ATTRIBUTE_NAME = 'data-embernotifyme-message-id';

export default Component.extend({
	classNames: ['notification-message'],
	classNameBindings: ['message.type'],
	attributeBindings: ['messageId:' + MESSAGE_ID_ATTRIBUTE_NAME],

	layout,

	message: null,
	animationDurationCss: null,
	cssAnimationPlayProperty: null,

	removeMe: false,
	closeIconHTML: null,
	messageIcon: null,
	clickable: alias('message.onClick'),

	_handleMouseEnterFn: null,
	_handleMouseLeaveFn: null,

	didInsertElement() {
		this._super(...arguments);

		this.set('messageId', `${this.message.id}-${this.message.timestamp}`);

		this.set('_handleMouseEnterFn', this.handleMouseEnter.bind(this));
		this.set('_handleMouseLeaveFn', this.handleMouseLeave.bind(this));

		this.element.addEventListener('mouseenter', this.get('_handleMouseEnterFn'));
		this.element.addEventListener('mouseleave', this.get('_handleMouseLeaveFn'));

		next(() => {

			if (this.get('isDestroyed') || this.get('isDestroying')) {
				return;
			}

			this.startCountdown();

			let message = this.get('message');
			let timeout = message.get('timeout');

			let sticky = message.get('sticky');
			if (!sticky) {
				let animationDurationCss = `animation-duration: ${timeout}ms; -webkit-animation-duration: ${timeout}ms;`;
				this.set('animationDurationCss', htmlSafe(animationDurationCss));
			}

			let messageIconSafe = message.get('icon');
			if (isEmpty(messageIconSafe)) {
				messageIconSafe = configuration.getMessageIcon(this.get('message.type'));
			}
			messageIconSafe = htmlSafe(messageIconSafe);
			this.set('messageIcon', messageIconSafe);

			this.set('closeIconHTML', configuration.getCloseIconHTML());

			if (message.get('htmlContent')) {
				message.set('message', htmlSafe(message.get('message')));
			}

		});
	},

	willDestroyElement() {
		this._super(...arguments);

		this.element.removeEventListener('mouseenter', this.get('_handleMouseEnterFn'));
		this.element.removeEventListener('mouseleave', this.get('_handleMouseLeaveFn'));

	},

	removeMeObserver: observer('message.removeMe', function() {
		if (this.get('message.removeMe') === true) {
			this.animateRemoval(() => {
				this.notifications.removeMessageFromList(this.get('message'));
			});
		}
	}),

	handleMouseEnter() {
		if (!this.get('message.sticky')) {
			this.stopCountdown();
			this.notifications.pauseMessageTimeout(this.get('message'));
		}
	},

	handleMouseLeave() {
		if (!this.get('message.sticky')) {
			this.startCountdown();
			this.notifications.startMessageTimer(this.get('message'));
		}
	},

	animateRemoval(onAnimationDone) {
		velocity(this.element, {
			scale: 1.05
		}, {
			duration: 200
		});

		velocity(this.element, {
			scale: 0
		}, {
			duration: 500,
			complete: onAnimationDone
		});
	},

	stopCountdown() {
		let $countdown = $(this.element).find(".countdown");
		if ($countdown.length !== 0) {
			velocity($countdown[0], "stop", true);
		}
	},

	startCountdown() {
		if (this.get('message.sticky') === true) {
			return;
		}
		schedule('afterRender', this, function() {
			let $element = $(this.element);
			velocity($element.find(".countdown")[0], {
				width: $element.width()
			}, {
				duration: this.get('message.timeout'),
				easing: "linear"
			});
		});
	},

	actions: {

		messageClicked() {
			let message = this.get('message');
			let onClick = message.get('onClick');
			onClick(message);

			if (message.get('closeOnClick') === true) {
				this.notifications.removeMessage(message);
			}
		},

		messageClosed() {
			let message = this.get('message');
			let onClose = message.get('onClose');
			onClose(message);
			this.notifications.removeMessage(message);
		}

	}
});
<|endoftext|>


<commit_before>exports.up = function(knex, Promise) {
	return Promise.all([
		knex('person').insert({name: 'knex', age: 3 })
	]);
};

exports.down = function(knex, Promise) {
	return Promise.all([
		knex('person')
			.where('name', 'knex')
			.del()
	]);
};
<commit_msg>Fix broken tests<commit_after>exports.do = function(knex, done) {
	knex('person').insert({name: 'knex', age: 3 }).asCallback(done);
};

exports.undo = function(knex, done) {
	knex('person').where('name', 'knex').del().asCallback(done);
};
<|endoftext|>