<commit_before>/*global $, jQuery, alert, console, error, success, endless, ajax, templateHelper, Routing, appLocale, exports, module, require, define*/
/*jslint nomen: true */ /* Tolerate dangling _ in identifiers */
/*jslint vars: true */ /* Tolerate many var statements per function */
/*jslint white: true */
/*jslint browser: true */
/*jslint devel: true */ /* Assume console, alert, ... */
/*jslint windows: true */ /* Assume Windows */
/*jslint maxerr: 100 */ /* Maximum number of errors */

/*
 * Class dependencies:
 *      jquery > 1.8.3
 *      isotope
 *      jsrender
 *      jsviews
 * external dependencies:
 *      templateHelper
 *      base genericAction
 */

// fansWorld TV Class Module 1.0

(function (root, factory) {
    "use strict";
    if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory(require('Routing'), require('templateHelper'), require('ajax'), require('ExposeTranslation'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jQuery', 'Routing', 'templateHelper', 'ajax', 'ExposeTranslation'], factory);
    } else {
        // Browser globals (root is window)
        root.TV = factory(root.jQuery, root.Routing, root.templateHelper, root.ajax, root.ExposeTranslation);
    }
}(this, function (jQuery, Routing, templateHelper, ajax, ExposeTranslation) {
    "use strict";
    var TV = (function() {
        function TV(filtersList, channelsList) {
            //////////////
            // Internal //
            //////////////
            var that = this;
            this.jQuery = jQuery;
            this.name = filtersList;
            this.channelsList = channelsList;
            this.channel = $('.filter-channels').closest('ul').find("li.active").attr("data-channel-id");
            this.filter = $('#list-filters ul').find('li.active').attr('data-list-filter-type');

            this.page = 1;

            this.contentContainer = $('body');
            this.isotopeContainer = $(this.contentContainer).find('.isotope_container').last();
            if(this.isotopeContainer.length <= 0) {
                return;
            }
            this.feedSource = $(this.isotopeContainer).attr('data-feed-source');
            if(typeof this.feedSource === 'undefined'){
                this.entityId   = $("[data-list]").attr('data-entity-id');
                this.entityType = $("[data-list]").attr('data-entity-type');
                this.dataList = $("[data-list]").attr('data-list');
                this.isProfile = true;
                console.log("in-profile");
                var feed = that.getProfileVideoFeed();
                console.log("filter: " + that.criteria + " feed: " + feed);
                var opts = {
                    'sort': that.criteria,
                    'page': that.page,
                    'entityId': that.entityId,
                    'entityType': that.entityType
                };
                $(this.isotopeContainer).attr('data-feed-source', feed);
                console.log(opts);

            } else {
                this.isTeve = true;
            }
            this.defaultTags = [
                {filter: 'day', title: ExposeTranslation.get('day')},
                {filter: 'week', title: ExposeTranslation.get('week')},
                {filter: 'month', title: ExposeTranslation.get('month')}
            ];

            $(this.isotopeContainer).empty();

            //////////////
            // Bindings //
            //////////////
            // modalPopup
            $('#montage-video-list a').modalPopup();
            // subscribe buttons
            $('[data-subscribe-channel]').click(function () {
                that.subscribe($(this));
            });
            // Handle channel list
            this.channelToggle();
            // Handle Filter tabs (popular, views, latest)
            this.filterToggle();
            this.filterToolbar();

            ////////////////////
            // New TV Gallery //
            ////////////////////
            // load isotope gallery
            if(this.isTeve) {
                this.profileGallery();
            } else {
                this.loadGallery();
            }
            // Tags
            this.myTags();
            // custom tags
            if(this.filter === 'views') {
                this.addCustomTags(this.defaultTags);
            }
        }
        TV.prototype.loadGallery = function() {
            var that = this;
            $(this.isotopeContainer).fwGalerizer({
                normalize: false,
                endless: true,
                feedfilter: {
                    'sort': that.criteria,
                    'page': that.page,
                    'entityId': that.entityId,
                    'entityType': that.entityType
                },
                onEndless: function( plugin ) {
                    plugin.options.feedfilter.page += 1;
                    return plugin.options.feedfilter;
                },
                onDataReady: function(videos) {
                    console.log("data ready")
                    console.log(videos)
                    console.log("endo ready")
                    var i, outp = [];
                    var normalize = function(video) {
                        var href = Routing.generate(appLocale + '_video_show', {
                            'id': video.id,
                            'slug': video.slug
                        });
                        var hrefModal = Routing.generate(appLocale + '_modal_media', {
                            'id': video.id,
                            'type': 'video'
                        });
                        var authorUrl = Routing.generate(appLocale + '_user_land', {
                            'username': 'juan.perez'
                        });
                        return {
                                'type': 'video',
                                'date': video.createdAt,
                                'href': href,
                                'hrefModal': hrefModal,
                                'image': video.imgsrc,
                                'slug': video.slug,
                                'title': video.title,
                                'author': 'juan.perez',
                                'authorHref': authorUrl,
                                'authorImage': 'http://fansworld.dodici.local/uploads/media/default/0001/02/thumb_1000_default_small_square_81dfa380953b084fb7eefb0273ac602bdee11874.jpg'
                        };
                    };
                    for(i in videos.elements) {
                        if (videos.elements.hasOwnProperty(i)) {
                            outp.push(normalize(videos.elements[i]));
                        }
                    }
                    return outp;
                    this.page += 1;
                }
            });
        };
        TV.prototype.profileGallery = function() {
            this.channel = $('.filter-channels').closest('ul').find("li.active").attr("data-channel-id");
            this.filter = $('#list-filters ul').find('li.active').attr('data-list-filter-type');
            this.page  = 1;
            $(this.isotopeContainer).fwGalerizer({
                normalize: false,
                endless: true,
                feedfilter: {'channel': this.channel, 'filter': this.filter, 'page': this.page},
                onEndless: function( plugin ) {
                    plugin.options.feedfilter.page += 1;
                    console.log("loading video gallery for channel %s with filter %s page: %s", plugin.options.feedfilter.channel, plugin.options.feedfilter.filter, plugin.options.feedfilter.page);
                    return plugin.options.feedfilter;
                },
                onDataReady: function(videos) {
                    var i, outp = [];
                    var normalize = function(video) {
                        var href = Routing.generate(appLocale + '_video_show', {
                            'id': video.id,
                            'slug': video.slug
                        });
                        var hrefModal = Routing.generate(appLocale + '_modal_media', {
                            'id': video.id,
                            'type': 'video'
                        });
                        var authorUrl = Routing.generate(appLocale + '_user_land', {
                            'username': video.author.username
                        });
                        return {
                                'type': 'video',
                                'date': video.createdAt,
                                'href': href,
                                'hrefModal': hrefModal,
                                'image': video.image,
                                'slug': video.slug,
                                'title': video.title,
                                'author': video.author.username,
                                'authorHref': authorUrl,
                                'authorImage': video.author.image
                        };
                    };
                    for(i in videos.videos) {
                        if (videos.videos.hasOwnProperty(i)) {
                            outp.push(normalize(videos.videos[i]));
                        }
                    }
                    return outp;
                }
            });
            this.page += 1;
        };
        TV.prototype.channelToggle = function() {
            var that = this;
            $('.filter-channels').closest('ul').find("li").click(function(e){
                var i;
                var selectedChannel = $(this).first().attr('data-list-target');
                $(".channels-widget .content .active").removeClass('active');
                $('.filter-channels').closest('ul').find("li.active").removeClass('active');
                $(this).first().addClass('active');

                $(".channels-widget .content #" + selectedChannel).addClass('active');

                // Update channel
                that.channel = $('.filter-channels').closest('ul').find("li.active").attr("data-channel-id");
                // update tags
                that.myTags(that.channel, that.filter);
                // custom tags
                if(that.filter === 'views') {
                    that.addCustomTags(that.defaultTags);
                }
                // Destroy gallery items
                that.destroyGallery();
                // Load new gallery
                that.profileGallery();
            });
        };
        TV.prototype.customFilterToggler = function(element) {
            var that = this;
            element.click(function(e){
                $('[data-list-filter-type=' + that.filter + ']').removeClass();
                that.filter = $(this).attr('data-list-filter-type');
                // update tags
                that.myTags(that.channel, that.filter);
                // create custom UI filter elements
                that.addCustomTags(that.defaultTags);
                $('[data-list-filter-type=' + that.filter + ']').addClass('active');
                // Destroy gallery items
                that.destroyGallery();
                // Load new gallery
                that.loadGallery();
            });
        };
        TV.prototype.getFilterName = function(id) {
            // body...
        };
        TV.prototype.getMethodName = function() {
            var that = this;
            var criteria = '';
            switch($("[data-sort] .btn-group").find('.active').attr('data-type')){
                case "0":
                    criteria = "highlight";
                    break;
                case "1":
                    criteria = "most-visited";
                    break;
                case "2":
                    criteria = "popular";
                    break;
                case "3":
                    criteria = "most-visited-today";
                    break;
            }
            that.criteria = criteria;
            return criteria;
        };
        TV.prototype.getProfileVideoFeed = function() {
            var that = this;
            var type = $("[data-sort] .btn-group").find('.active').attr('data-type');
            if(typeof(type) === 'undefined'){
                type = 'popular';
            }
            var methodName = that.getMethodName();
            var opts = {
                'sort': that.criteria,
                'page': that.page,
                'entityId': that.entityId,
                'entityType': that.entityType
            };
            var route = '';
            switch(that.criteria){
                case 'popular':
                    route = that.dataList + "_popular";
                    break;
                case 'highlight':
                    route = that.dataList + "_highlighted";
                    break;
                case 'most-visited':
                    route = that.dataList + "_visited";
                    break;
                case 'most-visited-today':
                    route = that.dataList + "_visited";
                    opts.today = true;
                    break;
            }
            return route;

            //ajax.genericAction(methodName, opts, function(r){ console.log(r) }, function(error) { console.log(error)});
        };
        TV.prototype.filterToolbar = function($toolbar) {
            var that = this;
            var method = '';
            $("[data-sort] .btn-group .btn").on('click', function(){
                $(this).parent().find('.active').removeClass('active');
                $(this).addClass('active');
                switch($(this).attr('data-type')){
                    case "0":
                        that.criteria = "highlight";
                        break;
                    case "1":
                        that.criteria = "most-visited";
                        break;
                    case "2":
                        that.criteria = "popular";
                        break;
                    case "3":
                        that.criteria = "most-visited-today";
                        break;
                }
                var feed = that.getProfileVideoFeed();
                console.log("filter: " + that.criteria + " feed: " + feed);
                var opts = {
                    'sort': that.criteria,
                    'page': that.page,
                    'entityId': that.entityId,
                    'entityType': that.entityType
                };
                console.log(opts);
                //ajax.genericAction(feed, opts, function(r){ console.log(r); }, function(error) { console.log(error); });
                // Destroy gallery items
                that.destroyGallery();
                that.page = 1;
                var feed = that.getProfileVideoFeed();
                $(that.isotopeContainer).attr('data-feed-source', feed);
                // Load new gallery
                that.loadGallery();
            });
        };
        TV.prototype.getSortedGallery = function() {
            /*

        sort.page       = 1;
        sort.entityId   = $("[data-list]").attr('data-entity-id');
        sort.entityType = $("[data-list]").attr('data-entity-type');

    var methodName = "";
    var opts = {
        'sort': sort.criteria,
        'page': sort.page,
        'entityId': sort.entityId,
        'entityType': sort.entityType
    };

    switch(sort.criteria){
        case 'popular':
            methodName = sort.dataList + "_popular";
            break;
        case 'highlight':
            methodName = sort.dataList + "_highlighted";
            break;
        case 'most-visited':
            methodName = sort.dataList + "_visited";
            break;
        case 'most-visited-today':
            methodName = sort.dataList + "_visited";
            opts['today'] = true;
            break;
    }
    window.endlessScrollPaused = true;
    ajax.genericAction(methodName, opts, function(r){
        */
        };
        TV.prototype.filterToggle = function() {
            var that = this;
            $('#list-filters').find("li").click(function(e){
                var i;
                var selectedFilter = $(this).first().attr('data-list-filter-type');
                $('#list-filters').find("li.active").removeClass('active');
                $(this).first().addClass('active');

                that.filter = $('#list-filters ul').find('li.active').attr('data-list-filter-type');
                // update tags
                that.myTags(that.channel, that.filter);
                // custom tags
                if(that.filter === 'views') {
                    that.addCustomTags(that.defaultTags);
                }
                // Destroy gallery items
                that.destroyGallery();
                // Load new gallery
                that.profileGallery();
            });
        };
        TV.prototype.myTags = function(channel, filter) {
            var $tagList = $(".content-container").find(".tag-list-container ul");
            $tagList.empty();
            ajax.genericAction("tag_ajaxgetusedinvideos", {
                "channel": channel,
                "filter": filter
            }, function(r) {
                var i;
                for (i in r.tags) {
                    if (r.tags.hasOwnProperty(i)) {
                        var tagHref = Routing.generate(appLocale + "_teve_taggedvideos", {
                            term: r.tags[i].slug
                        });
                        //console.log(r.tags[i]);
                        $tagList.append("
" + r.tags[i].title + "
");
                    }
                }
            });
        };
        TV.prototype.addCustomTags = function(tags, options) {
            var that = this;
            var i;
            var $tagList = $(".content-container").find(".tag-list-container ul");
            for(i in tags) {
                if (tags.hasOwnProperty(i)) {
                    var $customFilter = $("
" + tags[i].title + "
");
                    that.customFilterToggler($customFilter);
                    $tagList.prepend($customFilter);
                }
            }
            return;
        };
        TV.prototype.destroyGallery = function() {
            $(this.isotopeContainer).data('fwGalerizer').destroy();
            return;
        };
        TV.prototype.subscribe = function ($button) {
            var channel = $button.attr('data-subscribe-channel');
            var params = {};

            if (!channel || channel === 'all') {
                return alert('Por favor elija un canal antes de suscribirse.');
            }
            params.channel = channel;

            $button.addClass('loading-small');

            ajax.genericAction('teve_channelsubscribe', params, function (response) {
                success(response.message);
                $button.text(response.buttontext);

                if (response.state === true) {
                    $button.prepend($('').attr('class', 'icon-remove').after(' '));
                } else if (response.state === false) {
                    $button.prepend($('').attr('class', 'icon-ok').after(' '));
                }
                $button.removeClass('loading-small');
            }, function (msg) {
                error(msg);
                $button.removeClass('loading-small');
            });
        };
        return TV;
    }());
    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return TV;
}));

// implicit init that adds module to global scope
// TODO: refactor inside curl
$(document).ready(function () {
    "use strict";
    window.fansworld = window.fansworld || {};
    var defaultChannel = null; //
    var defaultFilter = 'popular';
    window.fansworld.tv = new window.TV(defaultChannel, defaultFilter);
    return;
});<commit_msg>sin console.logs al pedo<commit_after>/*global $, jQuery, alert, console, error, success, endless, ajax, templateHelper, Routing, appLocale, exports, module, require, define*/
/*jslint nomen: true */ /* Tolerate dangling _ in identifiers */
/*jslint vars: true */ /* Tolerate many var statements per function */
/*jslint white: true */
/*jslint browser: true */
/*jslint devel: true */ /* Assume console, alert, ... */
/*jslint windows: true */ /* Assume Windows */
/*jslint maxerr: 100 */ /* Maximum number of errors */

/*
 * Class dependencies:
 *      jquery > 1.8.3
 *      isotope
 *      jsrender
 *      jsviews
 * external dependencies:
 *      templateHelper
 *      base genericAction
 */

// fansWorld TV Class Module 1.1 (con galerias de profiles)
// 1.0

(function (root, factory) {
    "use strict";
    if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory(require('Routing'), require('templateHelper'), require('ajax'), require('ExposeTranslation'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jQuery', 'Routing', 'templateHelper', 'ajax', 'ExposeTranslation'], factory);
    } else {
        // Browser globals (root is window)
        root.TV = factory(root.jQuery, root.Routing, root.templateHelper, root.ajax, root.ExposeTranslation);
    }
}(this, function (jQuery, Routing, templateHelper, ajax, ExposeTranslation) {
    "use strict";
    var TV = (function() {
        function TV(filtersList, channelsList) {
            //////////////
            // Internal //
            //////////////
            var that = this;
            this.jQuery = jQuery;
            this.name = filtersList;
            this.channelsList = channelsList;
            this.channel = $('.filter-channels').closest('ul').find("li.active").attr("data-channel-id");
            this.filter = $('#list-filters ul').find('li.active').attr('data-list-filter-type');

            this.page = 1;

            this.contentContainer = $('body');
            this.isotopeContainer = $(this.contentContainer).find('.isotope_container').last();
            if(this.isotopeContainer.length <= 0) {
                return;
            }
            this.feedSource = $(this.isotopeContainer).attr('data-feed-source');
            if(typeof this.feedSource === 'undefined'){
                this.entityId   = $("[data-list]").attr('data-entity-id');
                this.entityType = $("[data-list]").attr('data-entity-type');
                this.dataList = $("[data-list]").attr('data-list');
                this.isProfile = true;
                console.log("in-profile");
                var feed = that.getProfileVideoFeed();
                console.log("filter: " + that.criteria + " feed: " + feed);
                var opts = {
                    'sort': that.criteria,
                    'page': that.page,
                    'entityId': that.entityId,
                    'entityType': that.entityType
                };
                $(this.isotopeContainer).attr('data-feed-source', feed);
                console.log(opts);

            } else {
                this.isTeve = true;
            }
            this.defaultTags = [
                {filter: 'day', title: ExposeTranslation.get('day')},
                {filter: 'week', title: ExposeTranslation.get('week')},
                {filter: 'month', title: ExposeTranslation.get('month')}
            ];

            $(this.isotopeContainer).empty();

            //////////////
            // Bindings //
            //////////////
            // modalPopup
            $('#montage-video-list a').modalPopup();
            // subscribe buttons
            $('[data-subscribe-channel]').click(function () {
                that.subscribe($(this));
            });
            // Handle channel list
            this.channelToggle();
            // Handle Filter tabs (popular, views, latest)
            this.filterToggle();
            this.filterToolbar();

            ////////////////////
            // New TV Gallery //
            ////////////////////
            // load isotope gallery
            if(this.isTeve) {
                this.profileGallery();
            } else {
                this.loadGallery();
            }
            // Tags
            this.myTags();
            // custom tags
            if(this.filter === 'views') {
                this.addCustomTags(this.defaultTags);
            }
        }
        TV.prototype.loadGallery = function() {
            var that = this;
            $(this.isotopeContainer).fwGalerizer({
                normalize: false,
                endless: true,
                feedfilter: {
                    'sort': that.criteria,
                    'page': that.page,
                    'entityId': that.entityId,
                    'entityType': that.entityType
                },
                onEndless: function( plugin ) {
                    plugin.options.feedfilter.page += 1;
                    return plugin.options.feedfilter;
                },
                onDataReady: function(videos) {
                    var i, outp = [];
                    var normalize = function(video) {
                        var href = Routing.generate(appLocale + '_video_show', {
                            'id': video.id,
                            'slug': video.slug
                        });
                        var hrefModal = Routing.generate(appLocale + '_modal_media', {
                            'id': video.id,
                            'type': 'video'
                        });
                        var authorUrl = Routing.generate(appLocale + '_user_land', {
                            'username': 'juan.perez'
                        });
                        return {
                                'type': 'video',
                                'date': video.createdAt,
                                'href': href,
                                'hrefModal': hrefModal,
                                'image': video.imgsrc,
                                'slug': video.slug,
                                'title': video.title,
                                'author': 'juan.perez',
                                'authorHref': authorUrl,
                                'authorImage': 'http://fansworld.dodici.local/uploads/media/default/0001/02/thumb_1000_default_small_square_81dfa380953b084fb7eefb0273ac602bdee11874.jpg'
                        };
                    };
                    for(i in videos.elements) {
                        if (videos.elements.hasOwnProperty(i)) {
                            outp.push(normalize(videos.elements[i]));
                        }
                    }
                    return outp;
                }
            });
        };
        TV.prototype.profileGallery = function() {
            this.channel = $('.filter-channels').closest('ul').find("li.active").attr("data-channel-id");
            this.filter = $('#list-filters ul').find('li.active').attr('data-list-filter-type');
            this.page  = 1;
            $(this.isotopeContainer).fwGalerizer({
                normalize: false,
                endless: true,
                feedfilter: {'channel': this.channel, 'filter': this.filter, 'page': this.page},
                onEndless: function( plugin ) {
                    plugin.options.feedfilter.page += 1;
                    console.log("loading video gallery for channel %s with filter %s page: %s", plugin.options.feedfilter.channel, plugin.options.feedfilter.filter, plugin.options.feedfilter.page);
                    return plugin.options.feedfilter;
                },
                onDataReady: function(videos) {
                    var i, outp = [];
                    var normalize = function(video) {
                        var href = Routing.generate(appLocale + '_video_show', {
                            'id': video.id,
                            'slug': video.slug
                        });
                        var hrefModal = Routing.generate(appLocale + '_modal_media', {
                            'id': video.id,
                            'type': 'video'
                        });
                        var authorUrl = Routing.generate(appLocale + '_user_land', {
                            'username': video.author.username
                        });
                        return {
                                'type': 'video',
                                'date': video.createdAt,
                                'href': href,
                                'hrefModal': hrefModal,
                                'image': video.image,
                                'slug': video.slug,
                                'title': video.title,
                                'author': video.author.username,
                                'authorHref': authorUrl,
                                'authorImage': video.author.image
                        };
                    };
                    for(i in videos.videos) {
                        if (videos.videos.hasOwnProperty(i)) {
                            outp.push(normalize(videos.videos[i]));
                        }
                    }
                    return outp;
                }
            });
            this.page += 1;
        };
        TV.prototype.channelToggle = function() {
            var that = this;
            $('.filter-channels').closest('ul').find("li").click(function(e){
                var i;
                var selectedChannel = $(this).first().attr('data-list-target');
                $(".channels-widget .content .active").removeClass('active');
                $('.filter-channels').closest('ul').find("li.active").removeClass('active');
                $(this).first().addClass('active');

                $(".channels-widget .content #" + selectedChannel).addClass('active');

                // Update channel
                that.channel = $('.filter-channels').closest('ul').find("li.active").attr("data-channel-id");
                // update tags
                that.myTags(that.channel, that.filter);
                // custom tags
                if(that.filter === 'views') {
                    that.addCustomTags(that.defaultTags);
                }
                // Destroy gallery items
                that.destroyGallery();
                // Load new gallery
                that.profileGallery();
            });
        };
        TV.prototype.customFilterToggler = function(element) {
            var that = this;
            element.click(function(e){
                $('[data-list-filter-type=' + that.filter + ']').removeClass();
                that.filter = $(this).attr('data-list-filter-type');
                // update tags
                that.myTags(that.channel, that.filter);
                // create custom UI filter elements
                that.addCustomTags(that.defaultTags);
                $('[data-list-filter-type=' + that.filter + ']').addClass('active');
                // Destroy gallery items
                that.destroyGallery();
                // Load new gallery
                that.loadGallery();
            });
        };
        TV.prototype.getMethodName = function() {
            var that = this;
            var criteria = '';
            switch($("[data-sort] .btn-group").find('.active').attr('data-type')){
                case "0":
                    criteria = "highlight";
                    break;
                case "1":
                    criteria = "most-visited";
                    break;
                case "2":
                    criteria = "popular";
                    break;
                case "3":
                    criteria = "most-visited-today";
                    break;
            }
            that.criteria = criteria;
            return criteria;
        };
        TV.prototype.getProfileVideoFeed = function() {
            var that = this;
            var type = $("[data-sort] .btn-group").find('.active').attr('data-type');
            if(typeof(type) === 'undefined'){
                type = 'popular';
            }
            var methodName = that.getMethodName();
            var opts = {
                'sort': that.criteria,
                'page': that.page,
                'entityId': that.entityId,
                'entityType': that.entityType
            };
            var route = '';
            switch(that.criteria){
                case 'popular':
                    route = that.dataList + "_popular";
                    break;
                case 'highlight':
                    route = that.dataList + "_highlighted";
                    break;
                case 'most-visited':
                    route = that.dataList + "_visited";
                    break;
                case 'most-visited-today':
                    route = that.dataList + "_visited";
                    opts.today = true;
                    break;
            }
            return route;
        };
        TV.prototype.filterToolbar = function($toolbar) {
            var that = this;
            var method = '';
            $("[data-sort] .btn-group .btn").on('click', function(){
                $(this).parent().find('.active').removeClass('active');
                $(this).addClass('active');
                switch($(this).attr('data-type')){
                    case "0":
                        that.criteria = "highlight";
                        break;
                    case "1":
                        that.criteria = "most-visited";
                        break;
                    case "2":
                        that.criteria = "popular";
                        break;
                    case "3":
                        that.criteria = "most-visited-today";
                        break;
                }
                var feed = that.getProfileVideoFeed();
                $(that.isotopeContainer).attr('data-feed-source', feed);
                console.log("filter: " + that.criteria + " feed: " + feed);
                var opts = {
                    'sort': that.criteria,
                    'page': that.page,
                    'entityId': that.entityId,
                    'entityType': that.entityType
                };
                console.log(opts);
                // Destroy gallery items
                that.destroyGallery();
                that.page = 1;  // reset page count
                // Load new gallery
                that.loadGallery();
            });
        };
        TV.prototype.filterToggle = function() {
            var that = this;
            $('#list-filters').find("li").click(function(e){
                var i;
                var selectedFilter = $(this).first().attr('data-list-filter-type');
                $('#list-filters').find("li.active").removeClass('active');
                $(this).first().addClass('active');

                that.filter = $('#list-filters ul').find('li.active').attr('data-list-filter-type');
                // update tags
                that.myTags(that.channel, that.filter);
                // custom tags
                if(that.filter === 'views') {
                    that.addCustomTags(that.defaultTags);
                }
                // Destroy gallery items
                that.destroyGallery();
                // Load new gallery
                that.profileGallery();
            });
        };
        TV.prototype.myTags = function(channel, filter) {
            var $tagList = $(".content-container").find(".tag-list-container ul");
            $tagList.empty();
            ajax.genericAction("tag_ajaxgetusedinvideos", {
                "channel": channel,
                "filter": filter
            }, function(r) {
                var i;
                for (i in r.tags) {
                    if (r.tags.hasOwnProperty(i)) {
                        var tagHref = Routing.generate(appLocale + "_teve_taggedvideos", {
                            term: r.tags[i].slug
                        });
                        //console.log(r.tags[i]);
                        $tagList.append("
" + r.tags[i].title + "
");
                    }
                }
            });
        };
        TV.prototype.addCustomTags = function(tags, options) {
            var that = this;
            var i;
            var $tagList = $(".content-container").find(".tag-list-container ul");
            for(i in tags) {
                if (tags.hasOwnProperty(i)) {
                    var $customFilter = $("
" + tags[i].title + "
");
                    that.customFilterToggler($customFilter);
                    $tagList.prepend($customFilter);
                }
            }
            return;
        };
        TV.prototype.destroyGallery = function() {
            $(this.isotopeContainer).data('fwGalerizer').destroy();
            return;
        };
        TV.prototype.subscribe = function ($button) {
            var channel = $button.attr('data-subscribe-channel');
            var params = {};

            if (!channel || channel === 'all') {
                return alert('Por favor elija un canal antes de suscribirse.');
            }
            params.channel = channel;

            $button.addClass('loading-small');

            ajax.genericAction('teve_channelsubscribe', params, function (response) {
                success(response.message);
                $button.text(response.buttontext);

                if (response.state === true) {
                    $button.prepend($('').attr('class', 'icon-remove').after(' '));
                } else if (response.state === false) {
                    $button.prepend($('').attr('class', 'icon-ok').after(' '));
                }
                $button.removeClass('loading-small');
            }, function (msg) {
                error(msg);
                $button.removeClass('loading-small');
            });
        };
        return TV;
    }());
    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return TV;
}));

// implicit init that adds module to global scope
// TODO: refactor inside curl
$(document).ready(function () {
    "use strict";
    window.fansworld = window.fansworld || {};
    var defaultChannel = null; //
    var defaultFilter = 'popular';
    window.fansworld.tv = new window.TV(defaultChannel, defaultFilter);
    return;
});<|endoftext|>


<commit_before>/**
  * AIR - Adaptive Image Resizing
  * http://github.com/up/air
  * Copyright (c) 2012 Uli Preuss
  * Dual licensed under the MIT and GPL
*/
(function(){var e={a:[],display:null,set:function(a,c){0<e.a.length?e.b(a,c):e.d(a,c)},d:function(a,c){var d=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),h,f;d&&(d.onreadystatechange=function(){4==d.readyState&&200==d.status&&(h=d.responseText,f=h.match(/<noscript\b[^>]*>(?:(?=([^<]+))\1|<(?!noscript\b[^>]*>))*?<\/noscript>/gi),e.b(a,c,f))},d.open("GET",location.href,!0),d.send())},b:function(a,c,d){d?e.a=d:d=e.a;var h,f,j,b,k,g,i,m,n,p=document.getElementsByTagName("noscript"), l=0;g=0;var o,q=d.length;i=window.innerWidth||document.body.offsetWidth;for(f in a)i>=parseInt(f,10)&&(h=a[f]);if(e.display!==h)for(e.display=h;l<q;l++){g=d[l];i=p[l];m=i.parentNode;f=document.createElement("img");g=/<img[^>]+>/.exec(g)[0];n=g.match(/(\w+)=("[^<>"]*"|'[^<>']*'|"\w+)/gi);o=n.length;for(g=0;g<o;g++)b=n[g].split("="),k=b[0].toLowerCase(),b=b[1],j=b.match(/"|'/),b=b.replace(RegExp(j[0],"g"),""),"src"===k?(j=b.lastIndexOf("."),k=b.substring(0,j),b=b.substring(j,b.length),f.src=k+h+b): f[k]=b;c?m.replaceChild(f,i.previousSibling):(m.insertBefore(f,i),e.c("resize",function(){e.set(a,!0)}))}},c:function(a,c){window.attachEvent?(window["e"+a+c]=c,window[a+c]=function(){window["e"+a+c](window.event)},window.attachEvent("on"+a,window[a+c])):window.addEventListener(a,c,!1)}};window.air=e;window.air.set=e.set})();<commit_msg>some cleanup<commit_after>/**
  * AIR - Adaptive Image Resizing
  * http://github.com/up/air
  * Copyright (c) 2012 Uli Preuss
*/
(function(){var e={a:[],display:null,set:function(a,c){0<e.a.length?e.b(a,c):e.d(a,c)},d:function(a,c){var d=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),h,f;d&&(d.onreadystatechange=function(){4==d.readyState&&200==d.status&&(h=d.responseText,f=h.match(/<noscript\b[^>]*>(?:(?=([^<]+))\1|<(?!noscript\b[^>]*>))*?<\/noscript>/gi),e.b(a,c,f))},d.open("GET",location.href,!0),d.send())},b:function(a,c,d){d?e.a=d:d=e.a;var h,f,j,b,k,g,i,m,n,p=document.getElementsByTagName("noscript"), l=0;g=0;var o,q=d.length;i=window.innerWidth||document.body.offsetWidth;for(f in a)i>=parseInt(f,10)&&(h=a[f]);if(e.display!==h)for(e.display=h;l<q;l++){g=d[l];i=p[l];m=i.parentNode;f=document.createElement("img");g=/<img[^>]+>/.exec(g)[0];n=g.match(/(\w+)=("[^<>"]*"|'[^<>']*'|"\w+)/gi);o=n.length;for(g=0;g<o;g++)b=n[g].split("="),k=b[0].toLowerCase(),b=b[1],j=b.match(/"|'/),b=b.replace(RegExp(j[0],"g"),""),"src"===k?(j=b.lastIndexOf("."),k=b.substring(0,j),b=b.substring(j,b.length),f.src=k+h+b): f[k]=b;c?m.replaceChild(f,i.previousSibling):(m.insertBefore(f,i),e.c("resize",function(){e.set(a,!0)}))}},c:function(a,c){window.attachEvent?(window["e"+a+c]=c,window[a+c]=function(){window["e"+a+c](window.event)},window.attachEvent("on"+a,window[a+c])):window.addEventListener(a,c,!1)}};window.air=e;window.air.set=e.set})();<|endoftext|>


<commit_before>import { promise, arr } from "lively.lang";
import { Rectangle } from "lively.graphics";

function createIFrame(parentElement, url = "about:blank", bounds = new Rectangle(0,0, 700,700)) {
  return new Promise((resolve, reject) => {
    if (!parentElement) throw new Error("Need parent element!")
    var iframe = document.createElement('iframe');
    iframe.style.position = "absolute";
    iframe.style.top = bounds.top() + 'px';
    iframe.style.left = bounds.left() + 'px';
    iframe.style.width = bounds.width + 'px';
    iframe.style.height = bounds.height + 'px';
    iframe.src = url;
    var loaded = false;
    iframe.onload = function(evt) { loaded = true; iframe.onload = null; resolve(iframe); };
    promise.waitFor(1000, () => !!loaded).catch((err) => reject(new Error("iframe load timeout")))
    parentElement.appendChild(iframe);
  })
};

function requestAnimationFramePolyfill(window) {
  // based on requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
  // MIT license
  // https://gist.github.com/paulirish/1579671
  var lastTime = 0,
      vendors = ['ms', 'moz', 'webkit', 'o'];
  for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
      window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
      window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                 || window[vendors[x]+'CancelRequestAnimationFrame'];
  }

  if (!window.requestAnimationFrame)
    window.requestAnimationFrame = function(callback, element) {
      var currTime = Date.now(),
          timeToCall = Math.max(0, 16 - (currTime - lastTime)),
          id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };

  if (!window.cancelAnimationFrame)
      window.cancelAnimationFrame = function(id) { clearTimeout(id); };
}

async function createDOMEnvironment_browser() {
  var iframe = await createIFrame(document.body)
  return new DomEnvironment(
    iframe.contentWindow,
    iframe.contentWindow.document,
    () => {
      iframe.contentWindow && iframe.contentWindow.close();
      iframe.parentNode && iframe.parentNode.removeChild(iframe);
    });
}

function createDOMEnvironment_node() {
  var morphicDir = System.decanonicalize("lively.morphic/").replace(/file:\/\//, ""),
      jsdom = System._nodeRequire(morphicDir + "node_modules/jsdom"),
      virtualConsole = jsdom.createVirtualConsole().sendTo(console);
  return new Promise((resolve, reject) => {
    jsdom.env(
      '

',
      ["https://code.jquery.com/pep/0.4.1/pep.js"],
      { virtualConsole },
      (err, window) =>
        err ?
          reject(err) :
          resolve(new DomEnvironment(window, window.document, () => window.close())));
  })
}

export function createDOMEnvironment() {
  return System.get("@system-env").browser ?
    createDOMEnvironment_browser() :
    createDOMEnvironment_node();
}

class DomEnvironment {

  constructor(window, document, destroyFn) {
    requestAnimationFramePolyfill(window);
    this.window = window;
    this.document = document;
    this.destroyFn = destroyFn;
  }

  destroy() {
    if (typeof this.destroyFn === "function")
      this.destroyFn();
  }
}

var _defaultEnv;
export function defaultDOMEnv() {
  return _defaultEnv || (_defaultEnv = System.get("@system-env").browser ?
    new DomEnvironment(window, document) :
    createDOMEnvironment());
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function setCSSDef(node, cssDefString, doc) {
  arr.from(node.childNodes).forEach(c => node.removeChild(c));
  var rules = doc.createTextNode(cssDefString);
  if (node.styleSheet) node.styleSheet.cssText = rules.nodeValue
  else node.appendChild(rules);
  return node;
}

function addCSSDef(id, cssString, doc) {
  var style = doc.createElement('style');
  style.type = 'text/css';
  if (id) style.setAttribute('id', id);
  setCSSDef(style, cssString, doc);
  doc.head.appendChild(style);
  return style;
}

export function addOrChangeCSSDeclaration(id = "lively-css", cssString, doc = document) {
  var node = doc.getElementById(id);
  return node ?
    setCSSDef(node, cssString, doc) :
    addCSSDef(id, cssString, doc);
}

export function addOrChangeLinkedCSS(id, url, doc = document) {
  var link = doc.getElementById(id);
  if (!link) {
    link = doc.createElement('link');
    link.type = 'text/css';
    link.rel = "stylesheet";
    link.setAttribute('id', id);
    doc.head.appendChild(link);
  }
  link.setAttribute('href', url);
  var loaded = false; link.onload = () => loaded = true;
  return promise.waitFor(() => !!loaded && link);
}
<commit_msg>test env improvement<commit_after>import { promise, arr } from "lively.lang";
import { Rectangle } from "lively.graphics";

function createIFrame(parentElement, url = "about:blank", bounds = new Rectangle(0,0, 700,700)) {
  return new Promise((resolve, reject) => {
    if (!parentElement) throw new Error("Need parent element!")
    var iframe = document.createElement('iframe');
    iframe.style.position = "absolute";
    iframe.style.top = bounds.top() + 'px';
    iframe.style.left = bounds.left() + 'px';
    iframe.style.width = bounds.width + 'px';
    iframe.style.height = bounds.height + 'px';
    iframe.src = url;
    var loaded = false;
    iframe.onload = function(evt) { loaded = true; iframe.onload = null; resolve(iframe); };
    promise.waitFor(1000, () => !!loaded).catch((err) => reject(new Error("iframe load timeout")))
    parentElement.appendChild(iframe);
  })
};

function requestAnimationFramePolyfill(window) {
  // based on requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
  // MIT license
  // https://gist.github.com/paulirish/1579671
  var lastTime = 0,
      vendors = ['ms', 'moz', 'webkit', 'o'];
  for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
      window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
      window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                 || window[vendors[x]+'CancelRequestAnimationFrame'];
  }

  if (!window.requestAnimationFrame)
    window.requestAnimationFrame = function(callback, element) {
      var currTime = Date.now(),
          timeToCall = Math.max(0, 16 - (currTime - lastTime)),
          id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };

  if (!window.cancelAnimationFrame)
      window.cancelAnimationFrame = function(id) { clearTimeout(id); };
}

async function createDOMEnvironment_browser() {
  return new IFramedDomEnvironment(await createIFrame(document.body));
}

function createDOMEnvironment_node() {
  var morphicDir = System.decanonicalize("lively.morphic/").replace(/file:\/\//, ""),
      jsdom = System._nodeRequire(morphicDir + "node_modules/jsdom"),
      virtualConsole = jsdom.createVirtualConsole().sendTo(console);
  return new Promise((resolve, reject) => {
    jsdom.env(
      '

',
      ["https://code.jquery.com/pep/0.4.1/pep.js"],
      { virtualConsole },
      (err, window) =>
        err ?
          reject(err) :
          resolve(new DomEnvironment(window, window.document, () => window.close())));
  })
}

export function createDOMEnvironment() {
  return System.get("@system-env").browser ?
    createDOMEnvironment_browser() :
    createDOMEnvironment_node();
}

class DomEnvironment {

  constructor(window, document, destroyFn) {
    requestAnimationFramePolyfill(window);
    this.window = window;
    this.document = document;
    this.destroyFn = destroyFn;
  }

  destroy() {
    if (typeof this.destroyFn === "function")
      this.destroyFn();
  }
}

class IFramedDomEnvironment extends DomEnvironment {

  constructor(iframe) {
    super(
      iframe.contentWindow,
      iframe.contentWindow.document,
      () => {
        iframe.contentWindow && iframe.contentWindow.close();
        iframe.parentNode && iframe.parentNode.removeChild(iframe);
      }
    )
    this.iframe = iframe;
  }

}

var _defaultEnv;
export function defaultDOMEnv() {
  return _defaultEnv || (_defaultEnv = System.get("@system-env").browser ?
    new DomEnvironment(window, document) :
    createDOMEnvironment());
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function setCSSDef(node, cssDefString, doc) {
  arr.from(node.childNodes).forEach(c => node.removeChild(c));
  var rules = doc.createTextNode(cssDefString);
  if (node.styleSheet) node.styleSheet.cssText = rules.nodeValue
  else node.appendChild(rules);
  return node;
}

function addCSSDef(id, cssString, doc) {
  var style = doc.createElement('style');
  style.type = 'text/css';
  if (id) style.setAttribute('id', id);
  setCSSDef(style, cssString, doc);
  doc.head.appendChild(style);
  return style;
}

export function addOrChangeCSSDeclaration(id = "lively-css", cssString, doc = document) {
  var node = doc.getElementById(id);
  return node ?
    setCSSDef(node, cssString, doc) :
    addCSSDef(id, cssString, doc);
}

export function addOrChangeLinkedCSS(id, url, doc = document) {
  var link = doc.getElementById(id);
  if (!link) {
    link = doc.createElement('link');
    link.type = 'text/css';
    link.rel = "stylesheet";
    link.setAttribute('id', id);
    doc.head.appendChild(link);
  }
  link.setAttribute('href', url);
  var loaded = false; link.onload = () => loaded = true;
  return promise.waitFor(() => !!loaded && link);
}
<|endoftext|>


<commit_before>/*
 Copyright 2019 Carmilla Mina Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

const BaseView = require('./BaseView');

const userComposer = require('../../data/composers/UserComposer');
const eventCentral = require('../../EventCentral');
const elementCreator = require('../../ElementCreator');
const teamComposer = require('../../data/composers/TeamComposer');

class TeamInfo extends BaseView {
  constructor() {
    const teamSpan = elementCreator.createSpan({ text: '---' });
    const setTeamFunc = ({ user }) => {
      const identity = user || userComposer.getCurrentIdentity();

      teamSpan.innerHTML = '';

      if (identity.partOfTeams && identity.partOfTeams.length > 0) {
        const team = teamComposer.getTeam({ teamId: identity.partOfTeams[0] });

        teamSpan.appendChild(document.createTextNode(team.teamName));
      } else {
        teamSpan.appendChild(document.createTextNode('---'));
      }
    };

    super({});

    this.element = elementCreator.createContainer({
      classes: ['teamInfo'],
      clickFuncs: {
        leftFunc: () => {
          const identity = userComposer.getCurrentIdentity();

          if (identity.partOfTeams && identity.partOfTeams.length > 0) {
            const team = teamComposer.getTeam({ teamId: identity.partOfTeams[0] });
          }
        },
      },
    });
    this.element.appendChild(teamSpan);

    eventCentral.addWatcher({
      event: eventCentral.Events.COMPLETE_USER,
      func: () => {
        setTeamFunc({});
      },
    });

    eventCentral.addWatcher({
      event: eventCentral.Events.CHANGED_ALIAS,
      func: () => {
        setTeamFunc({});
      },
    });

    eventCentral.addWatcher({
      event: eventCentral.Events.LOGIN,
      func: () => {
        setTeamFunc({});
      },
    });

    eventCentral.addWatcher({
      event: eventCentral.Events.LOGOUT,
      func: () => {
        setTeamFunc({});
      },
    });

    eventCentral.addWatcher({
      event: eventCentral.Events.TEAM_MEMBER,
      func: ({ user }) => {
        const identity = userComposer.getCurrentIdentity();

        if (identity.objectId === user.objectId) {
          setTeamFunc({ user });
        }
      },
    });
  }
}

module.exports = TeamInfo;
<commit_msg>Team sent to team info on creation<commit_after>/*
 Copyright 2019 Carmilla Mina Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

const BaseView = require('./BaseView');

const userComposer = require('../../data/composers/UserComposer');
const eventCentral = require('../../EventCentral');
const elementCreator = require('../../ElementCreator');
const teamComposer = require('../../data/composers/TeamComposer');

class TeamInfo extends BaseView {
  constructor() {
    const teamSpan = elementCreator.createSpan({ text: '---' });
    const setTeamFunc = ({ user, team }) => {
      const identity = user || userComposer.getCurrentIdentity();

      teamSpan.innerHTML = '';

      if (identity.partOfTeams && identity.partOfTeams.length > 0) {
        const currentTeam = team || teamComposer.getTeam({ teamId: identity.partOfTeams[0] });

        teamSpan.appendChild(document.createTextNode(currentTeam.teamName));
      } else {
        teamSpan.appendChild(document.createTextNode('---'));
      }
    };

    super({});

    this.element = elementCreator.createContainer({
      classes: ['teamInfo'],
      clickFuncs: {
        leftFunc: () => {
          const identity = userComposer.getCurrentIdentity();

          if (identity.partOfTeams && identity.partOfTeams.length > 0) {
            const team = teamComposer.getTeam({ teamId: identity.partOfTeams[0] });
          }
        },
      },
    });
    this.element.appendChild(teamSpan);

    eventCentral.addWatcher({
      event: eventCentral.Events.COMPLETE_USER,
      func: () => {
        setTeamFunc({});
      },
    });

    eventCentral.addWatcher({
      event: eventCentral.Events.CHANGED_ALIAS,
      func: () => {
        setTeamFunc({});
      },
    });

    eventCentral.addWatcher({
      event: eventCentral.Events.LOGIN,
      func: () => {
        setTeamFunc({});
      },
    });

    eventCentral.addWatcher({
      event: eventCentral.Events.LOGOUT,
      func: () => {
        setTeamFunc({});
      },
    });

    eventCentral.addWatcher({
      event: eventCentral.Events.TEAM_MEMBER,
      func: ({ user, team }) => {
        const identity = userComposer.getCurrentIdentity();

        if (identity.objectId === user.objectId) {
          setTeamFunc({ user, team });
        }
      },
    });
  }
}

module.exports = TeamInfo;
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ActionMenu from '../../common/ActionMenu';
import withAsyncFetch from '../../common/hocs/AsyncContainer';
import withSummary from '../../common/hocs/SummarizedVizualization';
import withAttentionAggregation from '../../common/hocs/AttentionAggregation';
import AttentionOverTimeChart from '../../vis/AttentionOverTimeChart';
import { fetchTopicSplitStoryCounts, selectTimeAggregatePeriod } from '../../../actions/topicActions';
import messages from '../../../resources/messages';
import Permissioned from '../../common/Permissioned';
import { PERMISSION_LOGGED_IN } from '../../../lib/auth';
import { DownloadButton } from '../../common/IconButton';
import { getBrandDarkColor } from '../../../styles/colors';
import { filteredLinkTo, filtersAsUrlParams } from '../../util/location';
// import { PAST_WEEK } from '../../../lib/dateUtil';

const localMessages = {
  title: { id: 'topic.summary.splitStoryCount.title', defaultMessage: 'Attention Over Time' },
  descriptionIntro: { id: 'topic.summary.splitStoryCount.help.title', defaultMessage: '
Analyze attention to this topic over time to understand how it is covered. This chart shows the total number of stories that matched your topic query. Spikes in attention can reveal key events.  Plateaus can reveal stable, "normal", attention levels.
' },
  downloadCsv: { id: 'topic.summary.splitStoryCount.download', defaultMessage: 'Download daily story count CSV' },
};

class SplitStoryCountSummaryContainer extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { filters, fetchData } = this.props;
    if (nextProps.filters !== filters) {
      fetchData(nextProps);
    }
  }

  downloadCsv = () => {
    const { topicId, filters } = this.props;
    const url = `/api/topics/${topicId}/split-story/count.csv?${filtersAsUrlParams(filters)}`;
    window.location = url;
  }

  render() {
    const { total, counts } = this.props;
    return (
      <React.Fragment>
        <AttentionOverTimeChart
          total={total}
          data={counts}
          height={200}
          lineColor={getBrandDarkColor()}
          backgroundColor="#f5f5f5"
          interval={this.props.selectedTimePeriod}
        />
        <Permissioned onlyRole={PERMISSION_LOGGED_IN}>

            <ActionMenu actionTextMsg={messages.downloadOptions}>
              <MenuItem
                className="action-icon-menu-item"
                onClick={this.downloadCsv}
              >
                <ListItemText><FormattedMessage {...localMessages.downloadCsv} /></ListItemText>
                <ListItemIcon><DownloadButton /></ListItemIcon>
              </MenuItem>
            </ActionMenu>
            <ActionMenu actionTextMsg={messages.viewOptions}>
              {this.props.attentionViewOptions}
            </ActionMenu>

        </Permissioned>
      </React.Fragment>
    );
  }
}

SplitStoryCountSummaryContainer.propTypes = {
  // from composition chain
  intl: PropTypes.object.isRequired,
  // passed in
  topicId: PropTypes.number.isRequired,
  filters: PropTypes.object.isRequired,
  // from state
  fetchStatus: PropTypes.string.isRequired,
  total: PropTypes.number,
  counts: PropTypes.array, // array of {date: epochMS, count: int]
  // from dispath
  asyncFetch: PropTypes.func.isRequired,
  fetchData: PropTypes.func.isRequired,
  handleExplore: PropTypes.func.isRequired,

  handleTimePeriodClick: PropTypes.func,
  attentionViewOptions: PropTypes.object.isRequired, // from hoc
  selectedTimePeriod: PropTypes.string.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.summary.splitStoryCount.fetchStatus,
  total: state.topics.selected.summary.splitStoryCount.total,
  counts: state.topics.selected.summary.splitStoryCount.counts,
  selectedTimePeriod: state.topics.selected.summary.splitStoryCount.selectedTimePeriod,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (props) => {
    dispatch(fetchTopicSplitStoryCounts(props.topicId, props.filters));
  },
  handleExplore: () => {
    const exploreUrl = filteredLinkTo(`/topics/${ownProps.topicId}/attention`, ownProps.filters);
    dispatch(push(exploreUrl));
  },
  handleTimePeriodClick: (timeperiod) => {
    dispatch(selectTimeAggregatePeriod(timeperiod));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    asyncFetch: () => {
      dispatchProps.fetchData(ownProps);
    },
  });
}

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps, mergeProps)(
    withSummary(localMessages.title, localMessages.descriptionIntro, [messages.attentionChartHelpText])(
      withAttentionAggregation(
        withAsyncFetch(
          SplitStoryCountSummaryContainer
        )
      )
    )
  )
);
<commit_msg>#1334<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ActionMenu from '../../common/ActionMenu';
import withAsyncFetch from '../../common/hocs/AsyncContainer';
import withSummary from '../../common/hocs/SummarizedVizualization';
import withAttentionAggregation from '../../common/hocs/AttentionAggregation';
import AttentionOverTimeChart from '../../vis/AttentionOverTimeChart';
import { fetchTopicSplitStoryCounts, selectTimeAggregatePeriod } from '../../../actions/topicActions';
import messages from '../../../resources/messages';
import Permissioned from '../../common/Permissioned';
import { PERMISSION_LOGGED_IN } from '../../../lib/auth';
import { DownloadButton } from '../../common/IconButton';
import { getBrandDarkColor } from '../../../styles/colors';
import { filteredLinkTo, filtersAsUrlParams } from '../../util/location';
// import { PAST_WEEK } from '../../../lib/dateUtil';

const STACKED_VIEW = 0
const LINE_VIEW = 1

const localMessages = {
  title: { id: 'topic.summary.splitStoryCount.title', defaultMessage: 'Attention Over Time' },
  descriptionIntro: { id: 'topic.summary.splitStoryCount.help.title', defaultMessage: '
Analyze attention to this topic over time to understand how it is covered. This chart shows the total number of stories that matched your topic query. Spikes in attention can reveal key events.  Plateaus can reveal stable, "normal", attention levels.
' },
  downloadCsv: { id: 'topic.summary.splitStoryCount.download', defaultMessage: 'Download daily story count CSV' },
  stackedView: { id: 'topic.summary.splitStoryCount.view.stacked', defaultMessage: 'Stacked Area View' },
  lineView: { id: 'topic.summary.splitStoryCount.view.line', defaultMessage: 'Line View' },
};

class SplitStoryCountSummaryContainer extends React.Component {
  state = {
    view: LINE_VIEW,
  }

  componentWillReceiveProps(nextProps) {
    const { filters, fetchData } = this.props;
    if (nextProps.filters !== filters) {
      fetchData(nextProps);
    }
  }

  downloadCsv = () => {
    const { topicId, filters } = this.props;
    const url = `/api/topics/${topicId}/split-story/count.csv?${filtersAsUrlParams(filters)}`;
    window.location = url;
  }

  setView = (nextView) => {
    this.setState({ view: nextView });
  }

  render() {
    const { total, counts } = this.props;
    const stackedAreaView = (

        <MenuItem
          className="action-icon-menu-item"
          ddisabled={this.state.view === LINE_VIEW}
          onClick={() => this.setView(LINE_VIEW)}
        >
          <ListItemText><FormattedMessage {...localMessages.lineView} /></ListItemText>
        </MenuItem>
        <MenuItem
          className="action-icon-menu-item"
          disabled={this.state.view === STACKED_VIEW}
          onClick={() => this.setView(STACKED_VIEW)}
        >
          <ListItemText><FormattedMessage {...localMessages.stackedView} /></ListItemText>
        </MenuItem>

    );
    return (
      <React.Fragment>
        <AttentionOverTimeChart
          total={total}
          data={counts}
          height={200}
          lineColor={getBrandDarkColor()}
          backgroundColor="#f5f5f5"
          interval={this.props.selectedTimePeriod}
        />
        <Permissioned onlyRole={PERMISSION_LOGGED_IN}>

            <ActionMenu actionTextMsg={messages.downloadOptions}>
              <MenuItem
                className="action-icon-menu-item"
                onClick={this.downloadCsv}
              >
                <ListItemText><FormattedMessage {...localMessages.downloadCsv} /></ListItemText>
                <ListItemIcon><DownloadButton /></ListItemIcon>
              </MenuItem>
            </ActionMenu>
            <ActionMenu actionTextMsg={messages.viewOptions}>
              {this.props.attentionViewOptions}
              {stackedAreaView}
            </ActionMenu>

        </Permissioned>
      </React.Fragment>
    );
  }
}

SplitStoryCountSummaryContainer.propTypes = {
  // from composition chain
  intl: PropTypes.object.isRequired,
  // passed in
  topicId: PropTypes.number.isRequired,
  filters: PropTypes.object.isRequired,
  // from state
  fetchStatus: PropTypes.string.isRequired,
  total: PropTypes.number,
  counts: PropTypes.array, // array of {date: epochMS, count: int]
  // from dispath
  asyncFetch: PropTypes.func.isRequired,
  fetchData: PropTypes.func.isRequired,
  handleExplore: PropTypes.func.isRequired,

  handleTimePeriodClick: PropTypes.func,
  attentionViewOptions: PropTypes.object.isRequired, // from hoc
  selectedTimePeriod: PropTypes.string.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.summary.splitStoryCount.fetchStatus,
  total: state.topics.selected.summary.splitStoryCount.total,
  counts: state.topics.selected.summary.splitStoryCount.counts,
  selectedTimePeriod: state.topics.selected.summary.splitStoryCount.selectedTimePeriod,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (props) => {
    dispatch(fetchTopicSplitStoryCounts(props.topicId, props.filters));
  },
  handleExplore: () => {
    const exploreUrl = filteredLinkTo(`/topics/${ownProps.topicId}/attention`, ownProps.filters);
    dispatch(push(exploreUrl));
  },
  handleTimePeriodClick: (timeperiod) => {
    dispatch(selectTimeAggregatePeriod(timeperiod));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    asyncFetch: () => {
      dispatchProps.fetchData(ownProps);
    },
  });
}

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps, mergeProps)(
    withSummary(localMessages.title, localMessages.descriptionIntro, [messages.attentionChartHelpText])(
      withAttentionAggregation(
        withAsyncFetch(
          SplitStoryCountSummaryContainer
        )
      )
    )
  )
);
<|endoftext|>


<commit_before>var Bundle = function(bundle) {
    var templates = {};

    var defaults = {
        render_method: 'html'
    };

    var _parseDataURL = function(url, values) {
        var _newUrl = url;
        var matcher = /{{(\w*)}}/gi;

        var match;
        while((match = matcher.exec(url))) {
            _newUrl = _newUrl.replace(match[0], values[match[1]]);
        }

        return _newUrl;
    };

    return function(element, data, config) {
        element = $(element);
        data = $.extend({}, bundle.data, data);
        config = $.extend({}, defaults, bundle, config);

        var templateFetching = new $.Deferred();
        if (('template' in config) && typeof templates[config.template] === 'undefined') {
            $.get(config.template).done(function(template) {
                templates[config.template] = Handlebars.compile(template);
                templateFetching.resolve(templates[config.template]);
            }).fail(function(def, status, error) {
                throw new Error('The following error occured while fetching the template: ' + error);
            });
        } else {
            templateFetching.resolve(templates[config.template]);
        }

        var dataFetching = new $.Deferred();
        if ('data_src' in config) {
            config.data_src = _parseDataURL(config.data_src, data);

            $.getJSON(config.data_src).done(function(remote_data) {
                data = $.extend({}, data, remote_data);
                dataFetching.resolve(data);
            }).fail(function(def, status, error) {
                throw new Error('The following error occured while fetching the template: ' + error);
            });
        } else {
            dataFetching.resolve(data);
        }

        $.when(templateFetching, dataFetching).done(function(template, data) {
            var $template;
            if (typeof template === 'function') {
                $template = $(template(data));
            }

            if ('events' in config) {
                $.each(config.events, function(event, callback) {
                    var index = event.lastIndexOf(" ");
                    var element = $template.find(event.substring(0, index));
                    var action = event.substring(index, event.length);

                    element.on(action, function(event) {
                        callback.call(config, event, element);
                    });
                });
            }

            if ('render' in config) {
                config.render.call(config, element, data, template);
            } else {
                element[config.render_method]($template);
            }

            if ('init' in bundle) {
                bundle.init.call(config, element, data);
            }
        });
    };
};<commit_msg>wrapping things.<commit_after>;(function(namespace, $, Handlebars) {
    namespace.Bundle = function(bundle) {
        'use strict';

        var templates = {};

        var defaults = {
            render_method: 'html'
        };

        var _parseDataURL = function(url, values) {
            var _newUrl = url;
            var matcher = /{{(\w*)}}/gi;

            var match;
            while((match = matcher.exec(url))) {
                _newUrl = _newUrl.replace(match[0], values[match[1]]);
            }

            return _newUrl;
        };

        return function(element, data, config) {
            element = $(element);
            data = $.extend({}, bundle.data, data);
            config = $.extend({}, defaults, bundle, config);

            var templateFetching = new $.Deferred();
            if (('template' in config) && typeof templates[config.template] === 'undefined') {
                $.get(config.template).done(function(template) {
                    templates[config.template] = Handlebars.compile(template);
                    templateFetching.resolve(templates[config.template]);
                }).fail(function(def, status, error) {
                    throw new Error('The following error occured while fetching the template: ' + error);
                });
            } else {
                templateFetching.resolve(templates[config.template]);
            }

            var dataFetching = new $.Deferred();
            if ('data_src' in config) {
                config.data_src = _parseDataURL(config.data_src, data);

                $.getJSON(config.data_src).done(function(remote_data) {
                    data = $.extend({}, data, remote_data);
                    dataFetching.resolve(data);
                }).fail(function(def, status, error) {
                    throw new Error('The following error occured while fetching the template: ' + error);
                });
            } else {
                dataFetching.resolve(data);
            }

            $.when(templateFetching, dataFetching).done(function(template, data) {
                var $template;
                if (typeof template === 'function') {
                    $template = $(template(data));
                }

                if ('events' in config) {
                    $.each(config.events, function(event, callback) {
                        var index = event.lastIndexOf(' ');
                        var element = $template.find(event.substring(0, index));
                        var action = event.substring(index, event.length);

                        element.on(action, function(event) {
                            callback.call(config, event, element);
                        });
                    });
                }

                if ('render' in config) {
                    config.render.call(config, element, data, template);
                } else {
                    element[config.render_method]($template);
                }

                if ('init' in bundle) {
                    bundle.init.call(config, element, data);
                }
            });
        };
    };
}(this, jQuery, Handlebars));<|endoftext|>


<commit_before>var App;

module("ember-testing", {
  teardown: function() {
    Ember.run(App, App.destroy);
    App.removeTestHelpers();
    App = null;
  }
});

test("Ember.Application#injectTestHelpers/#removeTestHelpers", function() {
  App = Ember.run(Ember.Application, Ember.Application.create);
  ok(!window.visit);
  ok(!App.testHelpers.visit);
  ok(!window.click);
  ok(!App.testHelpers.click);
  ok(!window.fillIn);
  ok(!App.testHelpers.fillIn);
  ok(!window.wait);
  ok(!App.testHelpers.wait);

  App.injectTestHelpers();

  ok(window.visit);
  ok(App.testHelpers.visit);
  ok(window.click);
  ok(App.testHelpers.click);
  ok(window.fillIn);
  ok(App.testHelpers.fillIn);
  ok(window.wait);
  ok(App.testHelpers.wait);

  App.removeTestHelpers();

  ok(!window.visit);
  ok(!App.testHelpers.visit);
  ok(!window.click);
  ok(!App.testHelpers.click);
  ok(!window.fillIn);
  ok(!App.testHelpers.fillIn);
  ok(!window.wait);
  ok(!App.testHelpers.wait);
});

test("Ember.Application#setupForTesting", function() {
  Ember.run(function() {
    App = Ember.Application.create();
    App.setupForTesting();
  });

  equal(App.__container__.lookup('router:main').location.implementation, 'none');
});

test("Ember.Test.registerHelper/unregisterHelper", function() {
  expect(3);
  var appBooted = false;

  Ember.Test.registerHelper('boot', function(app) {
    Ember.run(app, app.advanceReadiness);
    appBooted = true;
    return window.wait();
  });

  Ember.run(function() {
    App = Ember.Application.create();
    App.setupForTesting();
    App.injectTestHelpers();
  });

  ok(window.boot);

  window.boot().then(function() {
    ok(appBooted);
  });

  App.removeTestHelpers();
  Ember.Test.unregisterHelper('boot');

  ok(!window.boot);
});
<commit_msg>Fix Ember.Test.registerHelper test<commit_after>var App;

module("ember-testing", {
  teardown: function() {
    Ember.run(App, App.destroy);
    App.removeTestHelpers();
    App = null;
  }
});

test("Ember.Application#injectTestHelpers/#removeTestHelpers", function() {
  App = Ember.run(Ember.Application, Ember.Application.create);
  ok(!window.visit);
  ok(!App.testHelpers.visit);
  ok(!window.click);
  ok(!App.testHelpers.click);
  ok(!window.fillIn);
  ok(!App.testHelpers.fillIn);
  ok(!window.wait);
  ok(!App.testHelpers.wait);

  App.injectTestHelpers();

  ok(window.visit);
  ok(App.testHelpers.visit);
  ok(window.click);
  ok(App.testHelpers.click);
  ok(window.fillIn);
  ok(App.testHelpers.fillIn);
  ok(window.wait);
  ok(App.testHelpers.wait);

  App.removeTestHelpers();

  ok(!window.visit);
  ok(!App.testHelpers.visit);
  ok(!window.click);
  ok(!App.testHelpers.click);
  ok(!window.fillIn);
  ok(!App.testHelpers.fillIn);
  ok(!window.wait);
  ok(!App.testHelpers.wait);
});

test("Ember.Application#setupForTesting", function() {
  Ember.run(function() {
    App = Ember.Application.create();
    App.setupForTesting();
  });

  equal(App.__container__.lookup('router:main').location.implementation, 'none');
});

test("Ember.Test.registerHelper/unregisterHelper", function() {
  expect(5);
  var appBooted = false;

  Ember.Test.registerHelper('boot', function(app) {
    Ember.run(app, app.advanceReadiness);
    appBooted = true;
    return window.wait();
  });

  Ember.run(function() {
    App = Ember.Application.create();
    App.setupForTesting();
    App.injectTestHelpers();
  });

  ok(App.testHelpers.boot);
  ok(window.boot);

  window.boot().then(function() {
    ok(appBooted);

    App.removeTestHelpers();
    Ember.Test.unregisterHelper('boot');

    ok(!App.testHelpers.boot);
    ok(!window.boot);
  });

});
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = {

	package: require('./../../../../package.json'),

	text: function (count, max) {
		if (max !== 0 && typeof max !== 'undefined' && max > count) {
			count = Math.floor(Math.random() * max) + count;
		}
		var text = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. ';
		text = text + text + text;
		return text.substr(0, count);
	},

	img: function (width, height, src) {
		var splitSrc = src.split('.');
		var fileEnding = splitSrc.pop();
		return '_assets/generated/' + splitSrc.join() + '_' + width + 'x' + height + '.' + fileEnding;
	},

	link: function () {
		return 'http://www.virtual-identity.com';
	},

	renderHbs: function (template, data) {
		require('./../../../../app/resources/js/handlebars.helper.js');
		var hbs = './../../../../.tmp/resources/js/handlebars.templates.js';
		delete require.cache[require.resolve(hbs)];
		require(hbs);

		try {
			// is data valid JSON
			data = JSON.parse(data);
		} catch (e) {

			try {
				//is data a JSON file
				var jsonString = fs.readFileSync(data, 'utf8');
				data = JSON.parse(jsonString);
			} catch (e) {
				return '';
			}

		}

		return global.configuration.data.tpl[template](data);
	},

	delayedImage: function () {
		console.log('TODO: zetzer->delayedImage()');
	},

	inc: function(file) {
		return this.include(file);
	}
};
<commit_msg>updated zetzerHelper to accept template variables<commit_after>var fs = require('fs');
var gutil = require('gulp-util');

module.exports = {

    template: gutil.env.template,

	package: require('./../../../../package.json'),

	text: function (count, max) {
		if (max !== 0 && typeof max !== 'undefined' && max > count) {
			count = Math.floor(Math.random() * max) + count;
		}
		var text = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. ';
		text = text + text + text;
		return text.substr(0, count);
	},

	img: function (width, height, src) {
		var splitSrc = src.split('.');
		var fileEnding = splitSrc.pop();
		return '_assets/generated/' + splitSrc.join() + '_' + width + 'x' + height + '.' + fileEnding;
	},

	link: function () {
		return 'http://www.virtual-identity.com';
	},

	renderHbs: function (template, data) {
		require('./../../../../app/resources/js/handlebars.helper.js');
		var hbs = './../../../../.tmp/resources/js/handlebars.templates.js';
		delete require.cache[require.resolve(hbs)];
		require(hbs);

		try {
			// is data valid JSON
			data = JSON.parse(data);
		} catch (e) {

			try {
				//is data a JSON file
				var jsonString = fs.readFileSync(data, 'utf8');
				data = JSON.parse(jsonString);
			} catch (e) {
				return '';
			}

		}

		return global.configuration.data.tpl[template](data);
	},

	delayedImage: function () {
		console.log('TODO: zetzer->delayedImage()');
	},

	inc: function(file) {
		return this.include(file);
	}
};
<|endoftext|>


<commit_before>import React from "react";
import run from "../maki-interpreter/interpreter";
import System from "../maki-interpreter/runtime/System";
import runtime from "../maki-interpreter/runtime";
import Variable from "./Variable";
import Value from "./Value";
import Command from "./Command";
import { useDropzone } from "react-dropzone";

function readFileAsArrayBuffer(file) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = () => {
      resolve(fileReader.result);
    };
    fileReader.onerror = reject;
    fileReader.readAsArrayBuffer(file);
  });
}

function Wrapper() {
  const [maki, setMaki] = React.useState(null);
  const onDrop = React.useCallback(async acceptedFiles => {
    if (acceptedFiles.length !== 1) {
      alert("Only drop one file at a time");
      return;
    }
    const file = acceptedFiles[0];
    const arrayBuffer = await readFileAsArrayBuffer(file);
    setMaki(arrayBuffer);
    // Do something with the files
  }, []);
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
  return (

      {maki == null ? (
        <>

            Drop a .maki file here to debug

          <input {...getInputProps()} type="file" />
        </>
      ) : (
        <Debugger maki={maki} />
      )}

  );
}

/*
async function fetchTestScript() {
  const response = await fetch(basicTestUrl);
  return response.arrayBuffer();
}
*/

const initialState = {
  variables: [],
  stack: [],
  commands: [],
  commandOffset: 0,
};

function Debugger({ maki }) {
  // This is all a huge disaster
  const getNextStepPromiseRef = React.useRef(null);
  const [next, setNext] = React.useState(() => {});
  const [breakPoints, setBreakpoints] = React.useState(new Set([2]));
  const [paused, setPaused] = React.useState(false);
  const [state, dispatch] = React.useReducer((state, action) => {
    switch (action.type) {
      case "STEPPED":
        const { variables, commands, commandOffset, stack } = action;
        return {
          ...state,
          variables,
          commands,
          commandOffset,
          stack,
        };
      default:
        throw new Error("Unknown action type");
    }
  }, initialState);

  const { variables, stack, commands, commandOffset } = state;

  getNextStepPromiseRef.current = i => {
    if (!paused) {
      if (breakPoints.has(i)) {
        setPaused(true);
      } else {
        return;
      }
    }
    return new Promise((resolve, reject) => {
      // setState accepts a creator function, so we have to pass a function that returns our function.
      setNext(() => resolve);
    });
  };
  const system = new System();

  React.useEffect(() => {
    run({
      runtime,
      data: maki,
      system,
      logger: ({ i, stack, program }) => {
        const { variables, commands } = program;
        dispatch({
          type: "STEPPED",
          variables,
          commands,
          commandOffset: i,
          stack,
        });
        return getNextStepPromiseRef.current(i);
      },
    });
  }, []);

  React.useEffect(() => {
    function handler(e) {
      switch (e.key) {
        case ";":
          next();
          break;
        default:
        // console.log(e.key);
      }
    }
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  });

  return (

        <button onClick={next}>Next</button>
        {paused ? (
          <button
            onClick={() => {
              setPaused(false);
              next();
            }}
          >
            Play
          </button>
        ) : (
          <button onClick={() => setPaused(true)}>Pause</button>
        )}

Commands

            {commands != null &&
              commands.map((command, i) => (

                    {breakPoints.has(i) ? (
                      <button
                        onClick={() => {
                          const newBreakPoints = new Set(breakPoints);
                          newBreakPoints.delete(i);
                          setBreakpoints(newBreakPoints);
                          if (commandOffset === i) {
                            next();
                          }
                        }}
                      >
                        Clear
                      </button>
                    ) : (
                      <button
                        onClick={() => {
                          const newBreakPoints = new Set(breakPoints);
                          newBreakPoints.add(i);
                          setBreakpoints(newBreakPoints);
                        }}
                      >
                        Pause
                      </button>
                    )}
                    {i}

                    <Command command={command} variables={variables} />

              ))}

Stack

            {stack != null &&
              stack.map((value, i) => (

                  {i}

                    <Value value={value} />

              ))}

Variables

            {variables != null &&
              variables.map((variable, i) => (

                  {i}

                    <Variable variable={variable} />

              ))}

  );
}

export default Wrapper;
<commit_msg>Fix initial paused state<commit_after>import React from "react";
import run from "../maki-interpreter/interpreter";
import System from "../maki-interpreter/runtime/System";
import runtime from "../maki-interpreter/runtime";
import Variable from "./Variable";
import Value from "./Value";
import Command from "./Command";
import { useDropzone } from "react-dropzone";

function readFileAsArrayBuffer(file) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = () => {
      resolve(fileReader.result);
    };
    fileReader.onerror = reject;
    fileReader.readAsArrayBuffer(file);
  });
}

function Wrapper() {
  const [maki, setMaki] = React.useState(null);
  const onDrop = React.useCallback(async acceptedFiles => {
    if (acceptedFiles.length !== 1) {
      alert("Only drop one file at a time");
      return;
    }
    const file = acceptedFiles[0];
    const arrayBuffer = await readFileAsArrayBuffer(file);
    setMaki(arrayBuffer);
    // Do something with the files
  }, []);
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
  return (

      {maki == null ? (
        <>

            Drop a .maki file here to debug

          <input {...getInputProps()} type="file" />
        </>
      ) : (
        <Debugger maki={maki} />
      )}

  );
}

/*
async function fetchTestScript() {
  const response = await fetch(basicTestUrl);
  return response.arrayBuffer();
}
*/

const initialState = {
  variables: [],
  stack: [],
  commands: [],
  commandOffset: 0,
};

function Debugger({ maki }) {
  // This is all a huge disaster
  const getNextStepPromiseRef = React.useRef(null);
  const [next, setNext] = React.useState(() => {});
  const [breakPoints, setBreakpoints] = React.useState(new Set([]));
  const [paused, setPaused] = React.useState(true);
  const [state, dispatch] = React.useReducer((state, action) => {
    switch (action.type) {
      case "STEPPED":
        const { variables, commands, commandOffset, stack } = action;
        return {
          ...state,
          variables,
          commands,
          commandOffset,
          stack,
        };
      default:
        throw new Error("Unknown action type");
    }
  }, initialState);

  const { variables, stack, commands, commandOffset } = state;

  getNextStepPromiseRef.current = i => {
    if (!paused) {
      if (breakPoints.has(i)) {
        setPaused(true);
      } else {
        return;
      }
    }
    return new Promise((resolve, reject) => {
      // setState accepts a creator function, so we have to pass a function that returns our function.
      setNext(() => resolve);
    });
  };
  const system = new System();

  React.useEffect(() => {
    run({
      runtime,
      data: maki,
      system,
      logger: ({ i, stack, program }) => {
        const { variables, commands } = program;
        dispatch({
          type: "STEPPED",
          variables,
          commands,
          commandOffset: i,
          stack,
        });
        return getNextStepPromiseRef.current(i);
      },
    });
  }, []);

  React.useEffect(() => {
    function handler(e) {
      switch (e.key) {
        case ";":
          next();
          break;
        default:
        // console.log(e.key);
      }
    }
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  });

  return (

        <button onClick={next}>Next</button>
        {paused ? (
          <button
            onClick={() => {
              setPaused(false);
              next();
            }}
          >
            Play
          </button>
        ) : (
          <button onClick={() => setPaused(true)}>Pause</button>
        )}

Commands

            {commands != null &&
              commands.map((command, i) => (

                    {breakPoints.has(i) ? (
                      <button
                        onClick={() => {
                          const newBreakPoints = new Set(breakPoints);
                          newBreakPoints.delete(i);
                          setBreakpoints(newBreakPoints);
                          if (commandOffset === i) {
                            next();
                          }
                        }}
                      >
                        Clear
                      </button>
                    ) : (
                      <button
                        onClick={() => {
                          const newBreakPoints = new Set(breakPoints);
                          newBreakPoints.add(i);
                          setBreakpoints(newBreakPoints);
                        }}
                      >
                        Pause
                      </button>
                    )}
                    {i}

                    <Command command={command} variables={variables} />

              ))}

Stack

            {stack != null &&
              stack.map((value, i) => (

                  {i}

                    <Value value={value} />

              ))}

Variables

            {variables != null &&
              variables.map((variable, i) => (

                  {i}

                    <Variable variable={variable} />

              ))}

  );
}

export default Wrapper;
<|endoftext|>


<commit_before>const { Argument } = require('klasa');

module.exports = class extends Argument {

	constructor(...args) {
		super(...args, { aliases: ['int'] });
	}

	run(arg, possible, msg) {
		const { min, max } = possible;
		const number = parseInt(arg);
		if (!Number.isInteger(number)) throw (msg.language || this.client.languages.default).get('RESOLVER_INVALID_INT', possible.name);
		return this.constructor.minOrMax(this.client, arg, min, max, possible, msg) ? arg : null;
	}

};
<commit_msg>fix integer<commit_after>const { Argument } = require('klasa');

module.exports = class extends Argument {

	constructor(...args) {
		super(...args, { aliases: ['int'] });
	}

	run(arg, possible, msg) {
		const { min, max } = possible;
		const number = parseInt(arg);
		if (!Number.isInteger(number)) throw (msg.language || this.client.languages.default).get('RESOLVER_INVALID_INT', possible.name);
		return this.constructor.minOrMax(this.client, number, min, max, possible, msg) ? number : null;
	}

};
<|endoftext|>


<commit_before>const roles = require('../models').Role;

class Roles {
  create(req, res) {
    return roles
    .create(req.body)
    .then((role) => {
      res.status(201).send({
        message: 'Role created succesfully',
        role,
      });
    })
    .catch(error => res.status(400).send(error.errors));
  }
  update(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return role
        .update(req.body)
        .then(() => res.status(200).send(role))
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }
  findOne(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return res.status(200).send(role);
    })
    .catch(error => res.status(400).send(error));
  }
  listAll(req, res) {
    return roles
    .findAll()
    .then(role => res.status(200).send({ message: 'Listing all available roles', role }))
    .catch(error => res.status(400).send(error));
  }
  delete(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role not found',
        });
      }
      return role
        .destroy()
        .then(() => {
          res.status(200).send({
            message: 'Role deleted successfully',
          });
        })
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }
}

exports.Roles = Roles;
<commit_msg>[feature #142608843] Add jdsoc comments as required<commit_after>const roles = require('../models').Role;
/**
 * Roles Class
 *
 * @class
 */
class Roles {
  /**
   * create
   *
   * Creates a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  create(req, res) {
    return roles
    .create(req.body)
    .then((role) => {
      res.status(201).send({
        message: 'Role created succesfully',
        role,
      });
    })
    .catch(error => res.status(400).send(error.errors));
  }

  /**
   * update
   *
   * Updates a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  update(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return role
        .update(req.body)
        .then(() => res.status(200).send(role))
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }

  /**
   * findOne
   *
   * Finds a specific role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  findOne(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return res.status(200).send(role);
    })
    .catch(error => res.status(400).send(error));
  }

  /**
   * listAll
   *
   * Lists all roles
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  listAll(req, res) {
    return roles
    .findAll()
    .then(role => res.status(200).send({ message: 'Listing all available roles', role }))
    .catch(error => res.status(400).send(error));
  }

  /**
   * delete
   *
   * Deletes a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  delete(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role not found',
        });
      }
      return role
        .destroy()
        .then(() => {
          res.status(200).send({
            message: 'Role deleted successfully',
          });
        })
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }
}

exports.Roles = Roles;
<|endoftext|>