<commit_before>/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/epam/ReportPortal
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

define(function (require) {
    'use strict';

    var SingletonLaunchFilterCollection = require('filters/SingletonLaunchFilterCollection');
    var Epoxy = require('backbone-epoxy');
    var Util = require('util');
    var $ = require('jquery');
    var _ = require('underscore');
    var Backbone = require('backbone');
    var WidgetService = require('newWidgets/WidgetService');
    var CoreService = require('coreService');
    var FilterModel = require('filters/FilterModel');
    var FilterItem = require('modals/addWidget/FilterSearchItemView');
    var FilterSearchEditView = require('modals/addWidget/FilterSearchEditView');
    var FilterSearchAddView = require('modals/addWidget/FilterSearchAddView');
    var App = require('app');

    var config = App.getInstance();

    var FilterCollection = Backbone.Collection.extend({
        model: FilterModel,
        initialize: function (data, options) {
            this.mainModel = options.mainModel;
            this.listenTo(this, 'change:active', this.onChangeActive);
        },
        onChangeActive: function (model, active) {
            if (active) {
                _.each(this.models, function (curModel) {
                    if (curModel !== model) {
                        curModel.set({ active: false });
                    }
                });
            }
        },
        parse: function (data) {
            var self = this;
            return _.map(data, function (itemData) {
                var item = itemData;
                item.entities = JSON.stringify(item.entities);
                item.selection_parameters = JSON.stringify(item.selection_parameters);
                item.active = !!(item.id === self.mainModel.get('filter_id'));
                return item;
            });
        }
    });

    var FilterSearchView = Epoxy.View.extend({
        className: 'modal-add-widget-filter-search',
        template: 'tpl-modal-add-widget-filter-search',
        events: {
            'validation:success [data-js-filter-name-search]': 'onChangeFilterName',
            'click [data-js-add-filter]': 'onClickAddFilter'
        },
        bindings: {
            ':el': 'classes: {hide: not(gadgetIsFilter)}',
            '[data-js-search-query]': 'text: search',
            '[data-js-filter-none]': 'classes: {hide:    not(empty)}',
            '[data-js-filter-empty]': 'classes: { hide:  not(notFound)  }',
            '[data-js-filter-name-search]': 'attr: {disabled: empty}'

        },
        bindingFilters: {
            filtersAvailability: function (search, empty) {
                if (!search && empty) {
                    return false;
                }
                return true;
            }
        },
        initialize: function (options) {
            this.modalType = options.modalType;
            this.firstActivate = true;
            this.collection = new FilterCollection([], { mainModel: this.model });
            this.renderViews = [];
            this.render();
            this.viewModel = new Epoxy.Model({
                search: '',
                empty: false,
                notFound: false,
                currentPage: 1,
                pageSize: 10,
                totalPage: 1
            });
            Util.hintValidator($('[data-js-filter-name-search]', this.$el), [{
                validator: 'minMaxNotRequired',
                type: 'filterName',
                min: 3,
                max: 128
            }]);

            this.listenTo(this.viewModel, 'change:search', _.debounce(this.updateFilters, 500));
            this.listenTo(this.collection, 'add', this.onAddCollectionItems);
            this.listenTo(this.collection, 'reset', this.onResetCollectionItems);
            this.listenTo(this.collection, 'change:active', this.onSelectFilterCheck);
            this.listenTo(this.collection, 'edit', this.onEditFilter);
        },
        render: function () {
            this.$el.html(Util.templates(this.template, {}));
        },
        setFilterModel: function (model) {
            this.selectFilterView && this.selectFilterView.destroy();
            if (model) {
                $('[data-js-select-filter-block]', this.$el).removeClass('empty-state');
                this.selectFilterView = new FilterItem({
                    model: model, searchTerm: this.viewModel.get('search')
                });
                $('[data-js-select-filter-container]', this.$el).html(this.selectFilterView.$el);
                this.selectedFilterModel = model;
                this.selectFilterView.$el.on('mouseenter', function () {
                    config.trackingDispatcher.trackEventNumber(296);
                });
            } else {
                $('[data-js-select-filter-block]', this.$el).addClass('empty-state');
            }
        },
        getSelectedFilterModel: function () {
            if (!this.selectedFilterModel && this.model.get('filter_id')) {
                this.launchFilterCollection = new SingletonLaunchFilterCollection();
                this.setFilterModel(this.launchFilterCollection.get(this.model.get('filter_id')));
            }
            return this.selectedFilterModel;
        },
        onSelectFilterCheck: function (model, active) {
            active && this.onSelectFilter(model);
        },
        onSelectFilter: function (filterModel) {
            this.model.set({ filter_id: filterModel.get('id') });
            var curOptions = this.model.getWidgetOptions();
            curOptions.filterName = [filterModel.get('name')];
            this.model.setWidgetOptions(curOptions);
            this.setFilterModel(filterModel);
        },
        onClickAddFilter: function (e) {
            var self = this;
            if (this.modalType === 'edit') {
                config.trackingDispatcher.trackEventNumber(328);
            } else {
                config.trackingDispatcher.trackEventNumber(295);
            }
            e.preventDefault();
            this.$el.addClass('hide-content');
            this.addFilterView && this.stopListening(this.addFilterView) &&
                this.addFilterView.destroy();
            this.addFilterView = new FilterSearchAddView({
                gadgetModel: this.model,
                modalType: this.modalType
            });
            this.listenTo(this.addFilterView, 'change:filter', this.onSelectFilter);
            this.addFilterView.activate();
            $('[data-js-filter-add-container]', this.$el).html(this.addFilterView.$el);
            this.trigger('disable:navigation', true);
            this.addFilterView.getReadyState()
                .always(function () {
                    self.addFilterView.destroy();
                    self.$el.removeClass('hide-content');
                    self.trigger('disable:navigation', false);
                    self.updateFilters();
                })
                .fail(function () {
                    self.model.set({ filter_id: '' });
                    self.setFilterModel(null);
                });
        },
        onEditFilter: function (model) {
            var self = this;
            this.$el.addClass('hide-content');
            this.editFilterView && this.editFilterView.destroy();
            this.editFilterView = new FilterSearchEditView({
                model: model,
                gadgetModel: this.model,
                modalType: this.modalType
            });
            $('[data-js-filter-edit-container]', this.$el).html(this.editFilterView.$el);
            this.trigger('disable:navigation', true);
            this.editFilterView.getReadyState()
                .always(function () {
                    self.editFilterView.destroy();
                    self.$el.removeClass('hide-content');
                    self.trigger('disable:navigation', false);
                });
        },
        activate: function () {
            var curWidget = WidgetService.getWidgetConfig(this.model.get('gadget'));
            var self = this;
            if (!this.firstActivate) {
                return;
            }
            if (!curWidget.noFilters) {
                this.firstActivate = false;
                this.load().always(function () {
                    self.baronScroll = Util.setupBaronScroll($('[data-js-filter-list-scroll]', self.$el));
                    Util.setupBaronScrollSize(self.baronScroll, { maxHeight: 330 });
                    self.baronScroll.on('scroll', function () {
                        var elem = self.baronScroll.get(0);
                        if (elem.scrollHeight - elem.scrollTop < elem.offsetHeight * 2) {
                            self.addLoadData();
                        }
                    });
                });
            }
        },
        addLoadData: function () {
            if (this.viewModel.get('currentPage') < this.viewModel.get('totalPage') && !this.$el.hasClass('load')) {
                this.viewModel.set('currentPage', this.viewModel.get('currentPage') + 1);
                this.load();
            }
        },
        onChangeFilterName: function (e) {
            var value = $(e.currentTarget).val();
            if (value) {
                if (this.modalType === 'edit') {
                    config.trackingDispatcher.trackEventNumber(327);
                } else {
                    config.trackingDispatcher.trackEventNumber(294);
                }
            }
            this.viewModel.set({ search: value });
        },
        onAddCollectionItems: function (model) {
            this.renderFilter(model);
        },
        onResetCollectionItems: function () {
            _.each(this.renderViews, function (view) {
                view.destroy();
            });
            this.renderViews = [];
            _.each(this.collection.models, function (model) {
                this.renderFilter(model);
            }, this);
        },
        renderFilter: function (model) {
            var filterItem = new FilterItem({
                model: model,
                searchTerm: this.viewModel.get('search'),
                modalType: this.modalType
            });
            $('[data-js-filter-list]', this.$el).append(filterItem.$el);
            this.renderViews.push(filterItem);
        },
        updateFilters: function () {
            var self = this;
            this.collection.destroyModels();
            this.collection.reset([]);
            this.viewModel.set({
                totalPage: 1,
                currentPage: 1
            });
            this.load()
                .done(function () {
                    Util.setupBaronScrollSize(self.baronScroll, { maxHeight: 330 });
                });
        },
        load: function () {
            var self = this;
            this.$el.addClass('load');
            self.viewModel.set({ empty: false, notFound: false });
            return CoreService.saveFilter(this.getQueryString({
                search: encodeURIComponent(this.viewModel.get('search')),
                page: this.viewModel.get('currentPage'),
                size: this.viewModel.get('pageSize')
            }))
                .always(function () {
                    self.$el.removeClass('load');
                })
                .done(function (data) {
                    var launchFilterCollection;
                    self.viewModel.set({
                        totalPage: data.page.totalPages,
                        currentPage: data.page.number
                    });
                    if (data.content.length) {
                        self.viewModel.set({ empty: false, notFound: false });
                    } else if (!self.viewModel.get('search')) {
                        self.viewModel.set({ empty: true, notFound: false });
                    } else {
                        self.viewModel.set({ empty: false, notFound: true });
                    }
                    self.collection.add(data.content, { parse: true });
                    if (self.model.get('filter_id')) {
                        if (self.collection.get(self.model.get('filter_id'))) {
                            self.setFilterModel(self.collection.get(self.model.get('filter_id')));
                        } else {
                            launchFilterCollection = new SingletonLaunchFilterCollection();
                            launchFilterCollection.ready.done(function () {
                                self.setFilterModel(launchFilterCollection.get(self.model.get('filter_id')));
                            });
                        }
                    }
                    $('[data-js-select-filter-block]', self.$el)[(!data.content.length ? 'add' : 'remove') + 'Class']('hide');
                });
        },
        getQueryString: function (query) {
            var url;
            var Query = query;
            if (!Query) Query = {};
            if (!Query.page) Query.page = 1;
            if (!Query.size) Query.size = 10;
            url = '?page.sort=name&page.page=' + Query.page + '&page.size=' + Query.size;
            if (Query.search) {
                url += '&filter.cnt.name=' + Query.search;
            }
            return url;
        },
        onDestroy: function () {
            this.collection.destroy(true);
            this.$el.remove();
        }
    });

    return FilterSearchView;
});
<commit_msg>Fix for creating passing rate summary widget from launches page.<commit_after>/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/epam/ReportPortal
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

define(function (require) {
    'use strict';

    var SingletonLaunchFilterCollection = require('filters/SingletonLaunchFilterCollection');
    var Epoxy = require('backbone-epoxy');
    var Util = require('util');
    var $ = require('jquery');
    var _ = require('underscore');
    var Backbone = require('backbone');
    var WidgetService = require('newWidgets/WidgetService');
    var CoreService = require('coreService');
    var FilterModel = require('filters/FilterModel');
    var FilterItem = require('modals/addWidget/FilterSearchItemView');
    var FilterSearchEditView = require('modals/addWidget/FilterSearchEditView');
    var FilterSearchAddView = require('modals/addWidget/FilterSearchAddView');
    var App = require('app');

    var config = App.getInstance();

    var FilterCollection = Backbone.Collection.extend({
        model: FilterModel,
        initialize: function (data, options) {
            this.mainModel = options.mainModel;
            this.listenTo(this, 'change:active', this.onChangeActive);
        },
        onChangeActive: function (model, active) {
            if (active) {
                _.each(this.models, function (curModel) {
                    if (curModel !== model) {
                        curModel.set({ active: false });
                    }
                });
            }
        },
        parse: function (data) {
            var self = this;
            return _.map(data, function (itemData) {
                var item = itemData;
                item.entities = JSON.stringify(item.entities);
                item.selection_parameters = JSON.stringify(item.selection_parameters);
                item.active = !!(item.id === self.mainModel.get('filter_id'));
                return item;
            });
        }
    });

    var FilterSearchView = Epoxy.View.extend({
        className: 'modal-add-widget-filter-search',
        template: 'tpl-modal-add-widget-filter-search',
        events: {
            'validation:success [data-js-filter-name-search]': 'onChangeFilterName',
            'click [data-js-add-filter]': 'onClickAddFilter'
        },
        bindings: {
            ':el': 'classes: {hide: not(gadgetIsFilter)}',
            '[data-js-search-query]': 'text: search',
            '[data-js-filter-none]': 'classes: {hide:    not(empty)}',
            '[data-js-filter-empty]': 'classes: { hide:  not(notFound)  }',
            '[data-js-filter-name-search]': 'attr: {disabled: empty}'

        },
        bindingFilters: {
            filtersAvailability: function (search, empty) {
                if (!search && empty) {
                    return false;
                }
                return true;
            }
        },
        initialize: function (options) {
            this.modalType = options.modalType;
            this.firstActivate = true;
            this.collection = new FilterCollection([], { mainModel: this.model });
            this.renderViews = [];
            this.render();
            this.viewModel = new Epoxy.Model({
                search: '',
                empty: false,
                notFound: false,
                currentPage: 1,
                pageSize: 10,
                totalPage: 1
            });
            Util.hintValidator($('[data-js-filter-name-search]', this.$el), [{
                validator: 'minMaxNotRequired',
                type: 'filterName',
                min: 3,
                max: 128
            }]);

            this.listenTo(this.viewModel, 'change:search', _.debounce(this.updateFilters, 500));
            this.listenTo(this.collection, 'add', this.onAddCollectionItems);
            this.listenTo(this.collection, 'reset', this.onResetCollectionItems);
            this.listenTo(this.collection, 'change:active', this.onSelectFilterCheck);
            this.listenTo(this.collection, 'edit', this.onEditFilter);
        },
        render: function () {
            this.$el.html(Util.templates(this.template, {}));
        },
        setFilterModel: function (model) {
            this.selectFilterView && this.selectFilterView.destroy();
            if (model) {
                $('[data-js-select-filter-block]', this.$el).removeClass('empty-state');
                this.selectFilterView = new FilterItem({
                    model: model, searchTerm: this.viewModel.get('search')
                });
                $('[data-js-select-filter-container]', this.$el).html(this.selectFilterView.$el);
                this.selectedFilterModel = model;
                this.selectFilterView.$el.on('mouseenter', function () {
                    config.trackingDispatcher.trackEventNumber(296);
                });
            } else {
                $('[data-js-select-filter-block]', this.$el).addClass('empty-state');
            }
        },
        getSelectedFilterModel: function () {
            if (!this.selectedFilterModel && this.model.get('filter_id')) {
                this.launchFilterCollection = new SingletonLaunchFilterCollection();
                this.setFilterModel(this.launchFilterCollection.get(this.model.get('filter_id')));
            }
            return this.selectedFilterModel;
        },
        onSelectFilterCheck: function (model, active) {
            active && this.onSelectFilter(model);
        },
        onSelectFilter: function (filterModel) {
            this.model.set({ filter_id: filterModel.get('id') });
            var curOptions = this.model.getWidgetOptions();
            curOptions.filterName = [filterModel.get('name')];
            this.model.setWidgetOptions(curOptions);
            this.setFilterModel(filterModel);
        },
        onClickAddFilter: function (e) {
            var self = this;
            if (this.modalType === 'edit') {
                config.trackingDispatcher.trackEventNumber(328);
            } else {
                config.trackingDispatcher.trackEventNumber(295);
            }
            e.preventDefault();
            this.$el.addClass('hide-content');
            this.addFilterView && this.stopListening(this.addFilterView) &&
                this.addFilterView.destroy();
            this.addFilterView = new FilterSearchAddView({
                gadgetModel: this.model,
                modalType: this.modalType
            });
            this.listenTo(this.addFilterView, 'change:filter', this.onSelectFilter);
            this.addFilterView.activate();
            $('[data-js-filter-add-container]', this.$el).html(this.addFilterView.$el);
            this.trigger('disable:navigation', true);
            this.addFilterView.getReadyState()
                .always(function () {
                    self.addFilterView.destroy();
                    self.$el.removeClass('hide-content');
                    self.trigger('disable:navigation', false);
                    self.updateFilters();
                })
                .fail(function () {
                    self.model.set({ filter_id: '' });
                    self.setFilterModel(null);
                });
        },
        onEditFilter: function (model) {
            var self = this;
            this.$el.addClass('hide-content');
            this.editFilterView && this.editFilterView.destroy();
            this.editFilterView = new FilterSearchEditView({
                model: model,
                gadgetModel: this.model,
                modalType: this.modalType
            });
            $('[data-js-filter-edit-container]', this.$el).html(this.editFilterView.$el);
            this.trigger('disable:navigation', true);
            this.editFilterView.getReadyState()
                .always(function () {
                    self.editFilterView.destroy();
                    self.$el.removeClass('hide-content');
                    self.trigger('disable:navigation', false);
                });
        },
        activate: function () {
            var curWidget = WidgetService.getWidgetConfig(this.model.get('gadget'));
            var self = this;
            if (!this.firstActivate) {
                return;
            }
            if (!curWidget.noFilters) {
                this.firstActivate = false;
                this.load().always(function () {
                    self.baronScroll = Util.setupBaronScroll($('[data-js-filter-list-scroll]', self.$el));
                    Util.setupBaronScrollSize(self.baronScroll, { maxHeight: 330 });
                    self.baronScroll.on('scroll', function () {
                        var elem = self.baronScroll.get(0);
                        if (elem.scrollHeight - elem.scrollTop < elem.offsetHeight * 2) {
                            self.addLoadData();
                        }
                    });
                });
            }
        },
        addLoadData: function () {
            if (this.viewModel.get('currentPage') < this.viewModel.get('totalPage') && !this.$el.hasClass('load')) {
                this.viewModel.set('currentPage', this.viewModel.get('currentPage') + 1);
                this.load();
            }
        },
        onChangeFilterName: function (e) {
            var value = $(e.currentTarget).val();
            if (value) {
                if (this.modalType === 'edit') {
                    config.trackingDispatcher.trackEventNumber(327);
                } else {
                    config.trackingDispatcher.trackEventNumber(294);
                }
            }
            this.viewModel.set({ search: value });
        },
        onAddCollectionItems: function (model) {
            this.renderFilter(model);
        },
        onResetCollectionItems: function () {
            _.each(this.renderViews, function (view) {
                view.destroy();
            });
            this.renderViews = [];
            _.each(this.collection.models, function (model) {
                this.renderFilter(model);
            }, this);
        },
        renderFilter: function (model) {
            var filterItem = new FilterItem({
                model: model,
                searchTerm: this.viewModel.get('search'),
                modalType: this.modalType
            });
            $('[data-js-filter-list]', this.$el).append(filterItem.$el);
            this.renderViews.push(filterItem);
        },
        updateFilters: function () {
            var self = this;
            this.collection.destroyModels();
            this.collection.reset([]);
            this.viewModel.set({
                totalPage: 1,
                currentPage: 1
            });
            this.load()
                .done(function () {
                    Util.setupBaronScrollSize(self.baronScroll, { maxHeight: 330 });
                });
        },
        load: function () {
            var self = this;
            this.$el.addClass('load');
            self.viewModel.set({ empty: false, notFound: false });
            return CoreService.saveFilter(this.getQueryString({
                search: encodeURIComponent(this.viewModel.get('search')),
                page: this.viewModel.get('currentPage'),
                size: this.viewModel.get('pageSize')
            }))
                .always(function () {
                    self.$el.removeClass('load');
                })
                .done(function (data) {
                    var launchFilterCollection;
                    var curOptions = self.model.getWidgetOptions();
                    self.viewModel.set({
                        totalPage: data.page.totalPages,
                        currentPage: data.page.number
                    });
                    if (data.content.length) {
                        self.viewModel.set({ empty: false, notFound: false });
                    } else if (!self.viewModel.get('search')) {
                        self.viewModel.set({ empty: true, notFound: false });
                    } else {
                        self.viewModel.set({ empty: false, notFound: true });
                    }
                    self.collection.add(data.content, { parse: true });
                    if (self.model.get('filter_id')) {
                        if (self.collection.get(self.model.get('filter_id'))) {
                            curOptions.filterName = [self.collection.get(self.model.get('filter_id')).get('name')];
                            self.model.setWidgetOptions(curOptions);
                            self.setFilterModel(self.collection.get(self.model.get('filter_id')));
                        } else {
                            launchFilterCollection = new SingletonLaunchFilterCollection();
                            launchFilterCollection.ready.done(function () {
                                curOptions.filterName = [launchFilterCollection.get(self.model.get('filter_id')).get('name')];
                                self.model.setWidgetOptions(curOptions);
                                self.setFilterModel(launchFilterCollection.get(self.model.get('filter_id')));
                            });
                        }
                    }
                    $('[data-js-select-filter-block]', self.$el)[(!data.content.length ? 'add' : 'remove') + 'Class']('hide');
                });
        },
        getQueryString: function (query) {
            var url;
            var Query = query;
            if (!Query) Query = {};
            if (!Query.page) Query.page = 1;
            if (!Query.size) Query.size = 10;
            url = '?page.sort=name&page.page=' + Query.page + '&page.size=' + Query.size;
            if (Query.search) {
                url += '&filter.cnt.name=' + Query.search;
            }
            return url;
        },
        onDestroy: function () {
            this.collection.destroy(true);
            this.$el.remove();
        }
    });

    return FilterSearchView;
});
<|endoftext|>


<commit_before>/*
 * Copyright 2015-2016 OpenCB
 *
 * 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.
 */

import {LitElement, html} from "lit";
import UtilsNew from "./../../../core/utilsNew.js";

export default class VariantConsequenceTypeView extends LitElement {

    constructor() {
        super();

        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            consequenceTypes: {
                type: Array
            },
            active: {
                type: Boolean
            }
        }
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);

        this._consequenceTypeColorMap = this._getConsequenceTypeColorMap();
    }

    updated(changedProperties) {
        if ((changedProperties.has("consequenceTypes") || changedProperties.has("active")) && this.active) {
            this.renderTable();
        }
    }

    _getConsequenceTypeColorMap() {
        let consequenceTypeToColor = {};
        if (CONSEQUENCE_TYPES) {
            for (let categoryIndex in CONSEQUENCE_TYPES.categories) {
                let terms = CONSEQUENCE_TYPES.categories[categoryIndex].terms;
                for (let termIndex in terms) {
                    consequenceTypeToColor[terms[termIndex].name] = CONSEQUENCE_TYPES.style[terms[termIndex].impact];
                }
            }
        }
        return consequenceTypeToColor;
    }

    detailFormatter(value, row) {
        let result = "
";
        let detailHtml = "";

        // Transcript Section
        detailHtml += `

Transcript Annotation

`;
        if (row.ensemblTranscriptId) {
            let exonOverlap = "NA";
            if (row.exonOverlap) {
                let exons = [];
                for (let exon in row.exonOverlap) {
                    exons.push(`${row.exonOverlap[exon].number} (${row.exonOverlap[exon].percentage})`);
                }
                exonOverlap = exons.join(", ");
            }
            detailHtml += `Ensembl Transcript ID:${row.ensemblTranscriptId || "NA"}

                           Strand:${row.strand || "NA"}

                           cDNA Position:${row.cdnaPosition || "NA"}

                           CDS Position:${row.cdsPosition || "NA"}

                           Codon:${row.codon || "NA"}

                           Exon Overlap (%):${exonOverlap}`;
        } else {
            detailHtml += "No Transcript Data Available";
        }
        detailHtml += "
";

        // Protein Section
        detailHtml += `

Protein Annotation

`;
        if (row.proteinVariantAnnotation) {
            let protAnnot = row.proteinVariantAnnotation;
            let uniprotAcc = protAnnot.uniprotAccession ? `<a href="https://www.uniprot.org/uniprot/${protAnnot.uniprotAccession}" target="_blank">${protAnnot.uniprotAccession}</a>` : "NA";
            let keywords = protAnnot.keywords ? protAnnot.keywords.join(", ") : "NA";
            let domains = "NA";
            if (protAnnot.features && protAnnot.features.length) {
                let _domains = [];
                for (let domainIndex in protAnnot.features) {
                    _domains.push(protAnnot.features[domainIndex].id);
                }
                domains = `${_domains.join(", ")} (check all protein domains at <a href="https://www.ebi.ac.uk/interpro/protein/reviewed/${protAnnot.uniprotAccession}" target="_blank">InterPro</a>)`;
            }
            detailHtml += `UniProt Accession:${uniprotAcc}

                           UniProt Variant ID:${protAnnot.uniprotVariantId || "NA"}

                           Functional Description:${protAnnot.functionalDescription || "NA"}

                           Keywords:${keywords}

                           Domains:${domains}`;
        } else {
            detailHtml += "No Uniprot Data Available";
        }
        detailHtml += "
";

        result += detailHtml + "
";
        return result;
    }

    geneNameFormatter(value, row, index) {
        if (value) {
            return `<a href="https://www.genenames.org/tools/search/#!/all?query=${value}" target="_blank">${value}</a>`;
        } else {
            return "-";
        }
    }

    ensemblGeneFormatter(value, row, index) {
        if (value) {
            return `<a href="https://www.ensembl.org/Homo_sapiens/Gene/Summary?db=core;g=${value}" target="_blank">${value}</a>`;
        } else {
            return "-";
        }
    }

    ensemblTranscriptFormatter(value, row, index) {
        if (value) {
            return `<a href="https://www.ensembl.org/Homo_sapiens/Transcript/Idhistory?t=${value}" target="_blank">${value}</a>`;
        } else {
            return "-";
        }
    }

    transcriptFlagFormatter(value, row, index) {
        if (row.ensemblTranscriptId) {
            return row.transcriptAnnotationFlags && row.transcriptAnnotationFlags.length ? row.transcriptAnnotationFlags.join(", ") : "NA";
        } else {
            return "-";
        }
    }

    consequenceTypeFormatter(values, row, index) {
        if (values) {
            let result = [];
            for (let soTerm of values) {
                let color = this._consequenceTypeColorMap && this._consequenceTypeColorMap[soTerm.name]
                    ? this._consequenceTypeColorMap[soTerm.name]
                    : "black";
                result.push(`<span style="color: ${color}">${soTerm.name}</span> (<a href="http://www.sequenceontology.org/browser/current_svn/term/${soTerm.accession}" target="_blank">${soTerm.accession}</a>)`);
            }
            return result.join("
");
        } else {
            return "-";
        }
    }

    uniprotAccessionFormatter(value, row, index) {
        if (value && value.uniprotAccession) {
            return `<a href="https://www.uniprot.org/uniprot/${value.uniprotAccession}" target="_blank">${value.uniprotAccession}</a>`;
        } else {
            return "-";
        }
    }

    proteinAlleleFormatter(value, row, index) {
        if (value && value.reference && value.alternate) {
            return value.reference + "/" + value.alternate;
        } else {
            return "-";
        }
    }

    siftScoreFormatter(value, row, index) {
        if (value) {
            for (let i in value) {
                if (value[i].source === "sift") {
                    let color = PROTEIN_SUBSTITUTION_SCORE.style.sift[value[i].description];
                    return `<span title="${value[i].score}" style="color: ${color}">${value[i].description}</span>`;
                }
            }
        } else {
            return "-";
        }
    }

    polyphenScoreFormatter(value, row, index) {
        if (value) {
            for (let i in value) {
                if (value[i].source === "polyphen") {
                    let color = PROTEIN_SUBSTITUTION_SCORE.style.polyphen[value[i].description];
                    return `<span title="${value[i].score}" style="color: ${color}">${value[i].description}</span>`;
                }
            }
        } else {
            return "-";
        }
    }

    renderTable() {

        $("#" + this._prefix + "ConsequenceTypeTable").bootstrapTable("destroy");
        $("#" + this._prefix + "ConsequenceTypeTable").bootstrapTable({
            data: this.consequenceTypes,
            pagination: true,
            showExport: true,
            detailView: true,
            detailFormatter: this.detailFormatter,
            columns: [
                [
                    {
                        title: "Gene",
                        field: "geneName",
                        rowspan: 2,
                        colspan: 1,
                        formatter: this.geneNameFormatter,
                        halign: "center"
                    },
                    {
                        title: "Ensembl Gene",
                        field: "ensemblGeneId",
                        rowspan: 2,
                        colspan: 1,
                        formatter: this.ensemblGeneFormatter,
                        halign: "center"
                    },
                    {
                        title: "Ensembl Transcript",
                        field: "ensemblTranscriptId",
                        rowspan: 2,
                        colspan: 1,
                        formatter: this.ensemblTranscriptFormatter,
                        halign: "center"
                    },
                    {
                        title: "Biotype",
                        field: "biotype",
                        rowspan: 2,
                        colspan: 1,
                        halign: "center"
                    },
                    {
                        title: "Transcript Flag",
                        field: "transcriptAnnotationFlags",
                        colspan: 1,
                        rowspan: 2,
                        formatter: this.transcriptFlagFormatter,
                        halign: "center"
                    },
                    {
                        title: "Consequence Types (SO Term)",
                        field: "sequenceOntologyTerms",
                        rowspan: 2,
                        colspan: 1,
                        formatter: this.consequenceTypeFormatter.bind(this),
                        halign: "center"
                    },
                    {
                        title: "Protein Variant Annotation",
                        rowspan: 1,
                        colspan: 5,
                        halign: "center"
                    }
                ],
                [
                    {
                        title: "UniProt Accession",
                        field: "proteinVariantAnnotation",
                        formatter: this.uniprotAccessionFormatter,
                        rowspan: 1,
                        colspan: 1,
                        halign: "center"
                    },
                    {
                        title: "Position",
                        field: "proteinVariantAnnotation.position",
                        rowspan: 1,
                        colspan: 1,
                        align: "right",
                        halign: "center"
                    },
                    {
                        title: "Ref/Alt",
                        field: "proteinVariantAnnotation",
                        rowspan: 1,
                        colspan: 1,
                        formatter: this.proteinAlleleFormatter,
                        halign: "center"
                    },
                    {
                        title: "Sift",
                        field: "proteinVariantAnnotation.substitutionScores",
                        rowspan: 1,
                        colspan: 1,
                        formatter: this.siftScoreFormatter,
                        halign: "center"
                    },
                    {
                        title: "Polyphen",
                        field: "proteinVariantAnnotation.substitutionScores",
                        rowspan: 1,
                        colspan: 1,
                        formatter: this.polyphenScoreFormatter,
                        halign: "center"
                    }
                ]
            ]
        });
    }

    render() {
        return html`

        `;
    }

}

customElements.define("variant-consequence-type-view", VariantConsequenceTypeView);
<commit_msg>wc: make consequence type detail component to display refseq<commit_after>/*
 * Copyright 2015-2016 OpenCB
 *
 * 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.
 */

import {LitElement, html} from "lit";
import UtilsNew from "./../../../core/utilsNew.js";

export default class VariantConsequenceTypeView extends LitElement {

    constructor() {
        super();

        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            consequenceTypes: {
                type: Array
            },
            active: {
                type: Boolean
            }
        }
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);

        this._consequenceTypeColorMap = this._getConsequenceTypeColorMap();
    }

    updated(changedProperties) {
        if ((changedProperties.has("consequenceTypes") || changedProperties.has("active")) && this.active) {
            this.renderTable();
        }
    }

    _getConsequenceTypeColorMap() {
        let consequenceTypeToColor = {};
        if (CONSEQUENCE_TYPES) {
            for (let categoryIndex in CONSEQUENCE_TYPES.categories) {
                let terms = CONSEQUENCE_TYPES.categories[categoryIndex].terms;
                for (let termIndex in terms) {
                    consequenceTypeToColor[terms[termIndex].name] = CONSEQUENCE_TYPES.style[terms[termIndex].impact];
                }
            }
        }
        return consequenceTypeToColor;
    }

    detailFormatter(value, row) {
        let result = "
";
        let detailHtml = "";

        // Transcript Section
        detailHtml += `

Transcript Annotation

`;
        if (row.transcriptId) {
            let exonOverlap = "NA";
            if (row.exonOverlap) {
                let exons = [];
                for (let exon in row.exonOverlap) {
                    exons.push(`${row.exonOverlap[exon].number} (${row.exonOverlap[exon].percentage})`);
                }
                exonOverlap = exons.join(", ");
            }
            detailHtml += `Ensembl Transcript ID:${row.transcriptId || "NA"}

                           Strand:${row.strand || "NA"}

                           cDNA Position:${row.cdnaPosition || "NA"}

                           CDS Position:${row.cdsPosition || "NA"}

                           Codon:${row.codon || "NA"}

                           Exon Overlap (%):${exonOverlap}`;
        } else {
            detailHtml += "No Transcript Data Available";
        }
        detailHtml += "
";

        // Protein Section
        detailHtml += `

Protein Annotation

`;
        if (row.proteinVariantAnnotation) {
            let protAnnot = row.proteinVariantAnnotation;
            let uniprotAcc = protAnnot.uniprotAccession ? `<a href="https://www.uniprot.org/uniprot/${protAnnot.uniprotAccession}" target="_blank">${protAnnot.uniprotAccession}</a>` : "NA";
            let keywords = protAnnot.keywords ? protAnnot.keywords.join(", ") : "NA";
            let domains = "NA";
            if (protAnnot.features && protAnnot.features.length) {
                let _domains = [];
                for (let domainIndex in protAnnot.features) {
                    _domains.push(protAnnot.features[domainIndex].id);
                }
                domains = `${_domains.join(", ")} (check all protein domains at <a href="https://www.ebi.ac.uk/interpro/protein/reviewed/${protAnnot.uniprotAccession}" target="_blank">InterPro</a>)`;
            }
            detailHtml += `UniProt Accession:${uniprotAcc}

                           UniProt Variant ID:${protAnnot.uniprotVariantId || "NA"}

                           Functional Description:${protAnnot.functionalDescription || "NA"}

                           Keywords:${keywords}

                           Domains:${domains}`;
        } else {
            detailHtml += "No Uniprot Data Available";
        }
        detailHtml += "
";

        result += detailHtml + "
";
        return result;
    }

    geneNameFormatter(value, row, index) {
        if (value) {
            return `<a href="https://www.genenames.org/tools/search/#!/all?query=${value}" target="_blank">${value}</a>`;
        } else {
            return "-";
        }
    }

    ensemblGeneFormatter(value, row, index) {
        if (value) {
            return `<a href="https://www.ensembl.org/Homo_sapiens/Gene/Summary?db=core;g=${value}" target="_blank">${value}</a>`;
        } else {
            return "-";
        }
    }

    ensemblTranscriptFormatter(value, row, index) {
        if (value) {
            return `<a href="https://www.ensembl.org/Homo_sapiens/Transcript/Idhistory?t=${value}" target="_blank">${value}</a>`;
        } else {
            return "-";
        }
    }

    transcriptFlagFormatter(value, row, index) {
        if (row.transcriptId) {
            return row.transcriptFlags && row.transcriptFlags.length ? row.transcriptFlags.join(", ") : "NA";
        } else {
            return "-";
        }
    }

    consequenceTypeFormatter(values, row, index) {
        if (values) {
            let result = [];
            for (let soTerm of values) {
                let color = this._consequenceTypeColorMap && this._consequenceTypeColorMap[soTerm.name]
                    ? this._consequenceTypeColorMap[soTerm.name]
                    : "black";
                result.push(`<span style="color: ${color}">${soTerm.name}</span> (<a href="http://www.sequenceontology.org/browser/current_svn/term/${soTerm.accession}" target="_blank">${soTerm.accession}</a>)`);
            }
            return result.join("
");
        } else {
            return "-";
        }
    }

    uniprotAccessionFormatter(value, row, index) {
        if (value && value.uniprotAccession) {
            return `<a href="https://www.uniprot.org/uniprot/${value.uniprotAccession}" target="_blank">${value.uniprotAccession}</a>`;
        } else {
            return "-";
        }
    }

    proteinAlleleFormatter(value, row, index) {
        if (value && value.reference && value.alternate) {
            return value.reference + "/" + value.alternate;
        } else {
            return "-";
        }
    }

    siftScoreFormatter(value, row, index) {
        if (value) {
            for (let i in value) {
                if (value[i].source === "sift") {
                    let color = PROTEIN_SUBSTITUTION_SCORE.style.sift[value[i].description];
                    return `<span title="${value[i].score}" style="color: ${color}">${value[i].description}</span>`;
                }
            }
        } else {
            return "-";
        }
    }

    polyphenScoreFormatter(value, row, index) {
        if (value) {
            for (let i in value) {
                if (value[i].source === "polyphen") {
                    let color = PROTEIN_SUBSTITUTION_SCORE.style.polyphen[value[i].description];
                    return `<span title="${value[i].score}" style="color: ${color}">${value[i].description}</span>`;
                }
            }
        } else {
            return "-";
        }
    }

    renderTable() {

        $("#" + this._prefix + "ConsequenceTypeTable").bootstrapTable("destroy");
        $("#" + this._prefix + "ConsequenceTypeTable").bootstrapTable({
            data: this.consequenceTypes,
            pagination: true,
            showExport: true,
            detailView: true,
            detailFormatter: this.detailFormatter,
            columns: [
                [
                    {
                        title: "Gene",
                        field: "geneName",
                        rowspan: 2,
                        colspan: 1,
                        formatter: this.geneNameFormatter,
                        halign: "center"
                    },
                    {
                        title: "Gene ID",
                        field: "geneId",
                        rowspan: 2,
                        colspan: 1,
                        formatter: this.ensemblGeneFormatter,
                        halign: "center"
                    },
                    {
                        title: "Transcript ID",
                        field: "transcriptId",
                        rowspan: 2,
                        colspan: 1,
                        formatter: this.ensemblTranscriptFormatter,
                        halign: "center"
                    },
                    {
                        title: "Source",
                        field: "source",
                        rowspan: 2,
                        colspan: 1,
                        halign: "center"
                    },
                    {
                        title: "Biotype",
                        field: "biotype",
                        rowspan: 2,
                        colspan: 1,
                        halign: "center"
                    },
                    {
                        title: "Transcript Flag",
                        field: "transcriptAnnotationFlags",
                        colspan: 1,
                        rowspan: 2,
                        formatter: this.transcriptFlagFormatter,
                        halign: "center"
                    },
                    {
                        title: "Consequence Types (SO Term)",
                        field: "sequenceOntologyTerms",
                        rowspan: 2,
                        colspan: 1,
                        formatter: this.consequenceTypeFormatter.bind(this),
                        halign: "center"
                    },
                    {
                        title: "Protein Variant Annotation",
                        rowspan: 1,
                        colspan: 5,
                        halign: "center"
                    }
                ],
                [
                    {
                        title: "UniProt Accession",
                        field: "proteinVariantAnnotation",
                        formatter: this.uniprotAccessionFormatter,
                        rowspan: 1,
                        colspan: 1,
                        halign: "center"
                    },
                    {
                        title: "Position",
                        field: "proteinVariantAnnotation.position",
                        rowspan: 1,
                        colspan: 1,
                        align: "right",
                        halign: "center"
                    },
                    {
                        title: "Ref/Alt",
                        field: "proteinVariantAnnotation",
                        rowspan: 1,
                        colspan: 1,
                        formatter: this.proteinAlleleFormatter,
                        halign: "center"
                    },
                    {
                        title: "Sift",
                        field: "proteinVariantAnnotation.substitutionScores",
                        rowspan: 1,
                        colspan: 1,
                        formatter: this.siftScoreFormatter,
                        halign: "center"
                    },
                    {
                        title: "Polyphen",
                        field: "proteinVariantAnnotation.substitutionScores",
                        rowspan: 1,
                        colspan: 1,
                        formatter: this.polyphenScoreFormatter,
                        halign: "center"
                    }
                ]
            ]
        });
    }

    render() {
        return html`

        `;
    }

}

customElements.define("variant-consequence-type-view", VariantConsequenceTypeView);
<|endoftext|>


<commit_before>var ReportSQLWidgetDisplay = function(elem, conf) {
  var query_mgr = EventSourceHandler();

  var loadQuery = function() {
    var tpl = $.getTemplate(
      "views/report",
      "zbase_report_sql_widget_main_tpl");

    var result_pane = $(".zbase_report_sql_result_pane", tpl);
    var query = query_mgr.get(
      "sql_query",
      "/api/v1/sql_stream?query=" + encodeURIComponent(conf.query));

    query.addEventListener('result', function(e) {
      query_mgr.close("sql_query");

      var data = JSON.parse(e.data);
      renderQueryResult(result_pane, data.results);
    });

    query.addEventListener('error', function(e) {
      query_mgr.close("sql_query");

      try {
        renderQueryError(result_pane, JSON.parse(e.data).error);
      } catch (e) {
        renderQueryError(result_pane, e.data);
      }
    });

    elem.appendChild(tpl);
  };

  var renderQueryResult = function(result_pane, results) {
    result_pane.innerHTML = "";
    for (var i = 0; i < results.length; i++) {
      //renderResultBar(result_pane, i, results.length > 1);

      switch (results[i].type) {
        case "chart":
          renderResultChart(result_pane, results[i].svg);
          break;
        case "table":
          renderResultTable(result_pane, results[i].rows, results[i].columns)
          break;
      }
    }
  };

  var renderResultBar = function(result_pane, result_index, multiple_results) {
    var bar = document.createElement("div");
    bar.className = "zbase_result_pane_bar";
    bar.setAttribute('data-active', 'active');
    bar.innerHTML ="Result " + (result_index + 1) + "";

    if (multiple_results) {
      bar.className += " clickable";
      bar.addEventListener('click', function() {
        if (this.hasAttribute('data-active')) {
          this.removeAttribute('data-active');
        } else {
          this.setAttribute('data-active', 'active');
        }
      }, false);
    }

    result_pane.appendChild(bar);
  };

  var renderResultChart = function(result_pane, svg) {
    var chart = document.createElement("div");
    chart.className = "zbase_sql_chart";
    chart.innerHTML = svg;
    result_pane.appendChild(chart);
  };

  var renderResultTable = function(result_pane, rows, columns) {
    var table = document.createElement("table");
    table.className = 'z-table';

    innerHTML = "

";
    columns.forEach(function(column) {
      innerHTML += "" + column + "	";
    });

    innerHTML += "

";

    rows.forEach(function(row) {
      innerHTML += "
";
      row.forEach(function(cell) {
        innerHTML += "" + cell + "	";
      });
      innerHTML += "
";
    });

    innerHTML += "
";
    table.innerHTML = innerHTML;
    result_pane.appendChild(table);
  };

  var renderQueryError = function(result_pane, error) {
    var error_msg = $.getTemplate(
        "report-widgets/report-sql-widget",
        "zbase_report_sql_error_msg_tpl");

    $(".error_text", error_msg).innerHTML = error;
    $.replaceContent(result_pane, error_msg);
  };

  var destroy = function() {

  };

  return {
    render: loadQuery,
    destroy: destroy
  };

};

var ReportSQLWidgetEditor = null;

ReportWidgetFactory.registerWidget(
    "sql-widget",
    ReportSQLWidgetDisplay,
    ReportSQLWidgetEditor);

<commit_msg>ReportSqlWidgetEditor render<commit_after>var ReportSQLWidgetDisplay = function(elem, conf) {
  var query_mgr = EventSourceHandler();

  var loadQuery = function() {
    var tpl = $.getTemplate(
      "views/report",
      "zbase_report_sql_widget_main_tpl");

    var result_pane = $(".zbase_report_sql_result_pane", tpl);
    var query = query_mgr.get(
      "report_sql",
      "/api/v1/sql_stream?query=" + encodeURIComponent(conf.query));

    query.addEventListener('result', function(e) {
      query_mgr.close("report_sql");

      var data = JSON.parse(e.data);
      renderQueryResult(result_pane, data.results);
    });

    query.addEventListener('error', function(e) {
      query_mgr.close("report_sql");

      try {
        renderQueryError(result_pane, JSON.parse(e.data).error);
      } catch (e) {
        renderQueryError(result_pane, e.data);
      }
    });

    elem.appendChild(tpl);
  };

  var renderQueryResult = function(result_pane, results) {
    result_pane.innerHTML = "";
    for (var i = 0; i < results.length; i++) {
      //renderResultBar(result_pane, i, results.length > 1);

      switch (results[i].type) {
        case "chart":
          renderResultChart(result_pane, results[i].svg);
          break;
        case "table":
          renderResultTable(result_pane, results[i].rows, results[i].columns)
          break;
      }
    }
  };

  var renderResultBar = function(result_pane, result_index, multiple_results) {
    var bar = document.createElement("div");
    bar.className = "zbase_result_pane_bar";
    bar.setAttribute('data-active', 'active');
    bar.innerHTML ="Result " + (result_index + 1) + "";

    if (multiple_results) {
      bar.className += " clickable";
      bar.addEventListener('click', function() {
        if (this.hasAttribute('data-active')) {
          this.removeAttribute('data-active');
        } else {
          this.setAttribute('data-active', 'active');
        }
      }, false);
    }

    result_pane.appendChild(bar);
  };

  var renderResultChart = function(result_pane, svg) {
    var chart = document.createElement("div");
    chart.className = "zbase_sql_chart";
    chart.innerHTML = svg;
    result_pane.appendChild(chart);
  };

  var renderResultTable = function(result_pane, rows, columns) {
    var table = document.createElement("table");
    table.className = 'z-table';

    innerHTML = "

";
    columns.forEach(function(column) {
      innerHTML += "" + column + "	";
    });

    innerHTML += "

";

    rows.forEach(function(row) {
      innerHTML += "
";
      row.forEach(function(cell) {
        innerHTML += "" + cell + "	";
      });
      innerHTML += "
";
    });

    innerHTML += "
";
    table.innerHTML = innerHTML;
    result_pane.appendChild(table);
  };

  var renderQueryError = function(result_pane, error) {
    var error_msg = $.getTemplate(
        "report-widgets/report-sql-widget",
        "zbase_report_sql_error_msg_tpl");

    $(".error_text", error_msg).innerHTML = error;
    $.replaceContent(result_pane, error_msg);
  };

  var destroy = function() {
    if (query_mgr) {
      query_mgr.closeAll();
    }
  };

  return {
    render: loadQuery,
    destroy: destroy
  };

};

var ReportSQLWidgetEditor = function(elem, conf) {
  var render = function() {
    console.log(elem, conf);
    var tpl = $.getTemplate(
      "views/report",
      "zbase_report_sql_widget_editor_main_tpl");

    elem.appendChild(tpl);
  };

  return {
    render: render
  }
};

ReportWidgetFactory.registerWidget(
    "sql-widget",
    ReportSQLWidgetDisplay,
    ReportSQLWidgetEditor);

<|endoftext|>


<commit_before>var ReportSQLWidgetDisplay = function(elem, conf) {
  var query_mgr = EventSourceHandler();

  var loadQuery = function() {
    var tpl = $.getTemplate(
      "views/report",
      "zbase_report_sql_widget_main_tpl");

    var result_pane = $(".zbase_report_sql_result_pane", tpl);
    var query = query_mgr.get(
      "report_sql",
      "/api/v1/sql_stream?query=" + encodeURIComponent(conf.query));

    query.addEventListener('result', function(e) {
      query_mgr.close("report_sql");

      var data = JSON.parse(e.data);
      renderQueryResult(result_pane, data.results);
    });

    query.addEventListener('error', function(e) {
      query_mgr.close("report_sql");

      try {
        renderQueryError(result_pane, JSON.parse(e.data).error);
      } catch (e) {
        renderQueryError(result_pane, e.data);
      }
    });

    elem.appendChild(tpl);
  };

  var renderQueryResult = function(result_pane, results) {
    result_pane.innerHTML = "";
    for (var i = 0; i < results.length; i++) {
      //renderResultBar(result_pane, i, results.length > 1);

      switch (results[i].type) {
        case "chart":
          renderResultChart(result_pane, results[i].svg);
          break;
        case "table":
          renderResultTable(result_pane, results[i].rows, results[i].columns)
          break;
      }
    }
  };

  var renderResultBar = function(result_pane, result_index, multiple_results) {
    var bar = document.createElement("div");
    bar.className = "zbase_result_pane_bar";
    bar.setAttribute('data-active', 'active');
    bar.innerHTML ="Result " + (result_index + 1) + "";

    if (multiple_results) {
      bar.className += " clickable";
      bar.addEventListener('click', function() {
        if (this.hasAttribute('data-active')) {
          this.removeAttribute('data-active');
        } else {
          this.setAttribute('data-active', 'active');
        }
      }, false);
    }

    result_pane.appendChild(bar);
  };

  var renderResultChart = function(result_pane, svg) {
    var chart = document.createElement("div");
    chart.className = "zbase_sql_chart";
    chart.innerHTML = svg;
    result_pane.appendChild(chart);
  };

  var renderResultTable = function(result_pane, rows, columns) {
    var table = document.createElement("table");
    table.className = 'z-table';

    innerHTML = "

";
    columns.forEach(function(column) {
      innerHTML += "" + column + "	";
    });

    innerHTML += "

";

    rows.forEach(function(row) {
      innerHTML += "
";
      row.forEach(function(cell) {
        innerHTML += "" + cell + "	";
      });
      innerHTML += "
";
    });

    innerHTML += "
";
    table.innerHTML = innerHTML;
    result_pane.appendChild(table);
  };

  var renderQueryError = function(result_pane, error) {
    var error_msg = $.getTemplate(
        "report-widgets/report-sql-widget",
        "zbase_report_sql_error_msg_tpl");

    $(".error_text", error_msg).innerHTML = error;
    $.replaceContent(result_pane, error_msg);
  };

  var destroy = function() {
    if (query_mgr) {
      query_mgr.closeAll();
    }
  };

  return {
    render: loadQuery,
    destroy: destroy
  };

};

var ReportSQLWidgetEditor = function(elem, conf) {
  var editor;
  var render = function() {
    var tpl = $.getTemplate(
      "views/report",
      "zbase_report_sql_widget_editor_main_tpl");

    // code editor
    editor = $("z-codeeditor", tpl);
    editor.setValue(conf.query);

    elem.appendChild(tpl);
  };

  var onSave = function(callback) {
    conf.query = editor.getValue();
    callback(conf);
  };

  var onCancel = function(callback) {
    callback();
  };

  return {
    render: render,
    onSave: onSave,
    onCancel: onCancel
  }
};

ReportWidgetFactory.registerWidget(
    "sql-widget",
    ReportSQLWidgetDisplay,
    ReportSQLWidgetEditor);

<commit_msg>ReportSqlWidgetEditor destroy<commit_after>var ReportSQLWidgetDisplay = function(elem, conf) {
  var query_mgr = EventSourceHandler();

  var loadQuery = function() {
    var tpl = $.getTemplate(
      "views/report",
      "zbase_report_sql_widget_main_tpl");

    var result_pane = $(".zbase_report_sql_result_pane", tpl);
    var query = query_mgr.get(
      "report_sql",
      "/api/v1/sql_stream?query=" + encodeURIComponent(conf.query));

    query.addEventListener('result', function(e) {
      query_mgr.close("report_sql");

      var data = JSON.parse(e.data);
      renderQueryResult(result_pane, data.results);
    });

    query.addEventListener('error', function(e) {
      query_mgr.close("report_sql");

      try {
        renderQueryError(result_pane, JSON.parse(e.data).error);
      } catch (e) {
        renderQueryError(result_pane, e.data);
      }
    });

    elem.appendChild(tpl);
  };

  var renderQueryResult = function(result_pane, results) {
    result_pane.innerHTML = "";
    for (var i = 0; i < results.length; i++) {
      //renderResultBar(result_pane, i, results.length > 1);

      switch (results[i].type) {
        case "chart":
          renderResultChart(result_pane, results[i].svg);
          break;
        case "table":
          renderResultTable(result_pane, results[i].rows, results[i].columns)
          break;
      }
    }
  };

  var renderResultBar = function(result_pane, result_index, multiple_results) {
    var bar = document.createElement("div");
    bar.className = "zbase_result_pane_bar";
    bar.setAttribute('data-active', 'active');
    bar.innerHTML ="Result " + (result_index + 1) + "";

    if (multiple_results) {
      bar.className += " clickable";
      bar.addEventListener('click', function() {
        if (this.hasAttribute('data-active')) {
          this.removeAttribute('data-active');
        } else {
          this.setAttribute('data-active', 'active');
        }
      }, false);
    }

    result_pane.appendChild(bar);
  };

  var renderResultChart = function(result_pane, svg) {
    var chart = document.createElement("div");
    chart.className = "zbase_sql_chart";
    chart.innerHTML = svg;
    result_pane.appendChild(chart);
  };

  var renderResultTable = function(result_pane, rows, columns) {
    var table = document.createElement("table");
    table.className = 'z-table';

    innerHTML = "

";
    columns.forEach(function(column) {
      innerHTML += "" + column + "	";
    });

    innerHTML += "

";

    rows.forEach(function(row) {
      innerHTML += "
";
      row.forEach(function(cell) {
        innerHTML += "" + cell + "	";
      });
      innerHTML += "
";
    });

    innerHTML += "
";
    table.innerHTML = innerHTML;
    result_pane.appendChild(table);
  };

  var renderQueryError = function(result_pane, error) {
    var error_msg = $.getTemplate(
        "report-widgets/report-sql-widget",
        "zbase_report_sql_error_msg_tpl");

    $(".error_text", error_msg).innerHTML = error;
    $.replaceContent(result_pane, error_msg);
  };

  var destroy = function() {
    if (query_mgr) {
      query_mgr.closeAll();
    }
  };

  return {
    render: loadQuery,
    destroy: destroy
  };

};

var ReportSQLWidgetEditor = function(elem, conf) {
  var editor;
  var render = function() {
    var tpl = $.getTemplate(
      "views/report",
      "zbase_report_sql_widget_editor_main_tpl");

    // code editor
    editor = $("z-codeeditor", tpl);
    editor.setValue(conf.query);

    elem.appendChild(tpl);
  };

  var onSave = function(callback) {
    conf.query = editor.getValue();
    callback(conf);
  };

  var onCancel = function(callback) {
    callback();
  };

  return {
    render: render,
    destroy: function() {},
    onSave: onSave,
    onCancel: onCancel
  }
};

ReportWidgetFactory.registerWidget(
    "sql-widget",
    ReportSQLWidgetDisplay,
    ReportSQLWidgetEditor);

<|endoftext|>


<commit_before>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

define('providers/edit', [
	'providers',
	'utils/str',
	'jquery',
    'jquery/utils',
    'jquery/rest',
    'jquery/superdesk',
    'jquery/tmpl',
    'jquery/avatar',
	'jqueryui/draggable',
    'jqueryui/texteditor',
	'providers/edit/adaptor',
    'tmpl!livedesk>providers/edit',
    'tmpl!livedesk>providers/edit/item',
], function( providers, str, $ ) {
	$.extend(providers.edit, {
        data: [],
        init: function(theBlog) {
            var
            initEdit = function(theBlog)
            {
                $(this)
                    .off('click.livedesk')
                    .on( 'click.livedesk','[ci="savepost"]', function(e){
                        e.preventDefault();
                        var data = {
                            Content: $.styledNodeHtml('.edit-block article.editable'),
                            Type: $('[name="type"]').val()
                        };
                        new $.restAuth(theBlog+'/Post').resetData().xfilter('Id,AuthorName,Content,Type.Key,PublishedOn,CreatedOn,Author.Source.Name').insert(data).done(function(post){
                            $('[name="body-text"]').val('');
                            $('[name="type"]').val('normal');
                            startx = self.data.length;
                            self.data[startx] = post;
                            post.startx = startx;
                            post.PublishedOn = true;
                            updatePost( post );
                            new $.restAuth(post.href+'/Publish').resetData().insert().done(function(){
                                require([$.superdesk.apiUrl+'/content/gui/superdesk/livedesk/scripts/js/edit-live-blogs.js'],
                                    function(EditApp){ new EditApp(theBlog).update(); });
                            });
                        });
                    })
                    .on('click.livedesk','[ci="save"]',function(e){
                        e.preventDefault();
                        var data = {
                            Content: $.styledNodeHtml('.edit-block article.editable'),
                            Type: $('[name="type"]').val()
                        };
                        new $.restAuth(theBlog+'/Post').resetData().xfilter('Id,AuthorName,Content,Type.Key,PublishedOn,CreatedOn,Author.Source.Name').insert(data).done(function(post){
                            $('[name="body-text"]').val('');
                            $('[name="type"]').val('normal');
                            startx = self.data.length;
                            self.data[startx] = post;
                            post.startx = startx;
                            updatePost( post );
                        });
                    });

                // editor
                fixedToolbar =
                {
                    _create: function(elements)
                    {
                        var self = this;
                        $(elements).on('toolbar-created', function()
                        {
                            self.plugins.toolbar.element.hide()
                                .appendTo($('.edit-block .toolbar-placeholder'));
                        });
                        $(elements).on('focusin.texteditor keydown.texteditor click.texteditor', function(event)
                        {
                            self.plugins.toolbar.element.fadeIn('fast');
                        });
                        $(elements).on('blur.texteditor focusout.texteditor', function()
                        {
                            self.plugins.toolbar.element.fadeOut('fast');
                        });
                    }
                };
                $('.edit-block article.editable').texteditor({ plugins:
                {
                    floatingToolbar: null,
                    draggableToolbar: null,
                    fixedToolbar: fixedToolbar
                }});

                $('form').submit(function() {
                    console.log($(this).serializeArray());
                    return false;
                });
                updatePosts();
            }, updatePost = function(post){
                var avatar = $.avatar.get($.superdesk.login.EMail);
                $.tmpl('livedesk>providers/edit/item', {Posts: posts, Avatar: avatar}, function(e,o){
                    if(!e) {
                        var $el = $(o).prependTo(self.el.find('#own-posts-results'));
                        if(!$.isDefined(post.PublishedOn)) {
                            $el.draggable({
                                revert: 'invalid',
                                containment:'document',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                start: function() {
                                    var idx = parseInt($(this).attr('idx'),10),
                                    startx = parseInt($(this).attr('startx'),10);
                                    startx = isNaN(startx)? 0: startx;
                                    idx = isNaN(idx)? 0: idx;
                                    $(this).data('post', self.adaptor.universal(self.data[startx+idx], $(this)));
                                }
                            });
                        }
                    }
                });
            }, updatePosts = function(){
                new $.restAuth(theBlog+'/Post/Owned').resetData().request({data: { desc: 'createdOn'}}).xfilter('Id,AuthorName,Content,Type.Key,PublishedOn,CreatedOn,Author.Source.Name')
                .done(function(postList)
                {
                    //$.tmpl('livedesk>providers/edit/item', {Posts: postList}, function(e,o){ console.log(o);});
                    var avatar = $.avatar.get($.superdesk.login.EMail);
                    self.data = postList;
                    self.el.find('#own-posts-results')
                    .tmpl('livedesk>providers/edit/item', {Posts: postList, Avatar: avatar}, function(){
                        $(this).find('li.draggable').draggable(
                            {
                                revert: 'invalid',
                                containment:'document',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                start: function() {
                                    var idx = parseInt($(this).attr('idx'),10),
                                        startx = parseInt($(this).attr('startx'),10);
                                    startx = isNaN(startx)? 0: startx;
                                    idx = isNaN(idx)? 0: idx;
                                    $(this).data('post', self.adaptor.universal(self.data[startx+idx], $(this)));
                                }
                            }

                        );
                    }).end()
                    .on('click.livedesk','.close',function(){
                        /*
                        new $.restAuth(postHref);
                        */
                    });
                });

                    //self.el.find('.own-posts-results').tmpl('')
            },self = this;
            new $.restAuth('Superdesk/PostType').xfilter('Key').done(function(PostTypes){
                self.el.tmpl('livedesk>providers/edit',{PostTypes: PostTypes},function(){
                    initEdit.call(this, theBlog);
               });
            });
		}
	});
	return providers;
});
<commit_msg>NR-155: Avatars aren't showing in edit page<commit_after>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

define('providers/edit', [
	'providers',
	'utils/str',
	'jquery',
    'jquery/utils',
    'jquery/rest',
    'jquery/superdesk',
    'jquery/tmpl',
    'jquery/avatar',
	'jqueryui/draggable',
    'jqueryui/texteditor',
	'providers/edit/adaptor',
    'tmpl!livedesk>providers/edit',
    'tmpl!livedesk>providers/edit/item',
], function( providers, str, $ ) {
	$.extend(providers.edit, {
        data: [],
        init: function(theBlog) {
            var
            initEdit = function(theBlog)
            {
                $(this)
                    .off('click.livedesk')
                    .on( 'click.livedesk','[ci="savepost"]', function(e){
                        e.preventDefault();
                        var data = {
                            Content: $.styledNodeHtml('.edit-block article.editable'),
                            Type: $('[name="type"]').val()
                        };
                        new $.restAuth(theBlog+'/Post').resetData().xfilter('Id,AuthorName,Content,Type.Key,PublishedOn,CreatedOn,Author.Source.Name').insert(data).done(function(post){
                            $('[name="body-text"]').val('');
                            $('[name="type"]').val('normal');
                            startx = self.data.length;
                            self.data[startx] = post;
                            post.startx = startx;
                            post.PublishedOn = true;
                            updatePost( post );
                            new $.restAuth(post.href+'/Publish').resetData().insert().done(function(){
                                require([$.superdesk.apiUrl+'/content/gui/superdesk/livedesk/scripts/js/edit-live-blogs.js'],
                                    function(EditApp){ new EditApp(theBlog).update(); });
                            });
                        });
                    })
                    .on('click.livedesk','[ci="save"]',function(e){
                        e.preventDefault();
                        var data = {
                            Content: $.styledNodeHtml('.edit-block article.editable'),
                            Type: $('[name="type"]').val()
                        };
                        new $.restAuth(theBlog+'/Post').resetData().xfilter('Id,AuthorName,Content,Type.Key,PublishedOn,CreatedOn,Author.Source.Name').insert(data).done(function(post){
                            $('[name="body-text"]').val('');
                            $('[name="type"]').val('normal');
                            startx = self.data.length;
                            self.data[startx] = post;
                            post.startx = startx;
                            updatePost( post );
                        });
                    });

                // editor
                fixedToolbar =
                {
                    _create: function(elements)
                    {
                        var self = this;
                        $(elements).on('toolbar-created', function()
                        {
                            self.plugins.toolbar.element.hide()
                                .appendTo($('.edit-block .toolbar-placeholder'));
                        });
                        $(elements).on('focusin.texteditor keydown.texteditor click.texteditor', function(event)
                        {
                            self.plugins.toolbar.element.fadeIn('fast');
                        });
                        $(elements).on('blur.texteditor focusout.texteditor', function()
                        {
                            self.plugins.toolbar.element.fadeOut('fast');
                        });
                    }
                };
                $('.edit-block article.editable').texteditor({ plugins:
                {
                    floatingToolbar: null,
                    draggableToolbar: null,
                    fixedToolbar: fixedToolbar
                }});

                $('form').submit(function() {
                    console.log($(this).serializeArray());
                    return false;
                });
                updatePosts();
            }, updatePost = function(post){
                var avatar = $.avatar.get($.superdesk.login.EMail);
                $.tmpl('livedesk>providers/edit/item', {Posts: [post], Avatar: avatar}, function(e,o){
                    if(!e) {
                        var $el = $(o).prependTo(self.el.find('#own-posts-results'));
                        if(!$.isDefined(post.PublishedOn)) {
                            $el.draggable({
                                revert: 'invalid',
                                containment:'document',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                start: function() {
                                    var idx = parseInt($(this).attr('idx'),10),
                                    startx = parseInt($(this).attr('startx'),10);
                                    startx = isNaN(startx)? 0: startx;
                                    idx = isNaN(idx)? 0: idx;
                                    $(this).data('post', self.adaptor.universal(self.data[startx+idx], $(this)));
                                }
                            });
                        }
                    }
                });
            }, updatePosts = function(){
                new $.restAuth(theBlog+'/Post/Owned').resetData().request({data: { desc: 'createdOn'}}).xfilter('Id,AuthorName,Content,Type.Key,PublishedOn,CreatedOn,Author.Source.Name')
                .done(function(postList)
                {
                    //$.tmpl('livedesk>providers/edit/item', {Posts: postList}, function(e,o){ console.log(o);});
                    var avatar = $.avatar.get($.superdesk.login.EMail);
                    self.data = postList;
                    self.el.find('#own-posts-results')
                    .tmpl('livedesk>providers/edit/item', {Posts: postList, Avatar: avatar}, function(){
                        $(this).find('li.draggable').draggable(
                            {
                                revert: 'invalid',
                                containment:'document',
                                helper: 'clone',
                                appendTo: 'body',
                                zIndex: 2700,
                                start: function() {
                                    var idx = parseInt($(this).attr('idx'),10),
                                        startx = parseInt($(this).attr('startx'),10);
                                    startx = isNaN(startx)? 0: startx;
                                    idx = isNaN(idx)? 0: idx;
                                    $(this).data('post', self.adaptor.universal(self.data[startx+idx], $(this)));
                                }
                            }

                        );
                    }).end()
                    .on('click.livedesk','.close',function(){
                        /*
                        new $.restAuth(postHref);
                        */
                    });
                });

                    //self.el.find('.own-posts-results').tmpl('')
            },self = this;
            new $.restAuth('Superdesk/PostType').xfilter('Key').done(function(PostTypes){
                self.el.tmpl('livedesk>providers/edit',{PostTypes: PostTypes},function(){
                    initEdit.call(this, theBlog);
               });
            });
		}
	});
	return providers;
});
<|endoftext|>