<commit_before>import { module, test } from 'qunit';
import Ember from 'ember';
import Resolver from 'ember-resolver/resolver';
import ContainerDebugAdapter from 'ember-resolver/container-debug-adapter';
import ContainerDebugAdapterInitializer from 'dummy/initializers/container-debug-adapter';

let containerDebugAdapter, App;

var modules = {};
function def(module) {
  modules[module] = {};
}

function undef(module) {
  if (module) {
    delete modules[module];
  } else {
    modules = {};
  }
}

module("Container Debug Adapter Tests", {
  beforeEach:function() {
    let BaseApplication = Ember.Application.extend({
      Resolver,
      ContainerDebugAdapter,
      modulePrefix: 'appkit',

      init() {
        this._super(...arguments);
        this.deferReadiness();
      },

      toString() {
        return 'App';
      }
    });

    BaseApplication.initializer(ContainerDebugAdapterInitializer);

    Ember.run(function() {
      App = BaseApplication.create();
    });

    Ember.run(function() {
      containerDebugAdapter = App.__container__.lookup('container-debug-adapter:main');
      containerDebugAdapter._moduleRegistry._entries = modules;
    });
  },
  afterEach: function() {
    Ember.run(function() {
      containerDebugAdapter.destroy();
      App.destroy();
      App = null;
    });
    undef();
  }
});

test("can access Container Debug Adapter which can catalog typical entries by type", function(assert) {
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('model'), true, "canCatalogEntriesByType should return false for model");
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('template'), true, "canCatalogEntriesByType should return false for template");
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('controller'), true, "canCatalogEntriesByType should return true for controller");
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('route'), true, "canCatalogEntriesByType should return true for route");
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('view'), true, "canCatalogEntriesByType should return true for view");
});

test("the default ContainerDebugAdapter catalogs controller entries", function(assert) {
  def('appkit/controllers/foo');
  def('appkit/controllers/users/foo');

  var controllers = containerDebugAdapter.catalogEntriesByType('controller');

  assert.equal(controllers.length, 2, "controllers discovered");
  assert.equal(controllers[0], 'foo', "found the right class");
  assert.equal(controllers[1], 'users/foo', "the name is correct");
});

test("Does not duplicate entries", function(assert) {
  def('appkit/models/foo');
  def('appkit/more/models/foo');

  var models = containerDebugAdapter.catalogEntriesByType('model');

  assert.equal(models.length, 1, "Only one is returned");
  assert.equal(models[0], 'foo', "the name is correct");
});

test("Pods support", function(assert) {
  def('appkit/user/model');
  def('appkit/post/model');

  var models = containerDebugAdapter.catalogEntriesByType('model');

  assert.equal(models.length, 2, "All models are found");
  assert.equal(models[0], 'user', "the name is correct");
  assert.equal(models[1], 'post', "the name is correct");
});

test("Pods podModulePrefix support", function(assert) {
  App.podModulePrefix = 'my-prefix';

  def('my-prefix/user/model');
  def('my-prefix/users/user/model');

  var models = containerDebugAdapter.catalogEntriesByType('model');

  assert.equal(models.length, 2, "models discovered");
  assert.equal(models[0], 'user', "the name is correct");
  assert.equal(models[1], 'users/user', "the name is correct");
});
<commit_msg>fix container-debug-adapter-test<commit_after>import { module, test } from 'qunit';
import Ember from 'ember';
import Resolver from 'ember-resolver/resolver';
import ContainerDebugAdapter from 'ember-resolver/container-debug-adapter';
import ContainerDebugAdapterInitializer from 'dummy/initializers/container-debug-adapter';

let containerDebugAdapter, App;

var modules = {};
function def(_module) {
  modules[_module] = {};
}

function undef(_module) {
  if (_module) {
    delete modules[_module];
  } else {
    modules = {};
  }
}

module("Container Debug Adapter Tests", {
  beforeEach:function() {
    let BaseApplication = Ember.Application.extend({
      Resolver,
      ContainerDebugAdapter,
      modulePrefix: 'appkit',

      init() {
        this._super(...arguments);
        this.deferReadiness();
      },

      toString() {
        return 'App';
      }
    });

    BaseApplication.initializer(ContainerDebugAdapterInitializer);

    Ember.run(function() {
      App = BaseApplication.create();
    });

    Ember.run(function() {
      containerDebugAdapter = App.__container__.lookup('container-debug-adapter:main');
      containerDebugAdapter._moduleRegistry._entries = modules;
    });
  },
  afterEach: function() {
    Ember.run(function() {
      containerDebugAdapter.destroy();
      App.destroy();
      App = null;
    });
    undef();
  }
});

test("can access Container Debug Adapter which can catalog typical entries by type", function(assert) {
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('model'), true, "canCatalogEntriesByType should return false for model");
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('template'), true, "canCatalogEntriesByType should return false for template");
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('controller'), true, "canCatalogEntriesByType should return true for controller");
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('route'), true, "canCatalogEntriesByType should return true for route");
  assert.equal(containerDebugAdapter.canCatalogEntriesByType('view'), true, "canCatalogEntriesByType should return true for view");
});

test("the default ContainerDebugAdapter catalogs controller entries", function(assert) {
  def('appkit/controllers/foo');
  def('appkit/controllers/users/foo');

  var controllers = containerDebugAdapter.catalogEntriesByType('controller');

  assert.equal(controllers.length, 2, "controllers discovered");
  assert.equal(controllers[0], 'foo', "found the right class");
  assert.equal(controllers[1], 'users/foo', "the name is correct");
});

test("Does not duplicate entries", function(assert) {
  def('appkit/models/foo');
  def('appkit/more/models/foo');

  var models = containerDebugAdapter.catalogEntriesByType('model');

  assert.equal(models.length, 1, "Only one is returned");
  assert.equal(models[0], 'foo', "the name is correct");
});

test("Pods support", function(assert) {
  def('appkit/user/model');
  def('appkit/post/model');

  var models = containerDebugAdapter.catalogEntriesByType('model');

  assert.equal(models.length, 2, "All models are found");
  assert.equal(models[0], 'user', "the name is correct");
  assert.equal(models[1], 'post', "the name is correct");
});

test("Pods podModulePrefix support", function(assert) {
  App.podModulePrefix = 'my-prefix';

  def('my-prefix/user/model');
  def('my-prefix/users/user/model');

  var models = containerDebugAdapter.catalogEntriesByType('model');

  assert.equal(models.length, 2, "models discovered");
  assert.equal(models[0], 'user', "the name is correct");
  assert.equal(models[1], 'users/user', "the name is correct");
});
<|endoftext|>


<commit_before>'use strict';

const EXTENSION = '.mjs';

function withExtension(name) {
    return `${name}.mjs`;
}

function babelAddMjsSuffixPlugin({ types: t }) {
    return {
        visitor: {
            ImportDeclaration(path, _state) {
                const node = path.node;
                const source = node.source;
                if (
                    t.isStringLiteral(source) &&
                    source.value.endsWith(EXTENSION)
                ) {
                    return;
                }

                if (node.specifiers.length === 0) {
                    return;
                }

                const specifiers = node.specifiers;

                const newSource = t.stringLiteral(withExtension(source.value));
                const declaration = t.importDeclaration(specifiers, newSource);
                t.assertImportDeclaration(declaration);

                path.replaceWith(declaration);
            },

            ExportNamedDeclaration(path, _state) {
                const node = path.node;
                const source = node.source;
                if (
                    t.isStringLiteral(source) &&
                    source.value.endsWith(EXTENSION)
                ) {
                    return;
                }

                if (node.specifiers.length === 0) {
                    return;
                }

                const specifiers = node.specifiers;

                const newSource = t.stringLiteral(withExtension(source.value));
                const declaration = t.exportNamedDeclaration(null, specifiers, newSource);
                t.assertExportNamedDeclaration(declaration);

                path.replaceWith(declaration);
            },
        },
    };
}

module.exports = babelAddMjsSuffixPlugin;
<commit_msg>Share the code both ImportDeclaration and ExportNamedDeclaration<commit_after>'use strict';

const EXTENSION = '.mjs';

function withExtension(name) {
    return `${name}${EXTENSION}`;
}

function rewriter(t, path, _state, declarationFactory) {
    const node = path.node;
    const source = node.source;
    if (t.isStringLiteral(source) && source.value.endsWith(EXTENSION)) {
        return;
    }

    if (node.specifiers.length === 0) {
        return;
    }

    const specifiers = node.specifiers;

    const newSource = t.stringLiteral(withExtension(source.value));
    const declaration = declarationFactory(specifiers, newSource);

    path.replaceWith(declaration);
}

function babelAddMjsSuffixPlugin({ types: t }) {
    return {
        visitor: {
            ImportDeclaration(path, state) {
                rewriter(t, path, state, (specifiers, source) => {
                    const d = t.importDeclaration(specifiers, source);
                    t.assertImportDeclaration(d);
                    return d;
                });
            },

            ExportNamedDeclaration(path, state) {
                rewriter(t, path, state, (specifiers, source) => {
                    const d = t.exportNamedDeclaration(null, specifiers, source);
                    t.assertExportNamedDeclaration(d);
                    return d;
                });
            },
        },
    };
}

module.exports = babelAddMjsSuffixPlugin;
<|endoftext|>


<commit_before>(function () {
    var webappRoot = "{{ webapp_root }}";
    var apiRoot = "{{ api_root }}"

//    var webappRoot = "impactstory.org" // for testing cross-domain stuff

    /******** Load jQuery if not present *********/
    var jQuery;
    // this embed pattern is from http://alexmarandon.com/articles/web_widget_jquery/
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src",
                                "https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js");
        if (script_tag.readyState) {
            script_tag.onreadystatechange = function () { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    scriptLoadHandler();
                }
            };
        } else {
            script_tag.onload = scriptLoadHandler;
        }
        // Try to find the head, otherwise default to the documentElement
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    } else {
        // The jQuery version on the window is the one we want to use
        jQuery = window.jQuery;
        main();
    }

    /******** Called once jQuery has loaded ******/
    function scriptLoadHandler() {
        // Restore $ and window.jQuery to their previous values and store the
        // new jQuery in our local jQuery variable
        jQuery = window.jQuery.noConflict(true);
        // Call our main function
        main();
    }

    /******** utility functions ******/

        // Based on http://drnicwilliams.com/2006/11/21/diy-widgets/
    function requestStylesheet(stylesheet_url) {
        var stylesheet = document.createElement("link");
        stylesheet.rel = "stylesheet";
        stylesheet.type = "text/css";
        stylesheet.href = stylesheet_url;
        stylesheet.media = "all";
        document.lastChild.firstChild.appendChild(stylesheet);
    }

    // Based on the Load jQuery function above.
    function requestScript(script_url) {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript")
        script_tag.setAttribute("src", script_url)
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag)
    }

    /******** ImpactStory functions ******/

    function loadBadgesTemplate(webAppRoot, callback) {
        jQuery.ajax({
            url:"http://" + webAppRoot + "/embed/templates/badges.html",
            type:"GET",
            success: function(data){
                ich.addTemplate("badges", data)
                // do callback stuff...not messing with it for now.
            }
        })
    }

    function getWindowCallback(div$, dict){
        callbackName = div$.attr("data-on-finish")
        if (callbackName) {
            window[callbackName].call(window, dict, div$)
        }
        else {
            // just a stub, doesn't do anything.
            return true
        }

    }

    /******** Our main function ********/

    function main() {
        var $ = jQuery
        $.support.cors = true;

        /* ===========================================================
         * bootstrap-tooltip.js v2.1.1
         * http://twitter.github.com/bootstrap/javascript.html#tooltips
         * Inspired by the original jQuery.tipsy by Jason Frame
         * ===========================================================
         * Copyright 2012 Twitter, Inc.
         *
         * 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.
         * ========================================================== */
        "use strict";var Tooltip=function(b,a){this.init("tooltip",b,a)};Tooltip.prototype={constructor:Tooltip,init:function(d,c,b){var e,a;this.type=d;this.$element=$(c);this.options=this.getOptions(b);this.enabled=true;if(this.options.trigger=="click"){this.$element.on("click."+this.type,this.options.selector,$.proxy(this.toggle,this))}else{if(this.options.trigger!="manual"){e=this.options.trigger=="hover"?"mouseenter":"focus";a=this.options.trigger=="hover"?"mouseleave":"blur";this.$element.on(e+"."+this.type,this.options.selector,$.proxy(this.enter,this));this.$element.on(a+"."+this.type,this.options.selector,$.proxy(this.leave,this))}}this.options.selector?(this._options=$.extend({},this.options,{trigger:"manual",selector:""})):this.fixTitle()},getOptions:function(a){a=$.extend({},$.fn[this.type].defaults,a,this.$element.data());if(a.delay&&typeof a.delay=="number"){a.delay={show:a.delay,hide:a.delay}}return a},enter:function(b){var a=$(b.currentTarget)[this.type](this._options).data(this.type);if(!a.options.delay||!a.options.delay.show){return a.show()}clearTimeout(this.timeout);a.hoverState="in";this.timeout=setTimeout(function(){if(a.hoverState=="in"){a.show()}},a.options.delay.show)},leave:function(b){var a=$(b.currentTarget)[this.type](this._options).data(this.type);if(this.timeout){clearTimeout(this.timeout)}if(!a.options.delay||!a.options.delay.hide){return a.hide()}a.hoverState="out";this.timeout=setTimeout(function(){if(a.hoverState=="out"){a.hide()}},a.options.delay.hide)},show:function(){var e,a,g,c,f,b,d;if(this.hasContent()&&this.enabled){e=this.tip();this.setContent();if(this.options.animation){e.addClass("fade")}b=typeof this.options.placement=="function"?this.options.placement.call(this,e[0],this.$element[0]):this.options.placement;a=/in/.test(b);e.remove().css({top:0,left:0,display:"block"}).appendTo(a?this.$element:document.body);g=this.getPosition(a);c=e[0].offsetWidth;f=e[0].offsetHeight;switch(a?b.split(" ")[1]:b){case"bottom":d={top:g.top+g.height,left:g.left+g.width/2-c/2};break;case"top":d={top:g.top-f,left:g.left+g.width/2-c/2};break;case"left":d={top:g.top+g.height/2-f/2,left:g.left-c};break;case"right":d={top:g.top+g.height/2-f/2,left:g.left+g.width};break}e.css(d).addClass(b).addClass("in")}},setContent:function(){var b=this.tip(),a=this.getTitle();b.find(".tooltip-inner")[this.options.html?"html":"text"](a);b.removeClass("fade in top bottom left right")},hide:function(){var a=this,b=this.tip();b.removeClass("in");function c(){var d=setTimeout(function(){b.off($.support.transition.end).remove()},500);b.one($.support.transition.end,function(){clearTimeout(d);b.remove()})}$.support.transition&&this.$tip.hasClass("fade")?c():b.remove();return this},fixTitle:function(){var a=this.$element;if(a.attr("title")||typeof(a.attr("data-original-title"))!="string"){a.attr("data-original-title",a.attr("title")||"").removeAttr("title")}},hasContent:function(){return this.getTitle()},getPosition:function(a){return $.extend({},(a?{top:0,left:0}:this.$element.offset()),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight})},getTitle:function(){var c,a=this.$element,b=this.options;c=a.attr("data-original-title")||(typeof b.title=="function"?b.title.call(a[0]):b.title);return c},tip:function(){return this.$tip=this.$tip||$(this.options.template)},validate:function(){if(!this.$element[0].parentNode){this.hide();this.$element=null;this.options=null}},enable:function(){this.enabled=true},disable:function(){this.enabled=false},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(){this[this.tip().hasClass("in")?"hide":"show"]()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};$.fn.tooltip=function(a){return this.each(function(){var d=$(this),c=d.data("tooltip"),b=typeof a=="object"&&a;if(!c){d.data("tooltip",(c=new Tooltip(this,b)))}if(typeof a=="string"){c[a]()}})};$.fn.tooltip.Constructor=Tooltip;$.fn.tooltip.defaults={animation:true,placement:"top",selector:false,template:'

',trigger:"hover",title:"",delay:0,html:true};

        jQuery.ajaxSetup({ cache:false });
        var ajax_load = '';

        if (!window.console) {
            console = {log: function() {}};
        }

        requestStylesheet("http://" + webappRoot + "/static/css/embed.css");
        requestScript("http://" + webappRoot + "/static/js/icanhaz.min.js");
        requestScript("http://" + webappRoot + "/static/js/ti-item.js");

        jQuery(document).ready(function ($) {

            loadBadgesTemplate(webappRoot)
            $(".impactstory-embed").each(function(index){
                var thisDiv$ = $(this)

                // define the success callback here to use the context of the
                // *correct* impactstory-embed div; there may be several on teh
                // page.
                var insertBadges = function (dict, id) {
                    var itemView = new ItemView(jQuery)
                    var badgeSize = thisDiv$.attr("data-badge-size") == "small" ? "small" : ""
                    var badges$ = itemView.renderBadges(dict.awards, badgeSize)
                    badges$.find("span.label")
                        .wrap("")
                    thisDiv$.empty()
                    badges$.appendTo(thisDiv$)

                }

                var itemNamespace = thisDiv$.attr("data-id-type")
                var itemId = thisDiv$.attr("data-id")
                var item = new Item([itemNamespace, itemId], new ItemView($), $)
                var apiKey = thisDiv$.attr("data-api-key")
                if (apiKey === undefined) return false // remember to set this
                item.get(
                    apiRoot,
                    apiKey,
                    function(dict, id) { // run insertBadges, then a user-defined callback
                        console.log("item.get() finished.")
                        insertBadges(dict, id)
                        getWindowCallback(thisDiv$, dict)
                    },
                    function(data){
                        thisDiv$.append("Gathering metrics now...")
                    },
                    false
                )
            })

        });
    }
})()
<commit_msg>added semicolon.<commit_after>(function () {
    var webappRoot = "{{ webapp_root }}";
    var apiRoot = "{{ api_root }}"

//    var webappRoot = "impactstory.org" // for testing cross-domain stuff

    /******** Load jQuery if not present *********/
    var jQuery;
    // this embed pattern is from http://alexmarandon.com/articles/web_widget_jquery/
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src",
                                "https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js");
        if (script_tag.readyState) {
            script_tag.onreadystatechange = function () { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    scriptLoadHandler();
                }
            };
        } else {
            script_tag.onload = scriptLoadHandler;
        }
        // Try to find the head, otherwise default to the documentElement
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    } else {
        // The jQuery version on the window is the one we want to use
        jQuery = window.jQuery;
        main();
    }

    /******** Called once jQuery has loaded ******/
    function scriptLoadHandler() {
        // Restore $ and window.jQuery to their previous values and store the
        // new jQuery in our local jQuery variable
        jQuery = window.jQuery.noConflict(true);
        // Call our main function
        main();
    }

    /******** utility functions ******/

        // Based on http://drnicwilliams.com/2006/11/21/diy-widgets/
    function requestStylesheet(stylesheet_url) {
        var stylesheet = document.createElement("link");
        stylesheet.rel = "stylesheet";
        stylesheet.type = "text/css";
        stylesheet.href = stylesheet_url;
        stylesheet.media = "all";
        document.lastChild.firstChild.appendChild(stylesheet);
    }

    // Based on the Load jQuery function above.
    function requestScript(script_url) {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");

        script_tag.setAttribute("src", script_url);
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag)
    }

    /******** ImpactStory functions ******/

    function loadBadgesTemplate(webAppRoot, callback) {
        jQuery.ajax({
            url:"http://" + webAppRoot + "/embed/templates/badges.html",
            type:"GET",
            success: function(data){
                ich.addTemplate("badges", data)
                // do callback stuff...not messing with it for now.
            }
        })
    }

    function getWindowCallback(div$, dict){
        callbackName = div$.attr("data-on-finish")
        if (callbackName) {
            window[callbackName].call(window, dict, div$)
        }
        else {
            // just a stub, doesn't do anything.
            return true
        }

    }

    /******** Our main function ********/

    function main() {
        var $ = jQuery
        $.support.cors = true;

        /* ===========================================================
         * bootstrap-tooltip.js v2.1.1
         * http://twitter.github.com/bootstrap/javascript.html#tooltips
         * Inspired by the original jQuery.tipsy by Jason Frame
         * ===========================================================
         * Copyright 2012 Twitter, Inc.
         *
         * 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.
         * ========================================================== */
        "use strict";var Tooltip=function(b,a){this.init("tooltip",b,a)};Tooltip.prototype={constructor:Tooltip,init:function(d,c,b){var e,a;this.type=d;this.$element=$(c);this.options=this.getOptions(b);this.enabled=true;if(this.options.trigger=="click"){this.$element.on("click."+this.type,this.options.selector,$.proxy(this.toggle,this))}else{if(this.options.trigger!="manual"){e=this.options.trigger=="hover"?"mouseenter":"focus";a=this.options.trigger=="hover"?"mouseleave":"blur";this.$element.on(e+"."+this.type,this.options.selector,$.proxy(this.enter,this));this.$element.on(a+"."+this.type,this.options.selector,$.proxy(this.leave,this))}}this.options.selector?(this._options=$.extend({},this.options,{trigger:"manual",selector:""})):this.fixTitle()},getOptions:function(a){a=$.extend({},$.fn[this.type].defaults,a,this.$element.data());if(a.delay&&typeof a.delay=="number"){a.delay={show:a.delay,hide:a.delay}}return a},enter:function(b){var a=$(b.currentTarget)[this.type](this._options).data(this.type);if(!a.options.delay||!a.options.delay.show){return a.show()}clearTimeout(this.timeout);a.hoverState="in";this.timeout=setTimeout(function(){if(a.hoverState=="in"){a.show()}},a.options.delay.show)},leave:function(b){var a=$(b.currentTarget)[this.type](this._options).data(this.type);if(this.timeout){clearTimeout(this.timeout)}if(!a.options.delay||!a.options.delay.hide){return a.hide()}a.hoverState="out";this.timeout=setTimeout(function(){if(a.hoverState=="out"){a.hide()}},a.options.delay.hide)},show:function(){var e,a,g,c,f,b,d;if(this.hasContent()&&this.enabled){e=this.tip();this.setContent();if(this.options.animation){e.addClass("fade")}b=typeof this.options.placement=="function"?this.options.placement.call(this,e[0],this.$element[0]):this.options.placement;a=/in/.test(b);e.remove().css({top:0,left:0,display:"block"}).appendTo(a?this.$element:document.body);g=this.getPosition(a);c=e[0].offsetWidth;f=e[0].offsetHeight;switch(a?b.split(" ")[1]:b){case"bottom":d={top:g.top+g.height,left:g.left+g.width/2-c/2};break;case"top":d={top:g.top-f,left:g.left+g.width/2-c/2};break;case"left":d={top:g.top+g.height/2-f/2,left:g.left-c};break;case"right":d={top:g.top+g.height/2-f/2,left:g.left+g.width};break}e.css(d).addClass(b).addClass("in")}},setContent:function(){var b=this.tip(),a=this.getTitle();b.find(".tooltip-inner")[this.options.html?"html":"text"](a);b.removeClass("fade in top bottom left right")},hide:function(){var a=this,b=this.tip();b.removeClass("in");function c(){var d=setTimeout(function(){b.off($.support.transition.end).remove()},500);b.one($.support.transition.end,function(){clearTimeout(d);b.remove()})}$.support.transition&&this.$tip.hasClass("fade")?c():b.remove();return this},fixTitle:function(){var a=this.$element;if(a.attr("title")||typeof(a.attr("data-original-title"))!="string"){a.attr("data-original-title",a.attr("title")||"").removeAttr("title")}},hasContent:function(){return this.getTitle()},getPosition:function(a){return $.extend({},(a?{top:0,left:0}:this.$element.offset()),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight})},getTitle:function(){var c,a=this.$element,b=this.options;c=a.attr("data-original-title")||(typeof b.title=="function"?b.title.call(a[0]):b.title);return c},tip:function(){return this.$tip=this.$tip||$(this.options.template)},validate:function(){if(!this.$element[0].parentNode){this.hide();this.$element=null;this.options=null}},enable:function(){this.enabled=true},disable:function(){this.enabled=false},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(){this[this.tip().hasClass("in")?"hide":"show"]()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};$.fn.tooltip=function(a){return this.each(function(){var d=$(this),c=d.data("tooltip"),b=typeof a=="object"&&a;if(!c){d.data("tooltip",(c=new Tooltip(this,b)))}if(typeof a=="string"){c[a]()}})};$.fn.tooltip.Constructor=Tooltip;$.fn.tooltip.defaults={animation:true,placement:"top",selector:false,template:'

',trigger:"hover",title:"",delay:0,html:true};

        jQuery.ajaxSetup({ cache:false });
        var ajax_load = '';

        if (!window.console) {
            console = {log: function() {}};
        }

        requestStylesheet("http://" + webappRoot + "/static/css/embed.css");
        requestScript("http://" + webappRoot + "/static/js/icanhaz.min.js");
        requestScript("http://" + webappRoot + "/static/js/ti-item.js");

        jQuery(document).ready(function ($) {

            loadBadgesTemplate(webappRoot)
            $(".impactstory-embed").each(function(index){
                var thisDiv$ = $(this)

                // define the success callback here to use the context of the
                // *correct* impactstory-embed div; there may be several on teh
                // page.
                var insertBadges = function (dict, id) {
                    var itemView = new ItemView(jQuery)
                    var badgeSize = thisDiv$.attr("data-badge-size") == "small" ? "small" : ""
                    var badges$ = itemView.renderBadges(dict.awards, badgeSize)
                    badges$.find("span.label")
                        .wrap("")
                    thisDiv$.empty()
                    badges$.appendTo(thisDiv$)

                }

                var itemNamespace = thisDiv$.attr("data-id-type")
                var itemId = thisDiv$.attr("data-id")
                var item = new Item([itemNamespace, itemId], new ItemView($), $)
                var apiKey = thisDiv$.attr("data-api-key")
                if (apiKey === undefined) return false // remember to set this
                item.get(
                    apiRoot,
                    apiKey,
                    function(dict, id) { // run insertBadges, then a user-defined callback
                        console.log("item.get() finished.")
                        insertBadges(dict, id)
                        getWindowCallback(thisDiv$, dict)
                    },
                    function(data){
                        thisDiv$.append("Gathering metrics now...")
                    },
                    false
                )
            })

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


<commit_before>var Plotly = {};
exports.Plotly = Plotly;

Plotly.micropolar = require('./micropolar');
Plotly.micropolar.manager = require('./micropolar_manager');

Plotly.Lib = require('./lib');
Plotly.util = require('./plotly_util');
Plotly.Axes = require('./axes');
Plotly.Plots = require('./graph_obj');
Plotly.Color = require('./color');
Plotly.Drawing = require('./drawing');
Plotly.Scatter = require('./scatter');
Plotly.Annotations = require('./annotations');
Plotly.Bars = require('./bars');
Plotly.Boxes = require('./boxes');
Plotly.Colorbar = require('./colorbar');
Plotly.Contour = require('./contour');
Plotly.ErrorBars = require('./errorbars');
Plotly.Fx = require('./graph_interact');
Plotly.Heatmap = require('./heatmap');
Plotly.Histogram = require('./histogram');
Plotly.Legend = require('./legend');

// Modebar doesn't attach to Plotly object
// TODO: it should.
require('./modebar');

// promise polyfill, embed rather than requiring dependencies
// var promise = require('promise')
// if(!Promise) Promise = promise;
// else Promise.prototype.done = promise.prototype.done;
require('../../../../shelly/static/js/plugins/promise-1.0.0.min.js');
require('../../../../shelly/static/js/plugins/promise-done-1.0.0.js');
<commit_msg>include shapes in templates - next PR will be to use bundles :)<commit_after>var Plotly = {};
exports.Plotly = Plotly;

Plotly.micropolar = require('./micropolar');
Plotly.micropolar.manager = require('./micropolar_manager');

Plotly.Lib = require('./lib');
Plotly.util = require('./plotly_util');
Plotly.Axes = require('./axes');
Plotly.Plots = require('./graph_obj');
Plotly.Color = require('./color');
Plotly.Drawing = require('./drawing');
Plotly.Scatter = require('./scatter');
Plotly.Annotations = require('./annotations');
Plotly.Annotations = require('./shapes');
Plotly.Bars = require('./bars');
Plotly.Boxes = require('./boxes');
Plotly.Colorbar = require('./colorbar');
Plotly.Contour = require('./contour');
Plotly.ErrorBars = require('./errorbars');
Plotly.Fx = require('./graph_interact');
Plotly.Heatmap = require('./heatmap');
Plotly.Histogram = require('./histogram');
Plotly.Legend = require('./legend');

// Modebar doesn't attach to Plotly object
// TODO: it should.
require('./modebar');

// promise polyfill, embed rather than requiring dependencies
// var promise = require('promise')
// if(!Promise) Promise = promise;
// else Promise.prototype.done = promise.prototype.done;
require('../../../../shelly/static/js/plugins/promise-1.0.0.min.js');
require('../../../../shelly/static/js/plugins/promise-done-1.0.0.js');
<|endoftext|>


<commit_before>/**
 * Created by adi on 1/20/2017.
 */
var Utils = {
    locToTile : function(j , i) {
        var x = j* gameOptions.tileSize;
        var y = i* gameOptions.tileSize;
        if (x > gameOptions.gameWidth)
            x = gameOptions.gameWidth;
        if (y > gameOptions.gameHeight)
            y = gameOptions.gameHeight;
        return [x, y ];
    },

    tileToLoc : function (x, y) {
        return[Math.floor( x / gameOptions.tileSize) , Math.floor( y / gameOptions.tileSize)];
    }
}<commit_msg>Utilities.js<commit_after>/**
 * Created by adi on 1/20/2017.
 */
var Utils = {
    locToTile : function(i , j) {
        var x = i* gameOptions.tileSize;
        var y = j* gameOptions.tileSize;
        if (x > gameOptions.gameWidth)
            x = gameOptions.gameWidth;
        if (y > gameOptions.gameHeight)
            y = gameOptions.gameHeight;
        return {'x': x, 'y': y};
    },

    tileToLoc : function (x, y) {
        return {'i' : Math.floor( x / gameOptions.tileSize) , 'j': Math.floor( y / gameOptions.tileSize)};
    }
} <|endoftext|>


<commit_before>import { _parseAM, getAssetManager } from './assetManagers.js'
import { retrieve, insert, amend, deactivate, reactivate } from './assetManagers.js'
import AssetManager from '../../assetManagers/AssetManager/assetManager.js'

let token = process.env.API_TOKEN

describe('utils/assetManagers', () => {
  describe('_parseAM function', () => {
    it('should return an instance of AssetManager class', () => {
      const json = {
        assetManagerId: '48576',
        clientId: 'testClient',
        defaultTimezone: 'UTC',
        version: 1
      }
      const parsedAM = _parseAM(json)
      const expectedClass = new AssetManager({
        assetManagerId: '48576',
        clientId: 'testClient',
        defaultTimezone: 'UTC',
        version: 1
      })
      expect(parsedAM).toEqual(expectedClass)
    })
  })

  describe('retrieve', () => {
    test('with promise', () => {
      let promise = retrieve({
        token, AMaaSClass: 'assetManagers', AMId: 1
      }).catch(error => {})
      expect(promise).toBeInstanceOf(Promise)
    })
  })

  describe('insert', () => {
    test('with promise', () => {
      let promise = insert({
        token, AMaaSClass: 'assetManagers', AMId: 1
      }).catch(error => {})
      expect(promise).toBeInstanceOf(Promise)
    })

    test('should insert', () => {
      const data = {
        defaultBookCloseTime: "17:30:00",
        defaultTimezone: "UTC",
        assetManagerType: "Accredited Investor",
        clientId: 1,
        assetManagerStatus: "Active",
        defaultBookOwnerId: 2
      }
      insert({ assetManager: data, token })
        .then(res => {
          expect({ ...res }).toEqual(expect.objectContaining(data))
        })
        .catch(err => {
          expect(err).toBeUndefined()
        })
    })
  })

  describe('amend', () => {
    test('with promise', () => {
      let promise = amend({
        token, AMaaSClass: 'assetManagers', AMId: 1
      }).catch(error => {})
      expect(promise).toBeInstanceOf(Promise)
    })
  })

  describe('deactivate', () => {
    test('with promise', () => {
      let promise = deactivate({
        token, AMaaSClass: 'assetManagers', AMId: 1
      }).catch(error => {})
      expect(promise).toBeInstanceOf(Promise)
    })
  })

  describe('reactivate and deactivate', () => {
    // Get an Asset Manager. If it is inactive, reactivate, check then deactivate and check
    it('reactivates an inactive AM and deactivates an active AM', () => {
      retrieve({ AMId: 2, token })
        .then(res => {
          if (res.assetManagerStatus === 'Inactive') {
            return reactivate({ AMId: 2, token })
          }
          return Promise.resolve(res)
        })
        .then(res => {
          expect(res.assetManagerStatus).toEqual('Active')
          return deactivate({ AMId: 2, token })
        })
        .then(res => {
          expect(res.assetManagerStatus).toEqual('Inactive')
        })
        .catch(err => {
          expect(err).toBeUndefined()
        })
    })
  })
})
<commit_msg>Test AssetManager amend. AMAAS-385<commit_after>import { _parseAM, getAssetManager } from './assetManagers.js'
import { retrieve, insert, amend, deactivate, reactivate } from './assetManagers.js'
import AssetManager from '../../assetManagers/AssetManager/assetManager.js'

let token = process.env.API_TOKEN

describe('utils/assetManagers', () => {
  describe('_parseAM function', () => {
    it('should return an instance of AssetManager class', () => {
      const json = {
        assetManagerId: '48576',
        clientId: 'testClient',
        defaultTimezone: 'UTC',
        version: 1
      }
      const parsedAM = _parseAM(json)
      const expectedClass = new AssetManager({
        assetManagerId: '48576',
        clientId: 'testClient',
        defaultTimezone: 'UTC',
        version: 1
      })
      expect(parsedAM).toEqual(expectedClass)
    })
  })

  describe('retrieve', () => {
    test('with promise', () => {
      let promise = retrieve({
        token, AMaaSClass: 'assetManagers', AMId: 1
      }).catch(error => {})
      expect(promise).toBeInstanceOf(Promise)
    })
  })

  describe('insert', () => {
    test('with promise', () => {
      let promise = insert({
        token, AMaaSClass: 'assetManagers', AMId: 1
      }).catch(error => {})
      expect(promise).toBeInstanceOf(Promise)
    })

    test.skip('should insert', () => {
      const data = {
        defaultBookCloseTime: "17:30:00",
        defaultTimezone: "UTC",
        assetManagerType: "Accredited Investor",
        clientId: 1,
        assetManagerStatus: "Active",
        defaultBookOwnerId: 2
      }
      insert({ assetManager: data, token })
        .then(res => {
          expect({ ...res }).toEqual(expect.objectContaining(data))
        })
        .catch(err => {
          expect(err).toBeUndefined()
        })
    })
  })

  describe('amend', () => {
    test('with promise', () => {
      let promise = amend({
        token, AMaaSClass: 'assetManagers', AMId: 1
      }).catch(error => {})
      expect(promise).toBeInstanceOf(Promise)
    })
    test('amends', done => {
      let dboi
      retrieve({ AMId: 4, token })
        .then(res => {
          dboi = res.defaultBookOwnerId
          res.defaultBookOwnerId++
          return amend({ assetManager: res, AMId: res.assetManagerId, token })
        })
        .then(res => {
          expect(res.defaultBookOwnerId).toEqual(dboi+1)
          done()
        })
        .catch(err => {
          expect(err).toBeUndefined()
        })
    })
  })

  describe('deactivate', () => {
    test('with promise', () => {
      let promise = deactivate({
        token, AMaaSClass: 'assetManagers', AMId: 1
      }).catch(error => {})
      expect(promise).toBeInstanceOf(Promise)
    })
  })

  describe('reactivate and deactivate', () => {
    // Get an Asset Manager. If it is inactive, reactivate, check then deactivate and check
    it('reactivates an inactive AM and deactivates an active AM', () => {
      retrieve({ AMId: 2, token })
        .then(res => {
          if (res.assetManagerStatus === 'Inactive') {
            return reactivate({ AMId: 2, token })
          }
          return Promise.resolve(res)
        })
        .then(res => {
          expect(res.assetManagerStatus).toEqual('Active')
          return deactivate({ AMId: 2, token })
        })
        .then(res => {
          expect(res.assetManagerStatus).toEqual('Inactive')
        })
        .catch(err => {
          expect(err).toBeUndefined()
        })
    })
  })
})
<|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";
import "../../commons/opencga-active-filters.js";
import "../../commons/forms/select-field-filter.js";
import "../../loading-spinner.js";
import "../../commons/tool-header.js";
import "./rga-gene-view.js";
import "./rga-filter.js";
import "./rga-individual-view.js";
import "./rga-variant-view.js";

export default class RgaBrowser extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            query: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = "rga" + UtilsNew.randomString(6);
        this.query = {};
        this.preparedQuery = {};
        this.executedQuery = {};
        this.activeFilterAlias = {
        };
        this.activeTab = {"gene-tab": true};
        this.detail = {};
        this.resource = "RGA";

        // LoF as defaultQuery
        this.defaultQuery = {
            /* consequenceType: "transcript_ablation,splice_acceptor_variant,splice_donor_variant,stop_gained,frameshift_variant,stop_lost,start_lost,transcript_amplification,inframe_insertion,inframe_deletion",
            geneName: ["GRIK5", "ACTN3", "COMT", "TTN", "ABCA12", "ALMS1", "ALOX12B", "ATP8A2", "BLM",
                "CCNO", "CEP290", "CNGB3", "CUL7", "DNAAF1", "DOCK6", "EIF2B5", "ERCC6", "FLG", "HADA",
                "INPP5K", "MANIB1", "MERTK", "MUTYH", "NDUFAF5", "NDUFS7", "OTOG", "PAH", "PDZD7", "PHYH",
                "PKHD1", "PMM2", "RARS2", "SACS", "SGCA", "SIGMAR1", "SPG7", "TTN", "TYR", "USH2A", "WFS1"].join(","),
            // individualId: "118000206" // 118000208 is not a proband, 118000206 is a proband
            individualId: "210010274", // no case
            // knockoutType: "COMP_HET"*/
        };
    }

    connectedCallback() {
        super.connectedCallback();
        this._config = {...this.getDefaultConfig(), ...this.config};
    }

    firstUpdated(_changedProperties) {
        $(".bootstrap-select", this).selectpicker();
        UtilsNew.initTooltip(this);
    }

    update(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
            this.opencgaSessionObserver();
        }
        if (changedProperties.has("query")) {
            this.queryObserver();
        }
        super.update(changedProperties);
    }

    opencgaSessionObserver() {
        if (this?.opencgaSession?.study?.fqn) {
            this.query = {study: this.opencgaSession.study.fqn, ...this.defaultQuery};
            this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.defaultQuery};
            // this.requestUpdate().then(() => $(".bootstrap-select", this).selectpicker());
        }
    }

    queryObserver() {
        if (this?.opencgaSession?.study?.fqn) {
            // NOTE UtilsNew.objectCompare avoid repeating remote requests.
            if (this.forceQuery || !UtilsNew.objectCompare(this.query, this._query)) {
                this._query = this.query;
                if (this.query) {
                    this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
                    this.executedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
                } else {
                    this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.defaultQuery};
                    this.executedQuery = {study: this.opencgaSession.study.fqn, ...this.defaultQuery};
                }
                // onServerFilterChange() in opencga-active-filters fires an activeFilterChange event when the Filter dropdown is used
                this.dispatchEvent(new CustomEvent("queryChange", {
                    detail: this.preparedQuery
                }
                ));
                this.detail = {};
            } else {
                // console.error("same queries")
            }
            this.forceQuery = false;
            // this.requestUpdate();
        }
    }

    notifySearch(query) {
        this.dispatchEvent(new CustomEvent("querySearch", {
            detail: {
                query: query
            },
            bubbles: true,
            composed: true
        }));
    }

    async onRun() {
        // NOTE notifySearch() triggers this chain: notifySearch -> onQueryFilterSearch() on iva-app.js -> this.queries updated -> queryObserver() here in rga-browser
        // queryObserver() here stops the repetition of the remote request by checking if it has changed
        this.query = {...this.preparedQuery};
        // forceQuery is meant to force a new search on click on Search, even if the query hasn't changed
        this.forceQuery = true;
        // updates this.queries in iva-app
        this.notifySearch(this.preparedQuery);
    }

    onClickPill(e) {
        this._changeView(e.currentTarget.dataset.tabId);
    }

    _changeView(tabId) {
        $(".content-pills", this).removeClass("active");
        $(".content-tab", this).removeClass("active");
        for (const tab in this.activeTab) {
            if (Object.prototype.hasOwnProperty.call(this.activeTab, tab)) {
                this.activeTab[tab] = false;
            }
        }
        $(`button.content-pills[data-id=${tabId}]`, this).addClass("active");
        $("#" + tabId, this).addClass("active");
        this.activeTab[tabId] = true;
        this.requestUpdate();
    }

    onFilterChange(e) {
        this.query = e.detail;
    }

    onQueryFilterChange(e) {
        this.preparedQuery = e.detail.query;
        this.requestUpdate();
    }

    onActiveFilterChange(e) {
        this.preparedQuery = {study: this.opencgaSession.study.fqn, ...e.detail};
        this.query = {study: this.opencgaSession.study.fqn, ...e.detail};
    }

    onActiveFilterClear() {
        console.log("onActiveFilterClear");
        this.query = {study: this.opencgaSession.study.fqn};
        this.preparedQuery = {...this.query};
    }

    getDefaultConfig() {
        // return BrowserConf.config;
        return {
            title: "Recessive Variant Browser",
            icon: "fas fa-dna",
            active: false,
            searchButtonText: "Search",
            consequenceTypes: [
                "frameshift_variant",
                "incomplete_terminal_codon_variant",
                "inframe_deletion",
                "inframe_insertion",
                "missense_variant",
                "start_lost",
                "stop_gained",
                "stop_lost",
                "splice_acceptor_variant",
                "splice_donor_variant",
                "feature_truncation",
                "transcript_ablation"
            ],
            views: [
                {
                    id: "gene-tab",
                    name: "Genes",
                    icon: "fa fa-table",
                    active: true
                },
                {
                    id: "individual-tab",
                    name: "Individuals",
                    icon: "fas fa-table"
                },
                {
                    id: "variant-tab",
                    name: "Variants",
                    icon: "fas fa-table"
                }
            ],
            filter: {
                title: "Filter",
                activeFilters: {
                    alias: {
                        // Example:
                        // "region": "Region",
                        // "gene": "Gene",
                        "ct": "Consequence Types"
                    },
                    complexFields: [],
                    hiddenFields: []
                },
                sections: [ // sections and subsections, structure and order is respected
                    {
                        title: "Gene",
                        collapsed: false,
                        fields: [
                            {
                                id: "geneName",
                                name: "Gene",
                                description: "Gene selection"
                            },
                            {
                                id: "knockoutType",
                                name: "Knockout Type",
                                allowedValues: [{id: "COMP_HET", name: "Compound Heterozygous"}, {id: "HOM_ALT", name: "Homozygous"}]
                            }
                        ]
                    },
                    {
                        title: "Individual",
                        collapsed: false,
                        fields: [
                            {
                                id: "individualId",
                                name: "Individual",
                                description: "Individual selection"
                            }
                        ]
                    },
                    {
                        title: "Confidence",
                        fields: [
                            {
                                id: "numParents",
                                name: "Include families with",
                                description: "Confidence selection",
                                type: "checkbox",
                                allowedValues: [{id: 0, name: "No parents"}, {id: 1, name: "One parent"}, {id: 2, name: "Two parents"}]
                            }
                            /* {
                                id: "probandOnly",
                                name: "Affected individuals (proband) only",
                                type: "boolean",
                                defaultValue: "no",
                                tooltip: "other info here"
                                // allowedValues: ["father", "mother"]
                            }*/
                        ]
                    },
                    {
                        title: "Variants",
                        fields: [
                            /* {
                                id: "cohort",
                                name: "Cohort",
                                description: "Cohort selection"
                            },*/
                            {
                                id: "variants",
                                name: "Variant Id",
                                placeholder: "13:32906644:-:T,13:32912753:AC:-"
                            },
                            /* {
                                id: "region",
                                name: "Genomic Location",
                                tooltip: tooltips.region
                            },*/
                            {
                                id: "populationFrequency",
                                name: "Select Population Frequency",
                                onlyPopFreqAll: true
                            },
                            {
                                id: "type",
                                name: "Variant types",
                                types: ["SNV", "INDEL", "INSERTION", "DELETION"],
                                tooltip: tooltips.type
                                // layout: "horizontal"
                            },
                            {
                                id: "consequenceType",
                                name: "Consequence type",
                                tooltip: tooltips.consequenceTypeSelect,
                                value: CONSEQUENCE_TYPES.lof
                            },
                            {
                                id: "clinicalSignificance",
                                name: "Clinical Significance",
                            }
                        ]
                    }
                ],
                examples: [
                    {
                        id: "BRCA2 missense variants",
                        active: false,
                        query: {
                            geneName: "BRCA2",
                            ct: "missense_variant"
                        }
                    }
                ],
                result: {
                    grid: {}
                },
                detail: {
                    title: "Selected Variant",
                    views: [
                        {
                            id: "annotationSummary",
                            title: "Summary",
                            active: true
                        }
                    ]
                }
            }
        };
    }

    render() {

        if (!this?.opencgaSession?.study?.fqn) {
            return html`

No public projects available to browse. Please login to continue.

`;
        }

        if (this.opencgaSession.study?.attributes?.RGA?.status !== "INDEXED") {
            return html`

Study ${this?.opencgaSession?.study.name} is not enabled to Recessive Variant Analysis.

`;
        }

        return html`

            <tool-header title="${this._config.title}" icon="${this._config.icon}"></tool-header>

                        <button type="button" class="btn btn-primary ripple" @click="${this.onRun}">
                             ${this._config.searchButtonText || "Run"}
                        </button>

                            Filters

                            <rga-filter
                                    .opencgaSession="${this.opencgaSession}"
                                    .cellbaseClient="${this.cellbaseClient}"
                                    .config="${this._config.filter}"
                                    .query="${this.query}"
                                    .searchButton="${false}"
                                    @queryChange="${this.onQueryFilterChange}">
                            </rga-filter>

                            ${this._config.views && this._config.views.length ? this._config.views.map(tab => html`
                                <button type="button" class="btn btn-success ripple content-pills ${this.activeTab[tab.id] ? "active" : ""}" ?disabled=${tab.disabled} @click="${this.onClickPill}" data-tab-id="${tab.id}">
                                     ${tab.name}
                                </button>
                            `) : html`No view has been configured`}

                        <opencga-active-filters .resource="${this.resource}"
                                                .opencgaSession="${this.opencgaSession}"
                                                .defaultStudy="${this.opencgaSession?.study?.fqn}"
                                                .query="${this.preparedQuery}"
                                                .executedQuery="${this.executedQuery}"
                                                .alias="${this.activeFilterAlias}"
                                                .config="${this._config.activeFilters}"
                                                .filters="${this._config.filter.examples}"
                                                @activeFilterChange="${this.onActiveFilterChange}"
                                                @activeFilterClear="${this.onActiveFilterClear}">
                        </opencga-active-filters>

                                <rga-gene-view .query=${this.executedQuery} .opencgaSession="${this.opencgaSession}" .active="${this.activeTab["gene-tab"]}"></rga-gene-view>

                                <rga-individual-view .query=${this.executedQuery} .config=${this._config} .opencgaSession="${this.opencgaSession}" .active="${this.activeTab["individual-tab"]}"></rga-individual-view>

                                <rga-variant-view .query=${this.executedQuery}
                                                  .config=${this._config}
                                                  .opencgaSession="${this.opencgaSession}"
                                                  .cellbaseClient=${this.cellbaseClient}
                                                  .active="${this.activeTab["variant-tab"]}">
                                </rga-variant-view>

        `;
    }

}

customElements.define("rga-browser", RgaBrowser);
<commit_msg>RGA browser tabs order changed<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";
import "../../commons/opencga-active-filters.js";
import "../../commons/forms/select-field-filter.js";
import "../../loading-spinner.js";
import "../../commons/tool-header.js";
import "./rga-gene-view.js";
import "./rga-filter.js";
import "./rga-individual-view.js";
import "./rga-variant-view.js";

export default class RgaBrowser extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            query: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = "rga" + UtilsNew.randomString(6);
        this.query = {};
        this.preparedQuery = {};
        this.executedQuery = {};
        this.activeFilterAlias = {
        };
        this.activeTab = {"variant-tab": true};
        this.detail = {};
        this.resource = "RGA";

        // LoF as defaultQuery
        this.defaultQuery = {
            /* consequenceType: "transcript_ablation,splice_acceptor_variant,splice_donor_variant,stop_gained,frameshift_variant,stop_lost,start_lost,transcript_amplification,inframe_insertion,inframe_deletion",
            geneName: ["GRIK5", "ACTN3", "COMT", "TTN", "ABCA12", "ALMS1", "ALOX12B", "ATP8A2", "BLM",
                "CCNO", "CEP290", "CNGB3", "CUL7", "DNAAF1", "DOCK6", "EIF2B5", "ERCC6", "FLG", "HADA",
                "INPP5K", "MANIB1", "MERTK", "MUTYH", "NDUFAF5", "NDUFS7", "OTOG", "PAH", "PDZD7", "PHYH",
                "PKHD1", "PMM2", "RARS2", "SACS", "SGCA", "SIGMAR1", "SPG7", "TTN", "TYR", "USH2A", "WFS1"].join(","),
            // individualId: "118000206" // 118000208 is not a proband, 118000206 is a proband
            individualId: "210010274", // no case
            // knockoutType: "COMP_HET"*/
        };
    }

    connectedCallback() {
        super.connectedCallback();
        this._config = {...this.getDefaultConfig(), ...this.config};
    }

    firstUpdated(_changedProperties) {
        $(".bootstrap-select", this).selectpicker();
        UtilsNew.initTooltip(this);
    }

    update(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
            this.opencgaSessionObserver();
        }
        if (changedProperties.has("query")) {
            this.queryObserver();
        }
        super.update(changedProperties);
    }

    opencgaSessionObserver() {
        if (this?.opencgaSession?.study?.fqn) {
            this.query = {study: this.opencgaSession.study.fqn, ...this.defaultQuery};
            this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.defaultQuery};
            // this.requestUpdate().then(() => $(".bootstrap-select", this).selectpicker());
        }
    }

    queryObserver() {
        if (this?.opencgaSession?.study?.fqn) {
            // NOTE UtilsNew.objectCompare avoid repeating remote requests.
            if (this.forceQuery || !UtilsNew.objectCompare(this.query, this._query)) {
                this._query = this.query;
                if (this.query) {
                    this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
                    this.executedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
                } else {
                    this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.defaultQuery};
                    this.executedQuery = {study: this.opencgaSession.study.fqn, ...this.defaultQuery};
                }
                // onServerFilterChange() in opencga-active-filters fires an activeFilterChange event when the Filter dropdown is used
                this.dispatchEvent(new CustomEvent("queryChange", {
                    detail: this.preparedQuery
                }
                ));
                this.detail = {};
            } else {
                // console.error("same queries")
            }
            this.forceQuery = false;
            // this.requestUpdate();
        }
    }

    notifySearch(query) {
        this.dispatchEvent(new CustomEvent("querySearch", {
            detail: {
                query: query
            },
            bubbles: true,
            composed: true
        }));
    }

    async onRun() {
        // NOTE notifySearch() triggers this chain: notifySearch -> onQueryFilterSearch() on iva-app.js -> this.queries updated -> queryObserver() here in rga-browser
        // queryObserver() here stops the repetition of the remote request by checking if it has changed
        this.query = {...this.preparedQuery};
        // forceQuery is meant to force a new search on click on Search, even if the query hasn't changed
        this.forceQuery = true;
        // updates this.queries in iva-app
        this.notifySearch(this.preparedQuery);
    }

    onClickPill(e) {
        this._changeView(e.currentTarget.dataset.tabId);
    }

    _changeView(tabId) {
        $(".content-pills", this).removeClass("active");
        $(".content-tab", this).removeClass("active");
        for (const tab in this.activeTab) {
            if (Object.prototype.hasOwnProperty.call(this.activeTab, tab)) {
                this.activeTab[tab] = false;
            }
        }
        $(`button.content-pills[data-id=${tabId}]`, this).addClass("active");
        $("#" + tabId, this).addClass("active");
        this.activeTab[tabId] = true;
        this.requestUpdate();
    }

    onFilterChange(e) {
        this.query = e.detail;
    }

    onQueryFilterChange(e) {
        this.preparedQuery = e.detail.query;
        this.requestUpdate();
    }

    onActiveFilterChange(e) {
        this.preparedQuery = {study: this.opencgaSession.study.fqn, ...e.detail};
        this.query = {study: this.opencgaSession.study.fqn, ...e.detail};
    }

    onActiveFilterClear() {
        console.log("onActiveFilterClear");
        this.query = {study: this.opencgaSession.study.fqn};
        this.preparedQuery = {...this.query};
    }

    getDefaultConfig() {
        // return BrowserConf.config;
        return {
            title: "Recessive Variant Browser",
            icon: "fas fa-dna",
            active: false,
            searchButtonText: "Search",
            consequenceTypes: [
                "frameshift_variant",
                "incomplete_terminal_codon_variant",
                "inframe_deletion",
                "inframe_insertion",
                "missense_variant",
                "start_lost",
                "stop_gained",
                "stop_lost",
                "splice_acceptor_variant",
                "splice_donor_variant",
                "feature_truncation",
                "transcript_ablation"
            ],
            views: [
                {
                    id: "variant-tab",
                    name: "Variants",
                    icon: "fas fa-table"
                },
                {
                    id: "individual-tab",
                    name: "Individuals",
                    icon: "fas fa-table"
                },
                {
                    id: "gene-tab",
                    name: "Genes",
                    icon: "fa fa-table",
                    active: true
                }
            ],
            filter: {
                title: "Filter",
                activeFilters: {
                    alias: {
                        // Example:
                        // "region": "Region",
                        // "gene": "Gene",
                        "ct": "Consequence Types"
                    },
                    complexFields: [],
                    hiddenFields: []
                },
                sections: [ // sections and subsections, structure and order is respected
                    {
                        title: "Gene",
                        collapsed: false,
                        fields: [
                            {
                                id: "geneName",
                                name: "Gene",
                                description: "Gene selection"
                            },
                            {
                                id: "knockoutType",
                                name: "Knockout Type",
                                allowedValues: [{id: "COMP_HET", name: "Compound Heterozygous"}, {id: "HOM_ALT", name: "Homozygous"}]
                            }
                        ]
                    },
                    {
                        title: "Individual",
                        collapsed: false,
                        fields: [
                            {
                                id: "individualId",
                                name: "Individual",
                                description: "Individual selection"
                            }
                        ]
                    },
                    {
                        title: "Confidence",
                        fields: [
                            {
                                id: "numParents",
                                name: "Include families with",
                                description: "Confidence selection",
                                type: "checkbox",
                                allowedValues: [{id: 0, name: "No parents"}, {id: 1, name: "One parent"}, {id: 2, name: "Two parents"}]
                            }
                            /* {
                                id: "probandOnly",
                                name: "Affected individuals (proband) only",
                                type: "boolean",
                                defaultValue: "no",
                                tooltip: "other info here"
                                // allowedValues: ["father", "mother"]
                            }*/
                        ]
                    },
                    {
                        title: "Variants",
                        fields: [
                            /* {
                                id: "cohort",
                                name: "Cohort",
                                description: "Cohort selection"
                            },*/
                            {
                                id: "variants",
                                name: "Variant Id",
                                placeholder: "13:32906644:-:T,13:32912753:AC:-"
                            },
                            /* {
                                id: "region",
                                name: "Genomic Location",
                                tooltip: tooltips.region
                            },*/
                            {
                                id: "populationFrequency",
                                name: "Select Population Frequency",
                                onlyPopFreqAll: true
                            },
                            {
                                id: "type",
                                name: "Variant types",
                                types: ["SNV", "INDEL", "INSERTION", "DELETION"],
                                tooltip: tooltips.type
                                // layout: "horizontal"
                            },
                            {
                                id: "consequenceType",
                                name: "Consequence type",
                                tooltip: tooltips.consequenceTypeSelect,
                                value: CONSEQUENCE_TYPES.lof
                            },
                            {
                                id: "clinicalSignificance",
                                name: "Clinical Significance",
                            }
                        ]
                    }
                ],
                examples: [
                    {
                        id: "BRCA2 missense variants",
                        active: false,
                        query: {
                            geneName: "BRCA2",
                            ct: "missense_variant"
                        }
                    }
                ],
                result: {
                    grid: {}
                },
                detail: {
                    title: "Selected Variant",
                    views: [
                        {
                            id: "annotationSummary",
                            title: "Summary",
                            active: true
                        }
                    ]
                }
            }
        };
    }

    render() {

        if (!this?.opencgaSession?.study?.fqn) {
            return html`

No public projects available to browse. Please login to continue.

`;
        }

        if (this.opencgaSession.study?.attributes?.RGA?.status !== "INDEXED") {
            return html`

Study ${this?.opencgaSession?.study.name} is not enabled to Recessive Variant Analysis.

`;
        }

        return html`

            <tool-header title="${this._config.title}" icon="${this._config.icon}"></tool-header>

                        <button type="button" class="btn btn-primary ripple" @click="${this.onRun}">
                             ${this._config.searchButtonText || "Run"}
                        </button>

                            Filters

                            <rga-filter
                                    .opencgaSession="${this.opencgaSession}"
                                    .cellbaseClient="${this.cellbaseClient}"
                                    .config="${this._config.filter}"
                                    .query="${this.query}"
                                    .searchButton="${false}"
                                    @queryChange="${this.onQueryFilterChange}">
                            </rga-filter>

                            ${this._config.views && this._config.views.length ? this._config.views.map(tab => html`
                                <button type="button" class="btn btn-success ripple content-pills ${this.activeTab[tab.id] ? "active" : ""}" ?disabled=${tab.disabled} @click="${this.onClickPill}" data-tab-id="${tab.id}">
                                     ${tab.name}
                                </button>
                            `) : html`No view has been configured`}

                        <opencga-active-filters .resource="${this.resource}"
                                                .opencgaSession="${this.opencgaSession}"
                                                .defaultStudy="${this.opencgaSession?.study?.fqn}"
                                                .query="${this.preparedQuery}"
                                                .executedQuery="${this.executedQuery}"
                                                .alias="${this.activeFilterAlias}"
                                                .config="${this._config.activeFilters}"
                                                .filters="${this._config.filter.examples}"
                                                @activeFilterChange="${this.onActiveFilterChange}"
                                                @activeFilterClear="${this.onActiveFilterClear}">
                        </opencga-active-filters>

                                <rga-gene-view .query=${this.executedQuery} .opencgaSession="${this.opencgaSession}" .active="${this.activeTab["gene-tab"]}"></rga-gene-view>

                                <rga-individual-view .query=${this.executedQuery} .config=${this._config} .opencgaSession="${this.opencgaSession}" .active="${this.activeTab["individual-tab"]}"></rga-individual-view>

                                <rga-variant-view .query=${this.executedQuery}
                                                  .config=${this._config}
                                                  .opencgaSession="${this.opencgaSession}"
                                                  .cellbaseClient=${this.cellbaseClient}
                                                  .active="${this.activeTab["variant-tab"]}">
                                </rga-variant-view>

        `;
    }

}

customElements.define("rga-browser", RgaBrowser);
<|endoftext|>


<commit_before>import layout from '../../templates/components/nypr-account-forms/login';
import Component from 'ember-component';
import set from 'ember-metal/set';
import get from 'ember-metal/get';
import { next } from 'ember-runloop';
import computed from 'ember-computed';
import service from 'ember-service/inject';
import Changeset from 'ember-changeset';
import LoginValidations from 'nypr-account-settings/validations/nypr-accounts/login';
import messages from 'nypr-account-settings/validations/nypr-accounts/custom-messages';
import lookupValidator from 'ember-changeset-validations';

export default Component.extend({
  layout,
  messages,
  flashMessages: service(),
  authAPI: null,
  session: null,
  showSocialLogin: false,
  resendUrl: computed('authAPI', function() {
    return `${get(this, 'authAPI')}/v1/confirm/resend`;
  }),
  allowedKeys: ['email', 'password'],
  triedUnverifiedAccount: false,
  showLoginError: false,
  init() {
    this._super(...arguments);
    set(this, 'fields', {
      email: '',
      password: ''
    });
    set(this, 'changeset', new Changeset(get(this, 'fields'), lookupValidator(LoginValidations), LoginValidations));
    get(this, 'changeset').validate();
  },
  click() {
    get(this, 'flashMessages').clearMessages();
  },
  actions: {
    onSubmit() {
      set(this, 'showLoginError', false);
      return this.authenticate(get(this, 'fields.email'), get(this, 'fields.password'));
    },
    onFailure(e) {
      if (e) {
        if (get(e, 'errors.code') === 'AccountNotConfirmed') {
          set(this, 'triedUnconfirmedAccount', true);
        } else if (get(e, 'errors.code') === 'UnauthorizedAccess') {
          set(this, 'showLoginError', true);
        } else {
          this.applyErrorToChangeset(e.errors, get(this, 'changeset'));
        }
      }
    },
    loginWithFacebook() {
      let authOptions = {};
      if (get(this, 'emailWasDeclined')) {
        authOptions = {authType: 'rerequest'};
        //reset emailWasDeclined on a new attempt
        set(this, 'emailWasDeclined', false);
      }
      get(this, 'session').authenticate('authenticator:torii', 'facebook-connect', authOptions)
      .catch((e) => {
        if (e && e.code === 'MissingAttributeException' && e.values && e.values.includes("email")) {
          set(this, 'emailWasDeclined', true);
          return this.onFacebookLoginFailure(messages.socialAuthNoEmail);
        } else {
          return this.onFacebookLoginFailure(messages.socialAuthCancelled);
        }
      });
    }
  },
  onFacebookLoginFailure(message) {
    // because we clear flash messages when clicking this form,
    // wait a tick when we add one in an action that can
    // be triggered with a click
    next(() => {
      if (message) {
        this.get('flashMessages').add({
          message: message,
          type: 'warning',
          sticky: true,
        });
      }
    });
  },
  authenticate(email, password) {
    return get(this, 'session').authenticate('authenticator:nypr', email, password);
  },
  applyErrorToChangeset(error, changeset) {
    if (error && error.code) {
      changeset.rollback(); // so errors don't stack up
      if (error.message === 'User is disabled') {
        changeset.pushErrors('email', messages.userDisabled);
      } else if (error.code === "UserNotFoundException") {
        changeset.validate('email');
        changeset.pushErrors('password', messages.emailNotFound( changeset.get('email') ));
      }
    }
  }
});
<commit_msg>Change error handling to switch<commit_after>import layout from '../../templates/components/nypr-account-forms/login';
import Component from 'ember-component';
import set from 'ember-metal/set';
import get from 'ember-metal/get';
import { next } from 'ember-runloop';
import computed from 'ember-computed';
import service from 'ember-service/inject';
import Changeset from 'ember-changeset';
import LoginValidations from 'nypr-account-settings/validations/nypr-accounts/login';
import messages from 'nypr-account-settings/validations/nypr-accounts/custom-messages';
import lookupValidator from 'ember-changeset-validations';

export default Component.extend({
  layout,
  messages,
  flashMessages: service(),
  authAPI: null,
  session: null,
  showSocialLogin: false,
  resendUrl: computed('authAPI', function() {
    return `${get(this, 'authAPI')}/v1/confirm/resend`;
  }),
  allowedKeys: ['email', 'password'],
  triedUnverifiedAccount: false,
  showLoginError: false,
  init() {
    this._super(...arguments);
    set(this, 'fields', {
      email: '',
      password: ''
    });
    set(this, 'changeset', new Changeset(get(this, 'fields'), lookupValidator(LoginValidations), LoginValidations));
    get(this, 'changeset').validate();
  },
  click() {
    get(this, 'flashMessages').clearMessages();
  },
  actions: {
    onSubmit() {
      set(this, 'showLoginError', false);
      return this.authenticate(get(this, 'fields.email'), get(this, 'fields.password'));
    },
    onFailure(e) {
      if (e) {
        let errorCode = get(e, 'errors.code');
        switch (errorCode) {
          case 'AccountNotConfirmed':
            set(this, 'triedUnconfirmedAccount', true);
            break;
          case 'UnauthorizedAccess':
            set(this, 'showLoginError', true);
            break;
          default:
            this.applyErrorToChangeset(e.errors, get(this, 'changeset'));
        }
      }
    },
    loginWithFacebook() {
      let authOptions = {};
      if (get(this, 'emailWasDeclined')) {
        authOptions = {authType: 'rerequest'};
        //reset emailWasDeclined on a new attempt
        set(this, 'emailWasDeclined', false);
      }
      get(this, 'session').authenticate('authenticator:torii', 'facebook-connect', authOptions)
      .catch((e) => {
        if (e && e.code === 'MissingAttributeException' && e.values && e.values.includes("email")) {
          set(this, 'emailWasDeclined', true);
          return this.onFacebookLoginFailure(messages.socialAuthNoEmail);
        } else {
          return this.onFacebookLoginFailure(messages.socialAuthCancelled);
        }
      });
    }
  },
  onFacebookLoginFailure(message) {
    // because we clear flash messages when clicking this form,
    // wait a tick when we add one in an action that can
    // be triggered with a click
    next(() => {
      if (message) {
        this.get('flashMessages').add({
          message: message,
          type: 'warning',
          sticky: true,
        });
      }
    });
  },
  authenticate(email, password) {
    return get(this, 'session').authenticate('authenticator:nypr', email, password);
  },
  applyErrorToChangeset(error, changeset) {
    if (error && error.code) {
      changeset.rollback(); // so errors don't stack up
      if (error.message === 'User is disabled') {
        changeset.pushErrors('email', messages.userDisabled);
      } else if (error.code === "UserNotFoundException") {
        changeset.validate('email');
        changeset.pushErrors('password', messages.emailNotFound( changeset.get('email') ));
      }
    }
  }
});
<|endoftext|>