diff --git a/.travis.yml b/.travis.yml index 90c4a91b..188a0d95 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,7 @@ language: node_js node_js: - "lts/erbium" + - "lts/dubnium" cache: yarn: true directories: diff --git a/README.md b/README.md index c4fdfdbd..dd0e5931 100644 --- a/README.md +++ b/README.md @@ -221,14 +221,14 @@ $ npm install We recommend using node.js v12 or greater to build the library and run tests. -Once complete run `npm test && npm prod` from the top of the application directory to run all tests and build the LocusZoom library bundle. +Once complete run `npm run build` from the top of the application directory to run all tests and build the LocusZoom library bundle. This build process will also write sourcemaps, to help with debugging code even in production environments. #### Other supported gulp commands: * `npm run test` - Run unit tests (optional: `npm run test:coverage` to output a code coverage report) * `npm run dev` - Automatically rebuild the library whenever code changes (development mode) -* `npm run prod` - Build the library for release (production mode) +* `npm run build` - Run tests, and if they pass, build the library for release * `npm run css` - Rebuild the CSS using SASS * `npm run docs` - Build the library documentation diff --git a/css/locuszoom.scss b/css/locuszoom.scss index 3647364d..f5d9650e 100644 --- a/css/locuszoom.scss +++ b/css/locuszoom.scss @@ -580,6 +580,9 @@ div.#{$namespace}-data_layer-tooltip-arrow_bottom_right { .#{$namespace}-toolbar-button-group-middle { border-radius: 0px !important; border-left-width: 0px !important; } .#{$namespace}-toolbar-button-group-end { border-radius: 0px 3px 3px 0px !important; border-left-width: 0px !important; } + input { + line-height: normal; // override a bootstrap behavior so that text fields look good in toolbar + } } .#{$namespace}-panel-toolbar > .#{$namespace}-toolbar-left { diff --git a/dist/ext/lz-aggregation-tests.min.js b/dist/ext/lz-aggregation-tests.min.js index f6af0f77..063e9b8c 100644 --- a/dist/ext/lz-aggregation-tests.min.js +++ b/dist/ext/lz-aggregation-tests.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.12.0-beta.1 */ -var LzAggregationTests=function(t){var e={};function n(a){if(e[a])return e[a].exports;var r=e[a]={i:a,l:!1,exports:{}};return t[a].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,a){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:a})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(a,r,function(e){return t[e]}.bind(null,r));return a},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=24)}([function(t,e){t.exports=d3},function(t,e,n){"use strict";n.d(e,"a",(function(){return i})),n.d(e,"b",(function(){return s})),n.d(e,"c",(function(){return o})),n.d(e,"d",(function(){return l}));var a=n(0);function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function i(t,e,n){if(e?"string"==typeof e&&(e={default:e}):e={default:""},"string"==typeof t){for(var a,s,l,c,u=/\{\{namespace(\[[A-Za-z_0-9]+\]|)\}\}/g,h=[];null!==(a=u.exec(t));)s=a[0],l=a[1].length?a[1].replace(/(\[|\])/g,""):null,c=n,null!=e&&"object"==r(e)&&void 0!==e[l]&&(c=e[l]+(e[l].length?":":"")),h.push({base:s,namespace:c});for(var d in h)t=t.replace(h[d].base,h[d].namespace)}else if("object"==r(t)&&null!=t){var p,f;if(void 0!==t.namespace)e=o(e,"string"==typeof t.namespace?{default:t.namespace}:t.namespace);for(var y in t)"namespace"!==y&&(p=i(t[y],e,n),y!==(f=i(y,e,n))&&delete t[y],t[f]=p)}return t}function o(t,e){if("object"!==r(t)||"object"!==r(e))throw new Error("LocusZoom.Layouts.merge only accepts two layout objects; ".concat(r(t),", ").concat(r(e)," given"));for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var a=null===t[n]?"undefined":r(t[n]),i=r(e[n]);if("object"===a&&Array.isArray(t[n])&&(a="array"),"object"===i&&Array.isArray(e[n])&&(i="array"),"function"===a||"function"===i)throw new Error("LocusZoom.Layouts.merge encountered an unsupported property type");"undefined"!==a?"object"!==a||"object"!==i||(t[n]=o(t[n],e[n])):t[n]=s(e[n])}return t}function s(t){return JSON.parse(JSON.stringify(t))}function l(t){if(!t)return null;var e="symbol".concat(t.charAt(0).toUpperCase()+t.slice(1));return a[e]||null}},function(t,e,n){"use strict";n.d(e,"a",(function(){return c})),n.d(e,"b",(function(){return s})),n.d(e,"c",(function(){return l}));var a=n(0);function r(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],a=!0,r=!1,i=void 0;try{for(var o,s=t[Symbol.iterator]();!(a=(o=s.next()).done)&&(n.push(o.value),!e||n.length!==e);a=!0);}catch(t){r=!0,i=t}finally{try{a||null==s.return||s.return()}finally{if(r)throw i}}return n}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return i(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,a=new Array(e);n2&&void 0!==arguments[2]&&arguments[2];if(!n&&this._items.has(t))throw new Error("Item ".concat(t," is already defined"));return this._items.set(t,e),e}},{key:"remove",value:function(t){return this._items.delete(t)}},{key:"has",value:function(t){return this._items.has(t)}},{key:"list",value:function(){return Array.from(this._items.keys())}}]),t}(),p=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}(u,t);var e,n,a=(e=u,n=s(),function(){var t,a=l(e);if(n){var r=l(this).constructor;t=Reflect.construct(a,arguments,r)}else t=a.apply(this,arguments);return o(this,t)});function u(){return c(this,u),a.apply(this,arguments)}return h(u,[{key:"create",value:function(t){for(var e=this.get(t),n=arguments.length,a=new Array(n>1?n-1:0),i=1;i1&&(this.transformations=r[3].substring(1).split("|"),this.transformations.forEach((function(t,e){return n.transformations[e]=a.a.get(t)})))}var e,n,i;return e=t,(n=[{key:"_applyTransformations",value:function(t){return this.transformations.forEach((function(e){t=e(t)})),t}},{key:"resolve",value:function(t,e){if(void 0===t[this.full_name]){var n=null;void 0!==t["".concat(this.namespace,":").concat(this.name)]?n=t["".concat(this.namespace,":").concat(this.name)]:void 0!==t[this.name]?n=t[this.name]:e&&void 0!==e[this.full_name]&&(n=e[this.full_name]),t[this.full_name]=this._applyTransformations(n)}return t[this.full_name]}}])&&r(e.prototype,n),i&&r(e,i),t}()},function(t,e,n){"use strict";n.d(e,"a",(function(){return T})),n.d(e,"b",(function(){return D})),n.d(e,"c",(function(){return A})),n.d(e,"d",(function(){return N}));var a=n(0),r=n(5),i=n(1),o=n(7);function s(t,e){for(var n=0;ne&&w>t.parent.layout.width&&(r+=o,n=e,l.attr("transform","translate(".concat(n,", ").concat(r,")"))),n+=x.width+3*e}t.elements.push(l)}))}));var s=this.elements_group.node().getBoundingClientRect();return this.layout.width=s.width+2*this.layout.padding,this.layout.height=s.height+2*this.layout.padding,this.background_rect.attr("width",this.layout.width).attr("height",this.layout.height),this.selector.style("visibility",this.layout.hidden?"hidden":"visible"),this.position()}},{key:"position",value:function(){if(!this.selector)return this;var t=this.selector.node().getBoundingClientRect();isNaN(+this.layout.pad_from_bottom)||(this.layout.origin.y=this.parent.layout.height-t.height-+this.layout.pad_from_bottom),isNaN(+this.layout.pad_from_right)||(this.layout.origin.x=this.parent.layout.width-t.width-+this.layout.pad_from_right),this.selector.attr("transform","translate(".concat(this.layout.origin.x,", ").concat(this.layout.origin.y,")"))}},{key:"hide",value:function(){this.layout.hidden=!0,this.render()}},{key:"show",value:function(){this.layout.hidden=!1,this.render()}}])&&f(e.prototype,n),r&&f(e,r),t}(),g=n(9);function m(t){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function v(t,e){for(var n=0;n0)n.layout.z_index<0&&(n.layout.z_index=Math.max(this.data_layer_ids_by_z_index.length+n.layout.z_index,0)),this.data_layer_ids_by_z_index.splice(n.layout.z_index,0,n.id),this.data_layer_ids_by_z_index.forEach((function(t,n){e.data_layers[t].layout.z_index=n}));else{var a=this.data_layer_ids_by_z_index.push(n.id);this.data_layers[n.id].layout.z_index=a-1}var r=null;return this.layout.data_layers.forEach((function(t,e){t.id===n.id&&(r=e)})),null===r&&(r=this.layout.data_layers.push(this.data_layers[n.id].layout)-1),this.data_layers[n.id].layout_idx=r,this.data_layers[n.id]}},{key:"removeDataLayer",value:function(t){var e=this;if(!this.data_layers[t])throw new Error("Unable to remove data layer, ID not found: ".concat(t));return this.data_layers[t].destroyAllTooltips(),this.data_layers[t].svg.container&&this.data_layers[t].svg.container.remove(),this.layout.data_layers.splice(this.data_layers[t].layout_idx,1),delete this.state[this.data_layers[t].state_id],delete this.data_layers[t],this.data_layer_ids_by_z_index.splice(this.data_layer_ids_by_z_index.indexOf(t),1),this.applyDataLayerZIndexesToDataLayerLayouts(),this.layout.data_layers.forEach((function(t,n){e.data_layers[t.id].layout_idx=n})),this}},{key:"clearSelections",value:function(){var t=this;return this.data_layer_ids_by_z_index.forEach((function(e){t.data_layers[e].setAllElementStatus("selected",!1)})),this}},{key:"render",value:function(){var t=this;this.svg.container.attr("transform","translate(".concat(this.layout.origin.x,", ").concat(this.layout.origin.y,")")),this.svg.clipRect.attr("width",this.layout.width).attr("height",this.layout.height),this.inner_border.attr("x",this.layout.margin.left).attr("y",this.layout.margin.top).attr("width",this.layout.width-(this.layout.margin.left+this.layout.margin.right)).attr("height",this.layout.height-(this.layout.margin.top+this.layout.margin.bottom)),this.layout.inner_border&&this.inner_border.style("stroke-width",1).style("stroke",this.layout.inner_border),this.setTitle(),this.generateExtents();var e=function(t,e){var n=Math.pow(-10,e),a=Math.pow(-10,-e),r=Math.pow(10,-e),i=Math.pow(10,e);return t===1/0&&(t=i),t===-1/0&&(t=n),0===t&&(t=r),t>0&&(t=Math.max(Math.min(t,i),r)),t<0&&(t=Math.max(Math.min(t,a),n)),t},n={};if(this.x_extent){var r={start:0,end:this.layout.cliparea.width};this.layout.axes.x.range&&(r.start=this.layout.axes.x.range.start||r.start,r.end=this.layout.axes.x.range.end||r.end),n.x=[r.start,r.end],n.x_shifted=[r.start,r.end]}if(this.y1_extent){var i={start:this.layout.cliparea.height,end:0};this.layout.axes.y1.range&&(i.start=this.layout.axes.y1.range.start||i.start,i.end=this.layout.axes.y1.range.end||i.end),n.y1=[i.start,i.end],n.y1_shifted=[i.start,i.end]}if(this.y2_extent){var o={start:this.layout.cliparea.height,end:0};this.layout.axes.y2.range&&(o.start=this.layout.axes.y2.range.start||o.start,o.end=this.layout.axes.y2.range.end||o.end),n.y2=[o.start,o.end],n.y2_shifted=[o.start,o.end]}if(this.parent.interaction.panel_id&&(this.parent.interaction.panel_id===this.id||this.parent.interaction.linked_panel_ids.includes(this.id))){var s,l=null;if(this.parent.interaction.zooming&&"function"==typeof this.x_scale){var c=Math.abs(this.x_extent[1]-this.x_extent[0]),u=Math.round(this.x_scale.invert(n.x_shifted[1]))-Math.round(this.x_scale.invert(n.x_shifted[0])),h=this.parent.interaction.zooming.scale,d=Math.floor(u*(1/h));h<1&&!isNaN(this.parent.layout.max_region_scale)?h=1/(Math.min(d,this.parent.layout.max_region_scale)/u):h>1&&!isNaN(this.parent.layout.min_region_scale)&&(h=1/(Math.max(d,this.parent.layout.min_region_scale)/u));var p=Math.floor(c*h),f=(s=this.parent.interaction.zooming.center-this.layout.margin.left-this.layout.origin.x)/this.layout.cliparea.width,y=Math.max(Math.floor(this.x_scale.invert(n.x_shifted[0])-(p-u)*f),1);n.x_shifted=[this.x_scale(y),this.x_scale(y+p)]}else if(this.parent.interaction.dragging)switch(this.parent.interaction.dragging.method){case"background":n.x_shifted[0]=+this.parent.interaction.dragging.dragged_x,n.x_shifted[1]=this.layout.cliparea.width+this.parent.interaction.dragging.dragged_x;break;case"x_tick":a.event&&a.event.shiftKey?(n.x_shifted[0]=+this.parent.interaction.dragging.dragged_x,n.x_shifted[1]=this.layout.cliparea.width+this.parent.interaction.dragging.dragged_x):(l=e((s=this.parent.interaction.dragging.start_x-this.layout.margin.left-this.layout.origin.x)/(s+this.parent.interaction.dragging.dragged_x),3),n.x_shifted[0]=0,n.x_shifted[1]=Math.max(this.layout.cliparea.width*(1/l),1));break;case"y1_tick":case"y2_tick":var _="y".concat(this.parent.interaction.dragging.method[1],"_shifted");a.event&&a.event.shiftKey?(n[_][0]=this.layout.cliparea.height+this.parent.interaction.dragging.dragged_y,n[_][1]=+this.parent.interaction.dragging.dragged_y):(l=e((s=this.layout.cliparea.height-(this.parent.interaction.dragging.start_y-this.layout.margin.top-this.layout.origin.y))/(s-this.parent.interaction.dragging.dragged_y),3),n[_][0]=this.layout.cliparea.height,n[_][1]=this.layout.cliparea.height-this.layout.cliparea.height*(1/l))}}if(["x","y1","y2"].forEach((function(e){t["".concat(e,"_extent")]&&(t["".concat(e,"_scale")]=a.scaleLinear().domain(t["".concat(e,"_extent")]).range(n["".concat(e,"_shifted")]),t["".concat(e,"_extent")]=[t["".concat(e,"_scale")].invert(n[e][0]),t["".concat(e,"_scale")].invert(n[e][1])],t["".concat(e,"_scale")]=a.scaleLinear().domain(t["".concat(e,"_extent")]).range(n[e]),t.renderAxis(e))})),this.layout.interaction.scroll_to_zoom){var g=function(){if(a.event.shiftKey){if(a.event.preventDefault(),t.parent._canInteract(t.id)){var e=a.mouse(t.svg.container.node()),n=Math.max(-1,Math.min(1,a.event.wheelDelta||-a.event.detail||-a.event.deltaY));0!==n&&(t.parent.interaction={panel_id:t.id,linked_panel_ids:t.getLinkedPanelIds("x"),zooming:{scale:n<1?.9:1.1,center:e[0]}},t.render(),t.parent.interaction.linked_panel_ids.forEach((function(e){t.parent.panels[e].render()})),null!==t.zoom_timeout&&clearTimeout(t.zoom_timeout),t.zoom_timeout=setTimeout((function(){t.parent.interaction={},t.parent.applyState({start:t.x_extent[0],end:t.x_extent[1]})}),500))}}else t.parent._canInteract(t.id)&&t.loader.show("Press [SHIFT] while scrolling to zoom").hide(1e3)};this.zoom_listener=a.zoom(),this.svg.container.call(this.zoom_listener).on("wheel.zoom",g).on("mousewheel.zoom",g).on("DOMMouseScroll.zoom",g)}return this.data_layer_ids_by_z_index.forEach((function(e){t.data_layers[e].draw().render()})),this}},{key:"addBasicLoader",value:function(t){var e=this;return void 0!==t&&(t=!0),t&&this.loader.show("Loading...").animate(),this.on("data_requested",(function(){e.loader.show("Loading...").animate()})),this.on("data_rendered",(function(){e.loader.hide()})),this}},{key:"applyDataLayerZIndexesToDataLayerLayouts",value:function(){var t=this;this.data_layer_ids_by_z_index.forEach((function(e,n){t.data_layers[e].layout.z_index=n}))}},{key:"getBaseId",value:function(){return"".concat(this.parent.id,".").concat(this.id)}},{key:"_getPageOrigin",value:function(){var t=this.parent._getPageOrigin();return{x:t.x+this.layout.origin.x,y:t.y+this.layout.origin.y}}},{key:"initializeLayout",value:function(){var t=this;if(0===this.layout.width&&null===this.layout.proportional_width&&(this.layout.proportional_width=1),0===this.layout.height&&null===this.layout.proportional_height){var e=Object.keys(this.parent.panels).length;this.layout.proportional_height=e>0?1/e:1}return this.setDimensions(),this.setOrigin(),this.setMargin(),this.x_range=[0,this.layout.cliparea.width],this.y1_range=[this.layout.cliparea.height,0],this.y2_range=[this.layout.cliparea.height,0],["x","y1","y2"].forEach((function(e){Object.keys(t.layout.axes[e]).length&&!1!==t.layout.axes[e].render?(t.layout.axes[e].render=!0,t.layout.axes[e].label=t.layout.axes[e].label||null,t.layout.axes[e].label_function=t.layout.axes[e].label_function||null):t.layout.axes[e].render=!1})),this.layout.data_layers.forEach((function(e){t.addDataLayer(e)})),this}},{key:"setDimensions",value:function(t,e){return void 0!==t&&void 0!==e?!isNaN(t)&&t>=0&&!isNaN(e)&&e>=0&&(this.layout.width=Math.max(Math.round(+t),this.layout.min_width),this.layout.height=Math.max(Math.round(+e),this.layout.min_height)):(null!==this.layout.proportional_width&&(this.layout.width=Math.max(this.layout.proportional_width*this.parent.layout.width,this.layout.min_width)),null!==this.layout.proportional_height&&(this.layout.height=Math.max(this.layout.proportional_height*this.parent.layout.height,this.layout.min_height))),this.layout.cliparea.width=Math.max(this.layout.width-(this.layout.margin.left+this.layout.margin.right),0),this.layout.cliparea.height=Math.max(this.layout.height-(this.layout.margin.top+this.layout.margin.bottom),0),this.svg.clipRect&&this.svg.clipRect.attr("width",this.layout.width).attr("height",this.layout.height),this.initialized&&(this.render(),this.curtain.update(),this.loader.update(),this.toolbar.update(),this.legend&&this.legend.position()),this}},{key:"setOrigin",value:function(t,e){return!isNaN(t)&&t>=0&&(this.layout.origin.x=Math.max(Math.round(+t),0)),!isNaN(e)&&e>=0&&(this.layout.origin.y=Math.max(Math.round(+e),0)),this.initialized&&this.render(),this}},{key:"setMargin",value:function(t,e,n,a){var r,i=this;return!isNaN(t)&&t>=0&&(this.layout.margin.top=Math.max(Math.round(+t),0)),!isNaN(e)&&e>=0&&(this.layout.margin.right=Math.max(Math.round(+e),0)),!isNaN(n)&&n>=0&&(this.layout.margin.bottom=Math.max(Math.round(+n),0)),!isNaN(a)&&a>=0&&(this.layout.margin.left=Math.max(Math.round(+a),0)),this.layout.margin.top+this.layout.margin.bottom>this.layout.height&&(r=Math.floor((this.layout.margin.top+this.layout.margin.bottom-this.layout.height)/2),this.layout.margin.top-=r,this.layout.margin.bottom-=r),this.layout.margin.left+this.layout.margin.right>this.layout.width&&(r=Math.floor((this.layout.margin.left+this.layout.margin.right-this.layout.width)/2),this.layout.margin.left-=r,this.layout.margin.right-=r),["top","right","bottom","left"].forEach((function(t){i.layout.margin[t]=Math.max(i.layout.margin[t],0)})),this.layout.cliparea.width=Math.max(this.layout.width-(this.layout.margin.left+this.layout.margin.right),0),this.layout.cliparea.height=Math.max(this.layout.height-(this.layout.margin.top+this.layout.margin.bottom),0),this.layout.cliparea.origin.x=this.layout.margin.left,this.layout.cliparea.origin.y=this.layout.margin.top,this.initialized&&this.render(),this}},{key:"initialize",value:function(){var t=this,e=this.getBaseId();this.svg.container=this.parent.svg.append("g").attr("id","".concat(e,".panel_container")).attr("transform","translate(".concat(this.layout.origin.x||0,", ").concat(this.layout.origin.y||0,")"));var n=this.svg.container.append("clipPath").attr("id","".concat(e,".clip"));if(this.svg.clipRect=n.append("rect").attr("width",this.layout.width).attr("height",this.layout.height),this.svg.group=this.svg.container.append("g").attr("id","".concat(e,".panel")).attr("clip-path","url(#".concat(e,".clip)")),this.curtain=p.b.call(this),this.loader=p.c.call(this),this.toolbar=new h(this),this.inner_border=this.svg.group.append("rect").attr("class","lz-panel-background").on("click",(function(){"clear_selections"===t.layout.background_click&&t.clearSelections()})),this.title=this.svg.group.append("text").attr("class","lz-panel-title"),void 0!==this.layout.title&&this.setTitle(),this.svg.x_axis=this.svg.group.append("g").attr("id","".concat(e,".x_axis")).attr("class","lz-x lz-axis"),this.layout.axes.x.render&&(this.svg.x_axis_label=this.svg.x_axis.append("text").attr("class","lz-x lz-axis lz-label").attr("text-anchor","middle")),this.svg.y1_axis=this.svg.group.append("g").attr("id","".concat(e,".y1_axis")).attr("class","lz-y lz-y1 lz-axis"),this.layout.axes.y1.render&&(this.svg.y1_axis_label=this.svg.y1_axis.append("text").attr("class","lz-y1 lz-axis lz-label").attr("text-anchor","middle")),this.svg.y2_axis=this.svg.group.append("g").attr("id","".concat(e,".y2_axis")).attr("class","lz-y lz-y2 lz-axis"),this.layout.axes.y2.render&&(this.svg.y2_axis_label=this.svg.y2_axis.append("text").attr("class","lz-y2 lz-axis lz-label").attr("text-anchor","middle")),this.data_layer_ids_by_z_index.forEach((function(e){t.data_layers[e].initialize()})),this.legend=null,this.layout.legend&&(this.legend=new _(this)),this.layout.interaction.drag_background_to_pan){var a=".".concat(this.parent.id,".").concat(this.id,".interaction.drag"),r=function(){t.parent.startDrag(t,"background")};this.svg.container.select(".lz-panel-background").on("mousedown".concat(a,".background"),r).on("touchstart".concat(a,".background"),r)}return this}},{key:"resortDataLayers",value:function(){var t=this,e=[];this.data_layer_ids_by_z_index.forEach((function(n){e.push(t.data_layers[n].layout.z_index)})),this.svg.group.selectAll("g.lz-data_layer-container").data(e).sort(a.ascending),this.applyDataLayerZIndexesToDataLayerLayouts()}},{key:"getLinkedPanelIds",value:function(t){var e=this,n=[];return["x","y1","y2"].includes(t=t||null)&&this.layout.interaction["".concat(t,"_linked")]?(this.parent.panel_ids_by_y_index.forEach((function(a){a!==e.id&&e.parent.panels[a].layout.interaction["".concat(t,"_linked")]&&n.push(a)})),n):n}},{key:"moveUp",value:function(){return this.parent.panel_ids_by_y_index[this.layout.y_index-1]&&(this.parent.panel_ids_by_y_index[this.layout.y_index]=this.parent.panel_ids_by_y_index[this.layout.y_index-1],this.parent.panel_ids_by_y_index[this.layout.y_index-1]=this.id,this.parent.applyPanelYIndexesToPanelLayouts(),this.parent.positionPanels()),this}},{key:"moveDown",value:function(){return this.parent.panel_ids_by_y_index[this.layout.y_index+1]&&(this.parent.panel_ids_by_y_index[this.layout.y_index]=this.parent.panel_ids_by_y_index[this.layout.y_index+1],this.parent.panel_ids_by_y_index[this.layout.y_index+1]=this.id,this.parent.applyPanelYIndexesToPanelLayouts(),this.parent.positionPanels()),this}},{key:"reMap",value:function(){var t=this;for(var e in this.emit("data_requested"),this.data_promises=[],this.curtain.hide(),this.data_layers)try{this.data_promises.push(this.data_layers[e].reMap())}catch(t){console.error(t),this.curtain.show(t.message||t)}return Promise.all(this.data_promises).then((function(){t.initialized=!0,t.render(),t.emit("layout_changed",!0),t.emit("data_rendered")})).catch((function(e){console.error(e),t.curtain.show(e.message||e)}))}},{key:"generateExtents",value:function(){var t=this;for(var e in["x","y1","y2"].forEach((function(e){t["".concat(e,"_extent")]=null})),this.data_layers){var n=this.data_layers[e];if(n.layout.x_axis&&!n.layout.x_axis.decoupled&&(this.x_extent=a.extent((this.x_extent||[]).concat(n.getAxisExtent("x")))),n.layout.y_axis&&!n.layout.y_axis.decoupled){var r="y".concat(n.layout.y_axis.axis);this["".concat(r,"_extent")]=a.extent((this["".concat(r,"_extent")]||[]).concat(n.getAxisExtent("y")))}}return this.layout.axes.x&&"state"===this.layout.axes.x.extent&&(this.x_extent=[this.state.start,this.state.end]),this}},{key:"generateTicks",value:function(t){if(this.layout.axes[t].ticks){var e=this.layout.axes[t].ticks;if(Array.isArray(e))return e;if("object"===m(e)){var n=this,a={position:e.position};return this.data_layer_ids_by_z_index.reduce((function(e,r){var i=n.data_layers[r];return e.concat(i.getTicks(t,a))}),[]).map((function(t){var n={};return n=Object(i.c)(n,e),Object(i.c)(n,t)}))}}return this["".concat(t,"_extent")]?N(this["".concat(t,"_extent")],"both"):[]}},{key:"renderAxis",value:function(t){var e=this;if(!["x","y1","y2"].includes(t))throw new Error("Unable to render axis; invalid axis identifier: ".concat(t));var n=this.layout.axes[t].render&&"function"==typeof this["".concat(t,"_scale")]&&!isNaN(this["".concat(t,"_scale")](0));if(this["".concat(t,"_axis")]&&this.svg.container.select("g.lz-axis.lz-".concat(t)).style("display",n?null:"none"),!n)return this;var r={x:{position:"translate(".concat(this.layout.margin.left,", ").concat(this.layout.height-this.layout.margin.bottom,")"),orientation:"bottom",label_x:this.layout.cliparea.width/2,label_y:this.layout.axes[t].label_offset||0,label_rotate:null},y1:{position:"translate(".concat(this.layout.margin.left,", ").concat(this.layout.margin.top,")"),orientation:"left",label_x:-1*(this.layout.axes[t].label_offset||0),label_y:this.layout.cliparea.height/2,label_rotate:-90},y2:{position:"translate(".concat(this.layout.width-this.layout.margin.right,", ").concat(this.layout.margin.top,")"),orientation:"right",label_x:this.layout.axes[t].label_offset||0,label_y:this.layout.cliparea.height/2,label_rotate:-90}};this["".concat(t,"_ticks")]=this.generateTicks(t);var i,o=function(t){for(var e=0;e=t.length?{done:!0}:{done:!1,value:t[a++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return o=t.done,t},e:function(t){s=!0,i=t},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function O(t,e){if(t){if("string"==typeof t)return S(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?S(t,e):void 0}}function S(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,a=new Array(e);n0)e.layout.y_index<0&&(e.layout.y_index=Math.max(this.panel_ids_by_y_index.length+e.layout.y_index,0)),this.panel_ids_by_y_index.splice(e.layout.y_index,0,e.id),this.applyPanelYIndexesToPanelLayouts();else{var n=this.panel_ids_by_y_index.push(e.id);this.panels[e.id].layout.y_index=n-1}var a=null;return this.layout.panels.forEach((function(t,n){t.id===e.id&&(a=n)})),null===a&&(a=this.layout.panels.push(this.panels[e.id].layout)-1),this.panels[e.id].layout_idx=a,this.initialized&&(this.positionPanels(),this.panels[e.id].initialize(),this.panels[e.id].reMap(),this.setDimensions(this.layout.width,this.layout.height)),this.panels[e.id]}},{key:"clearPanelData",value:function(t,e){var n=this;return e=e||"wipe",(t?[t]:Object.keys(this.panels)).forEach((function(t){n.panels[t].data_layer_ids_by_z_index.forEach((function(a){var r=n.panels[t].data_layers[a];r.destroyAllTooltips(),delete r.layer_state,delete n.layout.state[r.state_id],"reset"===e&&r._setDefaultState()}))})),this}},{key:"removePanel",value:function(t){var e=this;if(!this.panels[t])throw new Error("Unable to remove panel, ID not found: ".concat(t));return this.panel_boundaries.hide(),this.clearPanelData(t),this.panels[t].loader.hide(),this.panels[t].toolbar.destroy(!0),this.panels[t].curtain.hide(),this.panels[t].svg.container&&this.panels[t].svg.container.remove(),this.layout.panels.splice(this.panels[t].layout_idx,1),delete this.panels[t],delete this.layout.state[t],this.layout.panels.forEach((function(t,n){e.panels[t.id].layout_idx=n})),this.panel_ids_by_y_index.splice(this.panel_ids_by_y_index.indexOf(t),1),this.applyPanelYIndexesToPanelLayouts(),this.initialized&&(this.layout.min_height=this._base_layout.min_height,this.layout.min_width=this._base_layout.min_width,this.positionPanels(),this.setDimensions(this.layout.width,this.layout.height)),this.emit("panel_removed",t),this}},{key:"refresh",value:function(){return this.applyState()}},{key:"subscribeToData",value:function(t,e,n){var a=this,r=(n=n||{}).onerror||function(t){console.log("An error occurred while acting on an external callback",t)},i=function(){try{a.lzd.getData(a.state,t).then((function(t){return e(n.discrete?t.discrete:t.body)})).catch(r)}catch(t){r(t)}};return this.on("data_rendered",i),i}},{key:"applyState",value:function(t){var e=this;if("object"!=z(t=t||{}))throw new Error("applyState only accepts an object; ".concat(z(t)," given"));var n={chr:this.state.chr,start:this.state.start,end:this.state.end};for(var a in t)n[a]=t[a];for(a in n=function(t,e){e=e||{};var n=!1;if(void 0!==(t=t||{}).chr&&void 0!==t.start&&void 0!==t.end){var a,r=null;if(t.start=Math.max(parseInt(t.start),1),t.end=Math.max(parseInt(t.end),1),isNaN(t.start)&&isNaN(t.end))t.start=1,t.end=1,r=.5,a=0;else if(isNaN(t.start)||isNaN(t.end))r=t.start||t.end,a=0,t.start=isNaN(t.start)?t.end:t.start,t.end=isNaN(t.end)?t.start:t.end;else{if(r=Math.round((t.start+t.end)/2),(a=t.end-t.start)<0){var i=t.start;t.end=t.start,t.start=i,a=t.end-t.start}r<0&&(t.start=1,t.end=1,a=0)}n=!0}return!isNaN(e.min_region_scale)&&n&&ae.max_region_scale&&(t.start=Math.max(r-Math.floor(e.max_region_scale/2),1),t.end=t.start+e.max_region_scale),t}(n,this.layout))this.state[a]=n[a];for(var r in this.emit("data_requested"),this.remap_promises=[],this.loading_data=!0,this.panels)this.remap_promises.push(this.panels[r].reMap());return Promise.all(this.remap_promises).catch((function(t){console.error(t),e.curtain.show(t.message||t),e.loading_data=!1})).then((function(){e.toolbar.update(),e.panel_ids_by_y_index.forEach((function(t){var n=e.panels[t];n.toolbar.update(),n.data_layer_ids_by_z_index.forEach((function(t){n.data_layers[t].applyAllElementStatus()}))})),e.emit("layout_changed"),e.emit("data_rendered"),e.emit("state_changed",t);var n=e.state,a=n.chr,r=n.start,i=n.end;Object.keys(t).some((function(t){return["chr","start","end"].includes(t)}))&&e.emit("region_changed",{chr:a,start:r,end:i}),e.loading_data=!1}))}},{key:"trackWindowListener",value:function(t,e){var n=this._window_listeners.get(t)||[];n.includes(e)||n.push(e),this._window_listeners.set(t,n)}},{key:"destroy",value:function(){var t,e=k(this._window_listeners.entries());try{for(e.s();!(t=e.n()).done;){var n,a=w(t.value,2),r=a[0],i=k(a[1]);try{for(i.s();!(n=i.n()).done;){var o=n.value;window.removeEventListener(r,o)}}catch(t){i.e(t)}finally{i.f()}}}catch(t){e.e(t)}finally{e.f()}var s=this.svg.node().parentNode;if(!s)throw new Error("Plot has already been removed");for(;s.lastElementChild;)s.removeChild(s.lastElementChild);s.outerHTML=s.outerHTML,this.initialized=!1}},{key:"_canInteract",value:function(t){return(t=t||null)?(void 0===this.interaction.panel_id||this.interaction.panel_id===t)&&!this.loading_data:!(this.interaction.dragging||this.interaction.zooming||this.loading_data)}},{key:"_getPageOrigin",value:function(){for(var t=this.svg.node().getBoundingClientRect(),e=document.documentElement.scrollLeft||document.body.scrollLeft,n=document.documentElement.scrollTop||document.body.scrollTop,r=this.svg.node();null!==r.parentNode;)if((r=r.parentNode)!==document&&"static"!==a.select(r).style("position")){e=-1*r.getBoundingClientRect().left,n=-1*r.getBoundingClientRect().top;break}return{x:e+t.left,y:n+t.top,width:t.width,height:t.height}}},{key:"getContainerOffset",value:function(){for(var t={top:0,left:0},e=this.container.offsetParent||null;null!==e;)t.top+=e.offsetTop,t.left+=e.offsetLeft,e=e.offsetParent||null;return t}},{key:"applyPanelYIndexesToPanelLayouts",value:function(){var t=this;this.panel_ids_by_y_index.forEach((function(e,n){t.panels[e].layout.y_index=n}))}},{key:"getBaseId",value:function(){return this.id}},{key:"sumProportional",value:function(t){if("height"!==t&&"width"!==t)throw new Error("Bad dimension value passed to sumProportional");var e=0;for(var n in this.panels)this.panels[n].layout["proportional_".concat(t)]||(this.panels[n].layout["proportional_".concat(t)]=1/Object.keys(this.panels).length),e+=this.panels[n].layout["proportional_".concat(t)];return e}},{key:"rescaleSVG",value:function(){var t=this.svg.node().getBoundingClientRect();return this.setDimensions(t.width,t.height),this}},{key:"initializeLayout",value:function(){var t=this;if(isNaN(this.layout.width)||this.layout.width<=0)throw new Error("Plot layout parameter `width` must be a positive number");if(isNaN(this.layout.height)||this.layout.height<=0)throw new Error("Plot layout parameter `width` must be a positive number");if(this.layout.responsive_resize=!!this.layout.responsive_resize,this.layout.responsive_resize){var e=function(){return t.rescaleSVG()};window.addEventListener("resize",e),this.trackWindowListener("resize",e);var n=function(){return t.setDimensions()};window.addEventListener("load",n),this.trackWindowListener("load",n)}return this.layout.panels.forEach((function(e){t.addPanel(e)})),this}},{key:"setDimensions",value:function(t,e){var n,r=this,i=parseFloat(this.layout.min_width)||0,o=parseFloat(this.layout.min_height)||0;for(n in this.panels)i=Math.max(i,this.panels[n].layout.min_width),parseFloat(this.panels[n].layout.min_height)>0&&parseFloat(this.panels[n].layout.proportional_height)>0&&(o=Math.max(o,this.panels[n].layout.min_height/this.panels[n].layout.proportional_height));if(this.layout.min_width=Math.max(i,1),this.layout.min_height=Math.max(o,1),a.select(this.svg.node().parentNode).style("min-width","".concat(this.layout.min_width,"px")).style("min-height","".concat(this.layout.min_height,"px")),!isNaN(t)&&t>=0&&!isNaN(e)&&e>=0){this.layout.width=Math.max(Math.round(+t),this.layout.min_width),this.layout.height=Math.max(Math.round(+e),this.layout.min_height),this.layout.responsive_resize&&this.svg&&(this.layout.width=Math.max(this.svg.node().parentNode.getBoundingClientRect().width,this.layout.min_width));var s=0;this.panel_ids_by_y_index.forEach((function(t){var e=r.layout.width,n=r.panels[t].layout.proportional_height*r.layout.height;r.panels[t].setDimensions(e,n),r.panels[t].setOrigin(0,s),r.panels[t].layout.proportional_origin.x=0,r.panels[t].layout.proportional_origin.y=s/r.layout.height,s+=n,r.panels[t].toolbar.update()}))}else if(Object.keys(this.panels).length){for(n in this.layout.width=0,this.layout.height=0,this.panels)this.layout.width=Math.max(this.panels[n].layout.width,this.layout.width),this.layout.height+=this.panels[n].layout.height;this.layout.width=Math.max(this.layout.width,this.layout.min_width),this.layout.height=Math.max(this.layout.height,this.layout.min_height)}return null!==this.svg&&(this.svg.attr("viewBox","0 0 ".concat(this.layout.width," ").concat(this.layout.height)),this.layout.responsive_resize?this.svg.attr("preserveAspectRatio","xMinYMin meet"):this.svg.attr("width",this.layout.width).attr("height",this.layout.height)),this.initialized&&(this.panel_boundaries.position(),this.toolbar.update(),this.curtain.update(),this.loader.update()),this.emit("layout_changed")}},{key:"positionPanels",value:function(){var t,e=this,n={left:0,right:0};for(t in this.panels)null===this.panels[t].layout.proportional_height&&(this.panels[t].layout.proportional_height=this.panels[t].layout.height/this.layout.height),null===this.panels[t].layout.proportional_width&&(this.panels[t].layout.proportional_width=1),this.panels[t].layout.interaction.x_linked&&(n.left=Math.max(n.left,this.panels[t].layout.margin.left),n.right=Math.max(n.right,this.panels[t].layout.margin.right));var a=this.sumProportional("height");if(!a)return this;var r=1/a;for(t in this.panels)this.panels[t].layout.proportional_height*=r;var i=0;this.panel_ids_by_y_index.forEach((function(t){if(e.panels[t].setOrigin(0,i),e.panels[t].layout.proportional_origin.x=0,i+=e.panels[t].layout.height,e.panels[t].layout.interaction.x_linked){var a=Math.max(n.left-e.panels[t].layout.margin.left,0)+Math.max(n.right-e.panels[t].layout.margin.right,0);e.panels[t].layout.width+=a,e.panels[t].layout.margin.left=n.left,e.panels[t].layout.margin.right=n.right,e.panels[t].layout.cliparea.origin.x=n.left}}));var o=i;return this.panel_ids_by_y_index.forEach((function(t){e.panels[t].layout.proportional_origin.y=e.panels[t].layout.origin.y/o})),this.setDimensions(),this.panel_ids_by_y_index.forEach((function(t){e.panels[t].setDimensions(e.layout.width*e.panels[t].layout.proportional_width,e.layout.height*e.panels[t].layout.proportional_height)})),this}},{key:"initialize",value:function(){var t=this;if(this.layout.responsive_resize&&a.select(this.container).classed("lz-container-responsive",!0),this.layout.mouse_guide){var e=this.svg.append("g").attr("class","lz-mouse_guide").attr("id","".concat(this.id,".mouse_guide")),n=e.append("rect").attr("class","lz-mouse_guide-vertical").attr("x",-1),r=e.append("rect").attr("class","lz-mouse_guide-horizontal").attr("y",-1);this.mouse_guide={svg:e,vertical:n,horizontal:r}}for(var i in this.curtain=p.b.call(this),this.loader=p.c.call(this),this.panel_boundaries={parent:this,hide_timeout:null,showing:!1,dragging:!1,selectors:[],corner_selector:null,show:function(){var t=this;if(!this.showing&&!this.parent.curtain.showing){this.showing=!0,this.parent.panel_ids_by_y_index.forEach((function(e,n){var r=a.select(t.parent.svg.node().parentNode).insert("div",".lz-data_layer-tooltip").attr("class","lz-panel-boundary").attr("title","Resize panel");r.append("span");var i=a.drag();i.on("start",(function(){t.dragging=!0})),i.on("end",(function(){t.dragging=!1})),i.on("drag",(function(){var e=t.parent.panels[t.parent.panel_ids_by_y_index[n]],r=e.layout.height;e.setDimensions(e.layout.width,e.layout.height+a.event.dy);var i=e.layout.height-r,o=t.parent.layout.height+i;t.parent.panel_ids_by_y_index.forEach((function(e,a){var r=t.parent.panels[t.parent.panel_ids_by_y_index[a]];r.layout.proportional_height=r.layout.height/o,a>n&&(r.setOrigin(r.layout.origin.x,r.layout.origin.y+i),r.toolbar.position())})),t.parent.positionPanels(),t.position()})),r.call(i),t.parent.panel_boundaries.selectors.push(r)}));var e=a.select(this.parent.svg.node().parentNode).insert("div",".lz-data_layer-tooltip").attr("class","lz-panel-corner-boundary").attr("title","Resize plot");e.append("span").attr("class","lz-panel-corner-boundary-outer"),e.append("span").attr("class","lz-panel-corner-boundary-inner");var n=a.drag();n.on("start",(function(){t.dragging=!0})),n.on("end",(function(){t.dragging=!1})),n.on("drag",(function(){t.parent.setDimensions(t.layout.width+a.event.dx,t.layout.height+a.event.dy)})),e.call(n),this.parent.panel_boundaries.corner_selector=e}return this.position()},position:function(){var t=this;if(!this.showing)return this;var e=this.parent._getPageOrigin();return this.selectors.forEach((function(n,a){var r=t.parent.panels[t.parent.panel_ids_by_y_index[a]]._getPageOrigin(),i=e.x,o=r.y+t.parent.panels[t.parent.panel_ids_by_y_index[a]].layout.height-12,s=t.parent.layout.width-1;n.style("top","".concat(o,"px")).style("left","".concat(i,"px")).style("width","".concat(s,"px")),n.select("span").style("width","".concat(s,"px"))})),this.corner_selector.style("top","".concat(e.y+this.parent.layout.height-10-16,"px")).style("left","".concat(e.x+this.parent.layout.width-10-16,"px")),this},hide:function(){return this.showing?(this.showing=!1,this.selectors.forEach((function(t){t.remove()})),this.selectors=[],this.corner_selector.remove(),this.corner_selector=null,this):this}},this.layout.panel_boundaries&&(a.select(this.svg.node().parentNode).on("mouseover.".concat(this.id,".panel_boundaries"),(function(){clearTimeout(t.panel_boundaries.hide_timeout),t.panel_boundaries.show()})),a.select(this.svg.node().parentNode).on("mouseout.".concat(this.id,".panel_boundaries"),(function(){t.panel_boundaries.hide_timeout=setTimeout((function(){t.panel_boundaries.hide()}),300)}))),this.toolbar=new h(this).show(),this.panels)this.panels[i].initialize();var o=".".concat(this.id);if(this.layout.mouse_guide){var s=function(){t.mouse_guide.vertical.attr("x",-1),t.mouse_guide.horizontal.attr("y",-1)};this.svg.on("mouseout".concat(o,"-mouse_guide"),s).on("touchleave".concat(o,"-mouse_guide"),s).on("mousemove".concat(o,"-mouse_guide"),(function(){var e=a.mouse(t.svg.node());t.mouse_guide.vertical.attr("x",e[0]),t.mouse_guide.horizontal.attr("y",e[1])}))}var l=function(){t.stopDrag()},c=function(){if(t.interaction.dragging){var e=a.mouse(t.svg.node());a.event&&a.event.preventDefault(),t.interaction.dragging.dragged_x=e[0]-t.interaction.dragging.start_x,t.interaction.dragging.dragged_y=e[1]-t.interaction.dragging.start_y,t.panels[t.interaction.panel_id].render(),t.interaction.linked_panel_ids.forEach((function(e){t.panels[e].render()}))}};this.svg.on("mouseup".concat(o),l).on("touchend".concat(o),l).on("mousemove".concat(o),c).on("touchmove".concat(o),c),a.select("body").empty()||a.select("body").on("mouseup".concat(o),l).on("touchend".concat(o),l),this.on("match_requested",(function(e){var n=e.data,a=n.active?n.value:null;t.applyState({lz_match_value:a})})),this.initialized=!0;var u=this.svg.node().getBoundingClientRect(),d=u.width?u.width:this.layout.width,f=u.height?u.height:this.layout.height;return this.setDimensions(d,f),this}},{key:"startDrag",value:function(t,e){t=t||null;var n=null;switch(e=e||null){case"background":case"x_tick":n="x";break;case"y1_tick":n="y1";break;case"y2_tick":n="y2"}if(!(t instanceof x&&n&&this._canInteract()))return this.stopDrag();var r=a.mouse(this.svg.node());return this.interaction={panel_id:t.id,linked_panel_ids:t.getLinkedPanelIds(n),dragging:{method:e,start_x:r[0],start_y:r[1],dragged_x:0,dragged_y:0,axis:n}},this.svg.style("cursor","all-scroll"),this}},{key:"stopDrag",value:function(){if(!this.interaction.dragging)return this;if("object"!=z(this.panels[this.interaction.panel_id]))return this.interaction={},this;var t=this.panels[this.interaction.panel_id],e=function(e,n,a){t.data_layer_ids_by_z_index.forEach((function(r){var i=t.data_layers[r].layout["".concat(e,"_axis")];i.axis===n&&(i.floor=a[0],i.ceiling=a[1],delete i.lower_buffer,delete i.upper_buffer,delete i.min_extent,delete i.ticks)}))};switch(this.interaction.dragging.method){case"background":case"x_tick":0!==this.interaction.dragging.dragged_x&&(e("x",1,t.x_extent),this.applyState({start:t.x_extent[0],end:t.x_extent[1]}));break;case"y1_tick":case"y2_tick":if(0!==this.interaction.dragging.dragged_y){var n=parseInt(this.interaction.dragging.method[1]);e("y",n,t["y".concat(n,"_extent")])}}return this.interaction={},this.svg.style("cursor",null),this}}])&&E(e.prototype,n),r&&E(e,r),t}();function P(t){return(P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function A(t,e,n){var a={0:"",3:"K",6:"M",9:"G"};if(n=n||!1,isNaN(e)||null===e){var r=Math.log(t)/Math.LN10;e=Math.min(Math.max(r-r%3,0),9)}var i=e-Math.floor((Math.log(t)/Math.LN10).toFixed(e+3)),o=Math.min(Math.max(e,0),2),s=Math.min(Math.max(i,o),12),l="".concat((t/Math.pow(10,e)).toFixed(s));return n&&void 0!==a[e]&&(l+=" ".concat(a[e],"b")),l}function R(t){var e=t.toUpperCase();e=e.replace(/,/g,"");var n=/([KMG])[B]*$/,a=n.exec(e),r=1;return a&&(r="M"===a[1]?1e6:"G"===a[1]?1e9:1e3,e=e.replace(n,"")),e=Number(e)*r}function N(t,e,n){(void 0===n||isNaN(parseInt(n)))&&(n=5);var a=(n=+n)/3,r=Math.abs(t[0]-t[1]),i=r/n;Math.log(r)/Math.LN10<-2&&(i=.75*Math.max(Math.abs(r))/a);var o=Math.pow(10,Math.floor(Math.log(i)/Math.LN10)),s=0;o<1&&0!==o&&(s=Math.abs(Math.round(Math.log(o)/Math.LN10)));var l=o;2*o-i<1.5*(i-l)&&5*o-i<2.75*(i-(l=2*o))&&10*o-i<1.5*(i-(l=5*o))&&(l=10*o);for(var c=[],u=parseFloat((Math.floor(t[0]/l)*l).toFixed(s));u0&&(u=parseFloat(u.toFixed(s)));return c.push(u),void 0!==e&&-1!==["low","high","both","neither"].indexOf(e)||(e="neither"),"low"!==e&&"both"!==e||c[0]t[1]&&c.pop(),c}function T(t,e){if("object"!=P(t))throw new Error("invalid arguments: data is not an object");if("string"!=typeof e)throw new Error("invalid arguments: html is not a string");for(var n=[],a=/{{(?:(#if )?([A-Za-z0-9_:|]+)|(\/if))}}/;e.length>0;){var i=a.exec(e);i?0!==i.index?(n.push({text:e.slice(0,i.index)}),e=e.slice(i.index)):"#if "===i[1]?(n.push({condition:i[2]}),e=e.slice(i[0].length)):i[2]?(n.push({variable:i[2]}),e=e.slice(i[0].length)):"/if"===i[3]?(n.push({close:"if"}),e=e.slice(i[0].length)):(console.error("Error tokenizing tooltip when remaining template is ".concat(JSON.stringify(e)," and previous tokens are ").concat(JSON.stringify(n)," and current regex match is ").concat(JSON.stringify([i[1],i[2],i[3]]))),e=e.slice(i[0].length)):(n.push({text:e}),e="")}for(var o=function t(){var e=n.shift();if(void 0!==e.text||e.variable)return e;if(e.condition){for(e.then=[];n.length>0;){if("if"===n[0].close){n.shift();break}e.then.push(t())}return e}return console.error("Error making tooltip AST due to unknown token ".concat(JSON.stringify(e))),{text:""}},s=[];n.length>0;)s.push(o());var l=function e(n){return Object.prototype.hasOwnProperty.call(e.cache,n)||(e.cache[n]=new r.a(n).resolve(t)),e.cache[n]};l.cache={};return s.map((function t(e){if(void 0!==e.text)return e.text;if(e.variable){try{var n=l(e.variable);if(-1!==["string","number","boolean"].indexOf(P(n)))return n;if(null===n)return""}catch(t){console.error("Error while processing variable ".concat(JSON.stringify(e.variable)))}return"{{".concat(e.variable,"}}")}if(e.condition){try{var a=l(e.condition);if(a||0===a)return e.then.map(t).join("")}catch(t){console.error("Error while processing condition ".concat(JSON.stringify(e.variable)))}return""}console.error("Error rendering tooltip due to unknown AST node ".concat(JSON.stringify(e)))})).join("")}function D(t,e,n){if(void 0===t)throw new Error("LocusZoom.populate selector not defined");var r;return a.select(t).html(""),a.select(t).call((function(t){if(void 0===t.node().id){for(var i=0;!a.select("#lz-".concat(i)).empty();)i++;t.attr("id","#lz-".concat(i))}if((r=new M(t.node().id,e,n)).container=t.node(),void 0!==t.node().dataset&&void 0!==t.node().dataset.region){var o=function(t){var e=/^(\w+):([\d,.]+[kmgbKMGB]*)([-+])([\d,.]+[kmgbKMGB]*)$/.exec(t);if(e){if("+"===e[3]){var n=R(e[2]),a=R(e[4]);return{chr:e[1],start:n-a,end:n+a}}return{chr:e[1],start:R(e[2]),end:R(e[4])}}if(e=/^(\w+):([\d,.]+[kmgbKMGB]*)$/.exec(t))return{chr:e[1],position:R(e[2])};return null}(t.node().dataset.region);Object.keys(o).forEach((function(t){r.state[t]=o[t]}))}r.svg=a.select("div#".concat(r.id)).append("svg").attr("version","1.1").attr("xmlns","http://www.w3.org/2000/svg").attr("id","".concat(r.id,"_svg")).attr("class","lz-locuszoom").call(p.a,r.layout.style),r.setDimensions(),r.positionPanels(),r.initialize(),e&&r.refresh()})),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return _})),n.d(e,"b",(function(){return g.a})),n.d(e,"c",(function(){return xt})),n.d(e,"d",(function(){return wt.a})),n.d(e,"e",(function(){return kt.a})),n.d(e,"f",(function(){return Ot.a}));var a={};n.r(a),n.d(a,"tooltip",(function(){return J})),n.d(a,"toolbar_widgets",(function(){return $})),n.d(a,"toolbar",(function(){return V})),n.d(a,"data_layer",(function(){return W})),n.d(a,"panel",(function(){return Y})),n.d(a,"plot",(function(){return X}));var r=n(3),i=n(8);function o(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],a=!0,r=!1,i=void 0;try{for(var o,s=t[Symbol.iterator]();!(a=(o=s.next()).done)&&(n.push(o.value),!e||n.length!==e);a=!0);}catch(t){r=!0,i=t}finally{try{a||null==s.return||s.return()}finally{if(r)throw i}}return n}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return s(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return s(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,a=new Array(e);n{{{{namespace[assoc]}}variant|htmlescape}}
\n P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
\n Ref. Allele: {{{{namespace[assoc]}}ref_allele|htmlescape}}
\n Make LD Reference
'},x=((f=Object(m.b)(b)).html+="Toggle label",f),w={closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'

{{gene_name|htmlescape}}

Gene ID: {{gene_id|htmlescape}}
Transcript ID: {{transcript_id|htmlescape}}
{{#if pLI}}
ConstraintExpected variantsObserved variantsConst. Metric
Synonymous{{exp_syn}}{{obs_syn}}z = {{syn_z}}
o/e = {{oe_syn}} ({{oe_syn_lower}} - {{oe_syn_upper}})
Missense{{exp_mis}}{{obs_mis}}z = {{mis_z}}
o/e = {{oe_mis}} ({{oe_mis_lower}} - {{oe_mis_upper}})
pLoF{{exp_lof}}{{obs_lof}}pLI = {{pLI}}
o/e = {{oe_lof}} ({{oe_lof_lower}} - {{oe_lof_upper}})

{{/if}}More data on gnomAD'},k={namespace:{assoc:"assoc",catalog:"catalog"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'{{{{namespace[catalog]}}variant|htmlescape}}
Catalog entries: {{n_catalog_matches|htmlescape}}
Top Trait: {{{{namespace[catalog]}}trait|htmlescape}}
Top P Value: {{{{namespace[catalog]}}log_pvalue|logtoscinotation}}
More: GWAS catalog / dbSNP'},O={namespace:{access:"access"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"Regulatory element
{{{{namespace[access]}}start1|htmlescape}}-{{{{namespace[access]}}end1|htmlescape}}
Promoter
{{{{namespace[access]}}start2|htmlescape}}-{{{{namespace[access]}}end2|htmlescape}}
{{#if {{namespace[access]}}target}}Target: {{{{namespace[access]}}target|htmlescape}}
{{/if}}Score: {{{{namespace[access]}}score|htmlescape}}"},S={id:"significance",type:"orthogonal_line",orientation:"horizontal",offset:7.301},z={namespace:{recomb:"recomb"},id:"recombrate",type:"line",fields:["{{namespace[recomb]}}position","{{namespace[recomb]}}recomb_rate"],z_index:1,style:{stroke:"#0000FF","stroke-width":"1.5px"},x_axis:{field:"{{namespace[recomb]}}position"},y_axis:{axis:2,field:"{{namespace[recomb]}}recomb_rate",floor:0,ceiling:100}},E={namespace:{assoc:"assoc",ld:"ld"},id:"associationpvalues",type:"scatter",point_shape:{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:"diamond",else:"circle"}},point_size:{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:80,else:40}},color:[{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:"#9632b8"}},{scale_function:"numerical_bin",field:"{{namespace[ld]}}state",parameters:{breaks:[0,.2,.4,.6,.8],values:["#357ebd","#46b8da","#5cb85c","#eea236","#d43f3a"]}},"#B8B8B8"],legend:[{shape:"diamond",color:"#9632b8",size:40,label:"LD Ref Var",class:"lz-data_layer-scatter"},{shape:"circle",color:"#d43f3a",size:40,label:"1.0 > r² ≥ 0.8",class:"lz-data_layer-scatter"},{shape:"circle",color:"#eea236",size:40,label:"0.8 > r² ≥ 0.6",class:"lz-data_layer-scatter"},{shape:"circle",color:"#5cb85c",size:40,label:"0.6 > r² ≥ 0.4",class:"lz-data_layer-scatter"},{shape:"circle",color:"#46b8da",size:40,label:"0.4 > r² ≥ 0.2",class:"lz-data_layer-scatter"},{shape:"circle",color:"#357ebd",size:40,label:"0.2 > r² ≥ 0.0",class:"lz-data_layer-scatter"},{shape:"circle",color:"#B8B8B8",size:40,label:"no r² data",class:"lz-data_layer-scatter"}],label:null,fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[assoc]}}log_pvalue|logtoscinotation","{{namespace[assoc]}}ref_allele","{{namespace[ld]}}state","{{namespace[ld]}}isrefvar"],id_field:"{{namespace[assoc]}}variant",z_index:2,x_axis:{field:"{{namespace[assoc]}}position"},y_axis:{axis:1,field:"{{namespace[assoc]}}log_pvalue",floor:0,upper_buffer:.1,min_extent:[0,10]},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:Object(m.b)(b)},j={namespace:{access:"access"},id:"coaccessibility",type:"arcs",fields:["{{namespace[access]}}start1","{{namespace[access]}}end1","{{namespace[access]}}start2","{{namespace[access]}}end2","{{namespace[access]}}id","{{namespace[access]}}target","{{namespace[access]}}score"],match:{send:"{{namespace[access]}}target",receive:"{{namespace[access]}}target"},id_field:"{{namespace[access]}}id",filters:[["{{namespace[access]}}score","!=",null]],color:[{field:"lz_highlight_match",scale_function:"if",parameters:{field_value:!0,then:"#ff0000"}},{field:"lz_highlight_match",scale_function:"if",parameters:{field_value:!1,then:"#EAE6E6"}},{scale_function:"ordinal_cycle",parameters:{values:["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"]}}],x_axis:{field1:"{{namespace[access]}}start1",field2:"{{namespace[access]}}start2"},y_axis:{axis:1,field:"{{namespace[access]}}score",upper_buffer:.1,min_extent:[0,1]},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:Object(m.b)(O)},M=function(){var t=Object(m.b)(E);return(t=Object(m.c)({id:"associationpvaluescatalog",fill_opacity:.7},t)).tooltip.html+='{{#if {{namespace[catalog]}}rsid}}
See hits in GWAS catalog{{/if}}',t.namespace.catalog="catalog",t.fields.push("{{namespace[catalog]}}rsid","{{namespace[catalog]}}trait","{{namespace[catalog]}}log_pvalue"),t}(),P={namespace:{phewas:"phewas"},id:"phewaspvalues",type:"category_scatter",point_shape:"circle",point_size:70,tooltip_positioning:"vertical",id_field:"{{namespace[phewas]}}id",fields:["{{namespace[phewas]}}id","{{namespace[phewas]}}log_pvalue","{{namespace[phewas]}}trait_group","{{namespace[phewas]}}trait_label"],x_axis:{field:"{{namespace[phewas]}}x",category_field:"{{namespace[phewas]}}trait_group",lower_buffer:.025,upper_buffer:.025},y_axis:{axis:1,field:"{{namespace[phewas]}}log_pvalue",floor:0,upper_buffer:.15},color:[{field:"{{namespace[phewas]}}trait_group",scale_function:"categorical_bin",parameters:{categories:[],values:[],null_value:"#B8B8B8"}}],fill_opacity:.7,tooltip:{closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:["Trait: {{{{namespace[phewas]}}trait_label|htmlescape}}
","Trait Category: {{{{namespace[phewas]}}trait_group|htmlescape}}
","P-value: {{{{namespace[phewas]}}log_pvalue|logtoscinotation|htmlescape}}
"].join("")},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},label:{text:"{{{{namespace[phewas]}}trait_label|htmlescape}}",spacing:6,lines:{style:{"stroke-width":"2px",stroke:"#333333","stroke-dasharray":"2px 2px"}},filters:[{field:"{{namespace[phewas]}}log_pvalue",operator:">=",value:20}],style:{"font-size":"14px","font-weight":"bold",fill:"#333333"}}},A={namespace:{gene:"gene",constraint:"constraint"},id:"genes",type:"genes",fields:["{{namespace[gene]}}all","{{namespace[constraint]}}all"],id_field:"gene_id",behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:Object(m.b)(w)},R={namespace:{assoc:"assoc",catalog:"catalog"},id:"annotation_catalog",type:"annotation_track",id_field:"{{namespace[catalog]}}variant",x_axis:{field:"{{namespace[assoc]}}position"},color:"#0000CC",fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}chromosome","{{namespace[assoc]}}position","{{namespace[catalog]}}variant","{{namespace[catalog]}}rsid","{{namespace[catalog]}}trait","{{namespace[catalog]}}log_pvalue","{{namespace[catalog]}}pos"],filters:[["{{namespace[catalog]}}rsid","!=",null],["{{namespace[catalog]}}log_pvalue",">",7.301]],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:Object(m.b)(k),tooltip_positioning:"top"},N={type:"set_state",position:"right",color:"blue",button_html:"LD Population: ",show_selected:!0,button_title:"Select LD Population: ",state_field:"ld_pop",options:[{display_name:"ALL (default)",value:"ALL"},{display_name:"AFR",value:"AFR"},{display_name:"AMR",value:"AMR"},{display_name:"EAS",value:"EAS"},{display_name:"EUR",value:"EUR"},{display_name:"SAS",value:"SAS"}]},T={widgets:[{type:"remove_panel",position:"right",color:"red",group_position:"end"},{type:"move_panel_up",position:"right",group_position:"middle"},{type:"move_panel_down",position:"right",group_position:"start",style:{"margin-left":"0.75em"}}]},D={widgets:[{type:"title",title:"LocusZoom",subtitle:'v'.concat(v.a,""),position:"left"},{type:"download",position:"right"},{type:"download_png",position:"right"}]},C=((y=Object(m.b)(D)).widgets.push(Object(m.b)(N),{type:"shift_region",step:5e5,button_html:">>",position:"right",group_position:"end"},{type:"shift_region",step:5e4,button_html:">",position:"right",group_position:"middle"},{type:"zoom_region",step:.2,position:"right",group_position:"middle"},{type:"zoom_region",step:-.2,position:"right",group_position:"middle"},{type:"shift_region",step:-5e4,button_html:"<",position:"right",group_position:"middle"},{type:"shift_region",step:-5e5,button_html:"<<",position:"right",group_position:"start"}),y),I={id:"association",width:800,height:225,min_width:400,min_height:200,proportional_width:1,margin:{top:35,right:50,bottom:40,left:50},inner_border:"rgb(210, 210, 210)",toolbar:function(){var t=Object(m.b)(T);return t.widgets.push({type:"toggle_legend",position:"right"}),t}(),axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"},y1:{label:"-log10 p-value",label_offset:28},y2:{label:"Recombination Rate (cM/Mb)",label_offset:40}},legend:{orientation:"vertical",origin:{x:55,y:40},hidden:!0},interaction:{drag_background_to_pan:!0,drag_x_ticks_to_scale:!0,drag_y1_ticks_to_scale:!0,drag_y2_ticks_to_scale:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[Object(m.b)(S),Object(m.b)(z),Object(m.b)(E)]},L={id:"coaccessibility",width:800,height:225,min_width:400,min_height:100,proportional_width:1,margin:{top:35,right:50,bottom:40,left:50},inner_border:"rgb(210, 210, 210)",toolbar:Object(m.b)(T),axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"},y1:{label:"Score",label_offset:28,render:!1}},interaction:{drag_background_to_pan:!0,drag_x_ticks_to_scale:!0,drag_y1_ticks_to_scale:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[Object(m.b)(j)]},B=function(){var t=Object(m.b)(I);return(t=Object(m.c)({id:"associationcatalog",namespace:{assoc:"assoc",ld:"ld",catalog:"catalog"}},t)).toolbar.widgets.push({type:"display_options",position:"right",color:"blue",button_html:"Display options...",button_title:"Control how plot items are displayed",layer_name:"associationpvaluescatalog",default_config_display_name:"No catalog labels (default)",options:[{display_name:"Label catalog traits",display:{label:{text:"{{{{namespace[catalog]}}trait|htmlescape}}",spacing:6,lines:{style:{"stroke-width":"2px",stroke:"#333333","stroke-dasharray":"2px 2px"}},filters:[{field:"{{namespace[catalog]}}trait",operator:"!=",value:null},{field:"{{namespace[catalog]}}log_pvalue",operator:">",value:7.301},{field:"{{namespace[ld]}}state",operator:">",value:.4}],style:{"font-size":"10px","font-weight":"bold",fill:"#333333"}}}}]}),t.data_layers=[Object(m.b)(S),Object(m.b)(z),Object(m.b)(M)],t}(),U={id:"genes",width:800,height:225,min_width:400,min_height:112.5,proportional_width:1,margin:{top:20,right:50,bottom:20,left:50},axes:{},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},toolbar:function(){var t=Object(m.b)(T);return t.widgets.push({type:"resize_to_data",position:"right",button_html:"Show all genes"}),t}(),data_layers:[Object(m.b)(A)]},F={id:"phewas",width:800,height:300,min_width:800,min_height:300,proportional_width:1,margin:{top:20,right:50,bottom:120,left:50},inner_border:"rgb(210, 210, 210)",axes:{x:{ticks:{style:{"font-weight":"bold","font-size":"11px","text-anchor":"start"},transform:"rotate(50)",position:"left"}},y1:{label:"-log10 p-value",label_offset:28}},data_layers:[Object(m.b)(S),Object(m.b)(P)]},q={id:"annotationcatalog",width:800,height:45,min_height:45,proportional_width:1,margin:{top:25,right:50,bottom:0,left:50},inner_border:"rgb(210, 210, 210)",toolbar:Object(m.b)(T),interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[Object(m.b)(R)]},H={state:{},width:800,height:450,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:Object(m.b)(C),panels:[Object(m.c)({proportional_height:.5},Object(m.b)(I)),Object(m.c)({proportional_height:.5},Object(m.b)(U))]},G={state:{},width:800,height:500,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:Object(m.b)(C),panels:[Object(m.b)(q),Object(m.b)(B),Object(m.b)(U)]},Z={width:800,height:600,min_width:800,min_height:600,responsive_resize:!0,toolbar:Object(m.b)(D),panels:[Object(m.c)({proportional_height:.5},Object(m.b)(F)),Object(m.c)({proportional_height:.5,margin:{bottom:40},axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"}}},Object(m.b)(U))],mouse_guide:!1},K={state:{},width:800,height:450,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:Object(m.b)(D),panels:[Object.assign({proportional_height:.4},Object(m.b)(L)),function(){var t=Object.assign({proportional_height:.6},Object(m.b)(U)),e=t.data_layers[0];e.match={send:"gene_name",receive:"gene_name"};var n=[{field:"lz_highlight_match",scale_function:"if",parameters:{field_value:!0,then:"#ff0000"}},{field:"lz_highlight_match",scale_function:"if",parameters:{field_value:!1,then:"#EAE6E6"}},"#363696"];return e.color=n,e.stroke=n,t}()]},J={standard_association:b,standard_association_with_label:x,standard_genes:w,catalog_variant:k,coaccessibility:O},$={ldlz2_pop_selector:N},V={standard_panel:T,standard_plot:D,region_nav_plot:C},W={significance:S,recomb_rate:z,association_pvalues:E,coaccessibility:j,association_pvalues_catalog:M,phewas_pvalues:P,genes:A,annotation_catalog:R},Y={association:I,coaccessibility:L,association_catalog:B,genes:U,phewas:F,annotation_catalog:q},X={standard_association:H,association_catalog:G,standard_phewas:Z,coaccessibility:K};function Q(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],a=!0,r=!1,i=void 0;try{for(var o,s=t[Symbol.iterator]();!(a=(o=s.next()).done)&&(n.push(o.value),!e||n.length!==e);a=!0);}catch(t){r=!0,i=t}finally{try{a||null==s.return||s.return()}finally{if(r)throw i}}return n}(t,e)||tt(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function tt(t,e){if(t){if("string"==typeof t)return et(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?et(t,e):void 0}}function et(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,a=new Array(e);n2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("Must specify both the type and name for the layout desired. See .list() for available options");var a=it(ct(o.prototype),"get",this).call(this,t).get(e);if((a=Object(m.c)(n,a)).unnamespaced)return delete a.unnamespaced,Object(m.b)(a);var r="";"string"==typeof a.namespace?r=a.namespace:"object"==nt(a.namespace)&&Object.keys(a.namespace).length&&(r=void 0!==a.namespace.default?a.namespace.default:a.namespace[Object.keys(a.namespace)[0]].toString()),r+=r.length?":":"";var i=Object(m.a)(a,a.namespace,r);return Object(m.b)(i)}},{key:"add",value:function(t,e,n){var a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!(t&&e&&n))throw new Error("To add a layout, type, name, and item must all be specified");if("object"!==nt(n))throw new Error("The configuration to be added must be an object");this.has(t)||it(ct(o.prototype),"add",this).call(this,t,new r.b);var i=Object(m.b)(n);return it(ct(o.prototype),"get",this).call(this,t).add(e,i,a)}},{key:"list",value:function(t){if(!t){var e,n={},a=function(t,e){var n;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(n=tt(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var a=0,r=function(){};return{s:r,n:function(){return a>=t.length?{done:!0}:{done:!1,value:t[a++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return o=t.done,t},e:function(t){s=!0,i=t},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}(this._items);try{for(a.s();!(e=a.n()).done;){var r=Q(e.value,2),i=r[0],s=r[1];n[i]=s.list()}}catch(t){a.e(t)}finally{a.f()}return n}return it(ct(o.prototype),"get",this).call(this,t).list()}},{key:"merge",value:function(t,e){return Object(m.c)(t,e)}}])&&rt(e.prototype,n),a&&rt(e,a),o}(r.b)),ht=0,dt=Object.entries(a);ht1&&(2!==e.length||!e.includes("isrefvar")))throw new Error("LD does not know how to get all fields: ".concat(e.join(", ")))}},{key:"findMergeFields",value:function(t){var e,n={id:this.params.id_field,position:this.params.position_field,pvalue:this.params.pvalue_field,_names_:null};if(t&&t.body&&t.body.length>0){var r=Object.keys(t.body[0]),i=(e=r,function(){for(var t=arguments,n=function(n){var a=t[n],r=e.filter((function(t){return t.match(a)}));if(r.length)return{v:r[0]}},r=0;re}:function(t,e){return te.log_pvalue))for(var s=0;sy-(m+b)?"top":"bottom"):"horizontal"===x&&(b=0,x=g<=h.width/2?"left":"right"),"top"===x||"bottom"===x){var w=Math.max(f.width/2-g,0),k=Math.max(f.width/2+g-_,0);s=p.x+g-f.width/2-k+w,u=p.x+g-s-7,"top"===x?(o=p.y+m-(b+f.height+8),l="down",c=f.height-1):(o=p.y+m+b+8,l="up",c=-8)}else{if("left"!==x&&"right"!==x)throw new Error("Unrecognized placement value");"left"===x?(s=p.x+g+v+8,l="left",u=-8):(s=p.x+g-f.width-v-8,l="right",u=f.width-1),m-f.height/2<=0?(o=p.y+m-10.5-6,c=6):m+f.height/2>=y?(o=p.y+m+7+6-f.height,c=f.height-14-6):(o=p.y+m-f.height/2,c=f.height/2-7)}return t.selector.style("left","".concat(s,"px")).style("top","".concat(o,"px")),t.arrow||(t.arrow=t.selector.append("div").style("position","absolute")),t.arrow.attr("class","lz-data_layer-tooltip-arrow_".concat(l)).style("left","".concat(u,"px")).style("top","".concat(c,"px")),this}},{key:"filter",value:function(t,e){if(void 0!==e&&["indexes","elements"].includes(e)||(e="indexes"),!Array.isArray(t))return[];var n=[];return this.data.forEach((function(a,r){var i=!0;t.forEach((function(t){(function(t,e){var n={"=":function(t,e){return t===e},"!=":function(t,e){return t!=e},"<":function(t,e){return t":function(t,e){return t>e},">=":function(t,e){return t>=e},"%":function(t,e){return t%e}};return!!Array.isArray(e)&&(2===e.length?t[e[0]]===e[1]:!(3!==e.length||!n[e[1]])&&n[e[1]](t[e[0]],e[2]))})(a,t)||(i=!1)})),i&&n.push("indexes"===e?r:a)})),n}},{key:"getElementAnnotation",value:function(t,e){var n=this.getElementId(t),a=this.layer_state.extra_fields[n];return a&&a[e]}},{key:"_setDefaultState",value:function(){var t={status_flags:{},extra_fields:{}},e=t.status_flags;o.a.adjectives.forEach((function(t){e[t]=e[t]||[]})),e.has_tooltip=e.has_tooltip||[],this.parent&&(this.state_id="".concat(this.parent.id,".").concat(this.id),this.state=this.parent.state,this.state[this.state_id]=t),this.layer_state=t}},{key:"getBaseId",value:function(){return this.parent?"".concat(this.parent_plot.id,".").concat(this.parent.id,".").concat(this.id):""}},{key:"getAbsoluteDataHeight",value:function(){return this.svg.group.node().getBoundingClientRect().height}},{key:"initialize",value:function(){var t=this.getBaseId();return this.svg.container=this.parent.svg.group.append("g").attr("class","lz-data_layer-container").attr("id","".concat(t,".data_layer_container")),this.svg.clipRect=this.svg.container.append("clipPath").attr("id","".concat(t,".clip")).append("rect"),this.svg.group=this.svg.container.append("g").attr("id","".concat(t,".data_layer")).attr("clip-path","url(#".concat(t,".clip)")),this}},{key:"createTooltip",value:function(t){if("object"!=h(this.layout.tooltip))throw new Error("DataLayer [".concat(this.id,"] layout does not define a tooltip"));var e=this.getElementId(t);if(!this.tooltips[e])return this.tooltips[e]={data:t,arrow:null,selector:i.select(this.parent_plot.svg.node().parentNode).append("div").attr("class","lz-data_layer-tooltip").attr("id","".concat(e,"-tooltip"))},this.layer_state.status_flags.has_tooltip.push(e),this.updateTooltip(t),this;this.positionTooltip(e)}},{key:"updateTooltip",value:function(t,e){var n=this;return void 0===e&&(e=this.getElementId(t)),this.tooltips[e].selector.html(""),this.tooltips[e].arrow=null,this.layout.tooltip.html&&this.tooltips[e].selector.html(Object(l.a)(t,this.layout.tooltip.html)),this.layout.tooltip.closable&&this.tooltips[e].selector.insert("button",":first-child").attr("class","lz-tooltip-close-button").attr("title","Close").text("×").on("click",(function(){n.destroyTooltip(e)})),this.tooltips[e].selector.data([t]),this.positionTooltip(e),this}},{key:"destroyTooltip",value:function(t,e){var n;if(n="string"==typeof t?t:this.getElementId(t),this.tooltips[n]&&("object"==h(this.tooltips[n].selector)&&this.tooltips[n].selector.remove(),delete this.tooltips[n]),!e){var a=this.layer_state.status_flags.has_tooltip,r=a.indexOf(n);a.splice(r,1)}return this}},{key:"destroyAllTooltips",value:function(){for(var t in this.tooltips)this.destroyTooltip(t,!0);return this}},{key:"positionTooltip",value:function(t){if("string"!=typeof t)throw new Error("Unable to position tooltip: id is not a string");if(!this.tooltips[t])throw new Error("Unable to position tooltip: id does not point to a valid tooltip");var e=this.tooltips[t],n=this._getTooltipPosition(e);if(!n)return null;this._drawTooltip(e,this.layout.tooltip_positioning,n.x_min,n.x_max,n.y_min,n.y_max)}},{key:"positionAllTooltips",value:function(){for(var t in this.tooltips)this.positionTooltip(t);return this}},{key:"showOrHideTooltip",value:function(t,e){if("object"!=h(this.layout.tooltip))return this;var n=this.getElementId(t),a=function t(e,n,a){var r=null;if("object"!=h(e)||null===e)return null;if(Array.isArray(n))a=a||"and",r=1===n.length?e[n[0]]:n.reduce((function(t,n){return"and"===a?e[t]&&e[n]:"or"===a?e[t]||e[n]:null}));else{if("object"!=h(n))return!1;var i;for(var o in n)i=t(e,n[o],o),null===r?r=i:"and"===a?r=r&&i:"or"===a&&(r=r||i)}return r},r={};"string"==typeof this.layout.tooltip.show?r={and:[this.layout.tooltip.show]}:"object"==h(this.layout.tooltip.show)&&(r=this.layout.tooltip.show);var i={};"string"==typeof this.layout.tooltip.hide?i={and:[this.layout.tooltip.hide]}:"object"==h(this.layout.tooltip.hide)&&(i=this.layout.tooltip.hide);var s=this.layer_state,l={};o.a.adjectives.forEach((function(t){var e="un".concat(t);l[t]=s.status_flags[t].includes(n),l[e]=!l[t]}));var c=a(l,r),u=a(l,i),d=s.status_flags.has_tooltip.includes(n);return!c||!e&&!d||u?this.destroyTooltip(t):this.createTooltip(t),this}},{key:"filterIndexes",value:function(t){return this.filter(t,"indexes")}},{key:"filterElements",value:function(t){return this.filter(t,"elements")}},{key:"setElementStatus",value:function(t,e,n,a){if("has_tooltip"===t)return this;var r;void 0===n&&(n=!0);try{r=this.getElementId(e)}catch(t){return this}a&&this.setAllElementStatus(t,!n),i.select("#".concat(r)).classed("lz-data_layer-".concat(this.layout.type,"-").concat(t),n);var o=this.getElementStatusNodeId(e);null!==o&&i.select("#".concat(o)).classed("lz-data_layer-".concat(this.layout.type,"-statusnode-").concat(t),n);var s=this.layer_state.status_flags[t].indexOf(r),l=-1===s;n&&l&&this.layer_state.status_flags[t].push(r),n||l||this.layer_state.status_flags[t].splice(s,1),this.showOrHideTooltip(e,l),l&&this.parent.emit("layout_changed",!0);var c="selected"===t;!c||!l&&n||this.parent.emit("element_selection",{element:e,active:n},!0);var u=this.layout.match&&this.layout.match.send;return c&&u&&(l||!n)&&this.parent.emit("match_requested",{value:e[u],active:n},!0),this}},{key:"setElementStatusByFilters",value:function(t,e,n,a){var r=this;if(void 0===t||!o.a.adjectives.includes(t))throw new Error("Invalid status");return void 0===this.layer_state.status_flags[t]||(e=void 0===e||!!e,a=void 0!==a&&!!a,Array.isArray(n)||(n=[]),a&&this.setAllElementStatus(t,!e),this.filterElements(n).forEach((function(n){r.setElementStatus(t,n,e)}))),this}},{key:"setAllElementStatus",value:function(t,e){var n=this;if(void 0===t||!o.a.adjectives.includes(t))throw new Error("Invalid status");return void 0===this.layer_state.status_flags[t]||(void 0===e&&(e=!0),e?this.data.forEach((function(e){return n.setElementStatus(t,e,!0)})):(this.layer_state.status_flags[t].slice().forEach((function(e){var a=n.getElementById(e);"object"==h(a)&&null!==a&&n.setElementStatus(t,a,!1)})),this.layer_state.status_flags[t]=[]),this.global_statuses[t]=e),this}},{key:"applyBehaviors",value:function(t){var e=this;"object"==h(this.layout.behaviors)&&Object.keys(this.layout.behaviors).forEach((function(n){var a=/(click|mouseover|mouseout)/.exec(n);a&&t.on("".concat(a[0],".").concat(n),e.executeBehaviors(n,e.layout.behaviors[n]))}))}},{key:"executeBehaviors",value:function(t,e){var n=t.includes("ctrl"),a=t.includes("shift"),r=this;return function(t){n===!!i.event.ctrlKey&&a===!!i.event.shiftKey&&e.forEach((function(e){if("object"==h(e)&&null!==e){var n=r.layer_state.status_flags[e.status].includes(r.getElementId(t)),a=e.exclusive&&!n;switch(e.action){case"set":r.setElementStatus(e.status,t,!0,e.exclusive);break;case"unset":r.setElementStatus(e.status,t,!1,e.exclusive);break;case"toggle":r.setElementStatus(e.status,t,!n,a);break;case"link":if("string"==typeof e.href){var i=Object(l.a)(t,e.href);"string"==typeof e.target?window.open(i,e.target):window.location.href=i}}}}))}}},{key:"_getPageOrigin",value:function(){var t=this.parent._getPageOrigin();return{x:t.x+this.parent.layout.margin.left,y:t.y+this.parent.layout.margin.top}}},{key:"applyAllElementStatus",value:function(){var t=this,e=this.layer_state.status_flags,n=this,a=function(a){if(!Object.prototype.hasOwnProperty.call(e,a))return"continue";Array.isArray(e[a])&&e[a].forEach((function(e){try{t.setElementStatus(a,t.getElementById(e),!0)}catch(t){console.warn("Unable to apply state: ".concat(n.state_id,", ").concat(a)),console.error(t)}}))};for(var r in e)a(r)}},{key:"draw",value:function(){return this.svg.container.attr("transform","translate(".concat(this.parent.layout.cliparea.origin.x,", ").concat(this.parent.layout.cliparea.origin.y,")")),this.svg.clipRect.attr("width",this.parent.layout.cliparea.width).attr("height",this.parent.layout.cliparea.height),this.positionAllTooltips(),this}},{key:"reMap",value:function(){var t=this;this.destroyAllTooltips();var e=this.parent_plot.lzd.getData(this.state,this.layout.fields);return e.then((function(e){t.data=e.body,t.applyDataMethods(),t.initialized=!0})),e}}])&&d(e.prototype,n),a&&d(e,a),t}();function y(t){return(y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function _(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function g(t,e){for(var n=0;n=1){var o=e[a-1],s=t.parent.x_scale(o[t.layout.x_axis.field]);i=Math.max(i,(r+s)/2)}return[i,r]};i.enter().append("rect").attr("class","lz-data_layer-".concat(this.layout.type)).attr("id",(function(e){return t.getElementId(e)})).merge(i).attr("height",this.parent.layout.height).attr("opacity",0).attr("x",(function(t,e){return o(t,e)[0]})).attr("width",(function(e,n){var a=o(e,n);return a[1]-a[0]+t.layout.hitarea_width/2})).call(this.applyBehaviors.bind(this)),i.exit().remove()}},{key:"_getTooltipPosition",value:function(t){var e=this.parent,n=e.layout.height-(e.layout.margin.top+e.layout.margin.bottom),a=e.x_scale(t.data[this.layout.x_axis.field]),r=n/2;return{x_min:a-1,x_max:a+1,y_min:r-e.layout.margin.top,y_max:r+e.layout.margin.bottom}}}])&&g(e.prototype,n),a&&g(e,a),i}(f),O=n(2);function S(t){return(S="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function z(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function E(t,e){for(var n=0;nt.state.end)e.display_range.start=e.display_range.end-e.display_range.label_width-t.layout.label_font_size,e.display_range.text_anchor="end";else{var a=(e.display_range.label_width-e.display_range.width)/2+t.layout.label_font_size;e.display_range.start-at.parent.x_scale(t.state.end)?(e.display_range.end=t.parent.x_scale(t.state.end),e.display_range.start=e.display_range.end-e.display_range.label_width,e.display_range.text_anchor="end"):(e.display_range.start-=a,e.display_range.end+=a)}e.display_range.width=e.display_range.end-e.display_range.start}e.display_range.start-=t.layout.bounding_box_padding,e.display_range.end+=t.layout.bounding_box_padding,e.display_range.width+=2*t.layout.bounding_box_padding,e.display_domain={start:t.parent.x_scale.invert(e.display_range.start),end:t.parent.x_scale.invert(e.display_range.end)},e.display_domain.width=e.display_domain.end-e.display_domain.start,e.track=null;for(var r=1,i=function(){var n=!1;t.gene_track_index[r].map((function(t){if(!n){var a=Math.min(t.display_range.start,e.display_range.start);Math.max(t.display_range.end,e.display_range.end)-at.tracks&&(t.tracks=r,t.gene_track_index[r]=[]):(e.track=r,t.gene_track_index[r].push(e))};null===e.track;)i();e.parent=t,e.transcripts.map((function(t,n){e.transcripts[n].parent=e,e.transcripts[n].exons.map((function(t,a){return e.transcripts[n].exons[a].parent=e.transcripts[n]}))}))})),this}},{key:"render",value:function(){var t,e,n,a,r=this,o=this;this.assignTracks();var s=this.svg.group.selectAll("g.lz-data_layer-genes").data(this.data,(function(t){return t.gene_name}));s.enter().append("g").attr("class","lz-data_layer-genes").merge(s).attr("id",(function(t){return r.getElementId(t)})).each((function(r){var s=r.parent,l=i.select(this).selectAll("rect.lz-data_layer-genes.lz-data_layer-genes-statusnode").data([r],(function(t){return s.getElementStatusNodeId(t)}));t=function(t){return t.display_range.width},e=s.getTrackHeight()-s.layout.track_vertical_spacing,n=function(t){return t.display_range.start},a=function(t){return(t.track-1)*s.getTrackHeight()},l.enter().append("rect").attr("class","lz-data_layer-genes lz-data_layer-genes-statusnode").merge(l).attr("id",(function(t){return s.getElementStatusNodeId(t)})).attr("rx",s.layout.bounding_box_padding).attr("ry",s.layout.bounding_box_padding).attr("width",t).attr("height",e).attr("x",n).attr("y",a),l.exit().remove();var c=i.select(this).selectAll("rect.lz-data_layer-genes.lz-boundary").data([r],(function(t){return"".concat(t.gene_name,"_boundary")})).style("fill",(function(t,e){return o.resolveScalableParameter(o.layout.color,t,e)})).style("stroke",(function(t,e){return o.resolveScalableParameter(o.layout.stroke,t,e)}));t=function(t){return s.parent.x_scale(t.end)-s.parent.x_scale(t.start)},e=1,n=function(t){return s.parent.x_scale(t.start)},a=function(t){return(t.track-1)*s.getTrackHeight()+s.layout.bounding_box_padding+s.layout.label_font_size+s.layout.label_exon_spacing+Math.max(s.layout.exon_height,3)/2},c.enter().append("rect").attr("class","lz-data_layer-genes lz-boundary").merge(c).attr("width",t).attr("height",e).attr("x",n).attr("y",a),c.exit().remove();var u=i.select(this).selectAll("text.lz-data_layer-genes.lz-label").data([r],(function(t){return"".concat(t.gene_name,"_label")}));n=function(t){return"middle"===t.display_range.text_anchor?t.display_range.start+t.display_range.width/2:"start"===t.display_range.text_anchor?t.display_range.start+s.layout.bounding_box_padding:"end"===t.display_range.text_anchor?t.display_range.end-s.layout.bounding_box_padding:void 0},a=function(t){return(t.track-1)*s.getTrackHeight()+s.layout.bounding_box_padding+s.layout.label_font_size},u.enter().append("text").attr("class","lz-data_layer-genes lz-label").merge(u).attr("text-anchor",(function(t){return t.display_range.text_anchor})).text((function(t){return"+"===t.strand?"".concat(t.gene_name,"→"):"←".concat(t.gene_name)})).style("font-size",r.parent.layout.label_font_size).attr("x",n).attr("y",a),u.exit().remove();var h=i.select(this).selectAll("rect.lz-data_layer-genes.lz-exon").data(r.transcripts[r.parent.transcript_idx].exons,(function(t){return t.exon_id}));t=function(t){return s.parent.x_scale(t.end)-s.parent.x_scale(t.start)},e=s.layout.exon_height,n=function(t){return s.parent.x_scale(t.start)},a=function(){return(r.track-1)*s.getTrackHeight()+s.layout.bounding_box_padding+s.layout.label_font_size+s.layout.label_exon_spacing},h.enter().append("rect").attr("class","lz-data_layer-genes lz-exon").merge(h).style("fill",(function(t,e){return o.resolveScalableParameter(o.layout.color,t.parent.parent,e)})).style("stroke",(function(t,e){return o.resolveScalableParameter(o.layout.stroke,t.parent.parent,e)})).attr("width",t).attr("height",e).attr("x",n).attr("y",a),h.exit().remove();var d=i.select(this).selectAll("rect.lz-data_layer-genes.lz-clickarea").data([r],(function(t){return"".concat(t.gene_name,"_clickarea")}));t=function(t){return t.display_range.width},e=s.getTrackHeight()-s.layout.track_vertical_spacing,n=function(t){return t.display_range.start},a=function(t){return(t.track-1)*s.getTrackHeight()},d.enter().append("rect").attr("class","lz-data_layer-genes lz-clickarea").merge(d).attr("id",(function(t){return"".concat(s.getElementId(t),"_clickarea")})).attr("rx",s.layout.bounding_box_padding).attr("ry",s.layout.bounding_box_padding).attr("width",t).attr("height",e).attr("x",n).attr("y",a).on("click.event_emitter",(function(t){return t.parent.parent.emit("element_clicked",t,!0)})).call(s.applyBehaviors.bind(s)),d.exit().remove()})),s.exit().remove()}},{key:"_getTooltipPosition",value:function(t){var e=this.getElementStatusNodeId(t.data),n=i.select("#".concat(e)).node().getBBox();return{x_min:this.parent.x_scale(t.data.start),x_max:this.parent.x_scale(t.data.end),y_min:n.y,y_max:n.y+n.height}}}])&&V(e.prototype,n),a&&V(e,a),o}(f);function nt(t){return(nt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function at(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function rt(t,e){for(var n=0;no){var c=a?i.select(t.label_lines.nodes()[r]):null;s(l,c)}})),t.label_texts.each((function(e,o){var l=i.select(this);if("end"!==l.style("text-anchor")){l.attr("x");var c=l.node().getBoundingClientRect(),u=a?i.select(t.label_lines.nodes()[o]):null;t.label_texts.each((function(){var t=i.select(this).node().getBoundingClientRect();c.leftt.left&&c.topt.top&&(s(l,u),+l.attr("x")-c.width-nc.left&&l.topc.top){a=!0;var u,h=s.attr("y"),d=.5*(l.top_?(u=p-+o,p=+o,f-=u):f+c.height/2>_&&(u=f-+h,f=+h,p-=u),r.attr("y",p),s.attr("y",f)}}}}))})),a){if(e.layout.label.lines){var r=e.label_texts.nodes();e.label_lines.attr("y2",(function(t,e){return i.select(r[e]).attr("y")}))}this.seperate_iterations<150&&setTimeout((function(){t.separate_labels()}),1)}}}},{key:"render",value:function(){var t=this,e=this,n="y".concat(this.layout.y_axis.axis,"_scale");if(this.layout.label){var a,r=e.layout.label.filters||[];a=r.length?this.data.filter((function(e){var n=!0;return r.forEach((function(a){var r=t.layer_state.extra_fields[t.getElementId(e)],i=new s.a(a.field).resolve(e,r);if(!["!=","="].includes(a.operator)&&isNaN(i))n=!1;else switch(a.operator){case"<":i":i>a.value||(n=!1);break;case">=":i>=a.value||(n=!1);break;case"=":i!==a.value&&(n=!1);break;case"!=":i==a.value&&(n=!1);break;default:n=!1}})),n})):this.data,this.label_groups=this.svg.group.selectAll("g.lz-data_layer-".concat(this.layout.type,"-label")).data(a,(function(e){return"".concat(e[t.layout.id_field],"_label")}));var o=this.label_groups.enter().append("g").attr("class","lz-data_layer-".concat(this.layout.type,"-label"));this.label_texts&&this.label_texts.remove(),this.label_texts=this.label_groups.merge(o).append("text").attr("class","lz-data_layer-".concat(this.layout.type,"-label")).text((function(t){return Object(l.a)(t,e.layout.label.text||"")})).attr("x",(function(t){var n=e.parent.x_scale(t[e.layout.x_axis.field])+Math.sqrt(e.resolveScalableParameter(e.layout.point_size,t))+e.layout.label.spacing;return isNaN(n)&&(n=-1e3),n})).attr("y",(function(t){var a=e.parent[n](t[e.layout.y_axis.field]);return isNaN(a)&&(a=-1e3),a})).attr("text-anchor","start").call(O.a,e.layout.label.style||{}),e.layout.label.lines&&(this.label_lines&&this.label_lines.remove(),this.label_lines=this.label_groups.merge(o).append("line").attr("class","lz-data_layer-".concat(this.layout.type,"-label")).attr("x1",(function(t){var n=e.parent.x_scale(t[e.layout.x_axis.field]);return isNaN(n)&&(n=-1e3),n})).attr("y1",(function(t){var a=e.parent[n](t[e.layout.y_axis.field]);return isNaN(a)&&(a=-1e3),a})).attr("x2",(function(t){var n=e.parent.x_scale(t[e.layout.x_axis.field])+Math.sqrt(e.resolveScalableParameter(e.layout.point_size,t))+e.layout.label.spacing/2;return isNaN(n)&&(n=-1e3),n})).attr("y2",(function(t){var a=e.parent[n](t[e.layout.y_axis.field]);return isNaN(a)&&(a=-1e3),a})).call(O.a,e.layout.label.lines.style||{})),this.label_groups.exit().remove()}else this.label_groups&&this.label_groups.remove(),this.label_lines&&this.label_lines.remove();var u=this.svg.group.selectAll("path.lz-data_layer-".concat(this.layout.type)).data(this.data,(function(e){return e[t.layout.id_field]})),h=isNaN(this.parent.layout.height)?0:this.parent.layout.height,d=i.symbol().size((function(e,n){return t.resolveScalableParameter(t.layout.point_size,e,n)})).type((function(e,n){return Object(c.d)(t.resolveScalableParameter(t.layout.point_shape,e,n))}));u.enter().append("path").attr("class","lz-data_layer-".concat(this.layout.type)).attr("id",(function(e){return t.getElementId(e)})).attr("transform","translate(0, ".concat(h,")")).merge(u).attr("transform",(function(e){var a=t.parent.x_scale(e[t.layout.x_axis.field]),r=t.parent[n](e[t.layout.y_axis.field]);return isNaN(a)&&(a=-1e3),isNaN(r)&&(r=-1e3),"translate(".concat(a,", ").concat(r,")")})).attr("fill",(function(e,n){return t.resolveScalableParameter(t.layout.color,e,n)})).attr("fill-opacity",(function(e,n){return t.resolveScalableParameter(t.layout.fill_opacity,e,n)})).attr("d",d).on("click.event_emitter",(function(e){return t.parent.emit("element_clicked",e,!0)})).call(this.applyBehaviors.bind(this)),u.exit().remove(),this.layout.label&&(this.flip_labels(),this.seperate_iterations=0,this.separate_labels(),this.label_texts.on("click.event_emitter",(function(e){return t.parent.emit("element_clicked",e,!0)})).call(this.applyBehaviors.bind(this)))}},{key:"makeLDReference",value:function(t){var e=null;if(void 0===t)throw new Error("makeLDReference requires one argument of any type");e="object"==yt(t)?this.layout.id_field&&void 0!==t[this.layout.id_field]?t[this.layout.id_field].toString():void 0!==t.id?t.id.toString():t.toString():t.toString(),this.parent_plot.applyState({ldrefvar:e})}}]),n}(f),zt=function(t){vt(n,t);var e=xt(n);function n(t){var a;return _t(this,n),(a=e.apply(this,arguments))._categories={},a}return mt(n,[{key:"_prepareData",value:function(){var t=this.layout.x_axis.field||"x",e=this.layout.x_axis.category_field;if(!e)throw new Error("Layout for ".concat(this.layout.id," must specify category_field"));var n=this.data.sort((function(t,n){var a=t[e],r=n[e],i="string"==typeof a?a.toLowerCase():a,o="string"==typeof r?r.toLowerCase():r;return i===o?0:it.length)&&(e=t.length);for(var n=0,a=new Array(e);n1?Math.ceil(Math.log(n)/Math.LN10):Math.floor(Math.log(n)/Math.LN10),Math.abs(e)<=3?t.toFixed(3):t.toExponential(2).replace("+","").replace("e"," × 10^")}function s(t){return t?(t="".concat(t)).replace(/['"<>&`]/g,(function(t){switch(t){case"'":return"'";case'"':return""";case"<":return"<";case">":return">";case"&":return"&";case"`":return"`"}})):""}function l(t){return encodeURIComponent(t)}function c(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],a=!0,r=!1,i=void 0;try{for(var o,s=t[Symbol.iterator]();!(a=(o=s.next()).done)&&(n.push(o.value),!e||n.length!==e);a=!0);}catch(t){r=!0,i=t}finally{try{a||null==s.return||s.return()}finally{if(r)throw i}}return n}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return u(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return u(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,a=new Array(e);nt.length)&&(e=t.length);for(var n=0,a=new Array(e);n")),this.title_selector.html(t),this}}]),n}(w),S=function(t){p(n,t);var e=y(n);function n(){return v(this,n),e.apply(this,arguments)}return x(n,[{key:"update",value:function(){var t=this.parent_plot.layout.width.toString().includes(".")?this.parent_plot.layout.width.toFixed(2):this.parent_plot.layout.width,e=this.parent_plot.layout.height.toString().includes(".")?this.parent_plot.layout.height.toFixed(2):this.parent_plot.layout.height;return this.selector.html("".concat(t,"px × ").concat(e,"px")),this.layout.class&&this.selector.attr("class",this.layout.class),this.layout.style&&Object(s.a)(this.selector,this.layout.style),this}}]),n}(w),z=function(t){p(n,t);var e=y(n);function n(){return v(this,n),e.apply(this,arguments)}return x(n,[{key:"update",value:function(){return isNaN(this.parent_plot.state.start)||isNaN(this.parent_plot.state.end)||null===this.parent_plot.state.start||null===this.parent_plot.state.end?this.selector.style("display","none"):(this.selector.style("display",null),this.selector.html(Object(o.c)(this.parent_plot.state.end-this.parent_plot.state.start,null,!0))),this.layout.class&&this.selector.attr("class",this.layout.class),this.layout.style&&Object(s.a)(this.selector,this.layout.style),this}}]),n}(w),E=function(t){p(n,t);var e=y(n);function n(t,a){var r;return v(this,n),(r=e.call(this,t,a))._filename=r.layout.filename||"locuszoom.svg",r._button_html=r.layout.button_html||"Save as SVG",r._button_title=r.layout.button_title||"Download hi-res image",r}return x(n,[{key:"update",value:function(){var t=this;return this.button||(this.button=new k(this).setColor(this.layout.color).setHtml(this._button_html).setTitle(this._button_title).setOnMouseover((function(){t.button.selector.classed("lz-toolbar-button-gray-disabled",!0).html("Preparing Image"),t._getBlobUrl().then((function(e){var n=t.button.selector.attr("href");n&&URL.revokeObjectURL(n),t.button.selector.attr("href",e).classed("lz-toolbar-button-gray-disabled",!1).classed("lz-toolbar-button-gray-highlighted",!0).html(t._button_html)}))})).setOnMouseout((function(){t.button.selector.classed("lz-toolbar-button-gray-highlighted",!1)})),this.button.show(),this.button.selector.attr("href-lang","image/svg+xml").attr("download",this._filename)),this}},{key:"_getCSS",value:function(t){for(var e=/^svg\.lz-locuszoom\s*/,n="",a=0;a0?">":"<"),"string"!=typeof t.button_title&&(t.button_title="Shift region by ".concat(t.step>0?"+":"-").concat(Object(o.c)(Math.abs(t.step),null,!0))),r=e.call(this,t,a),isNaN(r.parent_plot.state.start)||isNaN(r.parent_plot.state.end))throw new Error("Unable to add shift_region toolbar widget: plot state does not have region bounds");return r}return x(n,[{key:"update",value:function(){var t=this;return this.button||(this.button=new k(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title).setOnclick((function(){t.parent_plot.applyState({start:Math.max(t.parent_plot.state.start+t.layout.step,1),end:t.parent_plot.state.end+t.layout.step})})),this.button.show()),this}}]),n}(w),N=function(t){p(n,t);var e=y(n);function n(t,a){var r;if(v(this,n),(isNaN(t.step)||0===t.step)&&(t.step=.2),"string"!=typeof t.button_html&&(t.button_html=t.step>0?"z–":"z+"),"string"!=typeof t.button_title&&(t.button_title="Zoom region ".concat(t.step>0?"out":"in"," by ").concat((100*Math.abs(t.step)).toFixed(1),"%")),r=e.call(this,t,a),isNaN(r.parent_plot.state.start)||isNaN(r.parent_plot.state.end))throw new Error("Unable to add zoom_region toolbar widget: plot state does not have region bounds");return r}return x(n,[{key:"update",value:function(){var t=this;if(this.button){var e=!0,n=this.parent_plot.state.end-this.parent_plot.state.start;return this.layout.step>0&&!isNaN(this.parent_plot.layout.max_region_scale)&&n>=this.parent_plot.layout.max_region_scale&&(e=!1),this.layout.step<0&&!isNaN(this.parent_plot.layout.min_region_scale)&&n<=this.parent_plot.layout.min_region_scale&&(e=!1),this.button.disable(!e),this}return this.button=new k(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title).setOnclick((function(){var e=t.parent_plot.state.end-t.parent_plot.state.start,n=e*(1+t.layout.step);isNaN(t.parent_plot.layout.max_region_scale)||(n=Math.min(n,t.parent_plot.layout.max_region_scale)),isNaN(t.parent_plot.layout.min_region_scale)||(n=Math.max(n,t.parent_plot.layout.min_region_scale));var a=Math.floor((n-e)/2);t.parent_plot.applyState({start:Math.max(t.parent_plot.state.start-a,1),end:t.parent_plot.state.end+a})})),this.button.show(),this}}]),n}(w),T=function(t){p(n,t);var e=y(n);function n(){return v(this,n),e.apply(this,arguments)}return x(n,[{key:"update",value:function(){var t=this;return this.button||(this.button=new k(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title),this.button.menu.setPopulate((function(){t.button.menu.inner_selector.html(t.layout.menu_html)})),this.button.show()),this}}]),n}(w),D=function(t){p(n,t);var e=y(n);function n(){return v(this,n),e.apply(this,arguments)}return x(n,[{key:"update",value:function(){var t=this;return this.button||(this.button=new k(this).setColor(this.layout.color).setHtml(this.layout.button_html||"Resize to Data").setTitle(this.layout.button_title||"Automatically resize this panel to show all data available").setOnclick((function(){t.parent_panel.scaleHeightToData(),t.update()})),this.button.show()),this}}]),n}(w),C=function(t){p(n,t);var e=y(n);function n(){return v(this,n),e.apply(this,arguments)}return x(n,[{key:"update",value:function(){var t=this,e=this.parent_panel.legend.layout.hidden?"Show Legend":"Hide Legend";return this.button?(this.button.setHtml(e).show(),this.parent.position(),this):(this.button=new k(this).setColor(this.layout.color).setTitle("Show or hide the legend for this panel").setOnclick((function(){t.parent_panel.legend.layout.hidden=!t.parent_panel.legend.layout.hidden,t.parent_panel.legend.render(),t.update()})),this.update())}}]),n}(w),I=function(t){p(n,t);var e=y(n);function n(t,a){var r;v(this,n),"string"!=typeof t.button_html&&(t.button_html="Display options..."),"string"!=typeof t.button_title&&(t.button_title="Control how plot items are displayed"),r=e.apply(this,arguments);var i=t.fields_whitelist||["color","fill_opacity","filters","label","legend","point_shape","point_size","tooltip","tooltip_positioning"],o=r.parent_panel.data_layers[t.layer_name];if(!o)throw new Error("Display options could not locate the specified layer_name: '".concat(t.layer_name,"'"));var s=o.layout,c={};return i.forEach((function(t){var e=s[t];void 0!==e&&(c[t]=Object(l.b)(e))})),r._selected_item="default",r.button=new k(g(r)).setColor(t.color).setHtml(t.button_html).setTitle(t.button_title).setOnclick((function(){r.button.menu.populate()})),r.button.menu.setPopulate((function(){var t=Math.floor(1e4*Math.random()).toString();r.button.menu.inner_selector.html("");var e=r.button.menu.inner_selector.append("table"),n=r.layout,a=function(n,a,s){var l=e.append("tr"),u="".concat(t).concat(s);l.append("td").append("input").attr("id",u).attr("type","radio").attr("name","display-option-".concat(t)).attr("value",s).style("margin",0).property("checked",s===r._selected_item).on("click",(function(){i.forEach((function(t){o.layout[t]=a[t]||c[t]})),r._selected_item=s,r.parent_panel.render();var t=r.parent_panel.legend;t&&t.render()})),l.append("td").append("label").style("font-weight","normal").attr("for",u).text(n)},s=n.default_config_display_name||"Default style";return a(s,c,"default"),n.options.forEach((function(t,e){return a(t.display_name,t.display,e)})),g(r)})),r}return x(n,[{key:"update",value:function(){return this.button.show(),this}}]),n}(w),L=function(t){p(n,t);var e=y(n);function n(t,a){var r;if(v(this,n),"string"!=typeof t.button_html&&(t.button_html="Set option..."),"string"!=typeof t.button_title&&(t.button_title="Choose an option to customize the plot"),(r=e.call(this,t,a)).parent_panel)throw new Error("This widget is designed to set global options, so it can only be used at the top (plot) level");if(!t.state_field)throw new Error("Must specify the `state_field` that this widget controls");if(r._selected_item=r.parent_plot.state[t.state_field]||t.options[0].value,!t.options.find((function(t){return t.value===r._selected_item})))throw new Error("There is an existing state value that does not match the known values in this widget");return r.button=new k(g(r)).setColor(t.color).setHtml(t.button_html+(t.show_selected?r._selected_item:"")).setTitle(t.button_title).setOnclick((function(){r.button.menu.populate()})),r.button.menu.setPopulate((function(){var e=Math.floor(1e4*Math.random()).toString();r.button.menu.inner_selector.html("");var n=r.button.menu.inner_selector.append("table");return t.options.forEach((function(a,i){return o=a.display_name,s=a.value,l=i,c=n.append("tr"),u="".concat(e).concat(l),c.append("td").append("input").attr("id",u).attr("type","radio").attr("name","set-state-".concat(e)).attr("value",l).style("margin",0).property("checked",s===r._selected_item).on("click",(function(){var e={};e[t.state_field]=s,r._selected_item=s,r.parent_plot.applyState(e),r.button.setHtml(t.button_html+(t.show_selected?r._selected_item:""))})),void c.append("td").append("label").style("font-weight","normal").attr("for",u).text(o);var o,s,l,c,u})),g(r)})),r}return x(n,[{key:"update",value:function(){return this.button.show(),this}}]),n}(w);function B(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],a=!0,r=!1,i=void 0;try{for(var o,s=t[Symbol.iterator]();!(a=(o=s.next()).done)&&(n.push(o.value),!e||n.length!==e);a=!0);}catch(t){r=!0,i=t}finally{try{a||null==s.return||s.return()}finally{if(r)throw i}}return n}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return U(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return U(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,a=new Array(e);n=t&&+e=t.breaks[t.breaks.length-1])return a[n.length-1];var o=null;if(n.forEach((function(t,a){a&&n[a-1]<=+e&&n[a]>=+e&&(o=a)})),null===o)return r;var s=(+e-n[o-1])/(n[o]-n[o-1]);return isFinite(s)?i.interpolate(a[o-1],a[o])(s):r};function h(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],a=!0,r=!1,i=void 0;try{for(var o,s=t[Symbol.iterator]();!(a=(o=s.next()).done)&&(n.push(o.value),!e||n.length!==e);a=!0);}catch(t){r=!0,i=t}finally{try{a||null==s.return||s.return()}finally{if(r)throw i}}return n}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return d(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return d(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,a=new Array(e);nt.length)&&(e=t.length);for(var n=0,a=new Array(e);n2&&void 0!==arguments[2]&&arguments[2];if(this._registry.has(t))throw new Error("The namespace ".concat(t," is already in use by another source"));if(t.match(/[^A-Za-z0-9_]/))throw new Error("Data source namespace names can only contain alphanumeric characters or underscores");if(Array.isArray(e)){var a=e,r=o(a,2),i=r[0],l=r[1];e=this._registry.create(i,l)}return e.source_id=t,c(p(s.prototype),"add",this).call(this,t,e,n),this}}])&&l(e.prototype,n),a&&l(e,a),s}(a.b),y=n(8)},function(t,e){t.exports=raremetal},,,,,,,,function(t,e,n){"use strict";n.r(e);var a=n(16),r=n(15),i=n(1);function o(t){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function s(t,e,n){return(s="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var a=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=y(t)););return t}(t,e);if(a){var r=Object.getOwnPropertyDescriptor(a,e);return r.get?r.get.call(n):r.value}})(t,e,n||t)}function l(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function c(t,e){for(var n=0;ne?1:0}))}}]),n}(e),d=function(t){h(n,t);var e=p(n);function n(){return l(this,n),e.apply(this,arguments)}return u(n,[{key:"_getRequiredSources",value:function(){return["gene_ns","aggregation_ns"]}},{key:"combineChainBody",value:function(t,e){var n=this._source_name_mapping.aggregation_ns,a=this._source_name_mapping.gene_ns,r=e.discrete[n],i=e.discrete[a],o={};return r.groups.forEach((function(t){Object.prototype.hasOwnProperty.call(o,t.group)||(o[t.group]=[]),o[t.group].push(t.pvalue)})),i.forEach((function(t){var e=t.gene_name,n=o[e];n&&(t.aggregation_best_pvalue=Math.min.apply(null,n))})),i}}]),n}(n);t.Adapters.add("AggregationTestSourceLZ",o),t.Adapters.add("AssocFromAggregationLZ",c),t.Adapters.add("GeneAggregationConnectorLZ",d)}"undefined"!=typeof LocusZoom&&LocusZoom.use(_),e.default=_}]).default; +/*! Locuszoom 0.12.0-beta.3 */ +var LzAggregationTests=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=12)}({12:function(e,t,n){"use strict";n.r(t);var r=n(5),o=n(2);function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t,n){return(i="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var r=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=d(e)););return e}(e,t);if(r){var o=Object.getOwnPropertyDescriptor(r,t);return o.get?o.get.call(n):o.value}})(e,t,n||e)}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var n=0;nt?1:0}))}}]),n}(t),l=function(e){f(n,e);var t=h(n);function n(){return u(this,n),t.apply(this,arguments)}return c(n,[{key:"_getRequiredSources",value:function(){return["gene_ns","aggregation_ns"]}},{key:"combineChainBody",value:function(e,t){var n=this._source_name_mapping.aggregation_ns,r=this._source_name_mapping.gene_ns,o=t.discrete[n],a=t.discrete[r],i={};return o.groups.forEach((function(e){Object.prototype.hasOwnProperty.call(i,e.group)||(i[e.group]=[]),i[e.group].push(e.pvalue)})),a.forEach((function(e){var t=e.gene_name,n=i[t];n&&(e.aggregation_best_pvalue=Math.min.apply(null,n))})),a}}]),n}(n);e.Adapters.add("AggregationTestSourceLZ",a),e.Adapters.add("AssocFromAggregationLZ",s),e.Adapters.add("GeneAggregationConnectorLZ",l)}"undefined"!=typeof LocusZoom&&LocusZoom.use(y),t.default=y},2:function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t,n){return(o="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var r=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=c(e)););return e}(e,t);if(r){var o=Object.getOwnPropertyDescriptor(r,t);return o.get?o.get.call(n):o.value}})(e,t,n||e)}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&i(e,t)}function i(e,t){return(i=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function u(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=c(e);if(t){var o=c(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return s(this,n)}}function s(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function c(e){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function f(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){for(var n=0;n1&&(2!==t.length||!t.includes("isrefvar")))throw new Error("LD does not know how to get all fields: ".concat(t.join(", ")))}},{key:"findMergeFields",value:function(e){var t,n={id:this.params.id_field,position:this.params.position_field,pvalue:this.params.pvalue_field,_names_:null};if(e&&e.body&&e.body.length>0){var o=Object.keys(e.body[0]),a=(t=o,function(){for(var e=arguments,n=function(n){var r=e[n],o=t.filter((function(e){return e.match(r)}));if(o.length)return{v:o[0]}},o=0;ot}:function(e,t){return et.log_pvalue))for(var u=0;u d3.symbolCircle\n if (!shape) {\n return null;\n }\n const factory_name = `symbol${shape.charAt(0).toUpperCase() + shape.slice(1)}`;\n return d3[factory_name] || null;\n}\n\nexport { applyNamespaces, deepCopy, merge, nameToSymbol };\n","/**\n * @module\n * @private\n */\n// FIXME: A place for code that used to live under the `LocusZoom` namespace\n// Eventually this should be moved into classes or some other mechanism for code sharing. No external uses should\n// depend on any items in this module.\n\nimport * as d3 from 'd3';\n\n/**\n * Generate a curtain object for a plot, panel, or any other subdivision of a layout\n * The panel curtain, like the plot curtain is an HTML overlay that obscures the entire panel. It can be styled\n * arbitrarily and display arbitrary messages. It is useful for reporting error messages visually to an end user\n * when the error renders the panel unusable.\n * TODO: Improve type doc here\n * @returns {object}\n */\nfunction generateCurtain() {\n return {\n showing: false,\n selector: null,\n content_selector: null,\n hide_delay: null,\n\n /**\n * Generate the curtain. Any content (string) argument passed will be displayed in the curtain as raw HTML.\n * CSS (object) can be passed which will apply styles to the curtain and its content.\n * @param {string} content Content to be displayed on the curtain (as raw HTML)\n * @param {object} css Apply the specified styles to the curtain and its contents\n */\n show: (content, css) => {\n if (!this.curtain.showing) {\n this.curtain.selector = d3.select(this.parent_plot.svg.node().parentNode).insert('div')\n .attr('class', 'lz-curtain')\n .attr('id', `${this.id}.curtain`);\n this.curtain.content_selector = this.curtain.selector.append('div')\n .attr('class', 'lz-curtain-content');\n this.curtain.selector.append('div')\n .attr('class', 'lz-curtain-dismiss').html('Dismiss')\n .on('click', () => this.curtain.hide());\n this.curtain.showing = true;\n }\n return this.curtain.update(content, css);\n },\n\n /**\n * Update the content and css of the curtain that's currently being shown. This method also adjusts the size\n * and positioning of the curtain to ensure it still covers the entire panel with no overlap.\n * @param {string} content Content to be displayed on the curtain (as raw HTML)\n * @param {object} css Apply the specified styles to the curtain and its contents\n */\n update: (content, css) => {\n if (!this.curtain.showing) {\n return this.curtain;\n }\n clearTimeout(this.curtain.hide_delay);\n // Apply CSS if provided\n if (typeof css == 'object') {\n applyStyles(this.curtain.selector, css);\n }\n // Update size and position\n const page_origin = this._getPageOrigin();\n this.curtain.selector\n .style('top', `${page_origin.y}px`)\n .style('left', `${page_origin.x}px`)\n .style('width', `${this.layout.width}px`)\n .style('height', `${this.layout.height}px`);\n this.curtain.content_selector\n .style('max-width', `${this.layout.width - 40}px`)\n .style('max-height', `${this.layout.height - 40}px`);\n // Apply content if provided\n if (typeof content == 'string') {\n this.curtain.content_selector.html(content);\n }\n return this.curtain;\n },\n\n /**\n * Remove the curtain\n * @param {number} delay Time to wait (in ms)\n */\n hide: (delay) => {\n if (!this.curtain.showing) {\n return this.curtain;\n }\n // If a delay was passed then defer to a timeout\n if (typeof delay == 'number') {\n clearTimeout(this.curtain.hide_delay);\n this.curtain.hide_delay = setTimeout(this.curtain.hide, delay);\n return this.curtain;\n }\n // Remove curtain\n this.curtain.selector.remove();\n this.curtain.selector = null;\n this.curtain.content_selector = null;\n this.curtain.showing = false;\n return this.curtain;\n },\n };\n}\n\n/**\n * Generate a loader object for a plot, panel, or any other subdivision of a layout\n *\n * The panel loader is a small HTML overlay that appears in the lower left corner of the panel. It cannot be styled\n * arbitrarily, but can show a custom message and show a minimalist loading bar that can be updated to specific\n * completion percentages or be animated.\n * TODO Improve type documentation\n * @returns {object}\n */\nfunction generateLoader() {\n return {\n showing: false,\n selector: null,\n content_selector: null,\n progress_selector: null,\n cancel_selector: null,\n\n /**\n * Show a loading indicator\n * @param {string} [content='Loading...'] Loading message (displayed as raw HTML)\n */\n show: (content) => {\n // Generate loader\n if (!this.loader.showing) {\n this.loader.selector = d3.select(this.parent_plot.svg.node().parentNode).insert('div')\n .attr('class', 'lz-loader')\n .attr('id', `${this.id}.loader`);\n this.loader.content_selector = this.loader.selector.append('div')\n .attr('class', 'lz-loader-content');\n this.loader.progress_selector = this.loader.selector\n .append('div')\n .attr('class', 'lz-loader-progress-container')\n .append('div')\n .attr('class', 'lz-loader-progress');\n\n this.loader.showing = true;\n if (typeof content == 'undefined') {\n content = 'Loading...';\n }\n }\n return this.loader.update(content);\n },\n\n /**\n * Update the currently displayed loader and ensure the new content is positioned correctly.\n * @param {string} content The text to display (as raw HTML). If not a string, will be ignored.\n * @param {number} [percent] A number from 1-100. If a value is specified, it will stop all animations\n * in progress.\n */\n update: (content, percent) => {\n if (!this.loader.showing) {\n return this.loader;\n }\n clearTimeout(this.loader.hide_delay);\n // Apply content if provided\n if (typeof content == 'string') {\n this.loader.content_selector.html(content);\n }\n // Update size and position\n const padding = 6; // is there a better place to store/define this?\n const page_origin = this._getPageOrigin();\n const loader_boundrect = this.loader.selector.node().getBoundingClientRect();\n this.loader.selector\n .style('top', `${page_origin.y + this.layout.height - loader_boundrect.height - padding}px`)\n .style('left', `${page_origin.x + padding }px`);\n /* Uncomment this code when a functional cancel button can be shown\n var cancel_boundrect = this.loader.cancel_selector.node().getBoundingClientRect();\n this.loader.content_selector.style({\n \"padding-right\": (cancel_boundrect.width + padding) + \"px\"\n });\n */\n // Apply percent if provided\n if (typeof percent == 'number') {\n this.loader.progress_selector\n .style('width', `${Math.min(Math.max(percent, 1), 100)}%`);\n }\n return this.loader;\n },\n\n /**\n * Adds a class to the loading bar that makes it loop infinitely in a loading animation. Useful when exact\n * percent progress is not available.\n */\n animate: () => {\n this.loader.progress_selector.classed('lz-loader-progress-animated', true);\n return this.loader;\n },\n\n /**\n * Sets the loading bar in the loader to percentage width equal to the percent (number) value passed. Percents\n * will automatically be limited to a range of 1 to 100. Will stop all animations in progress.\n */\n setPercentCompleted: (percent) => {\n this.loader.progress_selector.classed('lz-loader-progress-animated', false);\n return this.loader.update(null, percent);\n },\n\n /**\n * Remove the loader\n * @param {number} delay Time to wait (in ms)\n */\n hide: (delay) => {\n if (!this.loader.showing) {\n return this.loader;\n }\n // If a delay was passed then defer to a timeout\n if (typeof delay == 'number') {\n clearTimeout(this.loader.hide_delay);\n this.loader.hide_delay = setTimeout(this.loader.hide, delay);\n return this.loader;\n }\n // Remove loader\n this.loader.selector.remove();\n this.loader.selector = null;\n this.loader.content_selector = null;\n this.loader.progress_selector = null;\n this.loader.cancel_selector = null;\n this.loader.showing = false;\n return this.loader;\n },\n };\n}\n\n/**\n * Modern d3 removed the ability to set many styles at once (object syntax). This is a helper so that layouts with\n * config-objects can set styles all at once\n * @private\n * @param {d3.selection} selection\n * @param {Object} styles\n */\nfunction applyStyles(selection, styles) {\n styles = styles || {};\n for (let [prop, value] of Object.entries(styles)) {\n selection.style(prop, value);\n }\n}\n\n\nexport { applyStyles, generateCurtain, generateLoader };\n","/** @module */\n\n/**\n * Base class for all registries\n *\n * LocusZoom is plugin-extensible, and layouts are string-based and JSON serializable. This is achieved through the use\n * of a central registry that holds a reference to each possible feature.\n *\n * Each registry has some syntactical sugar, with common elements are defined in a base class\n */\nclass RegistryBase {\n constructor() {\n this._items = new Map();\n }\n\n /**\n * Return the registry member. If the registry stores classes, this returns the class, not the instance.\n * @param {String} name\n * @returns {Function}\n */\n get(name) {\n if (!this._items.has(name)) {\n throw new Error(`Item not found: ${name}`);\n }\n return this._items.get(name);\n }\n\n /**\n * Add a new item to the registry\n * @param {String} name The name of the item to add to the registry\n * @param {*} item The item to be added (constructor, value, etc)\n * @param {boolean} override Allow redefining an existing item?\n * @return {*} The actual object as added to the registry\n */\n add(name, item, override = false) {\n if (!override && this._items.has(name)) {\n throw new Error(`Item ${name} is already defined`);\n }\n this._items.set(name, item);\n return item;\n }\n\n /**\n * Remove a datasource from the registry (if present)\n * @param {String} name\n * @returns {boolean} True if item removed, false if item was never present\n */\n remove(name) {\n return this._items.delete(name);\n }\n\n /**\n * Check whether the specified item is registered\n * @param {String} name\n * @returns {boolean}\n */\n has(name) {\n return this._items.has(name);\n }\n\n /**\n * Names of each allowed\n * @returns {String[]}\n */\n list() {\n return Array.from(this._items.keys());\n }\n}\n\n/**\n * A specialized registry whose members are class constructors. Contains helper methods for creating instances\n * and subclasses.\n */\nclass ClassRegistry extends RegistryBase {\n /**\n * Create an instance of the specified class from the registry\n * @param {String} name\n * @param {*} args Any additional arguments to be passed to the constructor\n * @returns {*}\n */\n create(name, ...args) {\n const base = this.get(name);\n return new base(...args);\n }\n}\n\n\nexport default RegistryBase;\nexport {RegistryBase, ClassRegistry};\n","/**\n * Available statuses that individual elements can have. Each status is described by\n * a verb and an adjective. Verbs are used to generate data layer\n * methods for updating the status on one or more elements. Adjectives are used in class\n * names and applied or removed from elements to have a visual representation of the status,\n * as well as used as keys in the state for tracking which elements are in which status(es)\n * @static\n * @type {{verbs: String[], adjectives: String[]}}\n * @private\n */\nexport const STATUSES = {\n verbs: ['highlight', 'select', 'fade', 'hide'],\n adjectives: ['highlighted', 'selected', 'faded', 'hidden'],\n};\n","/** @module */\nimport transforms from '../registry/transforms';\n\n/**\n * Represents an addressable unit of data from a namespaced datasource, subject to specified value transformations.\n *\n * When used by a data layer, fields will automatically be re-fetched from the appropriate data source whenever the\n * state of a plot fetches, eg pan or zoom operations that would affect what data is displayed.\n *\n * @private\n * @class\n * @param {String} field A string representing the namespace of the datasource, the name of the desired field to fetch\n * from that datasource, and arbitrarily many transformations to apply to the value. The namespace and\n * transformation(s) are optional and information is delimited according to the general syntax\n * `[namespace:]name[|transformation][|transformation]`. For example, `association:pvalue|neglog10`\n */\nclass Field {\n constructor(field) {\n const parts = /^(?:([^:]+):)?([^:|]*)(\\|.+)*$/.exec(field);\n /** @member {String} */\n this.full_name = field;\n /** @member {String} */\n this.namespace = parts[1] || null;\n /** @member {String} */\n this.name = parts[2] || null;\n /** @member {Array} */\n this.transformations = [];\n\n if (typeof parts[3] == 'string' && parts[3].length > 1) {\n this.transformations = parts[3].substring(1).split('|');\n this.transformations.forEach((transform, i) => this.transformations[i] = transforms.get(transform));\n }\n }\n\n _applyTransformations(val) {\n this.transformations.forEach(function(transform) {\n val = transform(val);\n });\n return val;\n }\n\n /**\n * Resolve the field for a given data element.\n * First look for a full match with transformations already applied by the data requester.\n * Otherwise prefer a namespace match and fall back to just a name match, applying transformations on the fly.\n * @param {Object} data Returned data/fields into for this element\n * @param {Object} [extra] User-applied annotations for this point (info not provided by the server that we want\n * to preserve across re-renders). Example usage: \"should_show_label\"\n * @returns {*}\n */\n resolve(data, extra) {\n if (typeof data[this.full_name] == 'undefined') { // Check for cached result\n let val = null;\n if (typeof (data[`${this.namespace}:${this.name}`]) != 'undefined') { // Fallback: value sans transforms\n val = data[`${this.namespace}:${this.name}`];\n } else if (typeof data[this.name] != 'undefined') { // Fallback: value present without namespace\n val = data[this.name];\n } else if (extra && typeof extra[this.full_name] != 'undefined') { // Fallback: check annotations\n val = extra[this.full_name];\n } // We should really warn if no value found, but many bad layouts exist and this could break compatibility\n data[this.full_name] = this._applyTransformations(val);\n }\n return data[this.full_name];\n }\n}\n\nexport {Field as default};\n","/**\n * @module\n * @private\n */\nimport { TRANSFORMS } from '../registry';\n\n/**\n * The Requester manages fetching of data across multiple data sources. It is used internally by LocusZoom data layers.\n * It passes state information and ensures that data is formatted in the manner expected by the plot.\n *\n * This object is not part of the public interface. It should almost **never** be replaced or modified directly.\n *\n * It is also responsible for constructing a \"chain\" of dependent requests, by requesting each datasource\n * sequentially in the order specified in the datalayer `fields` array. Data sources are only chained within a\n * data layer, and only if that layer requests more than one kind of data source.\n * @param {DataSources} sources A set of data sources used specifically by this plot instance\n * @private\n */\nclass Requester {\n constructor(sources) {\n this._sources = sources;\n }\n\n __split_requests(fields) {\n // Given a fields array, return an object specifying what datasource names the data layer should make requests\n // to, and how to handle the returned data\n var requests = {};\n // Regular expression finds namespace:field|trans\n var re = /^(?:([^:]+):)?([^:|]*)(\\|.+)*$/;\n fields.forEach(function(raw) {\n var parts = re.exec(raw);\n var ns = parts[1] || 'base';\n var field = parts[2];\n var trans = TRANSFORMS.get(parts[3]);\n if (typeof requests[ns] == 'undefined') {\n requests[ns] = {outnames:[], fields:[], trans:[]};\n }\n requests[ns].outnames.push(raw);\n requests[ns].fields.push(field);\n requests[ns].trans.push(trans);\n });\n return requests;\n }\n\n /**\n * Fetch data, and create a chain that only connects two data sources if they depend on each other\n * @param {Object} state The current \"state\" of the plot, such as chromosome and start/end positions\n * @param {String[]} fields The list of data fields specified in the `layout` for a specific data layer\n * @returns {Promise}\n */\n getData(state, fields) {\n var requests = this.__split_requests(fields);\n // Create an array of functions that, when called, will trigger the request to the specified datasource\n var request_handles = Object.keys(requests).map((key) => {\n if (!this._sources.get(key)) {\n throw new Error(`Datasource for namespace ${key} not found`);\n }\n return this._sources.get(key).getData(\n state,\n requests[key].fields,\n requests[key].outnames,\n requests[key].trans\n );\n });\n //assume the fields are requested in dependent order\n //TODO: better manage dependencies\n var ret = Promise.resolve({header:{}, body: [], discrete: {}});\n for (var i = 0; i < request_handles.length; i++) {\n // If a single datalayer uses multiple sources, perform the next request when the previous one completes\n ret = ret.then(request_handles[i]);\n }\n return ret;\n }\n}\n\n\nexport default Requester;\n","/** @module */\nimport widgets from '../../registry/widgets';\nimport * as d3 from 'd3';\n\n/**\n * A Toolbar is an HTML element used for presenting arbitrary user interface widgets. Toolbars are anchored\n * to either the entire Plot or to individual Panels.\n *\n * Each toolbar is an HTML-based (read: not SVG) collection of widgets used to display information or provide\n * user interface. Toolbars can exist on entire plots, where their visibility is permanent and vertically adjacent\n * to the plot, or on individual panels, where their visibility is tied to a behavior (e.g. a mouseover) and is as\n * an overlay.\n *\n * This class is used internally for rendering, and is not part of the public interface\n * @private\n */\nclass Toolbar {\n constructor(parent) {\n // parent must be a locuszoom plot or panel\n // if (!(parent instanceof LocusZoom.Plot) && !(parent instanceof LocusZoom.Panel)) {\n // throw new Error('Unable to create toolbar, parent must be a locuszoom plot or panel');\n // }\n /** @member {Plot|Panel} */\n this.parent = parent;\n\n /** @member {String} */\n this.id = `${this.parent.getBaseId()}.toolbar`;\n\n /** @member {('plot'|'panel')} */\n this.type = (this.parent.parent) ? 'panel' : 'plot';\n\n /** @member {Plot} */\n this.parent_plot = this.parent.parent_plot;\n\n /** @member {d3.selection} */\n this.selector = null;\n\n /** @member {BaseWidget[]} */\n this.widgets = [];\n\n /**\n * The timer identifier as returned by setTimeout\n * @member {Number}\n */\n this.hide_timeout = null;\n\n /**\n * Whether to hide the toolbar. Can be overridden by a child widget. Check via `shouldPersist`\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n\n this.initialize();\n }\n\n /**\n * Prepare the toolbar for first use: generate all widget instances for this toolbar, based on the provided\n * layout of the parent. Connects event listeners and shows/hides as appropriate.\n * @returns {Toolbar}\n */\n initialize() {\n // Parse layout to generate widget instances\n // In LZ 0.12, `dashboard.components` was renamed to `toolbar.widgets`. Preserve a backwards-compatible alias.\n const options = (this.parent.layout.dashboard && this.parent.layout.dashboard.components) || this.parent.layout.toolbar.widgets;\n if (Array.isArray(options)) {\n options.forEach((layout) => {\n try {\n const widget = widgets.create(layout.type, layout, this);\n this.widgets.push(widget);\n } catch (e) {\n console.warn('Failed to create widget');\n console.error(e);\n }\n });\n }\n\n // Add mouseover event handlers to show/hide panel toolbar\n if (this.type === 'panel') {\n d3.select(this.parent.parent.svg.node().parentNode)\n .on(`mouseover.${this.id}`, () => {\n clearTimeout(this.hide_timeout);\n if (!this.selector || this.selector.style('visibility') === 'hidden') {\n this.show();\n }\n }).on(`mouseout.${this.id}`, () => {\n clearTimeout(this.hide_timeout);\n this.hide_timeout = setTimeout(() => {\n this.hide();\n }, 300);\n });\n }\n\n return this;\n }\n\n /**\n * Whether to persist the toolbar. Returns true if at least one widget should persist, or if the panel is engaged\n * in an active drag event.\n * @returns {boolean}\n */\n shouldPersist() {\n if (this.persist) {\n return true;\n }\n let persist = false;\n // Persist if at least one widget should also persist\n this.widgets.forEach((widget) => {\n persist = persist || widget.shouldPersist();\n });\n // Persist if in a parent drag event\n persist = persist || (this.parent_plot.panel_boundaries.dragging || this.parent_plot.interaction.dragging);\n return !!persist;\n }\n\n /**\n * Make the toolbar appear. If it doesn't exist yet create it, including creating/positioning all widgets within,\n * and make sure it is set to be visible.\n */\n show() {\n if (!this.selector) {\n switch (this.type) {\n case 'plot':\n this.selector = d3.select(this.parent.svg.node().parentNode)\n .insert('div', ':first-child');\n break;\n case 'panel':\n this.selector = d3.select(this.parent.parent.svg.node().parentNode)\n .insert('div', '.lz-data_layer-tooltip, .lz-toolbar-menu, .lz-curtain').classed('lz-panel-toolbar', true);\n break;\n default:\n throw new Error(`Toolbar cannot be a child of ${this.type}`);\n }\n\n this.selector\n .classed('lz-toolbar', true)\n .classed(`lz-${this.type}-toolbar`, true)\n .attr('id', this.id);\n }\n this.widgets.forEach((widget) => widget.show());\n this.selector.style('visibility', 'visible');\n return this.update();\n }\n\n\n /**\n * Update the toolbar and rerender all child widgets. This can be called whenever plot state changes.\n * @returns {Toolbar}\n */\n update() {\n if (!this.selector) {\n return this;\n }\n this.widgets.forEach((widget) => widget.update());\n return this.position();\n }\n\n\n /**\n * Position the toolbar (and child widgets) within the panel\n * @returns {Toolbar}\n */\n position() {\n if (!this.selector) {\n return this;\n }\n // Position the toolbar itself (panel only)\n if (this.type === 'panel') {\n const page_origin = this.parent._getPageOrigin();\n const top = `${(page_origin.y + 3.5).toString()}px`;\n const left = `${page_origin.x.toString()}px`;\n const width = `${(this.parent.layout.width - 4).toString()}px`;\n this.selector\n .style('position', 'absolute')\n .style('top', top)\n .style('left', left)\n .style('width', width);\n }\n // Recursively position widgets\n this.widgets.forEach((widget) => widget.position());\n return this;\n }\n\n /**\n * Hide the toolbar (make invisible but do not destroy). Will do nothing if `shouldPersist` returns true.\n *\n * @returns {Toolbar}\n */\n hide() {\n if (!this.selector || this.shouldPersist()) {\n return this;\n }\n this.widgets.forEach((widget) => widget.hide());\n this.selector\n .style('visibility', 'hidden');\n return this;\n }\n\n /**\n * Completely remove toolbar and all child widgets. (may be overridden by persistence settings)\n * @param {Boolean} [force=false] If true, will ignore persistence settings and always destroy the toolbar\n * @returns {Toolbar}\n */\n destroy(force) {\n if (typeof force == 'undefined') {\n force = false;\n }\n if (!this.selector) {\n return this;\n }\n if (this.shouldPersist() && !force) {\n return this;\n }\n this.widgets.forEach((widget) => widget.destroy(true));\n this.widgets = [];\n this.selector.remove();\n this.selector = null;\n return this;\n }\n}\n\n\nexport {Toolbar as default};\n","/** @module */\nimport * as d3 from 'd3';\nimport {applyStyles} from '../helpers/common';\nimport {merge, nameToSymbol} from '../helpers/layouts';\n\n/**\n * The default layout used by legends (used internally)\n * @protected\n * @member {Object}\n */\nconst default_layout = {\n orientation: 'vertical',\n origin: { x: 0, y: 0 },\n width: 10,\n height: 10,\n padding: 5,\n label_size: 12,\n hidden: false,\n};\n\n/**\n * An SVG object used to display contextual information about a panel.\n * Panel layouts determine basic features of a legend - its position in the panel, orientation, title, etc.\n * Layouts of child data layers of the panel determine the actual content of the legend.\n *\n * @param {Panel} parent\n*/\nclass Legend {\n constructor(parent) {\n // if (!(parent instanceof LocusZoom.Panel)) {\n // throw new Error('Unable to create legend, parent must be a locuszoom panel');\n // }\n /** @member {Panel} */\n this.parent = parent;\n /** @member {String} */\n this.id = `${this.parent.getBaseId()}.legend`;\n\n this.parent.layout.legend = merge(this.parent.layout.legend || {}, default_layout);\n /** @member {Object} */\n this.layout = this.parent.layout.legend;\n\n /** @member {d3.selection} */\n this.selector = null;\n /** @member {d3.selection} */\n this.background_rect = null;\n /** @member {d3.selection[]} */\n this.elements = [];\n /**\n * SVG selector for the group containing all elements in the legend\n * @protected\n * @member {d3.selection|null}\n */\n this.elements_group = null;\n\n /**\n * TODO: Not sure if this property is used; the external-facing methods are setting `layout.hidden` instead. Tentatively mark deprecated.\n * @deprecated\n * @protected\n * @member {Boolean}\n */\n this.hidden = false;\n\n return this.render();\n }\n\n /**\n * Render the legend in the parent panel\n */\n render() {\n // Get a legend group selector if not yet defined\n if (!this.selector) {\n this.selector = this.parent.svg.group.append('g')\n .attr('id', `${this.parent.getBaseId()}.legend`).attr('class', 'lz-legend');\n }\n\n // Get a legend background rect selector if not yet defined\n if (!this.background_rect) {\n this.background_rect = this.selector.append('rect')\n .attr('width', 100)\n .attr('height', 100)\n .attr('class', 'lz-legend-background');\n }\n\n // Get a legend elements group selector if not yet defined\n if (!this.elements_group) {\n this.elements_group = this.selector.append('g');\n }\n\n // Remove all elements from the document and re-render from scratch\n this.elements.forEach((element) => element.remove());\n this.elements = [];\n\n // Gather all elements from data layers in order (top to bottom) and render them\n const padding = +this.layout.padding || 1;\n let x = padding;\n let y = padding;\n let line_height = 0;\n this.parent.data_layer_ids_by_z_index.slice().reverse().forEach((id) => {\n if (Array.isArray(this.parent.data_layers[id].layout.legend)) {\n this.parent.data_layers[id].layout.legend.forEach((element) => {\n const selector = this.elements_group.append('g')\n .attr('transform', `translate(${x}, ${y})`);\n const label_size = +element.label_size || +this.layout.label_size || 12;\n let label_x = 0;\n let label_y = (label_size / 2) + (padding / 2);\n line_height = Math.max(line_height, label_size + padding);\n // Draw the legend element symbol (line, rect, shape, etc)\n const shape = element.shape || '';\n const shape_factory = nameToSymbol(shape);\n if (shape === 'line') {\n // Line symbol\n const length = +element.length || 16;\n const path_y = (label_size / 4) + (padding / 2);\n selector\n .append('path')\n .attr('class', element.class || '')\n .attr('d', `M0,${path_y}L${length},${path_y}`)\n .call(applyStyles, element.style || {});\n label_x = length + padding;\n } else if (shape === 'rect') {\n // Rect symbol\n const width = +element.width || 16;\n const height = +element.height || width;\n selector\n .append('rect')\n .attr('class', element.class || '')\n .attr('width', width)\n .attr('height', height)\n .attr('fill', element.color || {})\n .call(applyStyles, element.style || {});\n\n label_x = width + padding;\n line_height = Math.max(line_height, height + padding);\n } else if (shape_factory) {\n // Shape symbol is a recognized d3 type, so we can draw it in the legend (circle, diamond, etc.)\n const size = +element.size || 40;\n const radius = Math.ceil(Math.sqrt(size / Math.PI));\n selector\n .append('path')\n .attr('class', element.class || '')\n .attr('d', d3.symbol().size(size).type(shape_factory))\n .attr('transform', `translate(${radius}, ${radius + (padding / 2)})`)\n .attr('fill', element.color || {})\n .call(applyStyles, element.style || {});\n\n label_x = (2 * radius) + padding;\n label_y = Math.max((2 * radius) + (padding / 2), label_y);\n line_height = Math.max(line_height, (2 * radius) + padding);\n }\n // Draw the legend element label\n selector\n .append('text')\n .attr('text-anchor', 'left')\n .attr('class', 'lz-label')\n .attr('x', label_x)\n .attr('y', label_y)\n .style('font-size', label_size)\n .text(element.label);\n\n // Position the legend element group based on legend layout orientation\n const bcr = selector.node().getBoundingClientRect();\n if (this.layout.orientation === 'vertical') {\n y += bcr.height + padding;\n line_height = 0;\n } else {\n // Ensure this element does not exceed the panel width\n // (E.g. drop to the next line if it does, but only if it's not the only element on this line)\n const right_x = this.layout.origin.x + x + bcr.width;\n if (x > padding && right_x > this.parent.layout.width) {\n y += line_height;\n x = padding;\n selector.attr('transform', `translate(${x}, ${y})`);\n }\n x += bcr.width + (3 * padding);\n }\n // Store the element\n this.elements.push(selector);\n });\n }\n });\n\n // Scale the background rect to the elements in the legend\n const bcr = this.elements_group.node().getBoundingClientRect();\n this.layout.width = bcr.width + (2 * this.layout.padding);\n this.layout.height = bcr.height + (2 * this.layout.padding);\n this.background_rect\n .attr('width', this.layout.width)\n .attr('height', this.layout.height);\n\n // Set the visibility on the legend from the \"hidden\" flag\n // TODO: `show()` and `hide()` call a full rerender; might be able to make this more lightweight?\n this.selector\n .style('visibility', this.layout.hidden ? 'hidden' : 'visible');\n\n return this.position();\n }\n\n /**\n * Place the legend in position relative to the panel, as specified in the layout configuration\n * @returns {Legend | null}\n * TODO: should this always be chainable?\n */\n position() {\n if (!this.selector) {\n return this;\n }\n const bcr = this.selector.node().getBoundingClientRect();\n if (!isNaN(+this.layout.pad_from_bottom)) {\n this.layout.origin.y = this.parent.layout.height - bcr.height - +this.layout.pad_from_bottom;\n }\n if (!isNaN(+this.layout.pad_from_right)) {\n this.layout.origin.x = this.parent.layout.width - bcr.width - +this.layout.pad_from_right;\n }\n this.selector.attr('transform', `translate(${this.layout.origin.x}, ${this.layout.origin.y})`);\n }\n\n /**\n * Hide the legend (triggers a re-render)\n * @public\n */\n hide() {\n this.layout.hidden = true;\n this.render();\n }\n\n /**\n * Show the legend (triggers a re-render)\n * @public\n */\n show() {\n this.layout.hidden = false;\n this.render();\n }\n}\n\nexport {Legend as default};\n","/** @module */\nimport * as d3 from 'd3';\n\nimport {STATUSES} from './constants';\nimport Toolbar from './toolbar';\nimport {applyStyles, generateCurtain, generateLoader} from '../helpers/common';\nimport {parseFields, positionIntToString, prettyTicks} from '../helpers/display';\nimport {merge} from '../helpers/layouts';\nimport Legend from './legend';\nimport data_layers from '../registry/data_layers';\n\n\n/**\n * Default panel layout\n * @static\n * @type {Object}\n */\nconst default_layout = {\n title: { text: '', style: {}, x: 10, y: 22 },\n y_index: null,\n width: 0,\n height: 0,\n origin: { x: 0, y: null },\n min_width: 1,\n min_height: 1,\n proportional_width: null,\n proportional_height: null,\n proportional_origin: { x: 0, y: null },\n margin: { top: 0, right: 0, bottom: 0, left: 0 },\n background_click: 'clear_selections',\n toolbar: {\n widgets: [],\n },\n cliparea: {\n height: 0,\n width: 0,\n origin: { x: 0, y: 0 },\n },\n axes: { // These are the only axes supported!!\n x: {},\n y1: {},\n y2: {},\n },\n legend: null,\n interaction: {\n drag_background_to_pan: false,\n drag_x_ticks_to_scale: false,\n drag_y1_ticks_to_scale: false,\n drag_y2_ticks_to_scale: false,\n scroll_to_zoom: false,\n x_linked: false,\n y1_linked: false,\n y2_linked: false,\n },\n data_layers: [],\n};\n\n/**\n * A panel is an abstract class representing a subdivision of the LocusZoom stage\n * to display a distinct data representation as a collection of data layers.\n */\nclass Panel {\n /**\n * @param {Object} layout\n * @param {Plot|null} parent\n */\n constructor(layout, parent) {\n if (typeof layout !== 'object') {\n throw new Error('Unable to create panel, invalid layout');\n }\n\n /**\n * @protected\n * @member {Plot|null}\n */\n this.parent = parent || null;\n /**\n * @protected\n * @member {Plot|null}\n */\n this.parent_plot = parent;\n\n // Ensure a valid ID is present. If there is no valid ID then generate one\n if (typeof layout.id !== 'string' || !layout.id.length) {\n if (!this.parent) {\n layout.id = `p${Math.floor(Math.random() * Math.pow(10, 8))}`;\n } else {\n const generateID = () => {\n let id = `p${Math.floor(Math.random() * Math.pow(10, 8))}`;\n if (id === null || typeof this.parent.panels[id] != 'undefined') {\n id = generateID();\n }\n return id;\n };\n layout.id = generateID();\n }\n } else if (this.parent) {\n if (typeof this.parent.panels[layout.id] !== 'undefined') {\n throw new Error(`Cannot create panel with id [${layout.id}]; panel with that id already exists`);\n }\n }\n /**\n * @public\n * @member {String}\n */\n this.id = layout.id;\n\n /**\n * @private\n * @member {Boolean}\n */\n this.initialized = false;\n /**\n * The index of this panel in the parent plot's `layout.panels`\n * @private\n * @member {number}\n * */\n this.layout_idx = null;\n /**\n * @private\n * @member {Object}\n */\n this.svg = {};\n\n /**\n * A JSON-serializable object used to describe the composition of the Panel\n * @public\n * @member {Object}\n */\n this.layout = merge(layout || {}, default_layout);\n\n // Define state parameters specific to this panel\n if (this.parent) {\n /**\n * @private\n * @member {Object}\n */\n this.state = this.parent.state;\n\n /**\n * @private\n * @member {String}\n */\n this.state_id = this.id;\n this.state[this.state_id] = this.state[this.state_id] || {};\n } else {\n this.state = null;\n this.state_id = null;\n }\n\n /**\n * @protected\n * @member {Object}\n */\n this.data_layers = {};\n /**\n * @private\n * @member {String[]}\n */\n this.data_layer_ids_by_z_index = [];\n\n /**\n * Track data requests in progress\n * @member {Promise[]}\n * @private\n */\n this.data_promises = [];\n\n /**\n * @private\n * @member {d3.scale}\n */\n this.x_scale = null;\n /**\n * @private\n * @member {d3.scale}\n */\n this.y1_scale = null;\n /**\n * @private\n * @member {d3.scale}\n */\n this.y2_scale = null;\n\n /**\n * @private\n * @member {d3.extent}\n */\n this.x_extent = null;\n /**\n * @private\n * @member {d3.extent}\n */\n this.y1_extent = null;\n /**\n * @private\n * @member {d3.extent}\n */\n this.y2_extent = null;\n\n /**\n * @private\n * @member {Number[]}\n */\n this.x_ticks = [];\n /**\n * @private\n * @member {Number[]}\n */\n this.y1_ticks = [];\n /**\n * @private\n * @member {Number[]}\n */\n this.y2_ticks = [];\n\n /**\n * A timeout ID as returned by setTimeout\n * @private\n * @member {number}\n */\n this.zoom_timeout = null;\n\n /**\n * Known event hooks that the panel can respond to\n * @protected\n * @member {Object}\n */\n this.event_hooks = {\n 'layout_changed': [],\n 'data_requested': [],\n 'data_rendered': [],\n 'element_clicked': [],\n 'element_selection': [],\n 'match_requested': [], // A data layer is attempting to highlight matching points (internal use only)\n };\n\n // Initialize the layout\n this.initializeLayout();\n }\n\n /******* Public methods: intended for direct external manipulation of panel internals */\n\n /**\n * There are several events that a LocusZoom panel can \"emit\" when appropriate, and LocusZoom supports registering\n * \"hooks\" for these events which are essentially custom functions intended to fire at certain times.\n *\n * The following panel-level events are currently supported:\n * - `layout_changed` - context: panel - Any aspect of the panel's layout (including dimensions or state) has changed.\n * - `data_requested` - context: panel - A request for new data from any data source used in the panel has been made.\n * - `data_rendered` - context: panel - Data from a request has been received and rendered in the panel.\n * - `element_clicked` - context: panel - A data element in any of the panel's data layers has been clicked.\n * - `element_selection` - context: panel - Triggered when an element changes \"selection\" status, and identifies\n * whether the element is being selected or deselected.\n *\n * To register a hook for any of these events use `panel.on('event_name', function() {})`.\n *\n * There can be arbitrarily many functions registered to the same event. They will be executed in the order they\n * were registered. The this context bound to each event hook function is dependent on the type of event, as\n * denoted above. For example, when data_requested is emitted the context for this in the event hook will be the\n * panel itself, but when element_clicked is emitted the context for this in the event hook will be the element\n * that was clicked.\n *\n * @public\n * @param {String} event The name of the event (as defined in `event_hooks`)\n * @param {function} hook\n * @returns {function} The registered event listener\n */\n on(event, hook) {\n // TODO: Dry plot and panel event code into a shared mixin\n if (typeof 'event' != 'string' || !Array.isArray(this.event_hooks[event])) {\n throw new Error(`Unable to register event hook, invalid event: ${event.toString()}`);\n }\n if (typeof hook != 'function') {\n throw new Error('Unable to register event hook, invalid hook function passed');\n }\n this.event_hooks[event].push(hook);\n return hook;\n }\n\n /**\n * Remove one or more previously defined event listeners\n * @public\n * @param {String} event The name of an event (as defined in `event_hooks`)\n * @param {eventCallback} [hook] The callback to deregister\n * @returns {Panel}\n */\n off(event, hook) {\n const theseHooks = this.event_hooks[event];\n if (typeof 'event' != 'string' || !Array.isArray(theseHooks)) {\n throw new Error(`Unable to remove event hook, invalid event: ${event.toString()}`);\n }\n if (hook === undefined) {\n // Deregistering all hooks for this event may break basic functionality, and should only be used during\n // cleanup operations (eg to prevent memory leaks)\n this.event_hooks[event] = [];\n } else {\n const hookMatch = theseHooks.indexOf(hook);\n if (hookMatch !== -1) {\n theseHooks.splice(hookMatch, 1);\n } else {\n throw new Error('The specified event listener is not registered and therefore cannot be removed');\n }\n }\n return this;\n }\n\n /**\n * Handle running of event hooks when an event is emitted\n *\n * There is a shorter overloaded form of this method: if the event does not have any data, the second\n * argument can be a boolean to control bubbling\n *\n * @public\n * @param {string} event A known event name\n * @param {*} [eventData] Data or event description that will be passed to the event listener\n * @param {boolean} [bubble=false] Whether to bubble the event to the parent\n * @returns {Panel}\n */\n emit(event, eventData, bubble) {\n bubble = bubble || false;\n\n // TODO: DRY this with the parent plot implementation. Ensure interfaces remain compatible.\n // TODO: Improve documentation for overloaded method signature (JSDoc may have trouble here)\n if (typeof 'event' != 'string' || !Array.isArray(this.event_hooks[event])) {\n throw new Error(`LocusZoom attempted to throw an invalid event: ${event.toString()}`);\n }\n if (typeof eventData === 'boolean' && arguments.length === 2) {\n // Overloaded method signature: emit(event, bubble)\n bubble = eventData;\n eventData = null;\n }\n const sourceID = this.getBaseId();\n const eventContext = { sourceID: sourceID, data: eventData || null };\n this.event_hooks[event].forEach((hookToRun) => {\n // By default, any handlers fired here will see the panel as the value of `this`. If a bound function is\n // registered as a handler, the previously bound `this` will override anything provided to `call` below.\n hookToRun.call(this, eventContext);\n });\n if (bubble && this.parent) {\n this.parent.emit(event, eventContext);\n }\n return this;\n }\n\n /**\n * Set the title for the panel. If passed an object, will merge the object with the existing layout configuration, so\n * that all or only some of the title layout object's parameters can be customized. If passed null, false, or an empty\n * string, the title DOM element will be set to display: none.\n *\n * @public\n * @param {string|object|null} title The title text, or an object with additional configuration\n * @param {string} title.text Text to display. Since titles are rendered as SVG text, HTML and newlines will not be rendered.\n * @param {number} title.x X-offset, in pixels, for the title's text anchor (default left) relative to the top-left corner of the panel.\n * @param {number} title.y Y-offset, in pixels, for the title's text anchor (default left) relative to the top-left corner of the panel.\n NOTE: SVG y values go from the top down, so the SVG origin of (0,0) is in the top left corner.\n * @param {object} title.style CSS styles object to be applied to the title's DOM element.\n * @returns {Panel}\n */\n setTitle(title) {\n if (typeof this.layout.title == 'string') {\n const text = this.layout.title;\n this.layout.title = { text: text, x: 0, y: 0, style: {} };\n }\n if (typeof title == 'string') {\n this.layout.title.text = title;\n } else if (typeof title == 'object' && title !== null) {\n this.layout.title = merge(title, this.layout.title);\n }\n if (this.layout.title.text.length) {\n this.title\n .attr('display', null)\n .attr('x', parseFloat(this.layout.title.x))\n .attr('y', parseFloat(this.layout.title.y))\n .text(this.layout.title.text)\n .call(applyStyles, this.layout.title.style);\n\n } else {\n this.title.attr('display', 'none');\n }\n return this;\n }\n\n /**\n * Create a new data layer from a provided layout object. Should have the keys specified in `DefaultLayout`\n * Will automatically add at the top (depth/z-index) of the panel unless explicitly directed differently\n * in the layout provided.\n * @public\n * @param {object} layout\n * @returns {*}\n */\n addDataLayer(layout) {\n\n // Sanity checks\n if (typeof layout !== 'object' || typeof layout.id !== 'string' || !layout.id.length) {\n throw new Error('Invalid data layer layout');\n }\n if (typeof this.data_layers[layout.id] !== 'undefined') {\n throw new Error(`Cannot create data_layer with id [${layout.id}]; data layer with that id already exists in the panel`);\n }\n if (typeof layout.type !== 'string') {\n throw new Error('Invalid data layer type');\n }\n\n // If the layout defines a y axis make sure the axis number is set and is 1 or 2 (default to 1)\n if (typeof layout.y_axis == 'object' && (typeof layout.y_axis.axis == 'undefined' || ![1, 2].includes(layout.y_axis.axis))) {\n layout.y_axis.axis = 1;\n }\n\n // Create the Data Layer\n const data_layer = data_layers.create(layout.type, layout, this);\n\n // Store the Data Layer on the Panel\n this.data_layers[data_layer.id] = data_layer;\n\n // If a discrete z_index was set in the layout then adjust other data layer z_index values to accommodate this one\n if (data_layer.layout.z_index !== null && !isNaN(data_layer.layout.z_index)\n && this.data_layer_ids_by_z_index.length > 0) {\n // Negative z_index values should count backwards from the end, so convert negatives to appropriate values here\n if (data_layer.layout.z_index < 0) {\n data_layer.layout.z_index = Math.max(this.data_layer_ids_by_z_index.length + data_layer.layout.z_index, 0);\n }\n this.data_layer_ids_by_z_index.splice(data_layer.layout.z_index, 0, data_layer.id);\n this.data_layer_ids_by_z_index.forEach((dlid, idx) => {\n this.data_layers[dlid].layout.z_index = idx;\n });\n } else {\n const length = this.data_layer_ids_by_z_index.push(data_layer.id);\n this.data_layers[data_layer.id].layout.z_index = length - 1;\n }\n\n // Determine if this data layer was already in the layout.data_layers array.\n // If it wasn't, add it. Either way store the layout.data_layers array index on the data_layer.\n let layout_idx = null;\n this.layout.data_layers.forEach((data_layer_layout, idx) => {\n if (data_layer_layout.id === data_layer.id) {\n layout_idx = idx;\n }\n });\n if (layout_idx === null) {\n layout_idx = this.layout.data_layers.push(this.data_layers[data_layer.id].layout) - 1;\n }\n this.data_layers[data_layer.id].layout_idx = layout_idx;\n\n return this.data_layers[data_layer.id];\n }\n\n /**\n * Remove a data layer by id\n * @public\n * @param {string} id\n * @returns {Panel}\n */\n removeDataLayer(id) {\n if (!this.data_layers[id]) {\n throw new Error(`Unable to remove data layer, ID not found: ${id}`);\n }\n\n // Destroy all tooltips for the data layer\n this.data_layers[id].destroyAllTooltips();\n\n // Remove the svg container for the data layer if it exists\n if (this.data_layers[id].svg.container) {\n this.data_layers[id].svg.container.remove();\n }\n\n // Delete the data layer and its presence in the panel layout and state\n this.layout.data_layers.splice(this.data_layers[id].layout_idx, 1);\n delete this.state[this.data_layers[id].state_id];\n delete this.data_layers[id];\n\n // Remove the data_layer id from the z_index array\n this.data_layer_ids_by_z_index.splice(this.data_layer_ids_by_z_index.indexOf(id), 1);\n\n // Update layout_idx and layout.z_index values for all remaining data_layers\n this.applyDataLayerZIndexesToDataLayerLayouts();\n this.layout.data_layers.forEach((data_layer_layout, idx) => {\n this.data_layers[data_layer_layout.id].layout_idx = idx;\n });\n\n return this;\n }\n\n /**\n * Clear all selections on all data layers\n * @public\n * @returns {Panel}\n */\n clearSelections() {\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].setAllElementStatus('selected', false);\n });\n return this;\n }\n\n /**\n * Update rendering of this panel whenever an event triggers a redraw. Assumes that the panel has already been\n * prepared the first time via `initialize`\n * @public\n * @returns {Panel}\n */\n render() {\n\n // Position the panel container\n this.svg.container.attr('transform', `translate(${this.layout.origin.x}, ${this.layout.origin.y})`);\n\n // Set size on the clip rect\n this.svg.clipRect\n .attr('width', this.layout.width)\n .attr('height', this.layout.height);\n\n // Set and position the inner border, style if necessary\n this.inner_border\n .attr('x', this.layout.margin.left)\n .attr('y', this.layout.margin.top)\n .attr('width', this.layout.width - (this.layout.margin.left + this.layout.margin.right))\n .attr('height', this.layout.height - (this.layout.margin.top + this.layout.margin.bottom));\n if (this.layout.inner_border) {\n this.inner_border\n .style('stroke-width', 1)\n .style('stroke', this.layout.inner_border);\n }\n\n // Set/update panel title if necessary\n this.setTitle();\n\n // Regenerate all extents\n this.generateExtents();\n\n // Helper function to constrain any procedurally generated vectors (e.g. ranges, extents)\n // Constraints applied here keep vectors from going to infinity or beyond a definable power of ten\n const constrain = function (value, limit_exponent) {\n const neg_min = Math.pow(-10, limit_exponent);\n const neg_max = Math.pow(-10, -limit_exponent);\n const pos_min = Math.pow(10, -limit_exponent);\n const pos_max = Math.pow(10, limit_exponent);\n if (value === Infinity) {\n value = pos_max;\n }\n if (value === -Infinity) {\n value = neg_min;\n }\n if (value === 0) {\n value = pos_min;\n }\n if (value > 0) {\n value = Math.max(Math.min(value, pos_max), pos_min);\n }\n if (value < 0) {\n value = Math.max(Math.min(value, neg_max), neg_min);\n }\n return value;\n };\n\n // Define default and shifted ranges for all axes\n const ranges = {};\n if (this.x_extent) {\n const base_x_range = { start: 0, end: this.layout.cliparea.width };\n if (this.layout.axes.x.range) {\n base_x_range.start = this.layout.axes.x.range.start || base_x_range.start;\n base_x_range.end = this.layout.axes.x.range.end || base_x_range.end;\n }\n ranges.x = [base_x_range.start, base_x_range.end];\n ranges.x_shifted = [base_x_range.start, base_x_range.end];\n }\n if (this.y1_extent) {\n const base_y1_range = { start: this.layout.cliparea.height, end: 0 };\n if (this.layout.axes.y1.range) {\n base_y1_range.start = this.layout.axes.y1.range.start || base_y1_range.start;\n base_y1_range.end = this.layout.axes.y1.range.end || base_y1_range.end;\n }\n ranges.y1 = [base_y1_range.start, base_y1_range.end];\n ranges.y1_shifted = [base_y1_range.start, base_y1_range.end];\n }\n if (this.y2_extent) {\n const base_y2_range = { start: this.layout.cliparea.height, end: 0 };\n if (this.layout.axes.y2.range) {\n base_y2_range.start = this.layout.axes.y2.range.start || base_y2_range.start;\n base_y2_range.end = this.layout.axes.y2.range.end || base_y2_range.end;\n }\n ranges.y2 = [base_y2_range.start, base_y2_range.end];\n ranges.y2_shifted = [base_y2_range.start, base_y2_range.end];\n }\n\n // Shift ranges based on any drag or zoom interactions currently underway\n if (this.parent.interaction.panel_id && (this.parent.interaction.panel_id === this.id || this.parent.interaction.linked_panel_ids.includes(this.id))) {\n let anchor, scalar = null;\n if (this.parent.interaction.zooming && typeof this.x_scale == 'function') {\n const current_extent_size = Math.abs(this.x_extent[1] - this.x_extent[0]);\n const current_scaled_extent_size = Math.round(this.x_scale.invert(ranges.x_shifted[1])) - Math.round(this.x_scale.invert(ranges.x_shifted[0]));\n let zoom_factor = this.parent.interaction.zooming.scale;\n const potential_extent_size = Math.floor(current_scaled_extent_size * (1 / zoom_factor));\n if (zoom_factor < 1 && !isNaN(this.parent.layout.max_region_scale)) {\n zoom_factor = 1 / (Math.min(potential_extent_size, this.parent.layout.max_region_scale) / current_scaled_extent_size);\n } else if (zoom_factor > 1 && !isNaN(this.parent.layout.min_region_scale)) {\n zoom_factor = 1 / (Math.max(potential_extent_size, this.parent.layout.min_region_scale) / current_scaled_extent_size);\n }\n const new_extent_size = Math.floor(current_extent_size * zoom_factor);\n anchor = this.parent.interaction.zooming.center - this.layout.margin.left - this.layout.origin.x;\n const offset_ratio = anchor / this.layout.cliparea.width;\n const new_x_extent_start = Math.max(Math.floor(this.x_scale.invert(ranges.x_shifted[0]) - ((new_extent_size - current_scaled_extent_size) * offset_ratio)), 1);\n ranges.x_shifted = [ this.x_scale(new_x_extent_start), this.x_scale(new_x_extent_start + new_extent_size) ];\n } else if (this.parent.interaction.dragging) {\n switch (this.parent.interaction.dragging.method) {\n case 'background':\n ranges.x_shifted[0] = +this.parent.interaction.dragging.dragged_x;\n ranges.x_shifted[1] = this.layout.cliparea.width + this.parent.interaction.dragging.dragged_x;\n break;\n case 'x_tick':\n if (d3.event && d3.event.shiftKey) {\n ranges.x_shifted[0] = +this.parent.interaction.dragging.dragged_x;\n ranges.x_shifted[1] = this.layout.cliparea.width + this.parent.interaction.dragging.dragged_x;\n } else {\n anchor = this.parent.interaction.dragging.start_x - this.layout.margin.left - this.layout.origin.x;\n scalar = constrain(anchor / (anchor + this.parent.interaction.dragging.dragged_x), 3);\n ranges.x_shifted[0] = 0;\n ranges.x_shifted[1] = Math.max(this.layout.cliparea.width * (1 / scalar), 1);\n }\n break;\n case 'y1_tick':\n case 'y2_tick': {\n const y_shifted = `y${this.parent.interaction.dragging.method[1]}_shifted`;\n if (d3.event && d3.event.shiftKey) {\n ranges[y_shifted][0] = this.layout.cliparea.height + this.parent.interaction.dragging.dragged_y;\n ranges[y_shifted][1] = +this.parent.interaction.dragging.dragged_y;\n } else {\n anchor = this.layout.cliparea.height - (this.parent.interaction.dragging.start_y - this.layout.margin.top - this.layout.origin.y);\n scalar = constrain(anchor / (anchor - this.parent.interaction.dragging.dragged_y), 3);\n ranges[y_shifted][0] = this.layout.cliparea.height;\n ranges[y_shifted][1] = this.layout.cliparea.height - (this.layout.cliparea.height * (1 / scalar));\n }\n }\n }\n }\n }\n\n // Generate scales and ticks for all axes, then render them\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (!this[`${axis}_extent`]) {\n return;\n }\n\n // Base Scale\n this[`${axis}_scale`] = d3.scaleLinear()\n .domain(this[`${axis}_extent`])\n .range(ranges[`${axis}_shifted`]);\n\n // Shift the extent\n this[`${axis}_extent`] = [\n this[`${axis}_scale`].invert(ranges[axis][0]),\n this[`${axis}_scale`].invert(ranges[axis][1]),\n ];\n\n // Finalize Scale\n this[`${axis}_scale`] = d3.scaleLinear()\n .domain(this[`${axis}_extent`]).range(ranges[axis]);\n\n // Render axis (and generate ticks as needed)\n this.renderAxis(axis);\n });\n\n // Establish mousewheel zoom event handers on the panel (namespacing not passed through by d3, so not used here)\n if (this.layout.interaction.scroll_to_zoom) {\n const zoom_handler = () => {\n // Look for a shift key press while scrolling to execute.\n // If not present, gracefully raise a notification and allow conventional scrolling\n if (!d3.event.shiftKey) {\n if (this.parent._canInteract(this.id)) {\n this.loader.show('Press [SHIFT] while scrolling to zoom').hide(1000);\n }\n return;\n }\n d3.event.preventDefault();\n if (!this.parent._canInteract(this.id)) {\n return;\n }\n const coords = d3.mouse(this.svg.container.node());\n const delta = Math.max(-1, Math.min(1, (d3.event.wheelDelta || -d3.event.detail || -d3.event.deltaY)));\n if (delta === 0) {\n return;\n }\n this.parent.interaction = {\n panel_id: this.id,\n linked_panel_ids: this.getLinkedPanelIds('x'),\n zooming: {\n scale: (delta < 1) ? 0.9 : 1.1,\n center: coords[0],\n },\n };\n this.render();\n this.parent.interaction.linked_panel_ids.forEach((panel_id) => {\n this.parent.panels[panel_id].render();\n });\n if (this.zoom_timeout !== null) {\n clearTimeout(this.zoom_timeout);\n }\n this.zoom_timeout = setTimeout(() => {\n this.parent.interaction = {};\n this.parent.applyState({ start: this.x_extent[0], end: this.x_extent[1] });\n }, 500);\n };\n this.zoom_listener = d3.zoom();\n this.svg.container.call(this.zoom_listener)\n .on('wheel.zoom', zoom_handler)\n .on('mousewheel.zoom', zoom_handler)\n .on('DOMMouseScroll.zoom', zoom_handler);\n }\n\n // Render data layers in order by z-index\n this.data_layer_ids_by_z_index.forEach((data_layer_id) => {\n this.data_layers[data_layer_id].draw().render();\n });\n\n return this;\n }\n\n /**\n * Add a \"basic\" loader to a panel\n * This method is just a shortcut for adding the most commonly used type of loading indicator, which appears when\n * data is requested, animates (e.g. shows an infinitely cycling progress bar as opposed to one that loads from\n * 0-100% based on actual load progress), and disappears when new data is loaded and rendered.\n *\n * @public\n * @param {Boolean} show_immediately\n * @returns {Panel}\n */\n addBasicLoader(show_immediately) {\n if (typeof show_immediately != 'undefined') {\n show_immediately = true;\n }\n if (show_immediately) {\n this.loader.show('Loading...').animate();\n }\n this.on('data_requested', () => {\n this.loader.show('Loading...').animate();\n });\n this.on('data_rendered', () => {\n this.loader.hide();\n });\n return this;\n }\n\n /************* Private interface: only used internally */\n /** @private */\n applyDataLayerZIndexesToDataLayerLayouts () {\n this.data_layer_ids_by_z_index.forEach((dlid, idx) => {\n this.data_layers[dlid].layout.z_index = idx;\n });\n }\n\n /**\n * @private\n * @returns {string}\n */\n getBaseId () {\n return `${this.parent.id}.${this.id}`;\n }\n\n /**\n * Get an object with the x and y coordinates of the panel's origin in terms of the entire page\n * Necessary for positioning any HTML elements over the panel\n * @private\n * @returns {{x: Number, y: Number}}\n */\n _getPageOrigin() {\n const plot_origin = this.parent._getPageOrigin();\n return {\n x: plot_origin.x + this.layout.origin.x,\n y: plot_origin.y + this.layout.origin.y,\n };\n }\n\n /**\n * Prepare the panel for first use by performing parameter validation, creating axes, setting default dimensions,\n * and preparing / positioning data layers as appropriate.\n * @private\n * @returns {Panel}\n */\n initializeLayout() {\n\n // If the layout is missing BOTH width and proportional width then set the proportional width to 1.\n // This will default the panel to taking up the full width of the plot.\n if (this.layout.width === 0 && this.layout.proportional_width === null) {\n this.layout.proportional_width = 1;\n }\n\n // If the layout is missing BOTH height and proportional height then set the proportional height to\n // an equal share of the plot's current height.\n if (this.layout.height === 0 && this.layout.proportional_height === null) {\n const panel_count = Object.keys(this.parent.panels).length;\n if (panel_count > 0) {\n this.layout.proportional_height = (1 / panel_count);\n } else {\n this.layout.proportional_height = 1;\n }\n }\n\n // Set panel dimensions, origin, and margin\n this.setDimensions();\n this.setOrigin();\n this.setMargin();\n\n // Set ranges\n // TODO: Define stub values in constructor\n this.x_range = [0, this.layout.cliparea.width];\n this.y1_range = [this.layout.cliparea.height, 0];\n this.y2_range = [this.layout.cliparea.height, 0];\n\n // Initialize panel axes\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (!Object.keys(this.layout.axes[axis]).length || this.layout.axes[axis].render === false) {\n // The default layout sets the axis to an empty object, so set its render boolean here\n this.layout.axes[axis].render = false;\n } else {\n this.layout.axes[axis].render = true;\n this.layout.axes[axis].label = this.layout.axes[axis].label || null;\n this.layout.axes[axis].label_function = this.layout.axes[axis].label_function || null;\n }\n });\n\n // Add data layers (which define x and y extents)\n this.layout.data_layers.forEach((data_layer_layout) => {\n this.addDataLayer(data_layer_layout);\n });\n\n return this;\n }\n\n /**\n * Set the dimensions for the panel. If passed with no arguments will calculate optimal size based on layout\n * directives and the available area within the plot. If passed discrete width (number) and height (number) will\n * attempt to resize the panel to them, but may be limited by minimum dimensions defined on the plot or panel.\n *\n * @private\n * @param {number} [width]\n * @param {number} [height]\n * @returns {Panel}\n */\n setDimensions(width, height) {\n if (typeof width != 'undefined' && typeof height != 'undefined') {\n if (!isNaN(width) && width >= 0 && !isNaN(height) && height >= 0) {\n this.layout.width = Math.max(Math.round(+width), this.layout.min_width);\n this.layout.height = Math.max(Math.round(+height), this.layout.min_height);\n }\n } else {\n if (this.layout.proportional_width !== null) {\n this.layout.width = Math.max(this.layout.proportional_width * this.parent.layout.width, this.layout.min_width);\n }\n if (this.layout.proportional_height !== null) {\n this.layout.height = Math.max(this.layout.proportional_height * this.parent.layout.height, this.layout.min_height);\n }\n }\n this.layout.cliparea.width = Math.max(this.layout.width - (this.layout.margin.left + this.layout.margin.right), 0);\n this.layout.cliparea.height = Math.max(this.layout.height - (this.layout.margin.top + this.layout.margin.bottom), 0);\n if (this.svg.clipRect) {\n this.svg.clipRect\n .attr('width', this.layout.width)\n .attr('height', this.layout.height);\n }\n if (this.initialized) {\n this.render();\n this.curtain.update();\n this.loader.update();\n this.toolbar.update();\n if (this.legend) {\n this.legend.position();\n }\n }\n return this;\n }\n\n /**\n * Set panel origin on the plot, and re-render as appropriate\n *\n * @private\n * @param {number} x\n * @param {number} y\n * @returns {Panel}\n */\n setOrigin(x, y) {\n if (!isNaN(x) && x >= 0) {\n this.layout.origin.x = Math.max(Math.round(+x), 0);\n }\n if (!isNaN(y) && y >= 0) {\n this.layout.origin.y = Math.max(Math.round(+y), 0);\n }\n if (this.initialized) {\n this.render();\n }\n return this;\n }\n\n /**\n * Set margins around this panel\n * @private\n * @param {number} top\n * @param {number} right\n * @param {number} bottom\n * @param {number} left\n * @returns {Panel}\n */\n setMargin(top, right, bottom, left) {\n let extra;\n if (!isNaN(top) && top >= 0) {\n this.layout.margin.top = Math.max(Math.round(+top), 0);\n }\n if (!isNaN(right) && right >= 0) {\n this.layout.margin.right = Math.max(Math.round(+right), 0);\n }\n if (!isNaN(bottom) && bottom >= 0) {\n this.layout.margin.bottom = Math.max(Math.round(+bottom), 0);\n }\n if (!isNaN(left) && left >= 0) {\n this.layout.margin.left = Math.max(Math.round(+left), 0);\n }\n if (this.layout.margin.top + this.layout.margin.bottom > this.layout.height) {\n extra = Math.floor(((this.layout.margin.top + this.layout.margin.bottom) - this.layout.height) / 2);\n this.layout.margin.top -= extra;\n this.layout.margin.bottom -= extra;\n }\n if (this.layout.margin.left + this.layout.margin.right > this.layout.width) {\n extra = Math.floor(((this.layout.margin.left + this.layout.margin.right) - this.layout.width) / 2);\n this.layout.margin.left -= extra;\n this.layout.margin.right -= extra;\n }\n ['top', 'right', 'bottom', 'left'].forEach((m) => {\n this.layout.margin[m] = Math.max(this.layout.margin[m], 0);\n });\n this.layout.cliparea.width = Math.max(this.layout.width - (this.layout.margin.left + this.layout.margin.right), 0);\n this.layout.cliparea.height = Math.max(this.layout.height - (this.layout.margin.top + this.layout.margin.bottom), 0);\n this.layout.cliparea.origin.x = this.layout.margin.left;\n this.layout.cliparea.origin.y = this.layout.margin.top;\n\n if (this.initialized) {\n this.render();\n }\n return this;\n }\n\n /**\n * Prepare the first rendering of the panel. This includes drawing the individual data layers, but also creates shared\n * elements such as axes, title, and loader/curtain.\n * @private\n * @returns {Panel}\n */\n initialize() {\n\n // Append a container group element to house the main panel group element and the clip path\n // Position with initial layout parameters\n const base_id = this.getBaseId();\n this.svg.container = this.parent.svg.append('g')\n .attr('id', `${base_id}.panel_container`)\n .attr('transform', `translate(${this.layout.origin.x || 0}, ${this.layout.origin.y || 0})`);\n\n // Append clip path to the parent svg element, size with initial layout parameters\n const clipPath = this.svg.container.append('clipPath')\n .attr('id', `${base_id}.clip`);\n this.svg.clipRect = clipPath.append('rect')\n .attr('width', this.layout.width)\n .attr('height', this.layout.height);\n\n // Append svg group for rendering all panel child elements, clipped by the clip path\n this.svg.group = this.svg.container.append('g')\n .attr('id', `${base_id}.panel`)\n .attr('clip-path', `url(#${base_id}.clip)`);\n\n // Add curtain and loader prototypes to the panel\n /** @member {Object} */\n this.curtain = generateCurtain.call(this);\n /** @member {Object} */\n this.loader = generateLoader.call(this);\n\n /**\n * Create the toolbar object and hang widgets on it as defined by panel layout\n * @member {Toolbar}\n */\n this.toolbar = new Toolbar(this);\n\n // Inner border\n this.inner_border = this.svg.group.append('rect')\n .attr('class', 'lz-panel-background')\n .on('click', () => {\n if (this.layout.background_click === 'clear_selections') {\n this.clearSelections();\n }\n });\n\n // Add the title\n /** @member {Element} */\n this.title = this.svg.group.append('text').attr('class', 'lz-panel-title');\n if (typeof this.layout.title != 'undefined') {\n this.setTitle();\n }\n\n // Initialize Axes\n this.svg.x_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.x_axis`)\n .attr('class', 'lz-x lz-axis');\n if (this.layout.axes.x.render) {\n this.svg.x_axis_label = this.svg.x_axis.append('text')\n .attr('class', 'lz-x lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n this.svg.y1_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.y1_axis`).attr('class', 'lz-y lz-y1 lz-axis');\n if (this.layout.axes.y1.render) {\n this.svg.y1_axis_label = this.svg.y1_axis.append('text')\n .attr('class', 'lz-y1 lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n this.svg.y2_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.y2_axis`)\n .attr('class', 'lz-y lz-y2 lz-axis');\n if (this.layout.axes.y2.render) {\n this.svg.y2_axis_label = this.svg.y2_axis.append('text')\n .attr('class', 'lz-y2 lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n\n // Initialize child Data Layers\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].initialize();\n });\n\n /**\n * Legend object, as defined by panel layout and child data layer layouts\n * @member {Legend}\n * */\n this.legend = null;\n if (this.layout.legend) {\n this.legend = new Legend(this);\n }\n\n // Establish panel background drag interaction mousedown event handler (on the panel background)\n if (this.layout.interaction.drag_background_to_pan) {\n const namespace = `.${this.parent.id}.${this.id}.interaction.drag`;\n const mousedown = () => {\n this.parent.startDrag(this, 'background');\n };\n this.svg.container.select('.lz-panel-background')\n .on(`mousedown${namespace}.background`, mousedown)\n .on(`touchstart${namespace}.background`, mousedown);\n }\n\n return this;\n }\n\n /**\n * Refresh the sort order of all data layers (called by data layer moveUp and moveDown methods)\n * @private\n */\n resortDataLayers() {\n const sort = [];\n this.data_layer_ids_by_z_index.forEach((id) => {\n sort.push(this.data_layers[id].layout.z_index);\n });\n this.svg.group\n .selectAll('g.lz-data_layer-container')\n .data(sort)\n .sort(d3.ascending);\n this.applyDataLayerZIndexesToDataLayerLayouts();\n }\n\n /**\n * Get an array of panel IDs that are axis-linked to this panel\n * @private\n * @param {('x'|'y1'|'y2')} axis\n * @returns {Array}\n */\n getLinkedPanelIds(axis) {\n axis = axis || null;\n const linked_panel_ids = [];\n if (!['x', 'y1', 'y2'].includes(axis)) {\n return linked_panel_ids;\n }\n if (!this.layout.interaction[`${axis}_linked`]) {\n return linked_panel_ids;\n }\n this.parent.panel_ids_by_y_index.forEach((panel_id) => {\n if (panel_id !== this.id && this.parent.panels[panel_id].layout.interaction[`${axis}_linked`]) {\n linked_panel_ids.push(panel_id);\n }\n });\n return linked_panel_ids;\n }\n\n /**\n * Move a panel up relative to others by y-index\n * @private\n * @returns {Panel}\n */\n moveUp() {\n if (this.parent.panel_ids_by_y_index[this.layout.y_index - 1]) {\n this.parent.panel_ids_by_y_index[this.layout.y_index] = this.parent.panel_ids_by_y_index[this.layout.y_index - 1];\n this.parent.panel_ids_by_y_index[this.layout.y_index - 1] = this.id;\n this.parent.applyPanelYIndexesToPanelLayouts();\n this.parent.positionPanels();\n }\n return this;\n }\n\n /**\n * Move a panel down (y-axis) relative to others in the plot\n * @private\n * @returns {Panel}\n */\n moveDown() {\n if (this.parent.panel_ids_by_y_index[this.layout.y_index + 1]) {\n this.parent.panel_ids_by_y_index[this.layout.y_index] = this.parent.panel_ids_by_y_index[this.layout.y_index + 1];\n this.parent.panel_ids_by_y_index[this.layout.y_index + 1] = this.id;\n this.parent.applyPanelYIndexesToPanelLayouts();\n this.parent.positionPanels();\n }\n return this;\n }\n\n /**\n * When the parent plot changes state, adjust the panel accordingly. For example, this may include fetching new data\n * from the API as the viewing region changes\n * @private\n * @returns {Promise}\n */\n reMap() {\n this.emit('data_requested');\n this.data_promises = [];\n\n // Remove any previous error messages before attempting to load new data\n this.curtain.hide();\n // Trigger reMap on each Data Layer\n for (let id in this.data_layers) {\n try {\n this.data_promises.push(this.data_layers[id].reMap());\n } catch (error) {\n console.error(error);\n this.curtain.show(error.message || error);\n }\n }\n // When all finished trigger a render\n return Promise.all(this.data_promises)\n .then(() => {\n this.initialized = true;\n this.render();\n this.emit('layout_changed', true);\n this.emit('data_rendered');\n })\n .catch((error) => {\n console.error(error);\n this.curtain.show(error.message || error);\n });\n }\n\n /**\n * Iterate over data layers to generate panel axis extents\n * @private\n * @returns {Panel}\n */\n generateExtents() {\n\n // Reset extents\n ['x', 'y1', 'y2'].forEach((axis) => {\n this[`${axis}_extent`] = null;\n });\n\n // Loop through the data layers\n for (let id in this.data_layers) {\n\n const data_layer = this.data_layers[id];\n\n // If defined and not decoupled, merge the x extent of the data layer with the panel's x extent\n if (data_layer.layout.x_axis && !data_layer.layout.x_axis.decoupled) {\n this.x_extent = d3.extent((this.x_extent || []).concat(data_layer.getAxisExtent('x')));\n }\n\n // If defined and not decoupled, merge the y extent of the data layer with the panel's appropriate y extent\n if (data_layer.layout.y_axis && !data_layer.layout.y_axis.decoupled) {\n const y_axis = `y${data_layer.layout.y_axis.axis}`;\n this[`${y_axis}_extent`] = d3.extent((this[`${y_axis}_extent`] || []).concat(data_layer.getAxisExtent('y')));\n }\n\n }\n\n // Override x_extent from state if explicitly defined to do so\n if (this.layout.axes.x && this.layout.axes.x.extent === 'state') {\n this.x_extent = [ this.state.start, this.state.end ];\n }\n\n return this;\n\n }\n\n /**\n * Generate an array of ticks for an axis. These ticks are generated in one of three ways (highest wins):\n * 1. An array of specific tick marks\n * 2. Query each data layer for what ticks are appropriate, and allow a panel-level tick configuration parameter\n * object to override the layer's default presentation settings\n * 3. Generate generic tick marks based on the extent of the data\n *\n * @private\n * @param {('x'|'y1'|'y2')} axis The string identifier of the axis\n * @returns {Number[]|Object[]} TODO: number format?\n * An array of numbers: interpreted as an array of axis value offsets for positioning.\n * An array of objects: each object must have an 'x' attribute to position the tick.\n * Other supported object keys:\n * * text: string to render for a given tick\n * * style: d3-compatible CSS style object\n * * transform: SVG transform attribute string\n * * color: string or LocusZoom scalable parameter object\n */\n generateTicks(axis) {\n\n // Parse an explicit 'ticks' attribute in the axis layout\n if (this.layout.axes[axis].ticks) {\n const layout = this.layout.axes[axis];\n\n const baseTickConfig = layout.ticks;\n if (Array.isArray(baseTickConfig)) {\n // Array of specific ticks hard-coded into a panel will override any ticks that an individual layer might specify\n return baseTickConfig;\n }\n\n if (typeof baseTickConfig === 'object') {\n // If the layout specifies base configuration for ticks- but without specific positions- then ask each\n // data layer to report the tick marks that it thinks it needs\n // TODO: Few layers currently need to specify custom ticks (which is ok!). But if it becomes common, consider adding mechanisms to deduplicate ticks across layers\n const self = this;\n\n // Pass any layer-specific customizations for how ticks are calculated. (styles are overridden separately)\n const config = { position: baseTickConfig.position };\n\n const combinedTicks = this.data_layer_ids_by_z_index.reduce((acc, data_layer_id) => {\n const nextLayer = self.data_layers[data_layer_id];\n return acc.concat(nextLayer.getTicks(axis, config));\n }, []);\n\n return combinedTicks.map((item) => {\n // The layer makes suggestions, but tick configuration params specified on the panel take precedence\n let itemConfig = {};\n itemConfig = merge(itemConfig, baseTickConfig);\n return merge(itemConfig, item);\n });\n }\n }\n\n // If no other configuration is provided, attempt to generate ticks from the extent\n if (this[`${axis}_extent`]) {\n return prettyTicks(this[`${axis}_extent`], 'both');\n }\n return [];\n }\n\n /**\n * Render ticks for a particular axis\n * @private\n * @param {('x'|'y1'|'y2')} axis The identifier of the axes\n * @returns {Panel}\n */\n renderAxis(axis) {\n\n if (!['x', 'y1', 'y2'].includes(axis)) {\n throw new Error(`Unable to render axis; invalid axis identifier: ${axis}`);\n }\n\n const canRender = this.layout.axes[axis].render\n && typeof this[`${axis}_scale`] == 'function'\n && !isNaN(this[`${axis}_scale`](0));\n\n // If the axis has already been rendered then check if we can/can't render it\n // Make sure the axis element is shown/hidden to suit\n if (this[`${axis}_axis`]) {\n this.svg.container.select(`g.lz-axis.lz-${axis}`)\n .style('display', canRender ? null : 'none');\n }\n\n if (!canRender) {\n return this;\n }\n\n // Axis-specific values to plug in where needed\n const axis_params = {\n x: {\n position: `translate(${this.layout.margin.left}, ${this.layout.height - this.layout.margin.bottom})`,\n orientation: 'bottom',\n label_x: this.layout.cliparea.width / 2,\n label_y: (this.layout.axes[axis].label_offset || 0),\n label_rotate: null,\n },\n y1: {\n position: `translate(${this.layout.margin.left}, ${this.layout.margin.top})`,\n orientation: 'left',\n label_x: -1 * (this.layout.axes[axis].label_offset || 0),\n label_y: this.layout.cliparea.height / 2,\n label_rotate: -90,\n },\n y2: {\n position: `translate(${this.layout.width - this.layout.margin.right}, ${this.layout.margin.top})`,\n orientation: 'right',\n label_x: (this.layout.axes[axis].label_offset || 0),\n label_y: this.layout.cliparea.height / 2,\n label_rotate: -90,\n },\n };\n\n // Generate Ticks\n this[`${axis}_ticks`] = this.generateTicks(axis);\n\n // Determine if the ticks are all numbers (d3-automated tick rendering) or not (manual tick rendering)\n const ticksAreAllNumbers = ((ticks) => {\n for (let i = 0; i < ticks.length; i++) {\n if (isNaN(ticks[i])) {\n return false;\n }\n }\n return true;\n })(this[`${axis}_ticks`]);\n\n // Initialize the axis; set scale and orientation\n let axis_factory;\n switch (axis_params[axis].orientation) {\n case 'right':\n axis_factory = d3.axisRight;\n break;\n case 'left':\n axis_factory = d3.axisLeft;\n break;\n case 'bottom':\n axis_factory = d3.axisBottom;\n break;\n default:\n throw new Error('Unrecognized axis orientation');\n }\n\n this[`${axis}_axis`] = axis_factory(this[`${axis}_scale`])\n .tickPadding(3);\n\n // Set tick values and format\n if (ticksAreAllNumbers) {\n this[`${axis}_axis`].tickValues(this[`${axis}_ticks`]);\n if (this.layout.axes[axis].tick_format === 'region') {\n this[`${axis}_axis`].tickFormat((d) => positionIntToString(d, 6));\n }\n } else {\n let ticks = this[`${axis}_ticks`].map((t) => {\n return (t[axis.substr(0, 1)]);\n });\n this[`${axis}_axis`].tickValues(ticks)\n .tickFormat((t, i) => {\n return this[`${axis}_ticks`][i].text;\n });\n }\n\n // Position the axis in the SVG and apply the axis construct\n this.svg[`${axis}_axis`]\n .attr('transform', axis_params[axis].position)\n .call(this[`${axis}_axis`]);\n\n // If necessary manually apply styles and transforms to ticks as specified by the layout\n if (!ticksAreAllNumbers) {\n const tick_selector = d3.selectAll(`g#${this.getBaseId().replace('.', '\\\\.')}\\\\.${axis}_axis g.tick`);\n const panel = this;\n tick_selector.each(function (d, i) {\n const selector = d3.select(this).select('text');\n if (panel[`${axis}_ticks`][i].style) {\n applyStyles(selector, panel[`${axis}_ticks`][i].style);\n }\n if (panel[`${axis}_ticks`][i].transform) {\n selector.attr('transform', panel[`${axis}_ticks`][i].transform);\n }\n });\n }\n\n // Render the axis label if necessary\n const label = this.layout.axes[axis].label || null;\n if (label !== null) {\n this.svg[`${axis}_axis_label`]\n .attr('x', axis_params[axis].label_x)\n .attr('y', axis_params[axis].label_y)\n .text(parseFields(this.state, label));\n if (axis_params[axis].label_rotate !== null) {\n this.svg[`${axis }_axis_label`]\n .attr('transform', `rotate(${axis_params[axis].label_rotate} ${axis_params[axis].label_x}, ${axis_params[axis].label_y})`);\n }\n }\n\n // Attach interactive handlers to ticks as needed\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (this.layout.interaction[`drag_${axis}_ticks_to_scale`]) {\n const namespace = `.${this.parent.id}.${this.id}.interaction.drag`;\n const tick_mouseover = function() {\n if (typeof d3.select(this).node().focus == 'function') {\n d3.select(this).node().focus();\n }\n let cursor = (axis === 'x') ? 'ew-resize' : 'ns-resize';\n if (d3.event && d3.event.shiftKey) {\n cursor = 'move';\n }\n d3.select(this)\n .style('font-weight', 'bold')\n .style('cursor', cursor )\n .on(`keydown${namespace}`, tick_mouseover)\n .on(`keyup${namespace}`, tick_mouseover);\n };\n this.svg.container.selectAll(`.lz-axis.lz-${axis} .tick text`)\n .attr('tabindex', 0) // necessary to make the tick focusable so keypress events can be captured\n .on(`mouseover${namespace}`, tick_mouseover)\n .on(`mouseout${namespace}`, function() {\n d3.select(this).style('font-weight', 'normal');\n d3.select(this).on(`keydown${namespace}`, null).on(`keyup${namespace}`, null);\n })\n .on(`mousedown${namespace}`, () => {\n this.parent.startDrag(this, `${axis}_tick`);\n });\n }\n });\n\n return this;\n }\n\n /**\n * Force the height of this panel to the largest absolute height of the data in\n * all child data layers (if not null for any child data layers)\n * @private\n * @param {number|null} [target_height] A target height, which will be used in situations when the expected height can be\n * pre-calculated (eg when the layers are transitioning)\n */\n scaleHeightToData(target_height) {\n target_height = +target_height || null;\n if (target_height === null) {\n this.data_layer_ids_by_z_index.forEach((id) => {\n const dh = this.data_layers[id].getAbsoluteDataHeight();\n if (+dh) {\n if (target_height === null) {\n target_height = +dh;\n } else {\n target_height = Math.max(target_height, +dh);\n }\n }\n });\n }\n if (+target_height) {\n target_height += +this.layout.margin.top + +this.layout.margin.bottom;\n this.setDimensions(this.layout.width, target_height);\n this.parent.setDimensions();\n this.parent.panel_ids_by_y_index.forEach((id) => {\n this.parent.panels[id].layout.proportional_height = null;\n });\n this.parent.positionPanels();\n }\n }\n\n /**\n * Methods to set/unset element statuses across all data layers\n * @private\n * @param {String} status\n * @param {Boolean} toggle\n * @param {Array} filters\n * @param {Boolean} exclusive\n */\n setElementStatusByFilters(status, toggle, filters, exclusive) {\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].setElementStatusByFilters(status, toggle, filters, exclusive);\n });\n }\n\n /**\n * Set/unset element statuses across all data layers\n * @private\n * @param {String} status\n * @param {Boolean} toggle\n */\n setAllElementStatus(status, toggle) {\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].setAllElementStatus(status, toggle);\n });\n }\n}\n\nSTATUSES.verbs.forEach((verb, idx) => {\n const adjective = STATUSES.adjectives[idx];\n const antiverb = `un${verb}`;\n // Set/unset status for arbitrarily many elements given a set of filters\n\n /**\n * @private\n * @function highlightElementsByFilters\n */\n /**\n * @private\n * @function selectElementsByFilters\n */\n /**\n * @private\n * @function fadeElementsByFilters\n */\n /**\n * @private\n * @function hideElementsByFilters\n */\n Panel.prototype[`${verb}ElementsByFilters`] = function(filters, exclusive) {\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n return this.setElementStatusByFilters(adjective, true, filters, exclusive);\n };\n\n /**\n * @private\n * @function unhighlightElementsByFilters\n */\n /**\n * @private\n * @function unselectElementsByFilters\n */\n /**\n * @private\n * @function unfadeElementsByFilters\n */\n /**\n * @private\n * @function unhideElementsByFilters\n */\n Panel.prototype[`${antiverb}ElementsByFilters`] = function(filters, exclusive) {\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n return this.setElementStatusByFilters(adjective, false, filters, exclusive);\n };\n\n // Set/unset status for all elements\n /**\n * @private\n * @function highlightAllElements\n */\n /**\n * @private\n * @function selectAllElements\n */\n /**\n * @private\n * @function fadeAllElements\n */\n /**\n * @private\n * @function hideAllElements\n */\n Panel.prototype[`${verb}AllElements`] = function() {\n this.setAllElementStatus(adjective, true);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightAllElements\n */\n /**\n * @private\n * @function unselectAllElements\n */\n /**\n * @private\n * @function unfadeAllElements\n */\n /**\n * @private\n * @function unhideAllElements\n */\n Panel.prototype[`${antiverb}AllElements`] = function() {\n this.setAllElementStatus(adjective, false);\n return this;\n };\n});\n\nexport {Panel as default};\n","/** @module */\nimport * as d3 from 'd3';\n\nimport {deepCopy, merge} from '../helpers/layouts';\nimport Requester from '../data/requester';\nimport Toolbar from './toolbar';\nimport Panel from './panel';\nimport {generateCurtain, generateLoader} from '../helpers/common';\n\n/**\n * Default/ expected configuration parameters for basic plotting; most plots will override\n *\n * @protected\n * @static\n * @type {Object}\n */\nconst default_layout = {\n state: {},\n width: 1,\n height: 1,\n min_width: 1,\n min_height: 1,\n responsive_resize: false, // Allowed values: false, \"width_only\" (synonym for true)\n panels: [],\n toolbar: {\n widgets: [],\n },\n panel_boundaries: true,\n mouse_guide: true,\n};\n\n/**\n * Check that position fields (chr, start, end) are provided where appropriate, and ensure that the plot fits within\n * any constraints specified by the layout\n *\n * This function has side effects; it mutates the proposed state in order to meet certain bounds checks etc.\n * @param {Object} new_state\n * @param {Number} new_state.chr\n * @param {Number} new_state.start\n * @param {Number} new_state.end\n * @param {Object} layout\n * @returns {*|{}}\n */\nfunction _updateStatePosition(new_state, layout) {\n\n new_state = new_state || {};\n layout = layout || {};\n\n // If a \"chr\", \"start\", and \"end\" are present then resolve start and end\n // to numeric values that are not decimal, negative, or flipped\n let validated_region = false;\n if (typeof new_state.chr != 'undefined' && typeof new_state.start != 'undefined' && typeof new_state.end != 'undefined') {\n // Determine a numeric scale and midpoint for the attempted region,\n var attempted_midpoint = null; var attempted_scale;\n new_state.start = Math.max(parseInt(new_state.start), 1);\n new_state.end = Math.max(parseInt(new_state.end), 1);\n if (isNaN(new_state.start) && isNaN(new_state.end)) {\n new_state.start = 1;\n new_state.end = 1;\n attempted_midpoint = 0.5;\n attempted_scale = 0;\n } else if (isNaN(new_state.start) || isNaN(new_state.end)) {\n attempted_midpoint = new_state.start || new_state.end;\n attempted_scale = 0;\n new_state.start = (isNaN(new_state.start) ? new_state.end : new_state.start);\n new_state.end = (isNaN(new_state.end) ? new_state.start : new_state.end);\n } else {\n attempted_midpoint = Math.round((new_state.start + new_state.end) / 2);\n attempted_scale = new_state.end - new_state.start;\n if (attempted_scale < 0) {\n const temp = new_state.start;\n new_state.end = new_state.start;\n new_state.start = temp;\n attempted_scale = new_state.end - new_state.start;\n }\n if (attempted_midpoint < 0) {\n new_state.start = 1;\n new_state.end = 1;\n attempted_scale = 0;\n }\n }\n validated_region = true;\n }\n\n // Constrain w/r/t layout-defined minimum region scale\n if (!isNaN(layout.min_region_scale) && validated_region && attempted_scale < layout.min_region_scale) {\n new_state.start = Math.max(attempted_midpoint - Math.floor(layout.min_region_scale / 2), 1);\n new_state.end = new_state.start + layout.min_region_scale;\n }\n\n // Constrain w/r/t layout-defined maximum region scale\n if (!isNaN(layout.max_region_scale) && validated_region && attempted_scale > layout.max_region_scale) {\n new_state.start = Math.max(attempted_midpoint - Math.floor(layout.max_region_scale / 2), 1);\n new_state.end = new_state.start + layout.max_region_scale;\n }\n\n return new_state;\n}\n\n\nclass Plot {\n /**\n * An independent LocusZoom object that renders a unique set of data and subpanels.\n * Many such LocusZoom objects can exist simultaneously on a single page, each having its own layout.\n *\n * This creates a new plot instance, but does not immediately render it. For practical use, it may be more convenient\n * to use the `LocusZoom.populate` helper method.\n *\n * @param {String} id The ID of the plot. Often corresponds to the ID of the container element on the page\n * where the plot is rendered..\n * @param {DataSources} datasource Ensemble of data providers used by the plot\n * @param {Object} layout A JSON-serializable object of layout configuration parameters\n */\n constructor(id, datasource, layout) {\n /**\n * @private\n * @member Boolean}\n */\n this.initialized = false;\n\n /**\n * @private\n * @member {Plot}\n */\n this.parent_plot = this;\n\n /**\n * @public\n * @member {String}\n */\n this.id = id;\n\n /**\n * @private\n * @member {Element}\n */\n this.container = null;\n /**\n * Selector for a node that will contain the plot. (set externally by populate methods)\n * @private\n * @member {d3.selection}\n */\n this.svg = null;\n\n /**\n * Direct access to panel instances, keyed by panel ID. Used primarily for introspection/ development.\n * @public\n * @member {Object.}\n */\n this.panels = {};\n /**\n * TODO: This is currently used by external classes that manipulate the parent and may indicate room for a helper method in the api to coordinate boilerplate\n * @private\n * @member {String[]}\n */\n this.panel_ids_by_y_index = [];\n\n /**\n * Track update operations (reMap) performed on all child panels, and notify the parent plot when complete\n * TODO: Reconsider whether we need to be tracking this as global state outside of context of specific operations\n * @protected\n * @member {Promise[]}\n */\n this.remap_promises = [];\n\n\n /**\n * The current layout options for the plot, including the effect of any resizing events or dynamically\n * generated config produced during rendering options.\n * @public\n * @type {Object}\n */\n this.layout = layout;\n merge(this.layout, default_layout); // TODO: evaluate how the default layout is applied\n\n /**\n * Values in the layout object may change during rendering etc. Retain a copy of the original plot options\n * @protected\n * @member {Object}\n */\n this._base_layout = deepCopy(this.layout);\n\n /**\n * Create a shortcut to the state in the layout on the Plot. Tracking in the layout allows the plot to be created\n * with initial state/setup.\n *\n * Tracks state of the plot, eg start and end position\n * @public\n * @member {Object}\n */\n this.state = this.layout.state;\n\n /**\n * @private\n * @member {Requester}\n */\n this.lzd = new Requester(datasource);\n\n /**\n * Track global event listeners that are used by LZ. This allows cleanup of listeners when plot is destroyed.\n * @private\n * @member {Map}\n */\n this._window_listeners = new Map();\n\n /**\n * Known event hooks that the panel can respond to\n * @protected\n * @member {Object}\n */\n this.event_hooks = {\n 'layout_changed': [], // Many rerendering operations, including dimensions changed, element highlighted, or rerender on chanegd data. Caution: Direct layout mutations might not be captured by this event.\n 'data_requested': [], // A request has been made for new data from any data source used in the plot\n 'data_rendered': [], // Data from a request has been received and rendered in the plot\n 'element_clicked': [], // Select or unselect\n 'element_selection': [], // Element becomes active (only)\n 'match_requested': [], // A data layer is attempting to highlight matching points (internal use only)\n 'panel_removed': [], // A panel has been removed (eg via the \"x\" button in plot)\n 'region_changed': [], // The viewing region (chr/start/end) has been changed\n 'state_changed': [], // Only triggered when a state change causes rerender\n };\n\n /**\n * @callback eventCallback\n * @param {object} eventData A description of the event\n * @param {String|null} eventData.sourceID The unique identifier (eg plot or parent name) of the element that\n * triggered the event. Will be automatically filled in if not explicitly provided.\n * @param {Object|null} eventData.context Any additional information to be passed to the callback, eg the data\n * associated with a clicked plot element\n */\n\n /**\n * Event information describing interaction (e.g. panning and zooming) is stored on the plot\n * TODO: Add/ document details of interaction structure as we expand\n * @private\n * @member {{panel_id: String, linked_panel_ids: Array, x_linked: *, dragging: *, zooming: *}}\n * @returns {Plot}\n */\n this.interaction = {};\n\n // Initialize the layout\n this.initializeLayout();\n }\n\n /******* User-facing methods that allow manipulation of the plot instance: the public interface */\n\n /**\n * There are several events that a LocusZoom plot can \"emit\" when appropriate, and LocusZoom supports registering\n * \"hooks\" for these events which are essentially custom functions intended to fire at certain times.\n *\n * The following plot-level events are currently supported:\n * - `layout_changed` - context: plot - Any aspect of the plot's layout (including dimensions or state) has changed.\n * - `data_requested` - context: plot - A request for new data from any data source used in the plot has been made.\n * - `data_rendered` - context: plot - Data from a request has been received and rendered in the plot.\n * - `element_clicked` - context: plot - A data element in any of the plot's data layers has been clicked.\n * - `element_selection` - context: plot - Triggered when an element changes \"selection\" status, and identifies\n * whether the element is being selected or deselected.\n *\n * To register a hook for any of these events use `plot.on('event_name', function() {})`.\n *\n * There can be arbitrarily many functions registered to the same event. They will be executed in the order they\n * were registered. The this context bound to each event hook function is dependent on the type of event, as\n * denoted above. For example, when data_requested is emitted the context for this in the event hook will be the\n * plot itself, but when element_clicked is emitted the context for this in the event hook will be the element\n * that was clicked.\n *\n * @public\n * @param {String} event The name of an event (as defined in `event_hooks`)\n * @param {eventCallback} hook\n * @returns {function} The registered event listener\n */\n on(event, hook) {\n if (typeof 'event' != 'string' || !Array.isArray(this.event_hooks[event])) {\n throw new Error(`Unable to register event hook, invalid event: ${event.toString()}`);\n }\n if (typeof hook != 'function') {\n throw new Error('Unable to register event hook, invalid hook function passed');\n }\n this.event_hooks[event].push(hook);\n return hook;\n }\n\n /**\n * Remove one or more previously defined event listeners\n * @public\n * @param {String} event The name of an event (as defined in `event_hooks`)\n * @param {eventCallback} [hook] The callback to deregister\n * @returns {Plot}\n */\n off(event, hook) {\n const theseHooks = this.event_hooks[event];\n if (typeof 'event' != 'string' || !Array.isArray(theseHooks)) {\n throw new Error(`Unable to remove event hook, invalid event: ${event.toString()}`);\n }\n if (hook === undefined) {\n // Deregistering all hooks for this event may break basic functionality, and should only be used during\n // cleanup operations (eg to prevent memory leaks)\n this.event_hooks[event] = [];\n } else {\n const hookMatch = theseHooks.indexOf(hook);\n if (hookMatch !== -1) {\n theseHooks.splice(hookMatch, 1);\n } else {\n throw new Error('The specified event listener is not registered and therefore cannot be removed');\n }\n }\n return this;\n }\n\n /**\n * Handle running of event hooks when an event is emitted\n * @public\n * @param {string} event A known event name\n * @param {*} eventData Data or event description that will be passed to the event listener\n * @returns {Plot}\n */\n emit(event, eventData) {\n // TODO: there are small differences between the emit implementation between plots and panels. In the future,\n // DRY this code via mixins, and make sure to keep the interfaces compatible when refactoring.\n if (typeof 'event' != 'string' || !Array.isArray(this.event_hooks[event])) {\n throw new Error(`LocusZoom attempted to throw an invalid event: ${event.toString()}`);\n }\n const sourceID = this.getBaseId();\n this.event_hooks[event].forEach((hookToRun) => {\n let eventContext;\n if (eventData && eventData.sourceID) {\n // If we detect that an event originated elsewhere (via bubbling or externally), preserve the context\n // when re-emitting the event to plot-level listeners\n eventContext = eventData;\n } else {\n eventContext = {sourceID: sourceID, data: eventData || null};\n }\n // By default, any handlers fired here (either directly, or bubbled) will see the plot as the\n // value of `this`. If a bound function is registered as a handler, the previously bound `this` will\n // override anything provided to `call` below.\n hookToRun.call(this, eventContext);\n });\n return this;\n }\n\n /**\n * Create a new panel from a layout, and handle the work of initializing and placing the panel on the plot\n * @public\n * @param {Object} layout\n * @returns {Panel}\n */\n addPanel(layout) {\n // Sanity checks\n if (typeof layout !== 'object') {\n throw new Error('Invalid panel layout');\n }\n\n // Create the Panel and set its parent\n const panel = new Panel(layout, this);\n\n // Store the Panel on the Plot\n this.panels[panel.id] = panel;\n\n // If a discrete y_index was set in the layout then adjust other panel y_index values to accommodate this one\n if (panel.layout.y_index !== null && !isNaN(panel.layout.y_index)\n && this.panel_ids_by_y_index.length > 0) {\n // Negative y_index values should count backwards from the end, so convert negatives to appropriate values here\n if (panel.layout.y_index < 0) {\n panel.layout.y_index = Math.max(this.panel_ids_by_y_index.length + panel.layout.y_index, 0);\n }\n this.panel_ids_by_y_index.splice(panel.layout.y_index, 0, panel.id);\n this.applyPanelYIndexesToPanelLayouts();\n } else {\n const length = this.panel_ids_by_y_index.push(panel.id);\n this.panels[panel.id].layout.y_index = length - 1;\n }\n\n // Determine if this panel was already in the layout.panels array.\n // If it wasn't, add it. Either way store the layout.panels array index on the panel.\n let layout_idx = null;\n this.layout.panels.forEach((panel_layout, idx) => {\n if (panel_layout.id === panel.id) {\n layout_idx = idx;\n }\n });\n if (layout_idx === null) {\n layout_idx = this.layout.panels.push(this.panels[panel.id].layout) - 1;\n }\n this.panels[panel.id].layout_idx = layout_idx;\n\n // Call positionPanels() to keep panels from overlapping and ensure filling all available vertical space\n if (this.initialized) {\n this.positionPanels();\n // Initialize and load data into the new panel\n this.panels[panel.id].initialize();\n this.panels[panel.id].reMap();\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n this.setDimensions(this.layout.width, this.layout.height);\n }\n return this.panels[panel.id];\n }\n\n /**\n * Clear all state, tooltips, and other persisted data associated with one (or all) panel(s) in the plot\n *\n * This is useful when reloading an existing plot with new data, eg \"click for genome region\" links.\n * This is a utility method for custom usage. It is not fired automatically during normal rerender of existing panels\n * @public\n * @param {String} [panelId] If provided, clear state for only this panel. Otherwise, clear state for all panels.\n * @param {('wipe'|'reset')} [mode='wipe'] Optionally specify how state should be cleared. `wipe` deletes all data\n * and is useful for when the panel is being removed; `reset` is best when the panel will be reused in place.\n * @returns {Plot}\n */\n clearPanelData(panelId, mode) {\n mode = mode || 'wipe';\n\n // TODO: Add unit tests for this method\n let panelsList;\n if (panelId) {\n panelsList = [panelId];\n } else {\n panelsList = Object.keys(this.panels);\n }\n\n panelsList.forEach((pid) => {\n this.panels[pid].data_layer_ids_by_z_index.forEach((dlid) => {\n const layer = this.panels[pid].data_layers[dlid];\n layer.destroyAllTooltips();\n\n delete layer.layer_state;\n delete this.layout.state[layer.state_id];\n if (mode === 'reset') {\n layer._setDefaultState();\n }\n });\n });\n return this;\n }\n\n /**\n * Remove the panel from the plot, and clear any state, tooltips, or other visual elements belonging to nested content\n * @public\n * @param {String} id\n * @returns {Plot}\n */\n removePanel(id) {\n if (!this.panels[id]) {\n throw new Error(`Unable to remove panel, ID not found: ${id}`);\n }\n\n // Hide all panel boundaries\n this.panel_boundaries.hide();\n\n // Destroy all tooltips and state vars for all data layers on the panel\n this.clearPanelData(id);\n\n // Remove all panel-level HTML overlay elements\n this.panels[id].loader.hide();\n this.panels[id].toolbar.destroy(true);\n this.panels[id].curtain.hide();\n\n // Remove the svg container for the panel if it exists\n if (this.panels[id].svg.container) {\n this.panels[id].svg.container.remove();\n }\n\n // Delete the panel and its presence in the plot layout and state\n this.layout.panels.splice(this.panels[id].layout_idx, 1);\n delete this.panels[id];\n delete this.layout.state[id];\n\n // Update layout_idx values for all remaining panels\n this.layout.panels.forEach((panel_layout, idx) => {\n this.panels[panel_layout.id].layout_idx = idx;\n });\n\n // Remove the panel id from the y_index array\n this.panel_ids_by_y_index.splice(this.panel_ids_by_y_index.indexOf(id), 1);\n this.applyPanelYIndexesToPanelLayouts();\n\n // Call positionPanels() to keep panels from overlapping and ensure filling all available vertical space\n if (this.initialized) {\n // Allow the plot to shrink when panels are removed, by forcing it to recalculate min dimensions from scratch\n this.layout.min_height = this._base_layout.min_height;\n this.layout.min_width = this._base_layout.min_width;\n\n this.positionPanels();\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n this.setDimensions(this.layout.width, this.layout.height);\n }\n\n this.emit('panel_removed', id);\n\n return this;\n }\n\n /**\n * Refresh (or fetch) a plot's data from sources, regardless of whether position or state has changed\n * @public\n * @returns {Promise}\n */\n refresh() {\n return this.applyState();\n }\n\n /**\n * A user-defined callback function that can receive (and potentially act on) new plot data.\n * @callback externalDataCallback\n * @param {Object} new_data The body resulting from a data request. This represents the same information that would be passed to\n * a data layer making an equivalent request.\n */\n\n /**\n * A user-defined callback function that can respond to errors received during a previous operation\n * @callback externalErrorCallback\n * @param err A representation of the error that occurred\n */\n\n /**\n * Allow newly fetched data to be made available outside the LocusZoom plot. For example, a callback could be\n * registered to draw an HTML table of top GWAS hits, and update that table whenever the plot region changes.\n *\n * This is a convenience method for external hooks. It registers an event listener and returns parsed data,\n * using the same fields syntax and underlying methods as data layers.\n *\n * @public\n * @param {String[]} fields An array of field names and transforms, in the same syntax used by a data layer.\n * Different data sources should be prefixed by the source name.\n * @param {externalDataCallback} success_callback Used defined function that is automatically called any time that\n * new data is received by the plot.\n * @param {Object} [opts] Options\n * @param {externalErrorCallback} [opts.onerror] User defined function that is automatically called if a problem\n * occurs during the data request or subsequent callback operations\n * @param {boolean} [opts.discrete=false] Normally the callback will subscribe to the combined body from the chain,\n * which may not be in a format that matches what the external callback wants to do. If discrete=true, returns the\n * uncombined record info\n * @return {function} The newly created event listener, to allow for later cleanup/removal\n */\n subscribeToData(fields, success_callback, opts) {\n opts = opts || {};\n\n // Register an event listener that is notified whenever new data has been rendered\n const error_callback = opts.onerror || function (err) {\n console.log('An error occurred while acting on an external callback', err);\n };\n\n const listener = () => {\n try {\n this.lzd.getData(this.state, fields)\n .then((new_data) => success_callback(opts.discrete ? new_data.discrete : new_data.body))\n .catch(error_callback);\n } catch (error) {\n // In certain cases, errors are thrown before a promise can be generated, and LZ error display seems to rely on these errors bubbling up\n error_callback(error);\n }\n };\n this.on('data_rendered', listener);\n return listener;\n }\n\n /**\n * Update state values and trigger a pull for fresh data on all data sources for all data layers\n * @public\n * @param state_changes\n * @returns {Promise} A promise that resolves when all data fetch and update operations are complete\n */\n applyState(state_changes) {\n state_changes = state_changes || {};\n if (typeof state_changes != 'object') {\n throw new Error(`applyState only accepts an object; ${typeof state_changes} given`);\n }\n\n // Track what parameters will be modified. For bounds checking, we must take some preset values into account.\n let mods = { chr: this.state.chr, start: this.state.start, end: this.state.end };\n for (var property in state_changes) {\n mods[property] = state_changes[property];\n }\n mods = _updateStatePosition(mods, this.layout);\n\n // Apply new state to the actual state\n for (property in mods) {\n this.state[property] = mods[property];\n }\n\n // Generate requests for all panels given new state\n this.emit('data_requested');\n this.remap_promises = [];\n this.loading_data = true;\n for (let id in this.panels) {\n this.remap_promises.push(this.panels[id].reMap());\n }\n\n return Promise.all(this.remap_promises)\n .catch((error) => {\n console.error(error);\n this.curtain.show(error.message || error);\n this.loading_data = false;\n })\n .then(() => {\n // Update toolbar / widgets\n this.toolbar.update();\n\n // Apply panel-level state values\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n panel.toolbar.update();\n // Apply data-layer-level state values\n panel.data_layer_ids_by_z_index.forEach((data_layer_id) => {\n panel.data_layers[data_layer_id].applyAllElementStatus();\n });\n });\n\n // Emit events\n this.emit('layout_changed');\n this.emit('data_rendered');\n this.emit('state_changed', state_changes);\n\n // An interesting quirk of region changing in LZ: the final region is not always the same as the requested region\n // (example: zoom out beyond max, or request non-integer position)\n // Echo the actual plot region as the final source of truth\n const { chr, start, end } = this.state;\n const position_changed = Object.keys(state_changes)\n .some((key) => ['chr', 'start', 'end'].includes(key));\n\n if (position_changed) {\n this.emit('region_changed', { chr, start, end });\n }\n\n this.loading_data = false;\n\n });\n }\n\n /**\n * Keep a record of window-level event listeners used by the plot.\n * This allows safe cleanup of the plot on removal from the page\n */\n trackWindowListener(event_name, listener) {\n const tracker = this._window_listeners.get(event_name) || [];\n if (!tracker.includes(listener)) {\n tracker.push(listener);\n }\n this._window_listeners.set(event_name, tracker);\n }\n\n /**\n * Remove the plot from the page, and clean up any globally registered event listeners\n */\n destroy() {\n for (let [event_name, listeners] of this._window_listeners.entries()) {\n for (let listener of listeners) {\n window.removeEventListener(event_name, listener);\n }\n }\n // Clear the SVG, plus other HTML nodes (like toolbar) that live under the same parent\n const parent = this.svg.node().parentNode;\n if (!parent) {\n throw new Error('Plot has already been removed');\n }\n while (parent.lastElementChild) {\n parent.removeChild(parent.lastElementChild);\n }\n // Clear toolbar event listeners defined on the parent lz-container. As of 2020 this appears to be the\n // state of the art cross-browser DOM API for this task.\n // eslint-disable-next-line no-self-assign\n parent.outerHTML = parent.outerHTML;\n\n this.initialized = false;\n }\n\n /******* The private interface: methods only used by LocusZoom internals */\n /**\n * Track whether the target panel can respond to mouse interaction events\n * @private\n * @param {String} panel_id\n * @returns {boolean}\n */\n _canInteract(panel_id) {\n panel_id = panel_id || null;\n if (panel_id) {\n return ((typeof this.interaction.panel_id == 'undefined' || this.interaction.panel_id === panel_id) && !this.loading_data);\n } else {\n return !(this.interaction.dragging || this.interaction.zooming || this.loading_data);\n }\n }\n\n /**\n * Get an object with the x and y coordinates of the plot's origin in terms of the entire page\n * This returns a result with absolute position relative to the page, regardless of current scrolling\n * Necessary for positioning any HTML elements over the plot\n * @private\n * @returns {{x: Number, y: Number, width: Number, height: Number}}\n */\n _getPageOrigin() {\n const bounding_client_rect = this.svg.node().getBoundingClientRect();\n let x_offset = document.documentElement.scrollLeft || document.body.scrollLeft;\n let y_offset = document.documentElement.scrollTop || document.body.scrollTop;\n let container = this.svg.node();\n while (container.parentNode !== null) {\n // TODO: Recursively seeks offsets for highest non-static parent node. This can lead to incorrect\n // calculations of, for example, x coordinate relative to the page. Revisit this logic.\n container = container.parentNode;\n if (container !== document && d3.select(container).style('position') !== 'static') {\n x_offset = -1 * container.getBoundingClientRect().left;\n y_offset = -1 * container.getBoundingClientRect().top;\n break;\n }\n }\n return {\n x: x_offset + bounding_client_rect.left,\n y: y_offset + bounding_client_rect.top,\n width: bounding_client_rect.width,\n height: bounding_client_rect.height,\n };\n }\n\n /**\n * Get the top and left offset values for the plot's container element (the div that was populated)\n * @private\n * @returns {{top: number, left: number}}\n */\n getContainerOffset() {\n const offset = { top: 0, left: 0 };\n let container = this.container.offsetParent || null;\n while (container !== null) {\n offset.top += container.offsetTop;\n offset.left += container.offsetLeft;\n container = container.offsetParent || null;\n }\n return offset;\n }\n\n /**\n * Notify each child panel of the plot of changes in panel ordering/ arrangement\n * @private\n */\n applyPanelYIndexesToPanelLayouts () {\n this.panel_ids_by_y_index.forEach((pid, idx) => {\n this.panels[pid].layout.y_index = idx;\n });\n }\n\n /**\n * Get the qualified ID pathname for the plot\n * @private\n * @returns {String}\n */\n getBaseId () {\n return this.id;\n }\n\n /**\n * Helper method to sum the proportional dimensions of panels, a value that's checked often as panels are added/removed\n * @private\n * @param {('Height'|'Width')} dimension\n * @returns {number}\n */\n sumProportional(dimension) {\n if (dimension !== 'height' && dimension !== 'width') {\n throw new Error('Bad dimension value passed to sumProportional');\n }\n let total = 0;\n for (let id in this.panels) {\n // Ensure every panel contributing to the sum has a non-zero proportional dimension\n if (!this.panels[id].layout[`proportional_${dimension}`]) {\n this.panels[id].layout[`proportional_${dimension}`] = 1 / Object.keys(this.panels).length;\n }\n total += this.panels[id].layout[`proportional_${dimension}`];\n }\n return total;\n }\n\n /**\n * Resize the plot to fit the bounding container\n * @private\n * @returns {Plot}\n */\n rescaleSVG() {\n const clientRect = this.svg.node().getBoundingClientRect();\n this.setDimensions(clientRect.width, clientRect.height);\n return this;\n }\n\n /**\n * Prepare the plot for first use by performing parameter validation, setting up panels, and calculating dimensions\n * @private\n * @returns {Plot}\n */\n initializeLayout() {\n\n // Sanity check layout values\n if (isNaN(this.layout.width) || this.layout.width <= 0) {\n throw new Error('Plot layout parameter `width` must be a positive number');\n }\n if (isNaN(this.layout.height) || this.layout.height <= 0) {\n throw new Error('Plot layout parameter `width` must be a positive number');\n }\n\n // Backwards compatible check: there was previously a third option. Anything truthy should thus act as \"responsive_resize: true\"\n this.layout.responsive_resize = !!this.layout.responsive_resize;\n\n // If this is a responsive layout then set a namespaced/unique onresize event listener on the window\n if (this.layout.responsive_resize) {\n const resize_listener = () => this.rescaleSVG();\n window.addEventListener('resize', resize_listener);\n this.trackWindowListener('resize', resize_listener);\n\n // Forcing one additional setDimensions() call after the page is loaded clears up\n // any disagreements between the initial layout and the loaded responsive container's size\n const load_listener = () => this.setDimensions();\n window.addEventListener('load', load_listener);\n this.trackWindowListener('load', load_listener);\n }\n\n // Add panels\n this.layout.panels.forEach((panel_layout) => {\n this.addPanel(panel_layout);\n });\n\n return this;\n }\n\n /**\n * Set the dimensions for a plot, and ensure that panels are sized and positioned correctly.\n *\n * If dimensions are provided, resizes each panel proportionally to match the new plot dimensions. Otherwise,\n * calculates the appropriate plot dimensions based on all panels.\n * @private\n * @param {Number} [width] If provided and larger than minimum size, set plot to this width\n * @param {Number} [height] If provided and larger than minimum size, set plot to this height\n * @returns {Plot}\n */\n setDimensions(width, height) {\n\n let id;\n\n // Update minimum allowable width and height by aggregating minimums from panels, then apply minimums to containing element.\n let min_width = parseFloat(this.layout.min_width) || 0;\n let min_height = parseFloat(this.layout.min_height) || 0;\n for (id in this.panels) {\n min_width = Math.max(min_width, this.panels[id].layout.min_width);\n if (parseFloat(this.panels[id].layout.min_height) > 0 && parseFloat(this.panels[id].layout.proportional_height) > 0) {\n min_height = Math.max(min_height, (this.panels[id].layout.min_height / this.panels[id].layout.proportional_height));\n }\n }\n this.layout.min_width = Math.max(min_width, 1);\n this.layout.min_height = Math.max(min_height, 1);\n d3.select(this.svg.node().parentNode)\n .style('min-width', `${this.layout.min_width}px`)\n .style('min-height', `${this.layout.min_height}px`);\n\n // If width and height arguments were passed then adjust them against plot minimums if necessary.\n // Then resize the plot and proportionally resize panels to fit inside the new plot dimensions.\n if (!isNaN(width) && width >= 0 && !isNaN(height) && height >= 0) {\n this.layout.width = Math.max(Math.round(+width), this.layout.min_width);\n this.layout.height = Math.max(Math.round(+height), this.layout.min_height);\n // Override discrete values if resizing responsively\n if (this.layout.responsive_resize) {\n // All resize modes will affect width\n if (this.svg) {\n this.layout.width = Math.max(this.svg.node().parentNode.getBoundingClientRect().width, this.layout.min_width);\n }\n }\n // Resize/reposition panels to fit, update proportional origins if necessary\n let y_offset = 0;\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel_width = this.layout.width;\n const panel_height = this.panels[panel_id].layout.proportional_height * this.layout.height;\n this.panels[panel_id].setDimensions(panel_width, panel_height);\n this.panels[panel_id].setOrigin(0, y_offset);\n this.panels[panel_id].layout.proportional_origin.x = 0;\n this.panels[panel_id].layout.proportional_origin.y = y_offset / this.layout.height;\n y_offset += panel_height;\n this.panels[panel_id].toolbar.update();\n });\n } else if (Object.keys(this.panels).length) {\n // If width and height arguments were NOT passed (and panels exist) then determine the plot dimensions\n // by making it conform to panel dimensions, assuming panels are already positioned correctly.\n this.layout.width = 0;\n this.layout.height = 0;\n for (id in this.panels) {\n this.layout.width = Math.max(this.panels[id].layout.width, this.layout.width);\n this.layout.height += this.panels[id].layout.height;\n }\n this.layout.width = Math.max(this.layout.width, this.layout.min_width);\n this.layout.height = Math.max(this.layout.height, this.layout.min_height);\n }\n\n // Apply layout width and height as discrete values or viewbox values\n if (this.svg !== null) {\n // The viewBox must always be specified in order for \"save as image\" button to work\n this.svg.attr('viewBox', `0 0 ${this.layout.width} ${this.layout.height}`);\n\n if (this.layout.responsive_resize) {\n this.svg\n .attr('preserveAspectRatio', 'xMinYMin meet');\n } else {\n this.svg\n .attr('width', this.layout.width)\n .attr('height', this.layout.height);\n }\n }\n\n // If the plot has been initialized then trigger some necessary render functions\n if (this.initialized) {\n this.panel_boundaries.position();\n this.toolbar.update();\n this.curtain.update();\n this.loader.update();\n }\n\n return this.emit('layout_changed');\n }\n\n /**\n * Automatically position panels based on panel positioning rules and values.\n * Keep panels from overlapping vertically by adjusting origins, and keep the sum of proportional heights at 1.\n *\n * LocusZoom panels can only be stacked vertically (not horizontally)\n * @private\n */\n positionPanels() {\n\n let id;\n\n // We want to enforce that all x-linked panels have consistent horizontal margins\n // (to ensure that aligned items stay aligned despite inconsistent initial layout parameters)\n // NOTE: This assumes panels have consistent widths already. That should probably be enforced too!\n const x_linked_margins = { left: 0, right: 0 };\n\n // Proportional heights for newly added panels default to null unless explicitly set, so determine appropriate\n // proportional heights for all panels with a null value from discretely set dimensions.\n // Likewise handle default nulls for proportional widths, but instead just force a value of 1 (full width)\n for (id in this.panels) {\n if (this.panels[id].layout.proportional_height === null) {\n this.panels[id].layout.proportional_height = this.panels[id].layout.height / this.layout.height;\n }\n if (this.panels[id].layout.proportional_width === null) {\n this.panels[id].layout.proportional_width = 1;\n }\n if (this.panels[id].layout.interaction.x_linked) {\n x_linked_margins.left = Math.max(x_linked_margins.left, this.panels[id].layout.margin.left);\n x_linked_margins.right = Math.max(x_linked_margins.right, this.panels[id].layout.margin.right);\n }\n }\n\n // Sum the proportional heights and then adjust all proportionally so that the sum is exactly 1\n const total_proportional_height = this.sumProportional('height');\n if (!total_proportional_height) {\n return this;\n }\n const proportional_adjustment = 1 / total_proportional_height;\n for (id in this.panels) {\n this.panels[id].layout.proportional_height *= proportional_adjustment;\n }\n\n // Update origins on all panels without changing plot-level dimensions yet\n // Also apply x-linked margins to x-linked panels, updating widths as needed\n let y_offset = 0;\n this.panel_ids_by_y_index.forEach((panel_id) => {\n this.panels[panel_id].setOrigin(0, y_offset);\n this.panels[panel_id].layout.proportional_origin.x = 0;\n y_offset += this.panels[panel_id].layout.height;\n if (this.panels[panel_id].layout.interaction.x_linked) {\n const delta = Math.max(x_linked_margins.left - this.panels[panel_id].layout.margin.left, 0)\n + Math.max(x_linked_margins.right - this.panels[panel_id].layout.margin.right, 0);\n this.panels[panel_id].layout.width += delta;\n this.panels[panel_id].layout.margin.left = x_linked_margins.left;\n this.panels[panel_id].layout.margin.right = x_linked_margins.right;\n this.panels[panel_id].layout.cliparea.origin.x = x_linked_margins.left;\n }\n });\n const calculated_plot_height = y_offset;\n this.panel_ids_by_y_index.forEach((panel_id) => {\n this.panels[panel_id].layout.proportional_origin.y = this.panels[panel_id].layout.origin.y / calculated_plot_height;\n });\n\n // Update dimensions on the plot to accommodate repositioned panels\n this.setDimensions();\n\n // Set dimensions on all panels using newly set plot-level dimensions and panel-level proportional dimensions\n this.panel_ids_by_y_index.forEach((panel_id) => {\n this.panels[panel_id].setDimensions(this.layout.width * this.panels[panel_id].layout.proportional_width,\n this.layout.height * this.panels[panel_id].layout.proportional_height);\n });\n\n return this;\n\n }\n\n /**\n * Prepare the first rendering of the plot. This includes initializing the individual panels, but also creates shared\n * elements such as mouse events, panel guides/boundaries, and loader/curtain.\n * @private\n * @returns {Plot}\n */\n initialize() {\n\n // Ensure proper responsive class is present on the containing node if called for\n if (this.layout.responsive_resize) {\n d3.select(this.container).classed('lz-container-responsive', true);\n }\n\n // Create an element/layer for containing mouse guides\n if (this.layout.mouse_guide) {\n const mouse_guide_svg = this.svg.append('g')\n .attr('class', 'lz-mouse_guide')\n .attr('id', `${this.id}.mouse_guide`);\n const mouse_guide_vertical_svg = mouse_guide_svg.append('rect')\n .attr('class', 'lz-mouse_guide-vertical')\n .attr('x', -1);\n const mouse_guide_horizontal_svg = mouse_guide_svg.append('rect')\n .attr('class', 'lz-mouse_guide-horizontal')\n .attr('y', -1);\n this.mouse_guide = {\n svg: mouse_guide_svg,\n vertical: mouse_guide_vertical_svg,\n horizontal: mouse_guide_horizontal_svg,\n };\n }\n\n // Add curtain and loader prototpyes to the plot\n this.curtain = generateCurtain.call(this);\n this.loader = generateLoader.call(this);\n\n // Create the panel_boundaries object with show/position/hide methods\n this.panel_boundaries = {\n parent: this,\n hide_timeout: null,\n showing: false,\n dragging: false,\n selectors: [],\n corner_selector: null,\n show: function() {\n // Generate panel boundaries\n if (!this.showing && !this.parent.curtain.showing) {\n this.showing = true;\n // Loop through all panels to create a horizontal boundary for each\n this.parent.panel_ids_by_y_index.forEach((panel_id, panel_idx) => {\n const selector = d3.select(this.parent.svg.node().parentNode).insert('div', '.lz-data_layer-tooltip')\n .attr('class', 'lz-panel-boundary')\n .attr('title', 'Resize panel');\n selector.append('span');\n const panel_resize_drag = d3.drag();\n panel_resize_drag.on('start', () => {\n this.dragging = true;\n });\n panel_resize_drag.on('end', () => {\n this.dragging = false;\n });\n panel_resize_drag.on('drag', () => {\n // First set the dimensions on the panel we're resizing\n const this_panel = this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]];\n const original_panel_height = this_panel.layout.height;\n this_panel.setDimensions(this_panel.layout.width, this_panel.layout.height + d3.event.dy);\n const panel_height_change = this_panel.layout.height - original_panel_height;\n const new_calculated_plot_height = this.parent.layout.height + panel_height_change;\n // Next loop through all panels.\n // Update proportional dimensions for all panels including the one we've resized using discrete heights.\n // Reposition panels with a greater y-index than this panel to their appropriate new origin.\n this.parent.panel_ids_by_y_index.forEach((loop_panel_id, loop_panel_idx) => {\n const loop_panel = this.parent.panels[this.parent.panel_ids_by_y_index[loop_panel_idx]];\n loop_panel.layout.proportional_height = loop_panel.layout.height / new_calculated_plot_height;\n if (loop_panel_idx > panel_idx) {\n loop_panel.setOrigin(loop_panel.layout.origin.x, loop_panel.layout.origin.y + panel_height_change);\n loop_panel.toolbar.position();\n }\n });\n // Reset dimensions on the entire plot and reposition panel boundaries\n this.parent.positionPanels();\n this.position();\n });\n selector.call(panel_resize_drag);\n this.parent.panel_boundaries.selectors.push(selector);\n });\n // Create a corner boundary / resize element on the bottom-most panel that resizes the entire plot\n const corner_selector = d3.select(this.parent.svg.node().parentNode)\n .insert('div', '.lz-data_layer-tooltip')\n .attr('class', 'lz-panel-corner-boundary')\n .attr('title', 'Resize plot');\n\n corner_selector\n .append('span')\n .attr('class', 'lz-panel-corner-boundary-outer');\n corner_selector\n .append('span')\n .attr('class', 'lz-panel-corner-boundary-inner');\n\n const corner_drag = d3.drag();\n corner_drag.on('start', () => {\n this.dragging = true;\n });\n corner_drag.on('end', () => {\n this.dragging = false;\n });\n corner_drag.on('drag', () => {\n this.parent.setDimensions(this.layout.width + d3.event.dx, this.layout.height + d3.event.dy);\n });\n corner_selector.call(corner_drag);\n this.parent.panel_boundaries.corner_selector = corner_selector;\n }\n return this.position();\n },\n position: function() {\n if (!this.showing) {\n return this;\n }\n // Position panel boundaries\n const plot_page_origin = this.parent._getPageOrigin();\n this.selectors.forEach((selector, panel_idx) => {\n const panel_page_origin = this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]]._getPageOrigin();\n const left = plot_page_origin.x;\n const top = panel_page_origin.y + this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]].layout.height - 12;\n const width = this.parent.layout.width - 1;\n selector\n .style('top', `${top}px`)\n .style('left', `${left}px`)\n .style('width', `${width}px`);\n selector.select('span')\n .style('width', `${width}px`);\n });\n // Position corner selector\n const corner_padding = 10;\n const corner_size = 16;\n this.corner_selector\n .style('top', `${plot_page_origin.y + this.parent.layout.height - corner_padding - corner_size}px`)\n .style('left', `${plot_page_origin.x + this.parent.layout.width - corner_padding - corner_size}px`);\n return this;\n },\n hide: function() {\n if (!this.showing) {\n return this;\n }\n this.showing = false;\n // Remove panel boundaries\n this.selectors.forEach((selector) => {\n selector.remove();\n });\n this.selectors = [];\n // Remove corner boundary\n this.corner_selector.remove();\n this.corner_selector = null;\n return this;\n },\n };\n\n // Show panel boundaries stipulated by the layout (basic toggle, only show on mouse over plot)\n if (this.layout.panel_boundaries) {\n d3.select(this.svg.node().parentNode).on(`mouseover.${this.id}.panel_boundaries`, () => {\n clearTimeout(this.panel_boundaries.hide_timeout);\n this.panel_boundaries.show();\n });\n d3.select(this.svg.node().parentNode).on(`mouseout.${this.id}.panel_boundaries`, () => {\n this.panel_boundaries.hide_timeout = setTimeout(() => {\n this.panel_boundaries.hide();\n }, 300);\n });\n }\n\n // Create the toolbar object and immediately show it\n this.toolbar = new Toolbar(this).show();\n\n // Initialize all panels\n for (let id in this.panels) {\n this.panels[id].initialize();\n }\n\n // Define plot-level mouse events\n const namespace = `.${this.id}`;\n if (this.layout.mouse_guide) {\n const mouseout_mouse_guide = () => {\n this.mouse_guide.vertical.attr('x', -1);\n this.mouse_guide.horizontal.attr('y', -1);\n };\n const mousemove_mouse_guide = () => {\n const coords = d3.mouse(this.svg.node());\n this.mouse_guide.vertical.attr('x', coords[0]);\n this.mouse_guide.horizontal.attr('y', coords[1]);\n };\n this.svg\n .on(`mouseout${namespace}-mouse_guide`, mouseout_mouse_guide)\n .on(`touchleave${namespace}-mouse_guide`, mouseout_mouse_guide)\n .on(`mousemove${namespace}-mouse_guide`, mousemove_mouse_guide);\n }\n const mouseup = () => {\n this.stopDrag();\n };\n const mousemove = () => {\n if (this.interaction.dragging) {\n const coords = d3.mouse(this.svg.node());\n if (d3.event) {\n d3.event.preventDefault();\n }\n this.interaction.dragging.dragged_x = coords[0] - this.interaction.dragging.start_x;\n this.interaction.dragging.dragged_y = coords[1] - this.interaction.dragging.start_y;\n this.panels[this.interaction.panel_id].render();\n this.interaction.linked_panel_ids.forEach((panel_id) => {\n this.panels[panel_id].render();\n });\n }\n };\n this.svg\n .on(`mouseup${namespace}`, mouseup)\n .on(`touchend${namespace}`, mouseup)\n .on(`mousemove${namespace}`, mousemove)\n .on(`touchmove${namespace}`, mousemove);\n\n // Add an extra namespaced mouseup handler to the containing body, if there is one\n // This helps to stop interaction events gracefully when dragging outside of the plot element\n if (!d3.select('body').empty()) {\n d3.select('body')\n .on(`mouseup${namespace}`, mouseup)\n .on(`touchend${namespace}`, mouseup);\n }\n\n this.on('match_requested', (eventData) => {\n // Layers can broadcast that a specific point has been selected, and the plot will tell every other layer\n // to look for that value. Whenever a point is de-selected, it clears the match.\n const data = eventData.data;\n const to_send = (data.active ? data.value : null);\n this.applyState({ lz_match_value: to_send });\n });\n\n this.initialized = true;\n\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n const client_rect = this.svg.node().getBoundingClientRect();\n var width = client_rect.width ? client_rect.width : this.layout.width;\n const height = client_rect.height ? client_rect.height : this.layout.height;\n this.setDimensions(width, height);\n\n return this;\n\n }\n\n /**\n * Register interactions along the specified axis, provided that the target panel allows interaction.\n * @private\n * @param {Panel} panel\n * @param {('x_tick'|'y1_tick'|'y2_tick')} method The direction (axis) along which dragging is being performed.\n * @returns {Plot}\n */\n startDrag(panel, method) {\n panel = panel || null;\n method = method || null;\n\n let axis = null;\n switch (method) {\n case 'background':\n case 'x_tick':\n axis = 'x';\n break;\n case 'y1_tick':\n axis = 'y1';\n break;\n case 'y2_tick':\n axis = 'y2';\n break;\n }\n\n if (!(panel instanceof Panel) || !axis || !this._canInteract()) {\n return this.stopDrag();\n }\n\n const coords = d3.mouse(this.svg.node());\n this.interaction = {\n panel_id: panel.id,\n linked_panel_ids: panel.getLinkedPanelIds(axis),\n dragging: {\n method: method,\n start_x: coords[0],\n start_y: coords[1],\n dragged_x: 0,\n dragged_y: 0,\n axis: axis,\n },\n };\n\n this.svg.style('cursor', 'all-scroll');\n\n return this;\n }\n\n /**\n * Process drag interactions across the target panel and synchronize plot state across other panels in sync;\n * clear the event when complete\n * @private\n * @returns {Plot}\n */\n stopDrag() {\n\n if (!this.interaction.dragging) {\n return this;\n }\n\n if (typeof this.panels[this.interaction.panel_id] != 'object') {\n this.interaction = {};\n return this;\n }\n const panel = this.panels[this.interaction.panel_id];\n\n // Helper function to find the appropriate axis layouts on child data layers\n // Once found, apply the extent as floor/ceiling and remove all other directives\n // This forces all associated axes to conform to the extent generated by a drag action\n const overrideAxisLayout = (axis, axis_number, extent) => {\n panel.data_layer_ids_by_z_index.forEach((id) => {\n const axis_layout = panel.data_layers[id].layout[`${axis}_axis`];\n if (axis_layout.axis === axis_number) {\n axis_layout.floor = extent[0];\n axis_layout.ceiling = extent[1];\n delete axis_layout.lower_buffer;\n delete axis_layout.upper_buffer;\n delete axis_layout.min_extent;\n delete axis_layout.ticks;\n }\n });\n };\n\n switch (this.interaction.dragging.method) {\n case 'background':\n case 'x_tick':\n if (this.interaction.dragging.dragged_x !== 0) {\n overrideAxisLayout('x', 1, panel.x_extent);\n this.applyState({ start: panel.x_extent[0], end: panel.x_extent[1] });\n }\n break;\n case 'y1_tick':\n case 'y2_tick':\n if (this.interaction.dragging.dragged_y !== 0) {\n // TODO: Hardcoded assumption of only two possible axes with single-digit #s (switch/case)\n const y_axis_number = parseInt(this.interaction.dragging.method[1]);\n overrideAxisLayout('y', y_axis_number, panel[`y${y_axis_number}_extent`]);\n }\n break;\n }\n\n this.interaction = {};\n this.svg.style('cursor', null);\n\n return this;\n\n }\n}\n\nexport {Plot as default};\n\n// Only for testing\nexport { _updateStatePosition };\n","/** @module */\nimport * as d3 from 'd3';\n\nimport Field from '../data/field';\nimport Plot from '../components/plot';\nimport {applyStyles} from './common';\n\n\n/**\n * Convert an integer chromosome position to an SI string representation (e.g. 23423456 => \"23.42\" (Mb))\n * @param {Number} pos Position\n * @param {Number} [exp] Exponent to use for the returned string, eg 6=> MB. If not specified, will attempt to guess\n * the most appropriate SI prefix based on the number provided.\n * @param {Boolean} [suffix=false] Whether or not to append a suffix (e.g. \"Mb\") to the end of the returned string\n * @returns {string}\n */\nfunction positionIntToString(pos, exp, suffix) {\n const exp_symbols = { 0: '', 3: 'K', 6: 'M', 9: 'G' };\n suffix = suffix || false;\n if (isNaN(exp) || exp === null) {\n const log = Math.log(pos) / Math.LN10;\n exp = Math.min(Math.max(log - (log % 3), 0), 9);\n }\n const places_exp = exp - Math.floor((Math.log(pos) / Math.LN10).toFixed(exp + 3));\n const min_exp = Math.min(Math.max(exp, 0), 2);\n const places = Math.min(Math.max(places_exp, min_exp), 12);\n let ret = `${(pos / Math.pow(10, exp)).toFixed(places)}`;\n if (suffix && typeof exp_symbols[exp] !== 'undefined') {\n ret += ` ${exp_symbols[exp]}b`;\n }\n return ret;\n}\n\n/**\n * Convert an SI string chromosome position to an integer representation (e.g. \"5.8 Mb\" => 58000000)\n * @param {String} p The chromosome position\n * @returns {Number}\n */\nfunction positionStringToInt(p) {\n let val = p.toUpperCase();\n val = val.replace(/,/g, '');\n const suffixre = /([KMG])[B]*$/;\n const suffix = suffixre.exec(val);\n let mult = 1;\n if (suffix) {\n if (suffix[1] === 'M') {\n mult = 1e6;\n } else if (suffix[1] === 'G') {\n mult = 1e9;\n } else {\n mult = 1e3; //K\n }\n val = val.replace(suffixre, '');\n }\n val = Number(val) * mult;\n return val;\n}\n\n/**\n * Generate a \"pretty\" set of ticks (multiples of 1, 2, or 5 on the same order of magnitude for the range)\n * Based on R's \"pretty\" function: https://github.com/wch/r-source/blob/b156e3a711967f58131e23c1b1dc1ea90e2f0c43/src/appl/pretty.c\n * @param {Number[]} range A two-item array specifying [low, high] values for the axis range\n * @param {('low'|'high'|'both'|'neither')} [clip_range='neither'] What to do if first and last generated ticks extend\n * beyond the range. Set this to \"low\", \"high\", \"both\", or \"neither\" to clip the first (low) or last (high) tick to\n * be inside the range or allow them to extend beyond.\n * e.g. \"low\" will clip the first (low) tick if it extends beyond the low end of the range but allow the\n * last (high) tick to extend beyond the range. \"both\" clips both ends, \"neither\" allows both to extend beyond.\n * @param {Number} [target_tick_count=5] The approximate number of ticks you would like to be returned; may not be exact\n * @returns {Number[]}\n */\nfunction prettyTicks(range, clip_range, target_tick_count) {\n if (typeof target_tick_count == 'undefined' || isNaN(parseInt(target_tick_count))) {\n target_tick_count = 5;\n }\n target_tick_count = +target_tick_count;\n\n const min_n = target_tick_count / 3;\n const shrink_sml = 0.75;\n const high_u_bias = 1.5;\n const u5_bias = 0.5 + 1.5 * high_u_bias;\n\n const d = Math.abs(range[0] - range[1]);\n let c = d / target_tick_count;\n if ((Math.log(d) / Math.LN10) < -2) {\n c = (Math.max(Math.abs(d)) * shrink_sml) / min_n;\n }\n\n const base = Math.pow(10, Math.floor(Math.log(c) / Math.LN10));\n let base_toFixed = 0;\n if (base < 1 && base !== 0) {\n base_toFixed = Math.abs(Math.round(Math.log(base) / Math.LN10));\n }\n\n let unit = base;\n if ( ((2 * base) - c) < (high_u_bias * (c - unit)) ) {\n unit = 2 * base;\n if ( ((5 * base) - c) < (u5_bias * (c - unit)) ) {\n unit = 5 * base;\n if ( ((10 * base) - c) < (high_u_bias * (c - unit)) ) {\n unit = 10 * base;\n }\n }\n }\n\n let ticks = [];\n let i = parseFloat((Math.floor(range[0] / unit) * unit).toFixed(base_toFixed));\n while (i < range[1]) {\n ticks.push(i);\n i += unit;\n if (base_toFixed > 0) {\n i = parseFloat(i.toFixed(base_toFixed));\n }\n }\n ticks.push(i);\n\n if (typeof clip_range == 'undefined' || ['low', 'high', 'both', 'neither'].indexOf(clip_range) === -1) {\n clip_range = 'neither';\n }\n if (clip_range === 'low' || clip_range === 'both') {\n if (ticks[0] < range[0]) {\n ticks = ticks.slice(1);\n }\n }\n if (clip_range === 'high' || clip_range === 'both') {\n if (ticks[ticks.length - 1] > range[1]) {\n ticks.pop();\n }\n }\n\n return ticks;\n}\n\n/**\n * Replace placeholders in an html string with field values defined in a data object\n * Only works on scalar values in data! Will ignore non-scalars. This is useful in, eg, tooltip templates.\n *\n * NOTE: Trusts content exactly as given. XSS prevention is the responsibility of the implementer.\n * @param {Object} data\n * @param {String} html A placeholder string in which to substitute fields. Supports several template options:\n * `{{field_name}}` is a variable placeholder for the value of `field_name` from the provided data\n * `{{#if field_name}} Conditional text {{/if}}` will insert the contents of the tag only if the value exists.\n * Since this is only an existence check, **variables with a value of 0 will be evaluated as true**.\n * This can be used with namespaced values, `{{#if assoc:field}}`; any dynamic namespacing will be applied when the\n * layout is first retrieved.\n * @returns {string}\n */\nfunction parseFields(data, html) {\n if (typeof data != 'object') {\n throw new Error('invalid arguments: data is not an object');\n }\n if (typeof html != 'string') {\n throw new Error('invalid arguments: html is not a string');\n }\n // `tokens` is like [token,...]\n // `token` is like {text: '...'} or {variable: 'foo|bar'} or {condition: 'foo|bar'} or {close: 'if'}\n const tokens = [];\n const regex = /{{(?:(#if )?([A-Za-z0-9_:|]+)|(\\/if))}}/;\n while (html.length > 0) {\n const m = regex.exec(html);\n if (!m) {\n tokens.push({text: html}); html = '';\n } else if (m.index !== 0) {\n tokens.push({text: html.slice(0, m.index)}); html = html.slice(m.index);\n } else if (m[1] === '#if ') {\n tokens.push({condition: m[2]}); html = html.slice(m[0].length);\n } else if (m[2]) {\n tokens.push({variable: m[2]}); html = html.slice(m[0].length);\n } else if (m[3] === '/if') {\n tokens.push({close: 'if'}); html = html.slice(m[0].length);\n } else {\n console.error(`Error tokenizing tooltip when remaining template is ${JSON.stringify(html)} and previous tokens are ${JSON.stringify(tokens)} and current regex match is ${JSON.stringify([m[1], m[2], m[3]])}`);\n html = html.slice(m[0].length);\n }\n }\n const astify = function () {\n const token = tokens.shift();\n if (typeof token.text !== 'undefined' || token.variable) {\n return token;\n } else if (token.condition) {\n token.then = [];\n while (tokens.length > 0) {\n if (tokens[0].close === 'if') {\n tokens.shift();\n break;\n }\n token.then.push(astify());\n }\n return token;\n } else {\n console.error(`Error making tooltip AST due to unknown token ${JSON.stringify(token)}`);\n return { text: '' };\n }\n };\n // `ast` is like [thing,...]\n // `thing` is like {text: \"...\"} or {variable:\"foo|bar\"} or {condition: \"foo|bar\", then:[thing,...]}\n const ast = [];\n while (tokens.length > 0) {\n ast.push(astify());\n }\n\n const resolve = function (variable) {\n if (!Object.prototype.hasOwnProperty.call(resolve.cache, variable)) {\n resolve.cache[variable] = (new Field(variable)).resolve(data);\n }\n return resolve.cache[variable];\n };\n resolve.cache = {};\n const render_node = function (node) {\n if (typeof node.text !== 'undefined') {\n return node.text;\n } else if (node.variable) {\n try {\n const value = resolve(node.variable);\n if (['string', 'number', 'boolean'].indexOf(typeof value) !== -1) {\n return value;\n }\n if (value === null) {\n return '';\n }\n } catch (error) {\n console.error(`Error while processing variable ${JSON.stringify(node.variable)}`);\n }\n return `{{${node.variable}}}`;\n } else if (node.condition) {\n try {\n const condition = resolve(node.condition);\n if (condition || condition === 0) {\n return node.then.map(render_node).join('');\n }\n } catch (error) {\n console.error(`Error while processing condition ${JSON.stringify(node.variable)}`);\n }\n return '';\n } else {\n console.error(`Error rendering tooltip due to unknown AST node ${JSON.stringify(node)}`);\n }\n };\n return ast.map(render_node).join('');\n}\n\n/**\n * Populate a single element with a LocusZoom plot. This is the primary means of generating a new plot, and is part\n * of the public interface for LocusZoom.\n * @public\n * @param {String|d3.selection} selector CSS selector for the container element where the plot will be mounted. Any pre-existing\n * content in the container will be completely replaced.\n * @param {DataSources} datasource Ensemble of data providers used by the plot\n * @param {Object} layout A JSON-serializable object of layout configuration parameters\n * @returns {Plot} The newly created plot instance\n */\nfunction populate(selector, datasource, layout) {\n if (typeof selector == 'undefined') {\n throw new Error('LocusZoom.populate selector not defined');\n }\n // Empty the selector of any existing content\n d3.select(selector).html('');\n let plot;\n d3.select(selector).call(function(target) {\n // Require each containing element have an ID. If one isn't present, create one.\n if (typeof target.node().id == 'undefined') {\n let iterator = 0;\n while (!d3.select(`#lz-${iterator}`).empty()) {\n iterator++;\n }\n target.attr('id', `#lz-${iterator}`);\n }\n // Create the plot\n plot = new Plot(target.node().id, datasource, layout);\n plot.container = target.node();\n // Detect HTML `data-region` attribute, and use it to fill in state values if present\n if (typeof target.node().dataset !== 'undefined' && typeof target.node().dataset.region !== 'undefined') {\n const parsed_state = parsePositionQuery(target.node().dataset.region);\n Object.keys(parsed_state).forEach(function(key) {\n plot.state[key] = parsed_state[key];\n });\n }\n // Add an SVG to the div and set its dimensions\n plot.svg = d3.select(`div#${plot.id}`)\n .append('svg')\n .attr('version', '1.1')\n .attr('xmlns', 'http://www.w3.org/2000/svg')\n .attr('id', `${plot.id}_svg`)\n .attr('class', 'lz-locuszoom')\n .call(applyStyles, plot.layout.style);\n\n plot.setDimensions();\n plot.positionPanels();\n // Initialize the plot\n plot.initialize();\n // If the plot has defined data sources then trigger its first mapping based on state values\n if (datasource) {\n plot.refresh();\n }\n });\n return plot;\n}\n\n/**\n * Parse region queries into their constituent parts\n * @param {String} x A chromosome position query. May be any of the forms `chr:start-end`, `chr:center+offset`,\n * or `chr:pos`\n * @returns {{chr:*, start: *, end:*} | {chr:*, position:*}}\n */\nfunction parsePositionQuery(x) {\n const chrposoff = /^(\\w+):([\\d,.]+[kmgbKMGB]*)([-+])([\\d,.]+[kmgbKMGB]*)$/;\n const chrpos = /^(\\w+):([\\d,.]+[kmgbKMGB]*)$/;\n let match = chrposoff.exec(x);\n if (match) {\n if (match[3] === '+') {\n const center = positionStringToInt(match[2]);\n const offset = positionStringToInt(match[4]);\n return {\n chr:match[1],\n start: center - offset,\n end: center + offset,\n };\n } else {\n return {\n chr: match[1],\n start: positionStringToInt(match[2]),\n end: positionStringToInt(match[4]),\n };\n }\n }\n match = chrpos.exec(x);\n if (match) {\n return {\n chr:match[1],\n position: positionStringToInt(match[2]),\n };\n }\n return null;\n}\n\nexport { parseFields, parsePositionQuery, populate, positionIntToString, positionStringToInt, prettyTicks };\n","/**\n * A registry of known data sources. Can be used to find sources by name, either from predefined\n * classes, or plugins.\n * @module\n * @private\n */\nimport {ClassRegistry} from './base';\n\nimport * as adapters from '../data/adapters';\n\n\n// KnownDataSources is a basic registry with no special behavior.\nconst registry = new ClassRegistry();\n\nfor (let [name, type] of Object.entries(adapters)) {\n registry.add(name, type);\n}\n\n// Add some hard-coded aliases for backwards compatibility\nregistry.add('StaticJSON', adapters.StaticSource);\nregistry.add('LDLZ2', adapters.LDServer);\n\n\nexport default registry;\n","/**\n * Predefined base layouts used to populate the LZ registry\n * @module\n * @private\n */\n\nimport { version } from '../../package.json';\nimport {deepCopy, merge} from '../helpers/layouts';\n\nconst LZ_SIG_THRESHOLD_LOGP = 7.301; // -log10(.05/1e6)\n\n/**\n * Tooltip Layouts\n */\nconst standard_association_tooltip = {\n namespace: { 'assoc': 'assoc' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: `{{{{namespace[assoc]}}variant|htmlescape}}
\n P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
\n Ref. Allele: {{{{namespace[assoc]}}ref_allele|htmlescape}}
\n Make LD Reference
`,\n};\n\nconst standard_association_tooltip_with_label = function() {\n // Add a special \"toggle label\" button to the base tooltip. This must be used in tandem with a custom layout\n // directive (label.filters should check a boolean annotation field called \"lz_show_label\").\n const base = deepCopy(standard_association_tooltip);\n base.html += `Toggle label`;\n return base;\n}();\n\nconst standard_genes_tooltip = {\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '

{{gene_name|htmlescape}}

'\n + 'Gene ID: {{gene_id|htmlescape}}
'\n + 'Transcript ID: {{transcript_id|htmlescape}}
'\n + '{{#if pLI}}'\n + ''\n + ''\n + ''\n + ''\n + '
ConstraintExpected variantsObserved variantsConst. Metric
Synonymous{{exp_syn}}{{obs_syn}}z = {{syn_z}}
o/e = {{oe_syn}} ({{oe_syn_lower}} - {{oe_syn_upper}})
Missense{{exp_mis}}{{obs_mis}}z = {{mis_z}}
o/e = {{oe_mis}} ({{oe_mis_lower}} - {{oe_mis_upper}})
pLoF{{exp_lof}}{{obs_lof}}pLI = {{pLI}}
o/e = {{oe_lof}} ({{oe_lof_lower}} - {{oe_lof_upper}})

{{/if}}'\n + 'More data on gnomAD',\n};\n\nconst catalog_variant_tooltip = {\n namespace: { 'assoc': 'assoc', 'catalog': 'catalog' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{{{namespace[catalog]}}variant|htmlescape}}
'\n + 'Catalog entries: {{n_catalog_matches|htmlescape}}
'\n + 'Top Trait: {{{{namespace[catalog]}}trait|htmlescape}}
'\n + 'Top P Value: {{{{namespace[catalog]}}log_pvalue|logtoscinotation}}
'\n // User note: if a different catalog is used, the tooltip will need to be replaced with a different link URL\n + 'More: GWAS catalog / dbSNP',\n};\n\nconst coaccessibility_tooltip = {\n namespace: { 'access': 'access' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n // TODO: Is there a more generic terminology? (eg not every technique is in terms of cis-regulatory element)\n html: 'Regulatory element
' +\n '{{{{namespace[access]}}start1|htmlescape}}-{{{{namespace[access]}}end1|htmlescape}}
' +\n 'Promoter
' +\n '{{{{namespace[access]}}start2|htmlescape}}-{{{{namespace[access]}}end2|htmlescape}}
' +\n '{{#if {{namespace[access]}}target}}Target: {{{{namespace[access]}}target|htmlescape}}
{{/if}}' +\n 'Score: {{{{namespace[access]}}score|htmlescape}}',\n};\n\n/**\n * Data Layer Layouts: represent specific information from a data source\n */\n\nconst significance_layer = {\n id: 'significance',\n type: 'orthogonal_line',\n orientation: 'horizontal',\n offset: LZ_SIG_THRESHOLD_LOGP,\n};\n\nconst recomb_rate_layer = {\n namespace: { 'recomb': 'recomb' },\n id: 'recombrate',\n type: 'line',\n fields: ['{{namespace[recomb]}}position', '{{namespace[recomb]}}recomb_rate'],\n z_index: 1,\n style: {\n 'stroke': '#0000FF',\n 'stroke-width': '1.5px',\n },\n x_axis: {\n field: '{{namespace[recomb]}}position',\n },\n y_axis: {\n axis: 2,\n field: '{{namespace[recomb]}}recomb_rate',\n floor: 0,\n ceiling: 100,\n },\n};\n\nconst association_pvalues_layer = {\n namespace: { 'assoc': 'assoc', 'ld': 'ld' },\n id: 'associationpvalues',\n type: 'scatter',\n point_shape: {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: 'diamond',\n else: 'circle',\n },\n },\n point_size: {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: 80,\n else: 40,\n },\n },\n color: [\n {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: '#9632b8',\n },\n },\n {\n scale_function: 'numerical_bin',\n field: '{{namespace[ld]}}state',\n parameters: {\n breaks: [0, 0.2, 0.4, 0.6, 0.8],\n values: ['#357ebd', '#46b8da', '#5cb85c', '#eea236', '#d43f3a'],\n },\n },\n '#B8B8B8',\n ],\n legend: [\n { shape: 'diamond', color: '#9632b8', size: 40, label: 'LD Ref Var', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#d43f3a', size: 40, label: '1.0 > r² ≥ 0.8', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#eea236', size: 40, label: '0.8 > r² ≥ 0.6', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#5cb85c', size: 40, label: '0.6 > r² ≥ 0.4', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#46b8da', size: 40, label: '0.4 > r² ≥ 0.2', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#357ebd', size: 40, label: '0.2 > r² ≥ 0.0', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#B8B8B8', size: 40, label: 'no r² data', class: 'lz-data_layer-scatter' },\n ],\n label: null,\n fields: ['{{namespace[assoc]}}variant', '{{namespace[assoc]}}position', '{{namespace[assoc]}}log_pvalue', '{{namespace[assoc]}}log_pvalue|logtoscinotation', '{{namespace[assoc]}}ref_allele', '{{namespace[ld]}}state', '{{namespace[ld]}}isrefvar'],\n id_field: '{{namespace[assoc]}}variant',\n z_index: 2,\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[assoc]}}log_pvalue',\n floor: 0,\n upper_buffer: 0.10,\n min_extent: [0, 10],\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: deepCopy(standard_association_tooltip),\n};\n\nconst coaccessibility_layer = {\n namespace: { 'access': 'access' },\n id: 'coaccessibility',\n type: 'arcs',\n fields: ['{{namespace[access]}}start1', '{{namespace[access]}}end1', '{{namespace[access]}}start2', '{{namespace[access]}}end2', '{{namespace[access]}}id', '{{namespace[access]}}target', '{{namespace[access]}}score'],\n match: { send: '{{namespace[access]}}target', receive: '{{namespace[access]}}target' },\n id_field: '{{namespace[access]}}id',\n filters: [\n ['{{namespace[access]}}score', '!=', null],\n // ['{{namespace[access]}}score', '>', 0.5], // Potentially useful but very situational\n ],\n color: [\n {\n field: 'lz_highlight_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#ff0000',\n },\n },\n {\n field: 'lz_highlight_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: false,\n then: '#EAE6E6',\n },\n },\n {\n scale_function: 'ordinal_cycle',\n parameters: {\n values: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'], // Drawn from d3v3 \"category20\"\n },\n },\n ],\n x_axis: {\n field1: '{{namespace[access]}}start1',\n field2: '{{namespace[access]}}start2',\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[access]}}score',\n upper_buffer: 0.1,\n min_extent: [0, 1],\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: deepCopy(coaccessibility_tooltip),\n};\n\nconst association_pvalues_catalog_layer = function () {\n // Slightly modify an existing layout\n let base = deepCopy(association_pvalues_layer);\n base = merge({ id: 'associationpvaluescatalog', fill_opacity: 0.7}, base);\n base.tooltip.html += '{{#if {{namespace[catalog]}}rsid}}
See hits in GWAS catalog{{/if}}';\n base.namespace.catalog = 'catalog';\n base.fields.push('{{namespace[catalog]}}rsid', '{{namespace[catalog]}}trait', '{{namespace[catalog]}}log_pvalue');\n return base;\n}();\n\nconst phewas_pvalues_layer = {\n namespace: { 'phewas': 'phewas' },\n id: 'phewaspvalues',\n type: 'category_scatter',\n point_shape: 'circle',\n point_size: 70,\n tooltip_positioning: 'vertical',\n id_field: '{{namespace[phewas]}}id',\n fields: ['{{namespace[phewas]}}id', '{{namespace[phewas]}}log_pvalue', '{{namespace[phewas]}}trait_group', '{{namespace[phewas]}}trait_label'],\n x_axis: {\n field: '{{namespace[phewas]}}x', // Synthetic/derived field added by `category_scatter` layer\n category_field: '{{namespace[phewas]}}trait_group',\n lower_buffer: 0.025,\n upper_buffer: 0.025,\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[phewas]}}log_pvalue',\n floor: 0,\n upper_buffer: 0.15,\n },\n color: [{\n field: '{{namespace[phewas]}}trait_group',\n scale_function: 'categorical_bin',\n parameters: {\n categories: [],\n values: [],\n null_value: '#B8B8B8',\n },\n }],\n fill_opacity: 0.7,\n tooltip: {\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: [\n 'Trait: {{{{namespace[phewas]}}trait_label|htmlescape}}
',\n 'Trait Category: {{{{namespace[phewas]}}trait_group|htmlescape}}
',\n 'P-value: {{{{namespace[phewas]}}log_pvalue|logtoscinotation|htmlescape}}
',\n ].join(''),\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n label: {\n text: '{{{{namespace[phewas]}}trait_label|htmlescape}}',\n spacing: 6,\n lines: {\n style: {\n 'stroke-width': '2px',\n 'stroke': '#333333',\n 'stroke-dasharray': '2px 2px',\n },\n },\n filters: [\n {\n field: '{{namespace[phewas]}}log_pvalue',\n operator: '>=',\n value: 20,\n },\n ],\n style: {\n 'font-size': '14px',\n 'font-weight': 'bold',\n 'fill': '#333333',\n },\n },\n};\n\nconst genes_layer = {\n namespace: { 'gene': 'gene', 'constraint': 'constraint' },\n id: 'genes',\n type: 'genes',\n fields: ['{{namespace[gene]}}all', '{{namespace[constraint]}}all'],\n id_field: 'gene_id',\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: deepCopy(standard_genes_tooltip),\n};\n\nconst annotation_catalog_layer = {\n // Identify GWAS hits that are present in the GWAS catalog\n namespace: { 'assoc': 'assoc', 'catalog': 'catalog' },\n id: 'annotation_catalog',\n type: 'annotation_track',\n id_field: '{{namespace[catalog]}}variant',\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n color: '#0000CC',\n fields: [\n '{{namespace[assoc]}}variant', '{{namespace[assoc]}}chromosome', '{{namespace[assoc]}}position',\n '{{namespace[catalog]}}variant', '{{namespace[catalog]}}rsid', '{{namespace[catalog]}}trait',\n '{{namespace[catalog]}}log_pvalue', '{{namespace[catalog]}}pos',\n ],\n filters: [\n // Specify which points to show on the track. Any selection must satisfy ALL filters\n ['{{namespace[catalog]}}rsid', '!=', null],\n ['{{namespace[catalog]}}log_pvalue', '>', LZ_SIG_THRESHOLD_LOGP],\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: deepCopy(catalog_variant_tooltip),\n tooltip_positioning: 'top',\n};\n\n/**\n * Individual toolbar buttons\n */\nconst ldlz2_pop_selector_menu = {\n // **Note**: this widget is aimed at the LDServer datasource, and the UM 1000G LDServer\n type: 'set_state',\n position: 'right',\n color: 'blue',\n button_html: 'LD Population: ',\n show_selected: true,\n button_title: 'Select LD Population: ',\n state_field: 'ld_pop',\n // This list below is hardcoded to work with the UMich LDServer, default 1000G populations\n // It can be customized to work with other LD servers that specify population differently\n // https://portaldev.sph.umich.edu/ld/genome_builds/GRCh37/references/1000G/populations\n options: [\n { display_name: 'ALL (default)', value: 'ALL' },\n { display_name: 'AFR', value: 'AFR' },\n { display_name: 'AMR', value: 'AMR' },\n { display_name: 'EAS', value: 'EAS' },\n { display_name: 'EUR', value: 'EUR' },\n { display_name: 'SAS', value: 'SAS' },\n ],\n};\n\n/**\n * Toolbar Layouts: Collections of toolbar buttons etc\n */\nconst standard_panel_toolbar = {\n widgets: [\n {\n type: 'remove_panel',\n position: 'right',\n color: 'red',\n group_position: 'end',\n },\n {\n type: 'move_panel_up',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'move_panel_down',\n position: 'right',\n group_position: 'start',\n style: { 'margin-left': '0.75em' },\n },\n ],\n};\n\nconst standard_plot_toolbar = {\n // Suitable for most any type of plot drawn with LZ\n widgets: [\n {\n type: 'title',\n title: 'LocusZoom',\n subtitle: `v${version}`,\n position: 'left',\n },\n {\n type: 'download',\n position: 'right',\n },\n {\n type: 'download_png',\n position: 'right',\n },\n ],\n};\n\nconst region_nav_plot_toolbar = function () {\n // Useful for most region-based plots\n const region_nav_plot_toolbar = deepCopy(standard_plot_toolbar);\n region_nav_plot_toolbar.widgets.push(\n deepCopy(ldlz2_pop_selector_menu),\n {\n type: 'shift_region',\n step: 500000,\n button_html: '>>',\n position: 'right',\n group_position: 'end',\n }, {\n type: 'shift_region',\n step: 50000,\n button_html: '>',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'zoom_region',\n step: 0.2,\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'zoom_region',\n step: -0.2,\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'shift_region',\n step: -50000,\n button_html: '<',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'shift_region',\n step: -500000,\n button_html: '<<',\n position: 'right',\n group_position: 'start',\n }\n );\n return region_nav_plot_toolbar;\n}();\n\n/**\n * Panel Layouts\n */\n\nconst association_panel = {\n id: 'association',\n width: 800,\n height: 225,\n min_width: 400,\n min_height: 200,\n proportional_width: 1,\n margin: { top: 35, right: 50, bottom: 40, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: (function () {\n const base = deepCopy(standard_panel_toolbar);\n base.widgets.push({\n type: 'toggle_legend',\n position: 'right',\n });\n return base;\n })(),\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: '-log10 p-value',\n label_offset: 28,\n },\n y2: {\n label: 'Recombination Rate (cM/Mb)',\n label_offset: 40,\n },\n },\n legend: {\n orientation: 'vertical',\n origin: { x: 55, y: 40 },\n hidden: true,\n },\n interaction: {\n drag_background_to_pan: true,\n drag_x_ticks_to_scale: true,\n drag_y1_ticks_to_scale: true,\n drag_y2_ticks_to_scale: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(significance_layer),\n deepCopy(recomb_rate_layer),\n deepCopy(association_pvalues_layer),\n ],\n};\n\nconst coaccessibility_panel = {\n id: 'coaccessibility',\n width: 800,\n height: 225,\n min_width: 400,\n min_height: 100,\n proportional_width: 1,\n margin: { top: 35, right: 50, bottom: 40, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: deepCopy(standard_panel_toolbar),\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: 'Score',\n label_offset: 28,\n render: false, // We are mainly concerned with the relative magnitudes: hide y axis to avoid clutter.\n },\n },\n interaction: {\n drag_background_to_pan: true,\n drag_x_ticks_to_scale: true,\n drag_y1_ticks_to_scale: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(coaccessibility_layer),\n ],\n};\n\nconst association_catalog_panel = function () {\n let base = deepCopy(association_panel);\n base = merge({\n id: 'associationcatalog',\n namespace: { 'assoc': 'assoc', 'ld': 'ld', 'catalog': 'catalog' }, // Required to resolve display options\n }, base);\n\n base.toolbar.widgets.push({\n type: 'display_options',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Display options...',\n button_title: 'Control how plot items are displayed',\n\n layer_name: 'associationpvaluescatalog',\n default_config_display_name: 'No catalog labels (default)', // display name for the default plot color option (allow user to revert to plot defaults)\n\n options: [\n {\n // First dropdown menu item\n display_name: 'Label catalog traits', // Human readable representation of field name\n display: { // Specify layout directives that control display of the plot for this option\n label: {\n text: '{{{{namespace[catalog]}}trait|htmlescape}}',\n spacing: 6,\n lines: {\n style: {\n 'stroke-width': '2px',\n 'stroke': '#333333',\n 'stroke-dasharray': '2px 2px',\n },\n },\n filters: [\n // Only label points if they are significant for some trait in the catalog, AND in high LD\n // with the top hit of interest\n {\n field: '{{namespace[catalog]}}trait',\n operator: '!=',\n value: null,\n },\n {\n field: '{{namespace[catalog]}}log_pvalue',\n operator: '>',\n value: LZ_SIG_THRESHOLD_LOGP,\n },\n {\n field: '{{namespace[ld]}}state',\n operator: '>',\n value: 0.4,\n },\n ],\n style: {\n 'font-size': '10px',\n 'font-weight': 'bold',\n 'fill': '#333333',\n },\n },\n },\n },\n ],\n });\n base.data_layers = [\n deepCopy(significance_layer),\n deepCopy(recomb_rate_layer),\n deepCopy(association_pvalues_catalog_layer),\n ];\n return base;\n}();\n\nconst genes_panel = {\n id: 'genes',\n width: 800,\n height: 225,\n min_width: 400,\n min_height: 112.5,\n proportional_width: 1,\n margin: { top: 20, right: 50, bottom: 20, left: 50 },\n axes: {},\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n toolbar: (function () {\n const base = deepCopy(standard_panel_toolbar);\n base.widgets.push({\n type: 'resize_to_data',\n position: 'right',\n button_html: 'Show all genes',\n });\n return base;\n })(),\n data_layers: [\n deepCopy(genes_layer),\n ],\n};\n\nconst phewas_panel = {\n id: 'phewas',\n width: 800,\n height: 300,\n min_width: 800,\n min_height: 300,\n proportional_width: 1,\n margin: { top: 20, right: 50, bottom: 120, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n axes: {\n x: {\n ticks: { // Object based config (shared defaults; allow layers to specify ticks)\n style: {\n 'font-weight': 'bold',\n 'font-size': '11px',\n 'text-anchor': 'start',\n },\n transform: 'rotate(50)',\n position: 'left', // Special param recognized by `category_scatter` layers\n },\n },\n y1: {\n label: '-log10 p-value',\n label_offset: 28,\n },\n },\n data_layers: [\n deepCopy(significance_layer),\n deepCopy(phewas_pvalues_layer),\n ],\n};\n\nconst annotation_catalog_panel = {\n id: 'annotationcatalog',\n width: 800,\n height: 45,\n min_height: 45,\n proportional_width: 1,\n margin: { top: 25, right: 50, bottom: 0, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: deepCopy(standard_panel_toolbar),\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(annotation_catalog_layer),\n ],\n};\n\n/**\n * Plot Layouts\n */\n\nconst standard_association_plot = {\n state: {},\n width: 800,\n height: 450,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: deepCopy(region_nav_plot_toolbar),\n panels: [\n merge({ proportional_height: 0.5}, deepCopy(association_panel)),\n merge({ proportional_height: 0.5}, deepCopy(genes_panel)),\n ],\n};\n\nconst association_catalog_plot = {\n state: {},\n width: 800,\n height: 500,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: deepCopy(region_nav_plot_toolbar),\n panels: [\n deepCopy(annotation_catalog_panel),\n deepCopy(association_catalog_panel),\n deepCopy(genes_panel),\n ],\n};\n\nconst standard_phewas_plot = {\n width: 800,\n height: 600,\n min_width: 800,\n min_height: 600,\n responsive_resize: true,\n toolbar: deepCopy(standard_plot_toolbar),\n panels: [\n merge({proportional_height: 0.5}, deepCopy(phewas_panel)),\n merge({\n proportional_height: 0.5,\n margin: { bottom: 40 },\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n },\n }, deepCopy(genes_panel)),\n ],\n mouse_guide: false,\n};\n\nconst coaccessibility_plot = {\n state: {},\n width: 800,\n height: 450,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: deepCopy(standard_plot_toolbar),\n panels: [\n Object.assign(\n { proportional_height: 0.4 },\n deepCopy(coaccessibility_panel)\n ),\n function () {\n // Take the default genes panel, and add a custom feature to highlight gene tracks based on short name\n // This is a companion to the \"match\" directive in the coaccessibility panel\n const base = Object.assign(\n { proportional_height: 0.6 },\n deepCopy(genes_panel)\n );\n const layer = base.data_layers[0];\n layer.match = { send: 'gene_name', receive: 'gene_name' };\n const color_config = [\n {\n field: 'lz_highlight_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#ff0000',\n },\n },\n {\n field: 'lz_highlight_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: false,\n then: '#EAE6E6',\n },\n },\n '#363696',\n ];\n layer.color = color_config;\n layer.stroke = color_config;\n return base;\n }(),\n ],\n};\n\n\nexport const tooltip = {\n standard_association: standard_association_tooltip,\n standard_association_with_label: standard_association_tooltip_with_label,\n standard_genes: standard_genes_tooltip,\n catalog_variant: catalog_variant_tooltip,\n coaccessibility: coaccessibility_tooltip,\n};\n\nexport const toolbar_widgets = {\n ldlz2_pop_selector: ldlz2_pop_selector_menu,\n};\n\nexport const toolbar = {\n standard_panel: standard_panel_toolbar,\n standard_plot: standard_plot_toolbar,\n region_nav_plot: region_nav_plot_toolbar,\n};\n\nexport const data_layer = {\n significance: significance_layer,\n recomb_rate: recomb_rate_layer,\n association_pvalues: association_pvalues_layer,\n coaccessibility: coaccessibility_layer,\n association_pvalues_catalog: association_pvalues_catalog_layer,\n phewas_pvalues: phewas_pvalues_layer,\n genes: genes_layer,\n annotation_catalog: annotation_catalog_layer,\n};\n\nexport const panel = {\n association: association_panel,\n coaccessibility: coaccessibility_panel,\n association_catalog: association_catalog_panel,\n genes: genes_panel,\n phewas: phewas_panel,\n annotation_catalog: annotation_catalog_panel,\n};\n\nexport const plot = {\n standard_association: standard_association_plot,\n association_catalog: association_catalog_plot,\n standard_phewas: standard_phewas_plot,\n coaccessibility: coaccessibility_plot,\n};\n","/**\n * @module\n * @private\n */\nimport {RegistryBase} from './base';\nimport {applyNamespaces, deepCopy, merge} from '../helpers/layouts';\nimport * as layouts from '../layouts';\n\n/**\n * Helper for working with predefined layouts\n *\n * This is part of the public interface with LocusZoom and a major way that users interact to configure plots.\n *\n * Each layout object that is added or retrieved here is a deep copy and totally independent from any other object\n * @public\n */\nclass LayoutRegistry extends RegistryBase {\n // Implemented as a \"registry of registries\"- one lookup each for panels, plots, etc...\n get(type, name, overrides = {}) {\n if (!(type && name)) {\n throw new Error('Must specify both the type and name for the layout desired. See .list() for available options');\n }\n // This is a registry of registries. Fetching an item may apply additional custom behaviors, such as\n // applying overrides or using namespaces to convert an abstract layout into a concrete one.\n let base = super.get(type).get(name);\n base = merge(overrides, base);\n if (base.unnamespaced) {\n delete base.unnamespaced;\n return deepCopy(base);\n }\n let default_namespace = '';\n if (typeof base.namespace == 'string') {\n default_namespace = base.namespace;\n } else if (typeof base.namespace == 'object' && Object.keys(base.namespace).length) {\n if (typeof base.namespace.default != 'undefined') {\n default_namespace = base.namespace.default;\n } else {\n default_namespace = base.namespace[Object.keys(base.namespace)[0]].toString();\n }\n }\n default_namespace += default_namespace.length ? ':' : '';\n const result = applyNamespaces(base, base.namespace, default_namespace);\n\n return deepCopy(result);\n }\n\n /**\n * Add a type of layout to the registry\n * @param {String} type\n * @param {String} name\n * @param {Object} item\n * @param {boolean} override\n * @return {*}\n */\n add(type, name, item, override = false) {\n if (!(type && name && item)) {\n throw new Error('To add a layout, type, name, and item must all be specified');\n }\n if (!(typeof item === 'object')) {\n throw new Error('The configuration to be added must be an object');\n }\n\n if (!this.has(type)) {\n super.add(type, new RegistryBase());\n }\n // Ensure that each use of a layout can be modified, by returning a copy is independent\n const copy = deepCopy(item);\n return super.get(type).add(name, copy, override);\n }\n\n /**\n * List all available types of layout (eg toolbar, panel, etc). If a specific type name is provided, list the\n * layouts for that widget type.\n * @param {String} [type] The type of layout (eg toolbar, panel, etc)\n * @return {String[]|Object}\n */\n list(type) {\n if (!type) {\n let result = {};\n for (let [type, contents] of this._items) {\n result[type] = contents.list();\n }\n return result;\n }\n return super.get(type).list();\n }\n\n /**\n * Static alias to a helper method. Preserved for backwards compatibility, so that UMD users can access this method.\n * @static\n */\n merge(custom_layout, default_layout) {\n return merge(custom_layout, default_layout);\n }\n}\n\nconst registry = new LayoutRegistry();\n\nfor (let [type, entries] of Object.entries(layouts)) {\n for (let [name, config] of Object.entries(entries)) {\n registry.add(type, name, config);\n }\n}\n\n\nexport default registry;\n\n// Export base class for unit testing\nexport {LayoutRegistry as _LayoutRegistry};\n","/**\n * Define standard data adapters used to retrieve data (usually from REST APIs)\n * @module\n */\n\nfunction validateBuildSource(class_name, build, source) {\n // Build OR Source, not both\n if ((build && source) || !(build || source)) {\n throw new Error(`${class_name} must provide a parameter specifying either \"build\" or \"source\". It should not specify both.`);\n }\n // If the build isn't recognized, our APIs can't transparently select a source to match\n if (build && !['GRCh37', 'GRCh38'].includes(build)) {\n throw new Error(`${class_name} must specify a valid genome build number`);\n }\n}\n\n\n/**\n * Base class for LocusZoom data sources (any). See also: RemoteAdapter\n * @public\n */\nclass BaseAdapter {\n constructor(config) {\n /**\n * Whether this source should enable caching\n * @member {Boolean}\n */\n this._enableCache = true;\n this._cachedKey = null;\n\n /**\n * Whether this data source type is dependent on previous requests- for example, the LD source cannot annotate\n * association data if no data was found for that region.\n * @member {boolean}\n */\n this.__dependentSource = false;\n\n // Parse configuration options\n this.parseInit(config);\n }\n\n /**\n * Parse configuration used to create the data source. Many custom sources will override this method to suit their\n * needs (eg specific config options, or for sources that do not retrieve data from a URL)\n * @protected\n * @param {String|Object} config Basic configuration- either a url, or a config object\n * @param {String} [config.url] The datasource URL\n * @param {String} [config.params] Initial config params for the datasource\n */\n parseInit(config) {\n /** @member {Object} */\n this.params = config.params || {};\n }\n\n /**\n * A unique identifier that indicates whether cached data is valid for this request. For most sources using GET\n * requests to a REST API, this is usually the URL.\n * @protected\n * @param {Object} state Information available in plot.state (chr, start, end). Sometimes used to inject globally\n * available information that influences the request being made.\n * @param {Object} chain The data chain from previous requests made in a sequence.\n * @param fields\n * @returns {String|undefined}\n */\n getCacheKey(state, chain, fields) {\n return this.getURL(state, chain, fields);\n }\n\n /**\n * Stub: build the URL for any requests made by this source.\n * @protected\n */\n getURL(state, chain, fields) {\n return this.url;\n }\n\n /**\n * Perform a network request to fetch data for this source. This is usually the method that is used to override\n * when defining how to retrieve data.\n * @protected\n * @param {Object} state The state of the parent plot\n * @param chain\n * @param fields\n * @returns {Promise}\n */\n fetchRequest(state, chain, fields) {\n const url = this.getURL(state, chain, fields);\n return fetch(url).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n });\n }\n\n /**\n * Gets the data for just this source, typically via a network request (but using cache where possible)\n *\n * For most use cases, it is better to override `fetchRequest` instead, to avoid bypassing the cache mechanism\n * by accident.\n * @protected\n */\n getRequest(state, chain, fields) {\n let req;\n const cacheKey = this.getCacheKey(state, chain, fields);\n if (this._enableCache && typeof(cacheKey) !== 'undefined' && cacheKey === this._cachedKey) {\n req = Promise.resolve(this._cachedResponse); // Resolve to the value of the current promise\n } else {\n req = this.fetchRequest(state, chain, fields);\n if (this._enableCache) {\n this._cachedKey = cacheKey;\n this._cachedResponse = req;\n }\n }\n return req;\n }\n\n /**\n * Ensure the server response is in a canonical form, an array of one object per record. [ {field: oneval} ].\n * If the server response contains columns, reformats the response from {column1: [], column2: []} to the above.\n *\n * Does not apply namespacing, transformations, or field extraction.\n *\n * May be overridden by data sources that inherently return more complex payloads, or that exist to annotate other\n * sources (eg, if the payload provides extra data rather than a series of records).\n * @protected\n * @param {Object[]|Object} data The original parsed server response\n */\n normalizeResponse(data) {\n if (Array.isArray(data)) {\n // Already in the desired form\n return data;\n }\n // Otherwise, assume the server response is an object representing columns of data.\n // Each array should have the same length (verify), and a given array index corresponds to a single row.\n const keys = Object.keys(data);\n const N = data[keys[0]].length;\n const sameLength = keys.every(function (key) {\n const item = data[key];\n return item.length === N;\n });\n if (!sameLength) {\n throw new Error(`${this.constructor.name} expects a response in which all arrays of data are the same length`);\n }\n\n // Go down the rows, and create an object for each record\n const records = [];\n const fields = Object.keys(data);\n for (let i = 0; i < N; i++) {\n const record = {};\n for (let j = 0; j < fields.length; j++) {\n record[fields[j]] = data[fields[j]][i];\n }\n records.push(record);\n }\n return records;\n }\n\n /**\n * Hook to post-process the data returned by this source with new, additional behavior.\n * (eg cleaning up API values or performing complex calculations on the returned data)\n *\n * @protected\n * @param {Object[]} records The parsed data from the source (eg standardized api response)\n * @param {Object} chain The data chain object. For example, chain.headers may provide useful annotation metadata\n * @returns {Object[]|Promise} The modified set of records\n */\n annotateData(records, chain) {\n // Default behavior: no transformations\n return records;\n }\n\n /**\n * Clean up the server records for use by datalayers: extract only certain fields, with the specified names.\n * Apply per-field transformations as appropriate.\n *\n * This hook can be overridden, eg to create a source that always returns all records and ignores the \"fields\" array.\n * This is particularly common for sources at the end of a chain- many \"dependent\" sources do not allow\n * cherry-picking individual fields, in which case by **convention** the fields array specifies \"last_source_name:all\"\n *\n * @protected\n * @param {Object[]} data One record object per element\n * @param {String[]} fields The names of fields to extract (as named in the source data). Eg \"afield\"\n * @param {String[]} outnames How to represent the source fields in the output. Eg \"namespace:afield|atransform\"\n * @param {function[]} trans An array of transformation functions (if any). One function per data element, or null.\n * @protected\n */\n extractFields (data, fields, outnames, trans) {\n //intended for an array of objects\n // [ {\"id\":1, \"val\":5}, {\"id\":2, \"val\":10}]\n // Since a number of sources exist that do not obey this format, we will provide a convenient pass-through\n if (!Array.isArray(data)) {\n return data;\n }\n\n if (!data.length) {\n // Sometimes there are regions that just don't have data- this should not trigger a missing field error message!\n return data;\n }\n\n const fieldFound = [];\n for (let k = 0; k < fields.length; k++) {\n fieldFound[k] = 0;\n }\n\n const records = data.map(function (item) {\n const output_record = {};\n for (let j = 0; j < fields.length; j++) {\n let val = item[fields[j]];\n if (typeof val != 'undefined') {\n fieldFound[j] = 1;\n }\n if (trans && trans[j]) {\n val = trans[j](val);\n }\n output_record[outnames[j]] = val;\n }\n return output_record;\n });\n fieldFound.forEach(function(v, i) {\n if (!v) {\n throw new Error(`field ${fields[i]} not found in response for ${outnames[i]}`);\n }\n });\n return records;\n }\n\n /**\n * Combine records from this source with others in the chain to yield final chain body.\n * Handles merging this data with other sources (if applicable).\n *\n * @protected\n * @param {Object[]} data The data That would be returned from this source alone\n * @param {Object} chain The data chain built up during previous requests\n * @param {String[]} fields\n * @param {String[]} outnames\n * @param {String[]} trans\n * @return {Promise|Object[]} The new chain body\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n return data;\n }\n\n /**\n * Coordinates the work of parsing a response and returning records. This is broken into 4 steps, which may be\n * overridden separately for fine-grained control. Each step can return either raw data or a promise.\n *\n * @protected\n *\n * @param {String|Object} resp The raw data associated with the response\n * @param {Object} chain The combined parsed response data from this and all other requests made in the chain\n * @param {String[]} fields Array of requested field names (as they would appear in the response payload)\n * @param {String[]} outnames Array of field names as they will be represented in the data returned by this source,\n * including the namespace. This must be an array with the same length as `fields`\n * @param {Function[]} trans The collection of transformation functions to be run on selected fields.\n * This must be an array with the same length as `fields`\n * @returns {Promise} A promise that resolves to an object containing\n * request metadata (`headers: {}`), the consolidated data for plotting (`body: []`), and the individual responses that would be\n * returned by each source in the chain in isolation (`discrete: {}`)\n */\n parseResponse (resp, chain, fields, outnames, trans) {\n const source_id = this.source_id || this.constructor.name;\n if (!chain.discrete) {\n chain.discrete = {};\n }\n\n const json = typeof resp == 'string' ? JSON.parse(resp) : resp;\n\n // Perform the 4 steps of parsing the payload and return a combined chain object\n return Promise.resolve(this.normalizeResponse(json.data || json))\n .then((standardized) => {\n // Perform calculations on the data from just this source\n return Promise.resolve(this.annotateData(standardized, chain));\n }).then((data) => {\n return Promise.resolve(this.extractFields(data, fields, outnames, trans));\n }).then((one_source_body) => {\n // Store a copy of the data that would be returned by parsing this source in isolation (and taking the\n // fields array into account). This is useful when we want to re-use the source output in many ways.\n chain.discrete[source_id] = one_source_body;\n return Promise.resolve(this.combineChainBody(one_source_body, chain, fields, outnames, trans));\n }).then((new_body) => {\n return { header: chain.header || {}, discrete: chain.discrete, body: new_body };\n });\n }\n\n /**\n * Fetch the data from the specified data source, and apply transformations requested by an external consumer.\n * This is the public-facing datasource method that will most be called by the plot, but custom data sources will\n * almost never want to override this method directly- more specific hooks are provided to control individual pieces\n * of the request lifecycle.\n *\n * @private\n * @param {Object} state The current \"state\" of the plot, such as chromosome and start/end positions\n * @param {String[]} fields Array of field names that the plot has requested from this data source. (without the \"namespace\" prefix)\n * @param {String[]} outnames Array describing how the output data should refer to this field. This represents the\n * originally requested field name, including the namespace. This must be an array with the same length as `fields`\n * @param {Function[]} trans The collection of transformation functions to be run on selected fields.\n * This must be an array with the same length as `fields`\n * @returns {function} A callable operation that can be used as part of the data chain\n */\n getData(state, fields, outnames, trans) {\n if (this.preGetData) { // TODO try to remove this method if at all possible\n const pre = this.preGetData(state, fields, outnames, trans);\n if (this.pre) {\n state = pre.state || state;\n fields = pre.fields || fields;\n outnames = pre.outnames || outnames;\n trans = pre.trans || trans;\n }\n }\n\n return (chain) => {\n if (this.__dependentSource && chain && chain.body && !chain.body.length) {\n // A \"dependent\" source should not attempt to fire a request if there is no data for it to act on.\n // Therefore, it should simply return the previous data chain.\n return Promise.resolve(chain);\n }\n\n return this.getRequest(state, chain, fields).then((resp) => {\n return this.parseResponse(resp, chain, fields, outnames, trans);\n });\n };\n }\n}\n\n/**\n * Base source for LocusZoom data sources that receive their data over the web. Adds default config parameters\n * (and potentially other behavior) that are relevant to URL-based requests.\n */\nclass RemoteAdapter extends BaseAdapter {\n parseInit(config) {\n super.parseInit(config);\n\n /** @member {String} */\n this.url = config.url;\n if (!this.url) {\n throw new Error('Source not initialized with required URL');\n }\n }\n}\n\n/**\n * Data Source for Association Data from the LocusZoom/ Portaldev API (or compatible). Defines how to make a requesr\n * @public\n */\nclass AssociationLZ extends RemoteAdapter {\n preGetData (state, fields, outnames, trans) {\n // TODO: Modify internals to see if we can go without this method\n const id_field = this.params.id_field || 'id';\n [id_field, 'position'].forEach(function(x) {\n if (!fields.includes(x)) {\n fields.unshift(x);\n outnames.unshift(x);\n trans.unshift(null);\n }\n });\n return {fields: fields, outnames:outnames, trans:trans};\n }\n\n getURL (state, chain, fields) {\n const analysis = chain.header.analysis || this.params.source || this.params.analysis; // Old usages called this param \"analysis\"\n if (typeof analysis == 'undefined') {\n throw new Error('Association source must specify an analysis ID to plot');\n }\n return `${this.url}results/?filter=analysis in ${analysis} and chromosome in '${state.chr}' and position ge ${state.start} and position le ${state.end}`;\n }\n\n normalizeResponse (data) {\n // Some association sources do not sort their data in a predictable order, which makes it hard to reliably\n // align with other sources (such as LD). For performance reasons, sorting is an opt-in argument.\n // TODO: Consider more fine grained sorting control in the future. This was added as a very specific\n // workaround for the original T2D portal.\n data = super.normalizeResponse(data);\n if (this.params && this.params.sort && data.length && data[0]['position']) {\n data.sort(function (a, b) {\n return a['position'] - b['position'];\n });\n }\n return data;\n }\n}\n\n/**\n * Fetch linkage disequilibrium information from a UMich LDServer-compatible API\n *\n * This source is designed to connect its results to association data, and therefore depends on association data having\n * been loaded by a previous request in the data chain.\n *\n * In older versions of LocusZoom, this was known as \"LDServer\". A prior source (targeted at older APIs) has been removed.\n */\nclass LDServer extends RemoteAdapter {\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n preGetData(state, fields) {\n if (fields.length > 1) {\n if (fields.length !== 2 || !fields.includes('isrefvar')) {\n throw new Error(`LD does not know how to get all fields: ${fields.join(', ')}`);\n }\n }\n }\n\n findMergeFields(chain) {\n // Find the fields (as provided by a previous step in the chain, like an association source) that will be needed to\n // combine LD data with existing information\n\n // Since LD information may be shared across multiple assoc sources with different namespaces,\n // we use regex to find columns to join on, rather than requiring exact matches\n const exactMatch = function (arr) {\n return function () {\n const regexes = arguments;\n for (let i = 0; i < regexes.length; i++) {\n const regex = regexes[i];\n const m = arr.filter(function (x) {\n return x.match(regex);\n });\n if (m.length) {\n return m[0];\n }\n }\n return null;\n };\n };\n let dataFields = {\n id: this.params.id_field,\n position: this.params.position_field,\n pvalue: this.params.pvalue_field,\n _names_:null,\n };\n if (chain && chain.body && chain.body.length > 0) {\n const names = Object.keys(chain.body[0]);\n const nameMatch = exactMatch(names);\n // Internally, fields are generally prefixed with the name of the source they come from.\n // If the user provides an id_field (like `variant`), it should work across data sources( `assoc1:variant`,\n // assoc2:variant), but not match fragments of other field names (assoc1:variant_thing)\n // Note: these lookups hard-code a couple of common fields that will work based on known APIs in the wild\n const id_match = dataFields.id && nameMatch(new RegExp(`${dataFields.id}\\\\b`));\n dataFields.id = id_match || nameMatch(/\\bvariant\\b/) || nameMatch(/\\bid\\b/);\n dataFields.position = dataFields.position || nameMatch(/\\bposition\\b/i, /\\bpos\\b/i);\n dataFields.pvalue = dataFields.pvalue || nameMatch(/\\bpvalue\\b/i, /\\blog_pvalue\\b/i);\n dataFields._names_ = names;\n }\n return dataFields;\n }\n\n findRequestedFields (fields, outnames) {\n // Assumption: all usages of this source will only ever ask for \"isrefvar\" or \"state\". This maps to output names.\n let obj = {};\n for (let i = 0; i < fields.length; i++) {\n if (fields[i] === 'isrefvar') {\n obj.isrefvarin = fields[i];\n obj.isrefvarout = outnames && outnames[i];\n } else {\n obj.ldin = fields[i];\n obj.ldout = outnames && outnames[i];\n }\n }\n return obj;\n }\n\n normalizeResponse (data) {\n // The LD API payload does not obey standard format conventions; do not try to transform it.\n return data;\n }\n\n /**\n * Get the LD reference variant, which by default will be the most significant hit in the assoc results\n * This will be used in making the original query to the LD server for pairwise LD information\n * @returns {*|string} The marker id (expected to be in `chr:pos_ref/alt` format) of the reference variant\n */\n getRefvar(state, chain, fields) {\n let findExtremeValue = function(records, pval_field) {\n // Finds the most significant hit (smallest pvalue, or largest -log10p). Will try to auto-detect the appropriate comparison.\n pval_field = pval_field || 'log_pvalue'; // The official LZ API returns log_pvalue\n const is_log = /log/.test(pval_field);\n let cmp;\n if (is_log) {\n cmp = function(a, b) {\n return a > b;\n };\n } else {\n cmp = function(a, b) {\n return a < b;\n };\n }\n let extremeVal = records[0][pval_field], extremeIdx = 0;\n for (let i = 1; i < records.length; i++) {\n if (cmp(records[i][pval_field], extremeVal)) {\n extremeVal = records[i][pval_field];\n extremeIdx = i;\n }\n }\n return extremeIdx;\n };\n\n let reqFields = this.findRequestedFields(fields);\n let refVar = reqFields.ldin;\n if (refVar === 'state') {\n refVar = state.ldrefvar || chain.header.ldrefvar || 'best';\n }\n if (refVar === 'best') {\n if (!chain.body) {\n throw new Error('No association data found to find best pvalue');\n }\n let keys = this.findMergeFields(chain);\n if (!keys.pvalue || !keys.id) {\n let columns = '';\n if (!keys.id) {\n columns += `${columns.length ? ', ' : ''}id`;\n }\n if (!keys.pvalue) {\n columns += `${columns.length ? ', ' : ''}pvalue`;\n }\n throw new Error(`Unable to find necessary column(s) for merge: ${columns} (available: ${keys._names_})`);\n }\n refVar = chain.body[findExtremeValue(chain.body, keys.pvalue)][keys.id];\n }\n return refVar;\n }\n\n getURL(state, chain, fields) {\n // Accept the following params in this.params:\n // - method (r, rsquare, cov)\n // - source (aka panel)\n // - population (ALL, AFR, EUR, etc)\n // - build\n // The LD source/pop can be overridden from plot.state for dynamic layouts\n const build = state.genome_build || this.params.build || 'GRCh37';\n const source = state.ld_source || this.params.source || '1000G';\n const population = state.ld_pop || this.params.population || 'ALL'; // LDServer panels will always have an ALL\n const method = this.params.method || 'rsquare';\n\n validateBuildSource(this.constructor.name, build, null); // LD doesn't need to validate `source` option\n\n let refVar = this.getRefvar(state, chain, fields);\n // Some datasets, notably the Portal, use a different marker format.\n // Coerce it into one that will work with the LDServer API. (CHROM:POS_REF/ALT)\n const REGEX_MARKER = /^(?:chr)?([a-zA-Z0-9]+?)[_:-](\\d+)[_:|-]?(\\w+)?[/_:|-]?([^_]+)?_?(.*)?/;\n const match = refVar && refVar.match(REGEX_MARKER);\n\n if (!match) {\n throw new Error('Could not request LD for a missing or incomplete marker format');\n }\n refVar = [match[1], ':', match[2], '_', match[3], '/', match[4]].join('');\n chain.header.ldrefvar = refVar;\n\n return [\n this.url, 'genome_builds/', build, '/references/', source, '/populations/', population, '/variants',\n '?correlation=', method,\n '&variant=', encodeURIComponent(refVar),\n '&chrom=', encodeURIComponent(state.chr),\n '&start=', encodeURIComponent(state.start),\n '&stop=', encodeURIComponent(state.end),\n ].join('');\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n let keys = this.findMergeFields(chain);\n let reqFields = this.findRequestedFields(fields, outnames);\n if (!keys.position) {\n throw new Error(`Unable to find position field for merge: ${keys._names_}`);\n }\n const leftJoin = function (left, right, lfield, rfield) {\n let i = 0, j = 0;\n while (i < left.length && j < right.position2.length) {\n if (left[i][keys.position] === right.position2[j]) {\n left[i][lfield] = right[rfield][j];\n i++;\n j++;\n } else if (left[i][keys.position] < right.position2[j]) {\n i++;\n } else {\n j++;\n }\n }\n };\n const tagRefVariant = function (data, refvar, idfield, outrefname, outldname) {\n for (let i = 0; i < data.length; i++) {\n if (data[i][idfield] && data[i][idfield] === refvar) {\n data[i][outrefname] = 1;\n data[i][outldname] = 1; // For label/filter purposes, implicitly mark the ref var as LD=1 to itself\n } else {\n data[i][outrefname] = 0;\n }\n }\n };\n\n // LD servers vary slightly. Some report corr as \"rsquare\", others as \"correlation\"\n let corrField = data.rsquare ? 'rsquare' : 'correlation';\n leftJoin(chain.body, data, reqFields.ldout, corrField);\n if (reqFields.isrefvarin && chain.header.ldrefvar) {\n tagRefVariant(chain.body, chain.header.ldrefvar, keys.id, reqFields.isrefvarout, reqFields.ldout);\n }\n return chain.body;\n }\n\n fetchRequest(state, chain, fields) {\n // The API is paginated, but we need all of the data to render a plot. Depaginate and combine where appropriate.\n let url = this.getURL(state, chain, fields);\n let combined = { data: {} };\n let chainRequests = function (url) {\n return fetch(url).then().then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n }).then(function(payload) {\n payload = JSON.parse(payload);\n Object.keys(payload.data).forEach(function (key) {\n combined.data[key] = (combined.data[key] || []).concat(payload.data[key]);\n });\n if (payload.next) {\n return chainRequests(payload.next);\n }\n return combined;\n });\n };\n return chainRequests(url);\n }\n}\n\n/**\n * Data source for GWAS catalogs of known variants\n * @public\n * @class\n * @param {Object|String} init Configuration (URL or object)\n * @param {Object} [init.params] Optional configuration parameters\n * @param {Number} [init.params.source=2] The ID of the chosen catalog. Defaults to EBI GWAS catalog, GRCh37\n * @param {('strict'|'loose')} [init.params.match_type='strict'] Whether to match on exact variant, or just position.\n */\nclass GwasCatalogLZ extends RemoteAdapter {\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n getURL(state, chain, fields) {\n // This is intended to be aligned with another source- we will assume they are always ordered by position, asc\n // (regardless of the actual match field)\n const build_option = state.genome_build || this.params.build;\n validateBuildSource(this.constructor.name, build_option, null); // Source can override build- not mutually exclusive\n\n // Most of our annotations will respect genome build before any other option.\n // But there can be more than one GWAS catalog version available in the same API, for the same build- an\n // explicit config option will always take\n // precedence.\n const default_source = (build_option === 'GRCh38') ? 1 : 2; // EBI GWAS catalog\n const source = this.params.source || default_source;\n return `${this.url }?format=objects&sort=pos&filter=id eq ${source} and chrom eq '${state.chr}' and pos ge ${state.start} and pos le ${state.end}`;\n }\n\n findMergeFields(records) {\n // Data from previous sources is already namespaced. Find the alignment field by matching.\n const knownFields = Object.keys(records);\n // Note: All API endoints involved only give results for 1 chromosome at a time; match is implied\n const posMatch = knownFields.find(function (item) {\n return item.match(/\\b(position|pos)\\b/i);\n });\n\n if (!posMatch) {\n throw new Error('Could not find data to align with GWAS catalog results');\n }\n return { 'pos': posMatch };\n }\n\n extractFields (data, fields, outnames, trans) {\n // Skip the \"individual field extraction\" step; extraction will be handled when building chain body instead\n return data;\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n if (!data.length) {\n return chain.body;\n }\n\n // TODO: Better reuse options in the future. This source is very specifically tied to the PortalDev API, where\n // the field name is always \"log_pvalue\". Relatively few sites will write their own gwas-catalog endpoint.\n const decider = 'log_pvalue';\n const decider_out = outnames[fields.indexOf(decider)];\n\n function leftJoin(left, right, fields, outnames, trans) { // Add `fields` from `right` to `left`\n // Add a synthetic, un-namespaced field to all matching records\n const n_matches = left['n_catalog_matches'] || 0;\n left['n_catalog_matches'] = n_matches + 1;\n if (decider && left[decider_out] && left[decider_out] > right[decider]) {\n // There may be more than one GWAS catalog entry for the same SNP. This source is intended for a 1:1\n // annotation scenario, so for now it only joins the catalog entry that has the best -log10 pvalue\n return;\n }\n\n for (let j = 0; j < fields.length; j++) {\n const fn = fields[j];\n const outn = outnames[j];\n\n let val = right[fn];\n if (trans && trans[j]) {\n val = trans[j](val);\n }\n left[outn] = val;\n }\n }\n\n const chainNames = this.findMergeFields(chain.body[0]);\n const catNames = this.findMergeFields(data[0]);\n\n var i = 0, j = 0;\n while (i < chain.body.length && j < data.length) {\n var left = chain.body[i];\n var right = data[j];\n\n if (left[chainNames.pos] === right[catNames.pos]) {\n // There may be multiple catalog entries for each matching SNP; evaluate match one at a time\n leftJoin(left, right, fields, outnames, trans);\n j += 1;\n } else if (left[chainNames.pos] < right[catNames.pos]) {\n i += 1;\n } else {\n j += 1;\n }\n }\n return chain.body;\n }\n}\n\n/**\n * Data Source for Gene Data, as fetched from the LocusZoom/Portaldev API server (or compatible format)\n * @public\n */\nclass GeneLZ extends RemoteAdapter {\n getURL(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n let source = this.params.source;\n validateBuildSource(this.constructor.name, build, source);\n\n if (build) { // If build specified, choose a known Portal API dataset IDs (build 37/38)\n source = (build === 'GRCh38') ? 1 : 3;\n }\n return `${this.url}?filter=source in ${source} and chrom eq '${state.chr}' and start le ${state.end} and end ge ${state.start}`;\n }\n\n normalizeResponse(data) {\n // Genes have a very complex internal data format. Bypass any record parsing, and provide the data layer with\n // the exact information returned by the API. (ignoring the fields array in the layout)\n return data;\n }\n\n extractFields(data, fields, outnames, trans) {\n return data;\n }\n}\n\n/**\n * Data Source for Gene Constraint Data, as fetched from the gnomAD server (or compatible)\n *\n * This is intended to be the second request in a chain, with special logic that connects it to Genes data\n * already fetched.\n *\n * @public\n*/\nclass GeneConstraintLZ extends RemoteAdapter {\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n getURL() {\n // GraphQL API: request details are encoded in the body, not the URL\n return this.url;\n }\n getCacheKey(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n // GraphQL API: request not defined solely by the URL\n // Gather the state params that govern constraint query for a given region.\n return `${this.url} ${state.chr} ${state.start} ${state.end} ${build}`;\n }\n\n normalizeResponse(data) {\n return data;\n }\n\n fetchRequest(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n if (!build) {\n throw new Error(`Data source ${this.constructor.name} must specify a 'genome_build' option`);\n }\n\n const unique_gene_names = chain.body.reduce(\n // In rare cases, the same gene symbol may appear at multiple positions. (issue #179) We de-duplicate the\n // gene names to avoid issuing a malformed GraphQL query.\n function (acc, gene) {\n acc[gene.gene_name] = null;\n return acc;\n },\n {}\n );\n let query = Object.keys(unique_gene_names).map(function (gene_name) {\n // GraphQL alias names must match a specific set of allowed characters: https://stackoverflow.com/a/45757065/1422268\n const alias = `_${gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`;\n // Each gene symbol is a separate graphQL query, grouped into one request using aliases\n return `${alias}: gene(gene_symbol: \"${gene_name}\", reference_genome: ${build}) { gnomad_constraint { exp_syn obs_syn syn_z oe_syn oe_syn_lower oe_syn_upper exp_mis obs_mis mis_z oe_mis oe_mis_lower oe_mis_upper exp_lof obs_lof pLI oe_lof oe_lof_lower oe_lof_upper } } `;\n });\n\n if (!query.length) {\n // If there are no genes, skip the network request\n return Promise.resolve({ data: null });\n }\n\n query = `{${query.join(' ')} }`; // GraphQL isn't quite JSON; items are separated by spaces but not commas\n const url = this.getURL(state, chain, fields);\n // See: https://graphql.org/learn/serving-over-http/\n const body = JSON.stringify({ query: query });\n const headers = { 'Content-Type': 'application/json' };\n\n return fetch(url, { method: 'POST', body, headers }).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n });\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n if (!data) {\n return chain;\n }\n\n chain.body.forEach(function(gene) {\n // Find payload keys that match gene names in this response\n const alias = `_${gene.gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`; // aliases are modified gene names\n const constraint = data[alias] && data[alias]['gnomad_constraint']; // gnomad API has two ways of specifying missing data for a requested gene\n if (constraint) {\n // Add all fields from constraint data- do not override fields present in the gene source\n Object.keys(constraint).forEach(function (key) {\n let val = constraint[key];\n if (typeof gene[key] === 'undefined') {\n if (typeof val == 'number' && val.toString().includes('.')) {\n val = parseFloat(val.toFixed(2));\n }\n gene[key] = val; // These two sources are both designed to bypass namespacing\n }\n });\n }\n });\n return chain.body;\n }\n}\n\n/**\n * Data Source for Recombination Rate Data, as fetched from the LocusZoom API server (or compatible)\n * @public\n */\nclass RecombLZ extends RemoteAdapter {\n getURL(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n let source = this.params.source;\n validateBuildSource(this.constructor.SOURCE_NAME, build, source);\n\n if (build) { // If build specified, choose a known Portal API dataset IDs (build 37/38)\n source = (build === 'GRCh38') ? 16 : 15;\n }\n return `${this.url}?filter=id in ${source} and chromosome eq '${state.chr}' and position le ${state.end} and position ge ${state.start}`;\n }\n}\n\n/**\n * Data Source for static blobs of data as raw JS objects. This does not perform additional parsing, and it bypasses\n * namespaces. Therefore it is the responsibility of the user to pass information in a format that can be read and\n * understood by the chosen plot- a StaticJSON source is rarely a drop-in replacement.\n *\n * This source is largely here for legacy reasons. More often, a convenient way to serve static data is as separate\n * JSON files to an existing source (with the JSON url in place of an API).\n * @public\n */\nclass StaticSource extends BaseAdapter {\n parseInit(data) {\n // Does not receive any config; the only argument is the raw data, embedded when source is created\n this._data = data;\n }\n getRequest(state, chain, fields) {\n return Promise.resolve(this._data);\n }\n}\n\n\n/**\n * Data source for PheWAS data retrieved from a LocusZoom/PortalDev compatible API\n * @public\n * @param {String[]} init.params.build This datasource expects to be provided the name of the genome build that will\n * be used to provide pheWAS results for this position. Note positions may not translate between builds.\n */\nclass PheWASLZ extends RemoteAdapter {\n getURL(state, chain, fields) {\n const build = (state.genome_build ? [state.genome_build] : null) || this.params.build;\n if (!build || !Array.isArray(build) || !build.length) {\n throw new Error(['Data source', this.constructor.SOURCE_NAME, 'requires that you specify array of one or more desired genome build names'].join(' '));\n }\n const url = [\n this.url,\n \"?filter=variant eq '\", encodeURIComponent(state.variant), \"'&format=objects&\",\n build.map(function (item) {\n return `build=${encodeURIComponent(item)}`;\n }).join('&'),\n ];\n return url.join('');\n }\n}\n\n\n/**\n * Base class for \"connectors\"- this is meant to be subclassed, rather than used directly.\n *\n * A connector is a source that makes no server requests and caches no data of its own. Instead, it decides how to\n * combine data from other sources in the chain. Connectors are useful when we want to request (or calculate) some\n * useful piece of information once, but apply it to many different kinds of record types.\n *\n * Typically, a subclass will implement the field merging logic in `combineChainBody`.\n *\n * @public\n * @param {Object} init Configuration for this source\n * @param {Object} init.sources Specify how the hard-coded logic should find the data it relies on in the chain,\n * as {internal_name: chain_source_id} pairs. This allows writing a reusable connector that does not need to make\n * assumptions about what namespaces a source is using.\n * @type {*|Function}\n */\nclass ConnectorSource extends BaseAdapter {\n constructor(config) {\n super(config);\n\n if (!config || !config.sources) {\n throw new Error('Connectors must specify the data they require as init.sources = {internal_name: chain_source_id}} pairs');\n }\n\n /**\n * Tells the connector how to find the data it relies on\n *\n * For example, a connector that applies burden test information to the genes layer might specify:\n * {gene_ns: \"gene\", aggregation_ns: \"aggregation\"}\n *\n * @member {Object}\n */\n this._source_name_mapping = config.sources;\n\n // Validate that this source has been told how to find the required information\n const specified_ids = Object.keys(config.sources);\n /** @property {String[]} Specifies the sources that must be provided in the original config object */\n\n this._getRequiredSources().forEach((k) => {\n if (!specified_ids.includes(k)) {\n // TODO: Fix constructor.name usage in minified bundles\n throw new Error(`Configuration for ${this.constructor.name} must specify a source ID corresponding to ${k}`);\n }\n });\n }\n\n // Stub- connectors don't have their own url or data, so the defaults don't make sense\n parseInit() {}\n\n getRequest(state, chain, fields) {\n // Connectors do not request their own data by definition, but they *do* depend on other sources having been loaded\n // first. This method performs basic validation, and preserves the accumulated body from the chain so far.\n Object.keys(this._source_name_mapping).forEach((ns) => {\n const chain_source_id = this._source_name_mapping[ns];\n if (chain.discrete && !chain.discrete[chain_source_id]) {\n throw new Error(`${this.constructor.name} cannot be used before loading required data for: ${chain_source_id}`);\n }\n });\n return Promise.resolve(chain.body || []);\n }\n\n parseResponse(data, chain, fields, outnames, trans) {\n // A connector source does not update chain.discrete, but it may use it. It bypasses data formatting\n // and field selection (both are assumed to have been done already, by the previous sources this draws from)\n\n // Because of how the chain works, connectors are not very good at applying new transformations or namespacing.\n // Typically connectors are called with `connector_name:all` in the fields array.\n return Promise.resolve(this.combineChainBody(data, chain, fields, outnames, trans))\n .then(function(new_body) {\n return {header: chain.header || {}, discrete: chain.discrete || {}, body: new_body};\n });\n }\n\n combineChainBody(records, chain) {\n // Stub method: specifies how to combine the data\n throw new Error('This method must be implemented in a subclass');\n }\n\n /**\n * Helper method since ES6 doesn't support class fields\n * @private\n */\n _getRequiredSources() {\n throw new Error('Must specify an array that identifes the kind of data required by this source');\n }\n}\n\nexport { BaseAdapter, RemoteAdapter };\n\nexport {\n AssociationLZ,\n ConnectorSource,\n GeneConstraintLZ,\n GeneLZ,\n GwasCatalogLZ,\n LDServer,\n PheWASLZ,\n RecombLZ,\n StaticSource,\n};\n","/** @module */\nimport * as d3 from 'd3';\n\nimport {STATUSES} from '../constants';\nimport Field from '../../data/field';\nimport {parseFields} from '../../helpers/display';\nimport {deepCopy, merge} from '../../helpers/layouts';\nimport scalable from '../../registry/scalable';\n\n\n/**\n * A basic description of keys expected in a layout. Not intended to be directly used or modified by an end user.\n * @protected\n * @type {{type: string, fields: Array, x_axis: {}, y_axis: {}}}\n */\nconst default_layout = {\n type: '',\n fields: [],\n x_axis: {},\n y_axis: {},\n // Not every layer allows this attribute, but it is available for the default implementation\n tooltip_positioning: 'horizontal',\n};\n\n\n/**\n * A data layer is an abstract class representing a data set and its graphical representation within a panel\n * @public\n * @param {Object} layout A JSON-serializable object describing the layout for this layer\n * @param {Panel|null} parent Where this layout is used\n*/\nclass BaseDataLayer {\n constructor(layout, parent) {\n /**\n * @private\n * @member {Boolean}\n */\n this.initialized = false;\n /**\n * @private\n * @member {Number}\n */\n this.layout_idx = null;\n\n /**\n * The unique identifier for this layer. Should be unique within this layer.\n * @public\n * @member {String}\n */\n this.id = null;\n /**\n * @protected\n * @member {Panel}\n */\n this.parent = parent || null;\n /**\n * @private\n * @member {{group: d3.selection, container: d3.selection, clipRect: d3.selection}}\n */\n this.svg = {};\n\n /**\n * @protected\n * @member {Plot}\n */\n this.parent_plot = null;\n if (parent) {\n this.parent_plot = parent.parent;\n }\n\n /**\n * The current layout configuration for this data layer. This reflects any resizing or dynamically generated\n * config options produced during rendering. Direct layout mutations are a powerful way to dynamically\n * modify the plot in response to user interactions, but require a deep knowledge of LZ internals to use\n * effectively.\n * @public\n * @member {Object}\n */\n this.layout = merge(layout || {}, default_layout);\n if (this.layout.id) {\n this.id = this.layout.id;\n }\n\n // Ensure any axes defined in the layout have an explicit axis number (default: 1)\n if (this.layout.x_axis !== {} && typeof this.layout.x_axis.axis !== 'number') {\n this.layout.x_axis.axis = 1;\n }\n if (this.layout.y_axis !== {} && typeof this.layout.y_axis.axis !== 'number') {\n this.layout.y_axis.axis = 1;\n }\n\n /**\n * Values in the layout object may change during rendering etc. Retain a copy of the original data layer state\n * @protected\n * @member {Object}\n */\n this._base_layout = deepCopy(this.layout);\n\n /**\n * @private\n * @member {Object}\n */\n this.state = {};\n /**\n * @private\n * @member {String}\n */\n this.state_id = null;\n\n /**\n * @private\n * @member {Object}\n * */\n this.layer_state = null;\n // Create a default state (and set any references to the parent as appropriate)\n this._setDefaultState();\n\n // Initialize parameters for storing data and tool tips\n /**\n * The data retrieved from a region request. This field is useful for debugging, but will be overridden on\n * re-render; do not modify it directly. The point annotation cache can be used to preserve markings\n * after re-render.\n * @protected\n * @member {Array}\n */\n this.data = [];\n if (this.layout.tooltip) {\n /**\n * @private\n * @member {Object}\n */\n this.tooltips = {};\n }\n\n // Initialize flags for tracking global statuses\n this.global_statuses = {\n 'highlighted': false,\n 'selected': false,\n 'faded': false,\n 'hidden': false,\n };\n }\n\n /****** Public interface: methods for external manipulation */\n /**\n * Instruct this datalayer to begin tracking additional fields from data sources (does not guarantee that such a field actually exists)\n *\n * Custom plots can use this to dynamically extend datalayer functionality after the plot is drawn. In practice,\n * it is usually better to define the required fields up front; this function is rarely used.\n *\n * (since removing core fields may break layer functionality, there is presently no hook for the inverse behavior)\n * @public\n * @deprecated\n * @param fieldName\n * @param namespace\n * @param {String|String[]} transformations The name (or array of names) of transformations to apply to this field\n * @returns {String} The raw string added to the fields array\n */\n addField (fieldName, namespace, transformations) {\n if (!fieldName || !namespace) {\n throw new Error('Must specify field name and namespace to use when adding field');\n }\n let fieldString = `${namespace}:${fieldName}`;\n if (transformations) {\n fieldString += '|';\n if (typeof transformations === 'string') {\n fieldString += transformations;\n } else if (Array.isArray(transformations)) {\n fieldString += transformations.join('|');\n } else {\n throw new Error('Must provide transformations as either a string or array of strings');\n }\n }\n const fields = this.layout.fields;\n if (!fields.includes(fieldString)) {\n fields.push(fieldString);\n }\n return fieldString;\n }\n\n /**\n * Move a data layer up relative to others by z-index\n * @public\n * @returns {BaseDataLayer}\n */\n moveUp() {\n if (this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1]) {\n this.parent.data_layer_ids_by_z_index[this.layout.z_index] = this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1];\n this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1] = this.id;\n this.parent.resortDataLayers();\n }\n return this;\n }\n\n /**\n * Move a data layer down relative to others by z-index\n * @public\n * @returns {BaseDataLayer}\n */\n moveDown() {\n if (this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1]) {\n this.parent.data_layer_ids_by_z_index[this.layout.z_index] = this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1];\n this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1] = this.id;\n this.parent.resortDataLayers();\n }\n return this;\n }\n\n /**\n * Set an \"annotation\": a piece of additional information about a point that is preserved across re-render,\n * or as the user pans and zooms near this region.\n *\n * Annotations can be referenced as a named pseudo-field in any filters and scalable parameters. (template support\n * may be added in the future)\n * Sample use case: user clicks a tooltip to \"label this specific point\". (or change any other display property)\n *\n * @public\n * @param {String|Object} element The data object or ID string for the element\n * @param {String} key The name of the annotation to track\n * @param {*} value The value of the marked field\n */\n setElementAnnotation (element, key, value) {\n const id = this.getElementId(element);\n if (!this.layer_state.extra_fields[id]) {\n this.layer_state.extra_fields[id] = {};\n }\n this.layer_state.extra_fields[id][key] = value;\n return this;\n }\n\n /********** Protected methods: useful in subclasses to manipulate data layer behaviors */\n /**\n * Implementation hook for fetching the min and max values of available data. Used to determine axis range, if no other\n * explicit axis settings override. Useful for data layers where the data extent depends on more than one field.\n * (eg confidence intervals in a forest plot)\n *\n * @protected\n * @param data\n * @param axis_config The configuration object for the specified axis.\n * @returns {Array} [min, max] without any padding applied\n */\n _getDataExtent (data, axis_config) {\n data = data || this.data;\n // By default this depends only on a single field.\n return d3.extent(data, (d) => {\n const f = new Field(axis_config.field);\n return +f.resolve(d);\n });\n }\n\n /**\n * Fetch the fully qualified ID to be associated with a specific visual element, based on the data to which that\n * element is bound. In general this element ID will be unique, allowing it to be addressed directly via selectors.\n * @protected\n * @param {String|Object} element\n * @returns {String}\n */\n getElementId (element) {\n let element_id = 'element';\n if (typeof element == 'string') {\n element_id = element;\n } else if (typeof element == 'object') {\n const id_field = this.layout.id_field || 'id';\n if (typeof element[id_field] == 'undefined') {\n throw new Error('Unable to generate element ID');\n }\n element_id = element[id_field].toString().replace(/\\W/g, '');\n }\n return (`${this.getBaseId()}-${element_id}`).replace(/([:.[\\],])/g, '_');\n }\n\n /**\n * Fetch an ID that may bind a data element to a separate visual node for displaying status\n * Examples of this might be seperate visual nodes to show select/highlight statuses, or\n * even a common/shared node to show status across many elements in a set.\n * Abstract method. It should be overridden by data layers that implement seperate status\n * nodes specifically to the use case of the data layer type.\n * @protected\n * @param {String|Object} element\n * @returns {String|null}\n */\n getElementStatusNodeId (element) {\n return null;\n }\n\n /**\n * Returns a reference to the underlying data associated with a single visual element in the data layer, as\n * referenced by the unique identifier for the element\n *\n * @protected\n * @param {String} id The unique identifier for the element, as defined by `getElementId`\n * @returns {Object|null} The data bound to that element\n */\n getElementById(id) {\n const selector = d3.select(`#${id.replace(/([:.[\\],])/g, '\\\\$1')}`); // escape special characters\n if (!selector.empty() && selector.data() && selector.data().length) {\n return selector.data()[0];\n } else {\n return null;\n }\n }\n\n /**\n * Basic method to apply arbitrary methods and properties to data elements.\n * This is called on all data immediately after being fetched.\n * @protected\n * @returns {BaseDataLayer}\n */\n applyDataMethods() {\n const field_to_match = (this.layout.match && this.layout.match.receive);\n const broadcast_value = this.parent_plot.state.lz_match_value;\n\n this.data.forEach((item, i) => {\n // Basic toHTML() method - return the stringified value in the id_field, if defined.\n\n // When this layer receives data, mark whether points match (via a synthetic boolean field)\n // Any field-based layout directives (color, size, shape) can then be used to control display\n if (field_to_match && broadcast_value !== null && broadcast_value !== undefined) {\n item.lz_highlight_match = (item[field_to_match] === broadcast_value);\n }\n\n item.toHTML = () => {\n const id_field = this.layout.id_field || 'id';\n let html = '';\n if (item[id_field]) {\n html = item[id_field].toString();\n }\n return html;\n };\n // Helper methods - return a reference to various plot levels. Useful for interactive tooltips.\n item.getDataLayer = () => this;\n item.getPanel = () => this.parent || null;\n item.getPlot = () => {\n // For unit testing etc, this layer may be created without a parent.\n const panel = this.parent;\n return panel ? panel.parent : null;\n };\n // deselect() method - shortcut method to deselect the element\n item.deselect = () => {\n const data_layer = this.getDataLayer();\n data_layer.unselectElement(this); // dynamically generated method name. It exists, honest.\n };\n });\n this.applyCustomDataMethods();\n return this;\n }\n\n /**\n * Hook that allows custom datalayers to apply additional methods and properties to data elements as needed\n * @protected\n * @returns {BaseDataLayer}\n */\n applyCustomDataMethods() {\n return this;\n }\n\n /**\n * Apply scaling functions to an element as needed, based on the layout rules governing display + the element's data\n * If the layout parameter is already a primitive type, simply return the value as given\n *\n * In the future this may be further expanded, so that scaling functions can operate similar to mappers\n * (item, index, array). Additional arguments would be added as the need arose.\n *\n * @protected\n * @param {Array|Number|String|Object} layout Either a scalar (\"color is red\") or a configuration object\n * (\"rules for how to choose color based on item value\")\n * @param {*} element_data The value to be used with the filter. May be a primitive value, or a data object for a single item\n * @param {Number} data_index The array index for the data element\n * @returns {*} The transformed value\n */\n resolveScalableParameter (layout, element_data, data_index) {\n let ret = null;\n if (Array.isArray(layout)) {\n let idx = 0;\n while (ret === null && idx < layout.length) {\n ret = this.resolveScalableParameter(layout[idx], element_data, data_index);\n idx++;\n }\n } else {\n switch (typeof layout) {\n case 'number':\n case 'string':\n ret = layout;\n break;\n case 'object':\n if (layout.scale_function) {\n const func = scalable.get(layout.scale_function);\n if (layout.field) {\n const f = new Field(layout.field);\n let extra;\n try {\n extra = this.layer_state && this.layer_state.extra_fields[this.getElementId(element_data)];\n } catch (e) {\n extra = null;\n }\n ret = func(layout.parameters || {}, f.resolve(element_data, extra), data_index);\n } else {\n ret = func(layout.parameters || {}, element_data, data_index);\n }\n }\n break;\n }\n }\n return ret;\n }\n\n /**\n * Generate dimension extent function based on layout parameters\n * @protected\n * @param {('x'|'y')} dimension\n */\n getAxisExtent (dimension) {\n\n if (!['x', 'y'].includes(dimension)) {\n throw new Error('Invalid dimension identifier');\n }\n\n const axis_name = `${dimension}_axis`;\n const axis_layout = this.layout[axis_name];\n\n // If a floor AND a ceiling are explicitly defined then just return that extent and be done\n if (!isNaN(axis_layout.floor) && !isNaN(axis_layout.ceiling)) {\n return [+axis_layout.floor, +axis_layout.ceiling];\n }\n\n // If a field is defined for the axis and the data layer has data then generate the extent from the data set\n let data_extent = [];\n if (axis_layout.field && this.data) {\n if (!this.data.length) {\n // If data has been fetched (but no points in region), enforce the min_extent (with no buffers,\n // because we don't need padding around an empty screen)\n data_extent = axis_layout.min_extent || [];\n return data_extent;\n } else {\n data_extent = this._getDataExtent(this.data, axis_layout);\n\n // Apply upper/lower buffers, if applicable\n const original_extent_span = data_extent[1] - data_extent[0];\n if (!isNaN(axis_layout.lower_buffer)) {\n data_extent[0] -= original_extent_span * axis_layout.lower_buffer;\n }\n if (!isNaN(axis_layout.upper_buffer)) {\n data_extent[1] += original_extent_span * axis_layout.upper_buffer;\n }\n\n if (typeof axis_layout.min_extent == 'object') {\n // The data should span at least the range specified by min_extent, an array with [low, high]\n const range_min = axis_layout.min_extent[0];\n const range_max = axis_layout.min_extent[1];\n if (!isNaN(range_min) && !isNaN(range_max)) {\n data_extent[0] = Math.min(data_extent[0], range_min);\n }\n if (!isNaN(range_max)) {\n data_extent[1] = Math.max(data_extent[1], range_max);\n }\n }\n // If specified, floor and ceiling will override the actual data range\n return [\n isNaN(axis_layout.floor) ? data_extent[0] : axis_layout.floor,\n isNaN(axis_layout.ceiling) ? data_extent[1] : axis_layout.ceiling,\n ];\n }\n }\n\n // If this is for the x axis and no extent could be generated yet but state has a defined start and end\n // then default to using the state-defined region as the extent\n if (dimension === 'x' && !isNaN(this.state.start) && !isNaN(this.state.end)) {\n return [this.state.start, this.state.end];\n }\n\n // No conditions met for generating a valid extent, return an empty array\n return [];\n\n }\n\n /**\n * Allow this data layer to tell the panel what axis ticks it thinks it will require. The panel may choose whether\n * to use some, all, or none of these when rendering, either alone or in conjunction with other data layers.\n *\n * This method is a stub and should be overridden in data layers that need to specify custom behavior.\n *\n * @protected\n * @param {('x'|'y1'|'y2')} dimension\n * @param {Object} [config] Additional parameters for the panel to specify how it wants ticks to be drawn. The names\n * and meanings of these parameters may vary between different data layers.\n * @returns {Object[]}\n * An array of objects: each object must have an 'x' attribute to position the tick.\n * Other supported object keys:\n * * text: string to render for a given tick\n * * style: d3-compatible CSS style object\n * * transform: SVG transform attribute string\n * * color: string or LocusZoom scalable parameter object\n */\n getTicks (dimension, config) {\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error(`Invalid dimension identifier ${dimension}`);\n }\n return [];\n }\n\n /**\n * Determine the coordinates for where to point the tooltip at. Typically, this is the center of a datum element (eg,\n * the middle of a scatter plot point). Also provide an offset if the tooltip should not be at that center (most\n * elements are not single points, eg a scatter plot point has a radius and a gene is a rectangle).\n * The default implementation is quite naive: it places the tooltip at the origin for that layer. Individual layers\n * should override this method to position relative to the chosen data element or mouse event.\n * @protected\n * @param {Object} tooltip A tooltip object (including attribute tooltip.data)\n * @returns {Object} as {x_min, x_max, y_min, y_max} in px, representing bounding box of a rectangle around the data pt\n * Note that these pixels are in the SVG coordinate system\n */\n _getTooltipPosition(tooltip) {\n const panel = this.parent;\n\n const y_scale = panel[`y${this.layout.y_axis.axis}_scale`];\n const y_extent = panel[`y${this.layout.y_axis.axis}_extent`];\n\n const x = panel.x_scale(panel.x_extent[0]);\n const y = y_scale(y_extent[0]);\n\n return { x_min: x, x_max: x, y_min: y, y_max: y };\n }\n\n /**\n * Draw a tooltip on the data layer pointed at the specified coordinates, in the specified orientation.\n * Tooltip will be drawn on the edge of the major axis, and centered along the minor axis- see diagram.\n * v\n * > o <\n * ^\n *\n * @protected\n * @param tooltip {Object} The object representing all data for the tooltip to be drawn\n * @param {'vertical'|'horizontal'|'top'|'bottom'|'left'|'right'} position Where to draw the tooltip relative to\n * the data\n * @param {Number} x_min The min x-coordinate for the bounding box of the data element\n * @param {Number} x_max The max x-coordinate for the bounding box of the data element\n * @param {Number} y_min The min y-coordinate for the bounding box of the data element\n * @param {Number} y_max The max y-coordinate for the bounding box of the data element\n */\n _drawTooltip(tooltip, position, x_min, x_max, y_min, y_max) {\n const panel_layout = this.parent.layout;\n const layer_layout = this.layout;\n\n // Tooltip position params: as defined in the default stylesheet, used in calculations\n const arrow_size = 7;\n const stroke_width = 1;\n const arrow_total = arrow_size + stroke_width; // Tooltip pos should account for how much space the arrow takes up\n\n const tooltip_padding = 6; // bbox size must account for any internal padding applied between data and border\n\n const page_origin = this._getPageOrigin();\n const tooltip_box = tooltip.selector.node().getBoundingClientRect();\n const data_layer_height = panel_layout.height - (panel_layout.margin.top + panel_layout.margin.bottom);\n const data_layer_width = panel_layout.width - (panel_layout.margin.left + panel_layout.margin.right);\n\n // Clip the edges of the datum to the available plot area\n x_min = Math.max(x_min, 0);\n x_max = Math.min(x_max, data_layer_width);\n y_min = Math.max(y_min, 0);\n y_max = Math.min(y_max, data_layer_height);\n\n const x_center = (x_min + x_max) / 2;\n const y_center = (y_min + y_max) / 2;\n // Default offsets are the far edge of the datum bounding box\n let x_offset = x_max - x_center;\n let y_offset = y_max - y_center;\n let placement = layer_layout.tooltip_positioning;\n\n // Coordinate system note: the tooltip is positioned relative to the plot/page; the arrow is positioned relative to\n // the tooltip boundaries\n let tooltip_top, tooltip_left, arrow_type, arrow_top, arrow_left;\n\n // The user can specify a generic orientation, and LocusZoom will autoselect whether to place the tooltip above or below\n if (placement === 'vertical') {\n // Auto-select whether to position above the item, or below\n x_offset = 0;\n if (tooltip_box.height + arrow_total > data_layer_height - (y_center + y_offset)) {\n placement = 'top';\n } else {\n placement = 'bottom';\n }\n } else if (placement === 'horizontal') {\n // Auto select whether to position to the left of the item, or to the right\n y_offset = 0;\n if (x_center <= panel_layout.width / 2) {\n placement = 'left';\n } else {\n placement = 'right';\n }\n }\n\n if (placement === 'top' || placement === 'bottom') {\n // Position horizontally centered above the point\n const offset_right = Math.max((tooltip_box.width / 2) - x_center, 0);\n const offset_left = Math.max((tooltip_box.width / 2) + x_center - data_layer_width, 0);\n tooltip_left = page_origin.x + x_center - (tooltip_box.width / 2) - offset_left + offset_right;\n arrow_left = page_origin.x + x_center - tooltip_left - arrow_size; // Arrow should be centered over the data\n // Position vertically above the point unless there's insufficient space, then go below\n if (placement === 'top') {\n tooltip_top = page_origin.y + y_center - (y_offset + tooltip_box.height + arrow_total);\n arrow_type = 'down';\n arrow_top = tooltip_box.height - stroke_width;\n } else {\n tooltip_top = page_origin.y + y_center + y_offset + arrow_total;\n arrow_type = 'up';\n arrow_top = 0 - arrow_total;\n }\n } else if (placement === 'left' || placement === 'right') {\n // Position tooltip horizontally on the left or the right depending on which side of the plot the point is on\n if (placement === 'left') {\n tooltip_left = page_origin.x + x_center + x_offset + arrow_total;\n arrow_type = 'left';\n arrow_left = -1 * (arrow_size + stroke_width);\n } else {\n tooltip_left = page_origin.x + x_center - tooltip_box.width - x_offset - arrow_total;\n arrow_type = 'right';\n arrow_left = tooltip_box.width - stroke_width;\n }\n // Position with arrow vertically centered along tooltip edge unless we're at the top or bottom of the plot\n if (y_center - (tooltip_box.height / 2) <= 0) { // Too close to the top, push it down\n tooltip_top = page_origin.y + y_center - (1.5 * arrow_size) - tooltip_padding;\n arrow_top = tooltip_padding;\n } else if (y_center + (tooltip_box.height / 2) >= data_layer_height) { // Too close to the bottom, pull it up\n tooltip_top = page_origin.y + y_center + arrow_size + tooltip_padding - tooltip_box.height;\n arrow_top = tooltip_box.height - (2 * arrow_size) - tooltip_padding;\n } else { // vertically centered\n tooltip_top = page_origin.y + y_center - (tooltip_box.height / 2);\n arrow_top = (tooltip_box.height / 2) - arrow_size;\n }\n } else {\n throw new Error('Unrecognized placement value');\n }\n\n // Position the div itself, relative to the layer origin\n tooltip.selector\n .style('left', `${tooltip_left}px`)\n .style('top', `${tooltip_top}px`);\n // Create / update position on arrow connecting tooltip to data\n if (!tooltip.arrow) {\n tooltip.arrow = tooltip.selector.append('div')\n .style('position', 'absolute');\n }\n tooltip.arrow\n .attr('class', `lz-data_layer-tooltip-arrow_${arrow_type}`)\n .style('left', `${arrow_left}px`)\n .style('top', `${arrow_top}px`);\n return this;\n }\n\n /**\n * Find the elements (or indices) that match any of a set of provided filters\n * @protected\n * @param {Array[]} filters A list of filter entries: [field, value] (for equivalence testing) or\n * [field, operator, value] for other operators\n * @param {('indexes'|'elements')} [return_type='indexes'] Specify whether to return either the indices of the matching\n * elements, or references to the elements themselves\n * @returns {Array}\n */\n filter(filters, return_type) {\n if (typeof return_type == 'undefined' || !['indexes', 'elements'].includes(return_type)) {\n return_type = 'indexes';\n }\n if (!Array.isArray(filters)) {\n return [];\n }\n const test = (element, filter) => {\n const operators = {\n '=': (a, b) => a === b,\n // eslint-disable-next-line eqeqeq\n '!=': (a, b) => a != b, // For absence of a value, deliberately allow weak comparisons (eg undefined/null)\n '<': (a, b) => a < b,\n '<=': (a, b) => a <= b,\n '>': (a, b) => a > b,\n '>=': (a, b) => a >= b,\n '%': (a, b) => a % b,\n };\n\n if (!Array.isArray(filter)) {\n return false;\n }\n if (filter.length === 2) {\n return element[filter[0]] === filter[1];\n } else if (filter.length === 3 && operators[filter[1]]) {\n return operators[filter[1]](element[filter[0]], filter[2]);\n } else {\n return false;\n }\n };\n const matches = [];\n this.data.forEach((element, idx) => {\n let match = true;\n filters.forEach((filter) => {\n if (!test(element, filter)) {\n match = false;\n }\n });\n if (match) {\n matches.push(return_type === 'indexes' ? idx : element);\n }\n });\n return matches;\n }\n\n /**\n * Get \"annotation\" metadata associated with a particular point.\n *\n * @protected\n * @param {String|Object} element The data object or ID string for the element\n * @param {String} key The name of the annotation to track\n * @return {*}\n */\n getElementAnnotation (element, key) {\n const id = this.getElementId(element);\n const extra = this.layer_state.extra_fields[id];\n return extra && extra[key];\n }\n\n /****** Private methods: rarely overridden or modified by external usages */\n\n /**\n * Define default state that should get tracked during the lifetime of this layer.\n *\n * In some special custom usages, it may be useful to completely reset a panel (eg \"click for\n * genome region\" links), plotting new data that invalidates any previously tracked state. This hook makes it\n * possible to reset without destroying the panel entirely. It is used by `Plot.clearPanelData`.\n * @private\n */\n _setDefaultState() {\n // Each datalayer tracks two kinds of status: flags for internal state (highlighted, selected, tooltip),\n // and \"extra fields\" (annotations like \"show a tooltip\" that are not determined by the server, but need to\n // persist across re-render)\n const layer_state = { status_flags: {}, extra_fields: {} };\n const status_flags = layer_state.status_flags;\n STATUSES.adjectives.forEach((status) => {\n status_flags[status] = status_flags[status] || [];\n });\n // Also initialize \"internal-only\" state fields (things that are tracked, but not set directly by external events)\n status_flags['has_tooltip'] = status_flags['has_tooltip'] || [];\n\n if (this.parent) {\n // If layer has a parent, store a reference in the overarching plot.state object\n this.state_id = `${this.parent.id}.${this.id}`;\n this.state = this.parent.state;\n this.state[this.state_id] = layer_state;\n }\n this.layer_state = layer_state;\n }\n\n /**\n * Get the fully qualified identifier for the data layer, prefixed by any parent or container elements\n *\n * @private\n * @returns {string} A dot-delimited string of the format ..\n */\n getBaseId () {\n if (this.parent) {\n return `${this.parent_plot.id}.${this.parent.id}.${this.id}`;\n } else {\n return '';\n }\n }\n\n /**\n * Determine the pixel height of data-bound objects represented inside this data layer. (excluding elements such as axes)\n *\n * May be used by operations that resize the data layer to fit available data\n *\n * @private\n * @returns {number}\n */\n getAbsoluteDataHeight() {\n const dataBCR = this.svg.group.node().getBoundingClientRect();\n return dataBCR.height;\n }\n\n /**\n * Initialize a data layer\n * @private\n * @returns {BaseDataLayer}\n */\n initialize() {\n\n // Append a container group element to house the main data layer group element and the clip path\n const base_id = this.getBaseId();\n this.svg.container = this.parent.svg.group.append('g')\n .attr('class', 'lz-data_layer-container')\n .attr('id', `${base_id}.data_layer_container`);\n\n // Append clip path to the container element\n this.svg.clipRect = this.svg.container.append('clipPath')\n .attr('id', `${base_id}.clip`)\n .append('rect');\n\n // Append svg group for rendering all data layer elements, clipped by the clip path\n this.svg.group = this.svg.container.append('g')\n .attr('id', `${base_id}.data_layer`)\n .attr('clip-path', `url(#${base_id}.clip)`);\n\n return this;\n\n }\n\n /**\n * Generate a tool tip for a given element\n * @private\n * @param {String|Object} data Data for the element associated with the tooltip\n */\n createTooltip (data) {\n if (typeof this.layout.tooltip != 'object') {\n throw new Error(`DataLayer [${this.id}] layout does not define a tooltip`);\n }\n const id = this.getElementId(data);\n if (this.tooltips[id]) {\n this.positionTooltip(id);\n return;\n }\n this.tooltips[id] = {\n data: data,\n arrow: null,\n selector: d3.select(this.parent_plot.svg.node().parentNode).append('div')\n .attr('class', 'lz-data_layer-tooltip')\n .attr('id', `${id}-tooltip`),\n };\n this.layer_state.status_flags['has_tooltip'].push(id);\n this.updateTooltip(data);\n return this;\n }\n\n /**\n * Update a tool tip (generate its inner HTML)\n *\n * @private\n * @param {String|Object} d The element associated with the tooltip\n * @param {String} [id] An identifier to the tooltip\n */\n updateTooltip(d, id) {\n if (typeof id == 'undefined') {\n id = this.getElementId(d);\n }\n // Empty the tooltip of all HTML (including its arrow!)\n this.tooltips[id].selector.html('');\n this.tooltips[id].arrow = null;\n // Set the new HTML\n if (this.layout.tooltip.html) {\n this.tooltips[id].selector.html(parseFields(d, this.layout.tooltip.html));\n }\n // If the layout allows tool tips on this data layer to be closable then add the close button\n // and add padding to the tooltip to accommodate it\n if (this.layout.tooltip.closable) {\n this.tooltips[id].selector.insert('button', ':first-child')\n .attr('class', 'lz-tooltip-close-button')\n .attr('title', 'Close')\n .text('×')\n .on('click', () => {\n this.destroyTooltip(id);\n });\n }\n // Apply data directly to the tool tip for easier retrieval by custom UI elements inside the tool tip\n this.tooltips[id].selector.data([d]);\n // Reposition and draw a new arrow\n this.positionTooltip(id);\n return this;\n }\n\n /**\n * Destroy tool tip - remove the tool tip element from the DOM and delete the tool tip's record on the data layer\n *\n * @private\n * @param {String|Object} element_or_id The element (or id) associated with the tooltip\n * @param {boolean} [temporary=false] Whether this is temporary (not to be tracked in state). Differentiates\n * \"recreate tooltips on re-render\" (which is temporary) from \"user has closed this tooltip\" (permanent)\n * @returns {BaseDataLayer}\n */\n destroyTooltip(element_or_id, temporary) {\n let id;\n if (typeof element_or_id == 'string') {\n id = element_or_id;\n } else {\n id = this.getElementId(element_or_id);\n }\n if (this.tooltips[id]) {\n if (typeof this.tooltips[id].selector == 'object') {\n this.tooltips[id].selector.remove();\n }\n delete this.tooltips[id];\n }\n // When a tooltip is removed, also remove the reference from the state\n if (!temporary) {\n const state = this.layer_state.status_flags['has_tooltip'];\n const label_mark_position = state.indexOf(id);\n state.splice(label_mark_position, 1);\n }\n return this;\n }\n\n /**\n * Loop through and destroy all tool tips on this data layer\n *\n * @private\n * @returns {BaseDataLayer}\n */\n destroyAllTooltips() {\n for (let id in this.tooltips) {\n this.destroyTooltip(id, true);\n }\n return this;\n }\n\n /**\n * Position and then redraw tool tip - naïve function to place a tool tip in the data layer. By default, positions wrt\n * the top-left corner of the data layer.\n *\n * Each layer type may have more specific logic. Consider overriding the provided hooks `_getTooltipPosition` or\n * `_drawTooltip` as appropriate\n *\n * @private\n * @param {String} id The identifier of the tooltip to position\n * @returns {BaseDataLayer}\n */\n positionTooltip(id) {\n if (typeof id != 'string') {\n throw new Error('Unable to position tooltip: id is not a string');\n }\n if (!this.tooltips[id]) {\n throw new Error('Unable to position tooltip: id does not point to a valid tooltip');\n }\n const tooltip = this.tooltips[id];\n const coords = this._getTooltipPosition(tooltip);\n\n if (!coords) {\n // Special cutout: normally, tooltips are positioned based on the datum element. Some, like lines/curves,\n // work better if based on a mouse event. Since not every redraw contains a mouse event, we can just skip\n // calculating position when no position information is available.\n return null;\n }\n this._drawTooltip(tooltip, this.layout.tooltip_positioning, coords.x_min, coords.x_max, coords.y_min, coords.y_max);\n }\n\n /**\n * Loop through and position all tool tips on this data layer\n *\n * @private\n * @returns {BaseDataLayer}\n */\n positionAllTooltips() {\n for (let id in this.tooltips) {\n this.positionTooltip(id);\n }\n return this;\n }\n\n /**\n * Show or hide a tool tip by ID depending on directives in the layout and state values relative to the ID\n *\n * @private\n * @param {String|Object} element The element associated with the tooltip\n * @param {boolean} first_time Because panels can re-render, the rules for showing a tooltip\n * depend on whether this is the first time a status change affecting display has been applied.\n * @returns {BaseDataLayer}\n */\n showOrHideTooltip(element, first_time) {\n if (typeof this.layout.tooltip != 'object') {\n return this;\n }\n const id = this.getElementId(element);\n\n /**\n * Apply rules and decide whether to show or hide the tooltip\n * @param {Object} statuses All statuses that apply to an element\n * @param {String[]|object} directive A layout directive object\n * @param operator\n * @returns {null|bool}\n */\n const resolveStatus = (statuses, directive, operator) => {\n let status = null;\n if (typeof statuses != 'object' || statuses === null) {\n return null;\n }\n if (Array.isArray(directive)) {\n // This happens when the function is called on the inner part of the directive\n operator = operator || 'and';\n if (directive.length === 1) {\n status = statuses[directive[0]];\n } else {\n status = directive.reduce((previousValue, currentValue) => {\n if (operator === 'and') {\n return statuses[previousValue] && statuses[currentValue];\n } else if (operator === 'or') {\n return statuses[previousValue] || statuses[currentValue];\n }\n return null;\n });\n }\n } else if (typeof directive == 'object') {\n let sub_status;\n for (let sub_operator in directive) {\n sub_status = resolveStatus(statuses, directive[sub_operator], sub_operator);\n if (status === null) {\n status = sub_status;\n } else if (operator === 'and') {\n status = status && sub_status;\n } else if (operator === 'or') {\n status = status || sub_status;\n }\n }\n } else {\n return false;\n }\n return status;\n };\n\n let show_directive = {};\n if (typeof this.layout.tooltip.show == 'string') {\n show_directive = { and: [ this.layout.tooltip.show ] };\n } else if (typeof this.layout.tooltip.show == 'object') {\n show_directive = this.layout.tooltip.show;\n }\n\n let hide_directive = {};\n if (typeof this.layout.tooltip.hide == 'string') {\n hide_directive = { and: [ this.layout.tooltip.hide ] };\n } else if (typeof this.layout.tooltip.hide == 'object') {\n hide_directive = this.layout.tooltip.hide;\n }\n\n // Find all the statuses that apply to just this single element\n const layer_state = this.layer_state;\n var status_flags = {}; // {status_name: bool}\n STATUSES.adjectives.forEach((status) => {\n const antistatus = `un${status}`;\n status_flags[status] = (layer_state.status_flags[status].includes(id));\n status_flags[antistatus] = !status_flags[status];\n });\n\n // Decide whether to show/hide the tooltip based solely on the underlying element\n const show_resolved = resolveStatus(status_flags, show_directive);\n const hide_resolved = resolveStatus(status_flags, hide_directive);\n\n // Most of the tooltip display logic depends on behavior layouts: was point (un)selected, (un)highlighted, etc.\n // But sometimes, a point is selected, and the user then closes the tooltip. If the panel is re-rendered for\n // some outside reason (like state change), we must track this in the create/destroy events as tooltip state.\n const has_tooltip = (layer_state.status_flags['has_tooltip'].includes(id));\n const tooltip_was_closed = first_time ? false : !has_tooltip;\n if (show_resolved && !tooltip_was_closed && !hide_resolved) {\n this.createTooltip(element);\n } else {\n this.destroyTooltip(element);\n }\n\n return this;\n }\n\n /**\n * @private\n * @param filters\n * @returns {Array}\n */\n filterIndexes(filters) {\n return this.filter(filters, 'indexes');\n }\n\n /**\n * @private\n * @param filters\n * @returns {Array}\n */\n filterElements(filters) {\n return this.filter(filters, 'elements');\n }\n\n /**\n * Toggle a status (e.g. highlighted, selected, identified) on an element\n *\n * @private\n *\n * @param {String} status The name of a recognized status to be added/removed on an appropriate element\n * @param {String|Object} element The data bound to the element of interest\n * @param {Boolean} active True to add the status (and associated CSS styles); false to remove it\n * @param {Boolean} exclusive Whether to only allow a state for a single element at a time\n * @returns {BaseDataLayer}\n */\n setElementStatus(status, element, active, exclusive) {\n if (status === 'has_tooltip') {\n // This is a special adjective that exists solely to track tooltip state. It has no CSS and never gets set\n // directly. It is invisible to the official enums.\n return this;\n }\n if (typeof active == 'undefined') {\n active = true;\n }\n\n // Get an ID for the element or return having changed nothing\n let element_id;\n try {\n element_id = this.getElementId(element);\n } catch (get_element_id_error) {\n return this;\n }\n\n // Enforce exclusivity (force all elements to have the opposite of toggle first)\n if (exclusive) {\n this.setAllElementStatus(status, !active);\n }\n\n // Set/unset the proper status class on the appropriate DOM element(s)\n d3.select(`#${element_id}`).classed(`lz-data_layer-${this.layout.type}-${status}`, active);\n const element_status_node_id = this.getElementStatusNodeId(element);\n if (element_status_node_id !== null) {\n d3.select(`#${element_status_node_id}`).classed(`lz-data_layer-${this.layout.type}-statusnode-${status}`, active);\n }\n\n // Track element ID in the proper status state array\n const element_status_idx = this.layer_state.status_flags[status].indexOf(element_id);\n const added_status = (element_status_idx === -1); // On a re-render, existing statuses will be reapplied.\n if (active && added_status) {\n this.layer_state.status_flags[status].push(element_id);\n }\n if (!active && !added_status) {\n this.layer_state.status_flags[status].splice(element_status_idx, 1);\n }\n\n // Trigger tool tip show/hide logic\n this.showOrHideTooltip(element, added_status);\n\n // Trigger layout changed event hook\n if (added_status) {\n this.parent.emit('layout_changed', true);\n }\n\n const is_selected = (status === 'selected');\n if (is_selected && (added_status || !active)) {\n // Notify parents that an element has changed selection status (either active, or inactive)\n this.parent.emit('element_selection', { element: element, active: active }, true);\n }\n\n const value_to_broadcast = (this.layout.match && this.layout.match.send);\n if (is_selected && value_to_broadcast && (added_status || !active)) {\n this.parent.emit(\n 'match_requested',\n { value: element[value_to_broadcast], active: active },\n true\n );\n }\n return this;\n }\n\n /**\n * Toggle a status on elements in the data layer based on a set of filters\n *\n * @private\n * @param {String} status\n * @param {Boolean} toggle\n * @param {Array} filters\n * @param {Boolean} exclusive\n * @returns {BaseDataLayer}\n */\n setElementStatusByFilters(status, toggle, filters, exclusive) {\n\n // Sanity check\n if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) {\n throw new Error('Invalid status');\n }\n if (typeof this.layer_state.status_flags[status] == 'undefined') {\n return this;\n }\n if (typeof toggle == 'undefined') {\n toggle = true;\n } else {\n toggle = !!toggle;\n }\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n if (!Array.isArray(filters)) {\n filters = [];\n }\n\n // Enforce exclusivity (force all elements to have the opposite of toggle first)\n if (exclusive) {\n this.setAllElementStatus(status, !toggle);\n }\n\n // Apply statuses\n this.filterElements(filters).forEach((element) => {\n this.setElementStatus(status, element, toggle);\n });\n\n return this;\n }\n\n /**\n * Toggle a status on all elements in the data layer\n *\n * @private\n * @param {String} status\n * @param {Boolean} toggle\n * @returns {BaseDataLayer}\n */\n setAllElementStatus(status, toggle) {\n\n // Sanity check\n if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) {\n throw new Error('Invalid status');\n }\n if (typeof this.layer_state.status_flags[status] == 'undefined') {\n return this;\n }\n if (typeof toggle == 'undefined') {\n toggle = true;\n }\n\n // Apply statuses\n if (toggle) {\n this.data.forEach((element) => this.setElementStatus(status, element, true));\n } else {\n const status_ids = this.layer_state.status_flags[status].slice();\n status_ids.forEach((id) => {\n const element = this.getElementById(id);\n if (typeof element == 'object' && element !== null) {\n this.setElementStatus(status, element, false);\n }\n });\n this.layer_state.status_flags[status] = [];\n }\n\n // Update global status flag\n this.global_statuses[status] = toggle;\n\n return this;\n }\n\n /**\n * Apply all layout-defined behaviors (DOM event handlers) to a selection of elements\n *\n * @private\n * @param {d3.selection} selection\n */\n applyBehaviors(selection) {\n if (typeof this.layout.behaviors != 'object') {\n return;\n }\n Object.keys(this.layout.behaviors).forEach((directive) => {\n const event_match = /(click|mouseover|mouseout)/.exec(directive);\n if (!event_match) {\n return;\n }\n selection.on(`${event_match[0]}.${directive}`, this.executeBehaviors(directive, this.layout.behaviors[directive]));\n });\n }\n\n /**\n * Generate a function that executes an arbitrary list of behaviors on an element during an event\n *\n * @private\n * @param {String} directive The name of the event, as described in layout.behaviors for this datalayer\n * @param {Object[]} behaviors An object describing the behavior to attach to this single element\n * @param {string} behaviors.action The name of the action that would trigger this behavior (eg click, mouseover, etc)\n * @param {string} behaviors.status What status to apply to the element when this behavior is triggered (highlighted,\n * selected, etc)\n * @param {boolean} [behaviors.exclusive] Whether triggering the event for this element should unset the relevant status\n * for all other elements. Useful for, eg, click events that exclusively highlight one thing.\n * @returns {function(this:BaseDataLayer)} Return a function that handles the event in context with the behavior\n * and the element- can be attached as an event listener\n */\n executeBehaviors(directive, behaviors) {\n\n // Determine the required state of control and shift keys during the event\n const requiredKeyStates = {\n 'ctrl': (directive.includes('ctrl')),\n 'shift': (directive.includes('shift')),\n };\n const self = this;\n return function(element) {\n\n // Do nothing if the required control and shift key presses (or lack thereof) doesn't match the event\n if (requiredKeyStates.ctrl !== !!d3.event.ctrlKey || requiredKeyStates.shift !== !!d3.event.shiftKey) {\n return;\n }\n\n // Loop through behaviors making each one go in succession\n behaviors.forEach((behavior) => {\n\n // Route first by the action, if defined\n if (typeof behavior != 'object' || behavior === null) {\n return;\n }\n\n const current_status_boolean = (self.layer_state.status_flags[behavior.status].includes(self.getElementId(element)));\n const exclusive = behavior.exclusive && !current_status_boolean;\n\n switch (behavior.action) {\n\n // Set a status (set to true regardless of current status, optionally with exclusivity)\n case 'set':\n self.setElementStatus(behavior.status, element, true, behavior.exclusive);\n break;\n\n // Unset a status (set to false regardless of current status, optionally with exclusivity)\n case 'unset':\n self.setElementStatus(behavior.status, element, false, behavior.exclusive);\n break;\n\n // Toggle a status\n case 'toggle':\n self.setElementStatus(behavior.status, element, !current_status_boolean, exclusive);\n break;\n\n // Link to a dynamic URL\n case 'link':\n if (typeof behavior.href == 'string') {\n const url = parseFields(element, behavior.href);\n if (typeof behavior.target == 'string') {\n window.open(url, behavior.target);\n } else {\n window.location.href = url;\n }\n }\n break;\n\n // Action not defined, just return\n default:\n break;\n }\n });\n };\n }\n\n /**\n * Get an object with the x and y coordinates of the panel's origin in terms of the entire page\n * Necessary for positioning any HTML elements over the panel\n *\n * @private\n * @returns {{x: Number, y: Number}}\n */\n _getPageOrigin() {\n const panel_origin = this.parent._getPageOrigin();\n return {\n x: panel_origin.x + this.parent.layout.margin.left,\n y: panel_origin.y + this.parent.layout.margin.top,\n };\n }\n\n /**\n * Apply all tracked element statuses. This is primarily intended for re-rendering the plot, in order to preserve\n * behaviors when items are updated.\n * @private\n */\n applyAllElementStatus () {\n const status_flags = this.layer_state.status_flags;\n const self = this;\n for (let property in status_flags) {\n if (!Object.prototype.hasOwnProperty.call(status_flags, property)) {\n continue;\n }\n if (Array.isArray(status_flags[property])) {\n status_flags[property].forEach((element_id) => {\n try {\n this.setElementStatus(property, this.getElementById(element_id), true);\n } catch (e) {\n console.warn(`Unable to apply state: ${self.state_id}, ${property}`);\n console.error(e);\n }\n });\n }\n }\n }\n\n /**\n * Position the datalayer and all tooltips\n * @private\n * @returns {BaseDataLayer}\n */\n draw() {\n this.svg.container\n .attr('transform', `translate(${this.parent.layout.cliparea.origin.x}, ${this.parent.layout.cliparea.origin.y})`);\n this.svg.clipRect\n .attr('width', this.parent.layout.cliparea.width)\n .attr('height', this.parent.layout.cliparea.height);\n this.positionAllTooltips();\n return this;\n }\n\n /**\n * Re-Map a data layer to reflect changes in the state of a plot (such as viewing region/ chromosome range)\n *\n * @private\n * @return {Promise}\n */\n reMap() {\n this.destroyAllTooltips(); // hack - only non-visible tooltips should be destroyed\n // and then recreated if returning to visibility\n\n // Fetch new data. Datalayers are only given access to the final consolidated data from the chain (not headers or raw payloads)\n const promise = this.parent_plot.lzd.getData(this.state, this.layout.fields);\n promise.then((new_data) => {\n this.data = new_data.body;\n this.applyDataMethods();\n this.initialized = true;\n });\n\n return promise;\n }\n}\n\nSTATUSES.verbs.forEach((verb, idx) => {\n const adjective = STATUSES.adjectives[idx];\n const antiverb = `un${verb}`;\n // Set/unset a single element's status\n\n /**\n * @private\n * @function highlightElement\n */\n /**\n * @private\n * @function selectElement\n */\n /**\n * @private\n * @function fadeElement\n */\n /**\n * @private\n * @function hideElement\n */\n BaseDataLayer.prototype[`${verb}Element`] = function(element, exclusive) {\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n this.setElementStatus(adjective, element, true, exclusive);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightElement\n */\n /**\n * @private\n * @function unselectElement\n */\n /**\n * @private\n * @function unfadeElement\n */\n /**\n * @private\n * @function unhideElement\n */\n BaseDataLayer.prototype[`${antiverb}Element`] = function(element, exclusive) {\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n this.setElementStatus(adjective, element, false, exclusive);\n return this;\n };\n\n\n /**\n * @private\n * @function highlightElementsByFilters\n */\n /**\n * @private\n * @function selectElementsByFilters\n */\n /**\n * @private\n * @function fadeElementsByFilters\n */\n /**\n * @private\n * @function hideElementsByFilters\n */\n // Set/unset status for arbitrarily many elements given a set of filters\n BaseDataLayer.prototype[`${verb}ElementsByFilters`] = function(filters, exclusive) {\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n return this.setElementStatusByFilters(adjective, true, filters, exclusive);\n };\n\n /**\n * @private\n * @function unhighlightElementsByFilters\n */\n /**\n * @private\n * @function unselectElementsByFilters\n */\n /**\n * @private\n * @function unfadeElementsByFilters\n */\n /**\n * @private\n * @function unhideElementsByFilters\n */\n BaseDataLayer.prototype[`${antiverb}ElementsByFilters`] = function(filters, exclusive) {\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n return this.setElementStatusByFilters(adjective, false, filters, exclusive);\n };\n\n /**\n * @private\n * @function highlightAllElements\n */\n /**\n * @private\n * @function selectAllElements\n */\n /**\n * @private\n * @function fadeAllElements\n */\n /**\n * @private\n * @function hideAllElements\n */\n // Set/unset status for all elements\n BaseDataLayer.prototype[`${verb}AllElements`] = function() {\n this.setAllElementStatus(adjective, true);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightAllElements\n */\n /**\n * @private\n * @function unselectAllElements\n */\n /**\n * @private\n * @function unfadeAllElements\n * */\n /**\n * @private\n * @function unhideAllElements\n */\n BaseDataLayer.prototype[`${antiverb}AllElements`] = function() {\n this.setAllElementStatus(adjective, false);\n return this;\n };\n});\n\nexport {BaseDataLayer as default};\n","/** @module */\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\n\nconst default_layout = {\n color: '#000000',\n filters: [],\n tooltip_positioning: 'vertical', // Allowed values: top, middle, bottom\n hitarea_width: 8,\n};\n\n/**\n * Create a single continuous 2D track that provides information about each datapoint\n *\n * For example, this can be used to color by membership in a group, alongside information in other panels\n *\n * @param {Object} layout\n * @param {Object|String} [layout.color]\n * @param {Array[]} An array of filter entries specifying which points to draw annotations for.\n * See `BaseDataLayer.filter` for details\n */\n\nclass AnnotationTrack extends BaseDataLayer {\n constructor(layout) {\n if (!Array.isArray(layout.filters)) {\n throw new Error('Annotation track must specify array of filters for selecting points to annotate');\n }\n merge(layout, default_layout);\n super(...arguments);\n }\n\n render() {\n // Only render points that currently satisfy all provided filter conditions.\n const trackData = this.filter(this.layout.filters, 'elements');\n\n // Put the containing visible lines before the one containing hit areas, so that the hit areas will be on top.\n let visible_lines_group = this.svg.group.select(`g.lz-data_layer-${this.layout.type}-visible_lines`);\n if (visible_lines_group.size() === 0) {\n visible_lines_group = this.svg.group.append('g')\n .attr('class', `lz-data_layer-${this.layout.type}-visible_lines`);\n }\n const selection = visible_lines_group.selectAll(`rect.lz-data_layer-${this.layout.type}`)\n .data(trackData, (d) => d[this.layout.id_field]);\n\n const width = 1;\n // Draw rectangles (visual and tooltip positioning)\n selection.enter()\n .append('rect')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n .attr('id', (d) => this.getElementId(d))\n .merge(selection)\n .attr('x', (d) => this.parent['x_scale'](d[this.layout.x_axis.field]) - width / 2)\n .attr('width', width)\n .attr('height', this.parent.layout.height)\n .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i));\n\n // Remove unused elements\n selection.exit()\n .remove();\n\n let hit_areas_group = this.svg.group.select(`g.lz-data_layer-${this.layout.type}-hit_areas`);\n if (hit_areas_group.size() === 0) {\n hit_areas_group = this.svg.group.append('g')\n .attr('class', `lz-data_layer-${this.layout.type}-hit_areas`);\n }\n const hit_areas_selection = hit_areas_group.selectAll(`rect.lz-data_layer-${this.layout.type}`)\n .data(trackData, (d) => d[this.layout.id_field]);\n\n const _getX = (d, i) => { // Helper for position calcs below\n const x_center = this.parent['x_scale'](d[this.layout.x_axis.field]);\n let x_left = x_center - this.layout.hitarea_width / 2;\n if (i >= 1) {\n // This assumes that the data are in sorted order.\n const left_node = trackData[i - 1];\n const left_node_x_center = this.parent['x_scale'](left_node[this.layout.x_axis.field]);\n x_left = Math.max(x_left, (x_center + left_node_x_center) / 2);\n }\n return [x_left, x_center];\n };\n\n // Add new elements as needed\n hit_areas_selection.enter()\n .append('rect')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n .attr('id', (d) => this.getElementId(d))\n // Update the set of elements to reflect new data\n .merge(hit_areas_selection)\n .attr('height', this.parent.layout.height)\n .attr('opacity', 0)\n .attr('x', (d, i) => {\n const crds = _getX(d, i);\n return crds[0];\n }).attr('width', (d, i) => {\n const crds = _getX(d, i);\n return (crds[1] - crds[0]) + this.layout.hitarea_width / 2;\n })\n // Set up tooltips and mouse interaction\n .call(this.applyBehaviors.bind(this));\n\n // Remove unused elements\n hit_areas_selection.exit()\n .remove();\n }\n\n _getTooltipPosition(tooltip) {\n const panel = this.parent;\n const data_layer_height = panel.layout.height - (panel.layout.margin.top + panel.layout.margin.bottom);\n const stroke_width = 1; // as defined in the default stylesheet\n\n const x_center = panel.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_center = data_layer_height / 2;\n return {\n x_min: x_center - stroke_width,\n x_max: x_center + stroke_width,\n y_min: y_center - panel.layout.margin.top,\n y_max: y_center + panel.layout.margin.bottom,\n };\n }\n}\n\nexport {AnnotationTrack as default};\n","/**\n * Arc Data Layer\n * Implements a data layer that will render chromatin accessibility tracks.\n * This layer draws arcs (one per datapoint) that connect two endpoints (x.field1 and x.field2) by means of an arc,\n * with a height determined by y.field.\n * @module\n */\nimport * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\nimport {applyStyles} from '../../helpers/common';\n\nconst default_layout = {\n color: 'seagreen',\n hitarea_width: '10px',\n style: {\n fill: 'none',\n 'stroke-width': '1px',\n 'stroke-opacity': '100%',\n },\n tooltip_positioning: 'top',\n};\n\nclass Arcs extends BaseDataLayer {\n constructor(layout) {\n layout = merge(layout, default_layout);\n super(...arguments);\n }\n\n // Implement the main render function\n render() {\n const self = this;\n const layout = self.layout;\n const x_scale = self.parent['x_scale'];\n const y_scale = self.parent[`y${layout.y_axis.axis}_scale`];\n\n // Optionally restrict the data to a specific set of filters\n const filters = layout.filters || [];\n const trackData = this.filter(filters, 'elements');\n\n // Helper: Each individual data point describes a path composed of 3 points, with a spline to smooth the line\n function _make_line(d) {\n const x1 = d[layout.x_axis.field1];\n const x2 = d[layout.x_axis.field2];\n const xmid = (x1 + x2) / 2;\n const coords = [\n [x_scale(x1), y_scale(0)],\n [x_scale(xmid), y_scale(d[layout.y_axis.field])],\n [x_scale(x2), y_scale(0)],\n ];\n // Smoothing options: https://bl.ocks.org/emmasaunders/f7178ed715a601c5b2c458a2c7093f78\n const line = d3.line()\n .x((d) => d[0])\n .y((d) => d[1])\n .curve(d3.curveNatural);\n return line(coords);\n }\n\n // Draw real lines, and also invisible hitareas for easier mouse events\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-arcs')\n .data(trackData, (d) => this.getElementId(d));\n\n const hitareas = this.svg.group\n .selectAll('path.lz-data_layer-arcs-hitarea')\n .data(trackData, (d) => this.getElementId(d));\n\n // Add new points as necessary\n selection\n .enter()\n .append('path')\n .attr('class', 'lz-data_layer-arcs')\n .attr('id', (d) => this.getElementId(d))\n .merge(selection)\n .attr('stroke', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))\n .attr('d', (d, i) => _make_line(d))\n .call(applyStyles, layout.style);\n\n hitareas\n .enter()\n .append('path')\n .attr('class', 'lz-data_layer-arcs-hitarea')\n .attr('id', (d) => this.getElementId(d))\n .merge(hitareas)\n .style('fill', 'none')\n .style('stroke-width', layout.hitarea_width)\n .style('stroke-opacity', 0)\n .style('stroke', 'transparent')\n .attr('d', (d) => _make_line(d))\n // Apply mouse behaviors to hitareas\n .call(this.applyBehaviors.bind(this));\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n hitareas.exit()\n .remove();\n return this;\n }\n\n _getTooltipPosition(tooltip) {\n // Center the tooltip arrow at the apex of the arc. Sometimes, only part of an arc shows on the screen, so we\n // clean up these values to ensure that the tooltip will appear within the window.\n const panel = this.parent;\n const layout = this.layout;\n\n const x1 = tooltip.data[layout.x_axis.field1];\n const x2 = tooltip.data[layout.x_axis.field2];\n\n const y_scale = panel[`y${layout.y_axis.axis}_scale`];\n\n return {\n x_min: panel.x_scale(Math.min(x1, x2)),\n x_max: panel.x_scale(Math.max(x1, x2)),\n y_min: y_scale(tooltip.data[layout.y_axis.field]),\n y_max: y_scale(0),\n };\n }\n\n}\n\nexport {Arcs as default};\n","/** @module */\nimport * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport Field from '../../data/field';\nimport {merge, nameToSymbol} from '../../helpers/layouts';\n\n\nconst default_layout = {\n point_size: 40,\n point_shape: 'square',\n color: '#888888',\n fill_opacity: 1,\n y_axis: {\n axis: 2,\n },\n id_field: 'id',\n confidence_intervals: {\n start_field: 'ci_start',\n end_field: 'ci_end',\n },\n show_no_significance_line: true,\n};\n\n/**\n * Forest Data Layer\n * Implements a standard forest plot. In order to space out points, any layout using this must specify axis ticks\n * and extent in advance.\n *\n * If you are using dynamically fetched data, consider using `category_forest` instead.\n *\n */\nclass Forest extends BaseDataLayer {\n constructor(layout) {\n layout = merge(layout, default_layout);\n super(...arguments);\n }\n\n _getTooltipPosition(tooltip) {\n const x_center = this.parent.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const y_center = this.parent[y_scale](tooltip.data[this.layout.y_axis.field]);\n\n const point_size = this.resolveScalableParameter(this.layout.point_size, tooltip.data);\n const offset = Math.sqrt(point_size / Math.PI);\n return {\n x_min: x_center - offset,\n x_max: x_center + offset,\n y_min: y_center - offset,\n y_max: y_center + offset,\n };\n }\n\n // Implement the main render function\n render() {\n\n const x_scale = 'x_scale';\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n\n // Generate confidence interval paths if fields are defined\n if (this.layout.confidence_intervals\n && this.layout.fields.includes(this.layout.confidence_intervals.start_field)\n && this.layout.fields.includes(this.layout.confidence_intervals.end_field)) {\n // Generate a selection for all forest plot confidence intervals\n const ci_selection = this.svg.group\n .selectAll('rect.lz-data_layer-forest.lz-data_layer-forest-ci')\n .data(this.data, (d) => {\n return d[this.layout.id_field];\n });\n\n const ci_transform = (d) => {\n let x = this.parent[x_scale](d[this.layout.confidence_intervals.start_field]);\n let y = this.parent[y_scale](d[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n return `translate(${x}, ${y})`;\n };\n const ci_width = (d) => {\n return this.parent[x_scale](d[this.layout.confidence_intervals.end_field])\n - this.parent[x_scale](d[this.layout.confidence_intervals.start_field]);\n };\n const ci_height = 1;\n // Create confidence interval rect elements\n ci_selection.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-forest lz-data_layer-forest-ci')\n .attr('id', (d) => `${this.getElementId(d)}_ci`)\n .attr('transform', `translate(0, ${isNaN(this.parent.layout.height) ? 0 : this.parent.layout.height})`)\n .merge(ci_selection)\n .attr('transform', ci_transform)\n .attr('width', ci_width)\n .attr('height', ci_height);\n\n // Remove old elements as needed\n ci_selection.exit()\n .remove();\n }\n\n // Generate a selection for all forest plot points\n const points_selection = this.svg.group\n .selectAll('path.lz-data_layer-forest.lz-data_layer-forest-point')\n .data(this.data, (d) => {\n return d[this.layout.id_field];\n });\n\n // Create elements, apply class, ID, and initial position\n const initial_y = isNaN(this.parent.layout.height) ? 0 : this.parent.layout.height;\n\n // Generate new values (or functions for them) for position, color, size, and shape\n const transform = (d) => {\n let x = this.parent[x_scale](d[this.layout.x_axis.field]);\n let y = this.parent[y_scale](d[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n return `translate(${x}, ${y})`;\n };\n\n const fill = (d, i) => this.resolveScalableParameter(this.layout.color, d, i);\n const fill_opacity = (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i);\n\n const shape = d3.symbol()\n .size((d, i) => this.resolveScalableParameter(this.layout.point_size, d, i))\n .type((d, i) => nameToSymbol(this.resolveScalableParameter(this.layout.point_shape, d, i)));\n\n points_selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-forest lz-data_layer-forest-point')\n .attr('id', (d) => this.getElementId(d))\n .attr('transform', `translate(0, ${initial_y})`)\n .merge(points_selection)\n .attr('transform', transform)\n .attr('fill', fill)\n .attr('fill-opacity', fill_opacity)\n .attr('d', shape)\n // Apply behaviors to points\n .on('click.event_emitter', (element_data) => {\n this.parent.emit('element_clicked', element_data, true);\n }).call(this.applyBehaviors.bind(this));\n\n // Remove old elements as needed\n points_selection.exit()\n .remove();\n }\n}\n\n\n/**\n * A y-aligned forest plot in which the y-axis represents item labels, which are dynamically chosen when data is loaded.\n * Each item is assumed to include both data and confidence intervals.\n * This allows generating forest plots without defining the layout in advance.\n *\n */\nclass CategoryForest extends Forest {\n _getDataExtent(data, axis_config) {\n // In a forest plot, the data range is determined by *three* fields (beta + CI start/end)\n const ci_config = this.layout.confidence_intervals;\n if (ci_config\n && this.layout.fields.includes(ci_config.start_field)\n && this.layout.fields.includes(ci_config.end_field)) {\n const min = (d) => {\n const f = new Field(ci_config.start_field);\n return +f.resolve(d);\n };\n\n const max = (d) => {\n const f = new Field(ci_config.end_field);\n return +f.resolve(d);\n };\n\n return [d3.min(data, min), d3.max(data, max)];\n }\n\n // If there are no confidence intervals set, then range must depend only on a single field\n return super._getDataExtent(data, axis_config);\n }\n\n getTicks(dimension, config) { // Overrides parent method\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error(`Invalid dimension identifier ${dimension}`);\n }\n\n // Design assumption: one axis (y1 or y2) has the ticks, and the layout says which to use\n // Also assumes that every tick gets assigned a unique matching label\n const axis_num = this.layout.y_axis.axis;\n if (dimension === (`y${axis_num}`)) {\n const category_field = this.layout.y_axis.category_field;\n if (!category_field) {\n throw new Error(`Layout for ${this.layout.id} must specify category_field`);\n }\n\n return this.data.map((item, index) => ({ y: index + 1, text: item[category_field] }));\n } else {\n return [];\n }\n }\n\n applyCustomDataMethods () {\n // Add a synthetic yaxis field to ensure data is spread out on plot. Then, set axis floor and ceiling to\n // correct extents.\n const field_to_add = this.layout.y_axis.field;\n if (!field_to_add) {\n throw new Error(`Layout for ${this.layout.id} must specify yaxis.field`);\n }\n\n this.data = this.data.map((item, index) => {\n item[field_to_add] = index + 1;\n return item;\n });\n // Update axis extents based on one label for every point (with a bit of padding above and below)\n this.layout.y_axis.floor = 0;\n this.layout.y_axis.ceiling = this.data.length + 1;\n return this;\n }\n}\n\nexport { Forest as forest, CategoryForest as category_forest };\n","/** @module */\nimport * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\n\nconst default_layout = {\n // Optionally specify different fill and stroke properties\n stroke: 'rgb(54, 54, 150)',\n color: '#363696',\n label_font_size: 12,\n label_exon_spacing: 3,\n exon_height: 10,\n bounding_box_padding: 3,\n track_vertical_spacing: 5,\n tooltip_positioning: 'top',\n};\n\n\n/*********************\n * Genes Data Layer\n * Implements a data layer that will render gene tracks\n*/\nclass Genes extends BaseDataLayer {\n constructor(layout) {\n layout = merge(layout, default_layout);\n super(...arguments);\n /**\n * A gene may have arbitrarily many transcripts, but this data layer isn't set up to render them yet.\n * Stash a transcript_idx to point to the first transcript and use that for all transcript refs.\n * @member {number}\n * @type {number}\n */\n this.transcript_idx = 0;\n\n /**\n * An internal counter for the number of tracks in the data layer. Used as an internal counter for looping\n * over positions / assignments\n * @protected\n * @member {number}\n */\n this.tracks = 1;\n\n /**\n * Store information about genes in dataset, in a hash indexed by track number: {track_number: [gene_indices]}\n * @member {Object.}\n */\n this.gene_track_index = { 1: [] };\n }\n\n /**\n * Generate a statusnode ID for a given element\n * @override\n * @returns {String}\n */\n getElementStatusNodeId(element) {\n return `${this.getElementId(element)}-statusnode`;\n }\n\n /**\n * Helper function to sum layout values to derive total height for a single gene track\n * @returns {number}\n */\n getTrackHeight() {\n return 2 * this.layout.bounding_box_padding\n + this.layout.label_font_size\n + this.layout.label_exon_spacing\n + this.layout.exon_height\n + this.layout.track_vertical_spacing;\n }\n\n /**\n * Ensure that genes in overlapping chromosome regions are positioned so that parts of different genes do not\n * overlap in the view. A track is a row used to vertically separate overlapping genes.\n * @returns {Genes}\n */\n assignTracks() {\n /**\n * Function to get the width in pixels of a label given the text and layout attributes\n * @param {String} gene_name\n * @param {number|string} font_size\n * @returns {number}\n */\n const _getLabelWidth = (gene_name, font_size) => {\n try {\n const temp_text = this.svg.group.append('text')\n .attr('x', 0)\n .attr('y', 0)\n .attr('class', 'lz-data_layer-genes lz-label')\n .style('font-size', font_size)\n .text(`${gene_name}→`);\n const label_width = temp_text.node().getBBox().width;\n temp_text.remove();\n return label_width;\n } catch (e) {\n return 0;\n }\n };\n\n // Reinitialize some metadata\n this.tracks = 1;\n this.gene_track_index = { 1: [] };\n\n this.data.map((item) => {\n\n // If necessary, split combined gene id / version fields into discrete fields.\n // NOTE: this may be an issue with CSG's genes data source that may eventually be solved upstream.\n if (item.gene_id && item.gene_id.indexOf('.')) {\n const split = item.gene_id.split('.');\n item.gene_id = split[0];\n item.gene_version = split[1];\n }\n\n // Stash the transcript ID on the parent gene\n item.transcript_id = item.transcripts[this.transcript_idx].transcript_id;\n\n // Determine display range start and end, based on minimum allowable gene display width, bounded by what we can see\n // (range: values in terms of pixels on the screen)\n item.display_range = {\n start: this.parent.x_scale(Math.max(item.start, this.state.start)),\n end: this.parent.x_scale(Math.min(item.end, this.state.end)),\n };\n item.display_range.label_width = _getLabelWidth(item.gene_name, this.layout.label_font_size);\n item.display_range.width = item.display_range.end - item.display_range.start;\n // Determine label text anchor (default to middle)\n item.display_range.text_anchor = 'middle';\n if (item.display_range.width < item.display_range.label_width) {\n if (item.start < this.state.start) {\n item.display_range.end = item.display_range.start\n + item.display_range.label_width\n + this.layout.label_font_size;\n item.display_range.text_anchor = 'start';\n } else if (item.end > this.state.end) {\n item.display_range.start = item.display_range.end\n - item.display_range.label_width\n - this.layout.label_font_size;\n item.display_range.text_anchor = 'end';\n } else {\n const centered_margin = ((item.display_range.label_width - item.display_range.width) / 2)\n + this.layout.label_font_size;\n if ((item.display_range.start - centered_margin) < this.parent.x_scale(this.state.start)) {\n item.display_range.start = this.parent.x_scale(this.state.start);\n item.display_range.end = item.display_range.start + item.display_range.label_width;\n item.display_range.text_anchor = 'start';\n } else if ((item.display_range.end + centered_margin) > this.parent.x_scale(this.state.end)) {\n item.display_range.end = this.parent.x_scale(this.state.end);\n item.display_range.start = item.display_range.end - item.display_range.label_width;\n item.display_range.text_anchor = 'end';\n } else {\n item.display_range.start -= centered_margin;\n item.display_range.end += centered_margin;\n }\n }\n item.display_range.width = item.display_range.end - item.display_range.start;\n }\n // Add bounding box padding to the calculated display range start, end, and width\n item.display_range.start -= this.layout.bounding_box_padding;\n item.display_range.end += this.layout.bounding_box_padding;\n item.display_range.width += 2 * this.layout.bounding_box_padding;\n // Convert and stash display range values into domain values\n // (domain: values in terms of the data set, e.g. megabases)\n item.display_domain = {\n start: this.parent.x_scale.invert(item.display_range.start),\n end: this.parent.x_scale.invert(item.display_range.end),\n };\n item.display_domain.width = item.display_domain.end - item.display_domain.start;\n\n // Using display range/domain data generated above cast each gene to tracks such that none overlap\n item.track = null;\n let potential_track = 1;\n while (item.track === null) {\n let collision_on_potential_track = false;\n this.gene_track_index[potential_track].map((placed_gene) => {\n if (!collision_on_potential_track) {\n const min_start = Math.min(placed_gene.display_range.start, item.display_range.start);\n const max_end = Math.max(placed_gene.display_range.end, item.display_range.end);\n if ((max_end - min_start) < (placed_gene.display_range.width + item.display_range.width)) {\n collision_on_potential_track = true;\n }\n }\n });\n if (!collision_on_potential_track) {\n item.track = potential_track;\n this.gene_track_index[potential_track].push(item);\n } else {\n potential_track++;\n if (potential_track > this.tracks) {\n this.tracks = potential_track;\n this.gene_track_index[potential_track] = [];\n }\n }\n }\n\n // Stash parent references on all genes, trascripts, and exons\n item.parent = this;\n item.transcripts.map((d, t) => {\n item.transcripts[t].parent = item;\n item.transcripts[t].exons.map((d, e) => item.transcripts[t].exons[e].parent = item.transcripts[t]);\n });\n\n });\n return this;\n }\n\n /**\n * Main render function\n */\n render() {\n\n const self = this;\n this.assignTracks();\n\n let width, height, x, y;\n\n // Render gene groups\n const selection = this.svg.group.selectAll('g.lz-data_layer-genes')\n .data(this.data, (d) => d.gene_name);\n\n selection.enter()\n .append('g')\n .attr('class', 'lz-data_layer-genes')\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .each(function(gene) {\n const data_layer = gene.parent;\n\n // Render gene bounding boxes (status nodes to show selected/highlighted)\n const bboxes = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-data_layer-genes-statusnode')\n .data([gene], (d) => data_layer.getElementStatusNodeId(d));\n\n width = (d) => d.display_range.width;\n height = data_layer.getTrackHeight() - data_layer.layout.track_vertical_spacing;\n x = (d) => d.display_range.start;\n y = (d) => ((d.track - 1) * data_layer.getTrackHeight());\n\n bboxes.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-data_layer-genes-statusnode')\n .merge(bboxes)\n .attr('id', (d) => data_layer.getElementStatusNodeId(d))\n .attr('rx', data_layer.layout.bounding_box_padding)\n .attr('ry', data_layer.layout.bounding_box_padding)\n .attr('width', width)\n .attr('height', height)\n .attr('x', x)\n .attr('y', y);\n\n bboxes.exit()\n .remove();\n\n // Render gene boundaries\n const boundary_fill = (d, i) => self.resolveScalableParameter(self.layout.color, d, i);\n const boundary_stroke = (d, i) => self.resolveScalableParameter(self.layout.stroke, d, i);\n const boundaries = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-boundary')\n .data([gene], (d) => `${d.gene_name}_boundary`)\n .style('fill', boundary_fill)\n .style('stroke', boundary_stroke);\n\n width = (d) => data_layer.parent.x_scale(d.end) - data_layer.parent.x_scale(d.start);\n height = 1;\n x = (d) => data_layer.parent.x_scale(d.start);\n y = function(d) {\n return ((d.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size\n + data_layer.layout.label_exon_spacing\n + (Math.max(data_layer.layout.exon_height, 3) / 2);\n };\n\n boundaries.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-boundary')\n .merge(boundaries)\n .attr('width', width)\n .attr('height', height)\n .attr('x', x)\n .attr('y', y);\n\n boundaries.exit()\n .remove();\n\n // Render gene labels\n const labels = d3.select(this).selectAll('text.lz-data_layer-genes.lz-label')\n .data([gene], (d) => `${d.gene_name}_label`);\n\n x = (d) => {\n if (d.display_range.text_anchor === 'middle') {\n return d.display_range.start + (d.display_range.width / 2);\n } else if (d.display_range.text_anchor === 'start') {\n return d.display_range.start + data_layer.layout.bounding_box_padding;\n } else if (d.display_range.text_anchor === 'end') {\n return d.display_range.end - data_layer.layout.bounding_box_padding;\n }\n };\n y = (d) => ((d.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size;\n\n labels.enter()\n .append('text')\n .attr('class', 'lz-data_layer-genes lz-label')\n .merge(labels)\n .attr('text-anchor', (d) => d.display_range.text_anchor)\n .text((d) => (d.strand === '+') ? `${d.gene_name}→` : `←${d.gene_name}`)\n .style('font-size', gene.parent.layout.label_font_size)\n .attr('x', x)\n .attr('y', y);\n\n labels.exit()\n .remove();\n\n // Render exon rects (first transcript only, for now)\n // Exons: by default color on gene properties for consistency with the gene boundary track- hence color uses d.parent.parent\n const exon_fill = (d, i) => self.resolveScalableParameter(self.layout.color, d.parent.parent, i);\n const exon_stroke = (d, i) => self.resolveScalableParameter(self.layout.stroke, d.parent.parent, i);\n\n const exons = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-exon')\n .data(gene.transcripts[gene.parent.transcript_idx].exons, (d) => d.exon_id);\n\n width = (d) => data_layer.parent.x_scale(d.end) - data_layer.parent.x_scale(d.start);\n height = data_layer.layout.exon_height;\n x = (d) => data_layer.parent.x_scale(d.start);\n y = function() {\n return ((gene.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size\n + data_layer.layout.label_exon_spacing;\n };\n\n exons.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-exon')\n .merge(exons)\n .style('fill', exon_fill)\n .style('stroke', exon_stroke)\n .attr('width', width)\n .attr('height', height)\n .attr('x', x)\n .attr('y', y);\n\n exons.exit()\n .remove();\n\n // Render gene click area\n const clickareas = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-clickarea')\n .data([gene], (d) => `${d.gene_name}_clickarea`);\n\n width = (d) => d.display_range.width;\n height = data_layer.getTrackHeight() - data_layer.layout.track_vertical_spacing;\n x = (d) => d.display_range.start;\n y = (d) => ((d.track - 1) * data_layer.getTrackHeight());\n clickareas.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-clickarea')\n .merge(clickareas)\n .attr('id', (d) => `${data_layer.getElementId(d)}_clickarea`)\n .attr('rx', data_layer.layout.bounding_box_padding)\n .attr('ry', data_layer.layout.bounding_box_padding)\n .attr('width', width)\n .attr('height', height)\n .attr('x', x)\n .attr('y', y)\n // Apply mouse behaviors & events to clickareas\n .on('click.event_emitter', (element) => element.parent.parent.emit('element_clicked', element, true))\n .call(data_layer.applyBehaviors.bind(data_layer));\n\n // Remove old clickareas as needed\n clickareas.exit()\n .remove();\n });\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n }\n\n _getTooltipPosition(tooltip) {\n const gene_bbox_id = this.getElementStatusNodeId(tooltip.data);\n const gene_bbox = d3.select(`#${gene_bbox_id}`).node().getBBox();\n return {\n x_min: this.parent.x_scale(tooltip.data.start),\n x_max: this.parent.x_scale(tooltip.data.end),\n y_min: gene_bbox.y,\n y_max: gene_bbox.y + gene_bbox.height,\n };\n }\n}\n\nexport {Genes as default};\n","/** @module */\nimport * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\nimport {STATUSES} from '../constants';\nimport {applyStyles} from '../../helpers/common';\n\nconst default_layout = {\n style: {\n fill: 'none',\n 'stroke-width': '2px',\n },\n interpolate: 'curveLinear',\n x_axis: { field: 'x' },\n y_axis: { field: 'y', axis: 1 },\n hitarea_width: 5,\n};\n\n/*********************\n * Line Data Layer\n * Implements a standard line plot, representing either a trace or a filled curve.\n*/\nclass Line extends BaseDataLayer {\n constructor(layout) {\n layout = merge(layout, default_layout);\n if (layout.tooltip) {\n throw new Error('The line / filled curve layer does not support tooltips');\n }\n super(...arguments);\n }\n\n /**\n * Implement the main render function\n */\n render() {\n // Several vars needed to be in scope\n const panel = this.parent;\n const x_field = this.layout.x_axis.field;\n const y_field = this.layout.y_axis.field;\n\n // Join data to the line selection\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-line')\n .data([this.data]);\n\n // Create path element, apply class\n this.path = selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-line');\n\n // Generate the line\n let line;\n const x_scale = panel['x_scale'];\n const y_scale = panel[`y${this.layout.y_axis.axis}_scale`];\n if (this.layout.style.fill && this.layout.style.fill !== 'none') {\n // Filled curve: define the line as a filled boundary\n line = d3.area()\n .x((d) => +x_scale(d[x_field]))\n .y0(+y_scale(0))\n .y1((d) => +y_scale(d[y_field]));\n } else {\n // Basic line\n line = d3.line()\n .x((d) => +x_scale(d[x_field]))\n .y((d) => +y_scale(d[y_field]))\n .curve(d3[this.layout.interpolate]);\n }\n\n // Apply line and style\n selection.merge(this.path)\n .attr('d', line)\n .call(applyStyles, this.layout.style);\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n }\n\n /**\n * Redefine setElementStatus family of methods as line data layers will only ever have a single path element\n * @param {String} status A member of `LocusZoom.DataLayer.Statuses.adjectives`\n * @param {String|Object} element\n * @param {Boolean} toggle\n * @returns {Line}\n */\n setElementStatus(status, element, toggle) {\n return this.setAllElementStatus(status, toggle);\n }\n\n setElementStatusByFilters(status, toggle) {\n return this.setAllElementStatus(status, toggle);\n }\n\n setAllElementStatus(status, toggle) {\n // Sanity check\n if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) {\n throw new Error('Invalid status');\n }\n if (typeof this.layer_state.status_flags[status] == 'undefined') {\n return this;\n }\n if (typeof toggle == 'undefined') {\n toggle = true;\n }\n\n // Update global status flag\n this.global_statuses[status] = toggle;\n\n // Apply class to path based on global status flags\n let path_class = 'lz-data_layer-line';\n Object.keys(this.global_statuses).forEach((global_status) => {\n if (this.global_statuses[global_status]) {\n path_class += ` lz-data_layer-line-${global_status}`;\n }\n });\n this.path.attr('class', path_class);\n\n // Trigger layout changed event hook\n this.parent.emit('layout_changed', true);\n return this;\n }\n}\n\nconst default_orthogonal_layout = {\n style: {\n 'stroke': '#D3D3D3',\n 'stroke-width': '3px',\n 'stroke-dasharray': '10px 10px',\n },\n orientation: 'horizontal',\n x_axis: {\n axis: 1,\n decoupled: true,\n },\n y_axis: {\n axis: 1,\n decoupled: true,\n },\n tooltip_positioning: 'vertical',\n offset: 0,\n};\n\n\n/***************************\n * Orthogonal Line Data Layer\n * Implements a horizontal or vertical line given an orientation and an offset in the layout\n * Does not require a data source\n*/\nclass OrthogonalLine extends BaseDataLayer {\n constructor(layout) {\n layout = merge(layout, default_orthogonal_layout);\n // Require that orientation be \"horizontal\" or \"vertical\" only\n if (!['horizontal', 'vertical'].includes(layout.orientation)) {\n layout.orientation = 'horizontal';\n }\n super(...arguments);\n\n // Vars for storing the data generated line\n /** @member {Array} */\n this.data = [];\n }\n\n getElementId(element) {\n // There is only one line per datalayer, so this is sufficient.\n return this.getBaseId();\n }\n\n /**\n * Implement the main render function\n */\n render() {\n\n // Several vars needed to be in scope\n const panel = this.parent;\n const x_scale = 'x_scale';\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const x_extent = 'x_extent';\n const y_extent = `y${this.layout.y_axis.axis}_extent`;\n const x_range = 'x_range';\n\n // Generate data using extents depending on orientation\n if (this.layout.orientation === 'horizontal') {\n this.data = [\n { x: panel[x_extent][0], y: this.layout.offset },\n { x: panel[x_extent][1], y: this.layout.offset },\n ];\n } else if (this.layout.orientation === 'vertical') {\n this.data = [\n { x: this.layout.offset, y: panel[y_extent][0] },\n { x: this.layout.offset, y: panel[y_extent][1] },\n ];\n } else {\n throw new Error('Unrecognized vertical line type. Must be \"vertical\" or \"horizontal\"');\n }\n\n // Join data to the line selection\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-line')\n .data([this.data]);\n\n // In some cases, a vertical line may overlay a track that has no inherent y-values (extent)\n // When that happens, provide a default height based on the current panel dimensions (accounting\n // for any resizing that happened after the panel was created)\n const default_y = [panel.layout.cliparea.height, 0];\n\n // Generate the line\n const line = d3.line()\n .x((d, i) => {\n const x = +panel[x_scale](d['x']);\n return isNaN(x) ? panel[x_range][i] : x;\n })\n .y((d, i) => {\n const y = +panel[y_scale](d['y']);\n return isNaN(y) ? default_y[i] : y;\n });\n\n // Create path element, apply class\n this.path = selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-line')\n .merge(selection)\n .attr('d', line)\n .call(applyStyles, this.layout.style)\n // Allow the layer to respond to mouseover events and show a tooltip.\n .call(this.applyBehaviors.bind(this));\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n }\n\n _getTooltipPosition(tooltip) {\n try {\n const coords = d3.mouse(this.svg.container.node());\n const x = coords[0];\n const y = coords[1];\n return { x_min: x - 1, x_max: x + 1, y_min: y - 1, y_max: y + 1 };\n } catch (e) {\n // On redraw, there won't be a mouse event, so skip tooltip repositioning.\n return null;\n }\n }\n\n}\n\n\nexport { Line as line, OrthogonalLine as orthogonal_line };\n","/** @module */\nimport * as d3 from 'd3';\nimport BaseDataLayer from './base';\nimport Field from '../../data/field';\nimport {applyStyles} from '../../helpers/common';\nimport {parseFields} from '../../helpers/display';\nimport {merge, nameToSymbol} from '../../helpers/layouts';\n\n\nconst default_layout = {\n point_size: 40,\n point_shape: 'circle',\n tooltip_positioning: 'horizontal',\n color: '#888888',\n fill_opacity: 1,\n y_axis: {\n axis: 1,\n },\n id_field: 'id',\n};\n/**\n * Scatter Data Layer\n * Implements a standard scatter plot\n */\nclass Scatter extends BaseDataLayer {\n constructor(layout) {\n layout = merge(layout, default_layout);\n\n // Extra default for layout spacing\n // Not in default layout since that would make the label attribute always present\n if (layout.label && isNaN(layout.label.spacing)) {\n layout.label.spacing = 4;\n }\n super(...arguments);\n }\n\n // Implement tooltip position to be layer-specific\n _getTooltipPosition(tooltip) {\n const x_center = this.parent.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const y_center = this.parent[y_scale](tooltip.data[this.layout.y_axis.field]);\n const point_size = this.resolveScalableParameter(this.layout.point_size, tooltip.data);\n const offset = Math.sqrt(point_size / Math.PI);\n\n return {\n x_min: x_center - offset, x_max: x_center + offset,\n y_min: y_center - offset, y_max: y_center + offset,\n };\n }\n\n // Function to flip labels from being anchored at the start of the text to the end\n // Both to keep labels from running outside the data layer and also as a first\n // pass on recursive separation\n flip_labels() {\n const data_layer = this;\n // Base positions on the default point size (which is what resolve scalable param returns if no data provided)\n const point_size = data_layer.resolveScalableParameter(data_layer.layout.point_size, {});\n const spacing = data_layer.layout.label.spacing;\n const handle_lines = Boolean(data_layer.layout.label.lines);\n const min_x = 2 * spacing;\n const max_x = this.parent.layout.width - this.parent.layout.margin.left - this.parent.layout.margin.right - (2 * spacing);\n\n const flip = (dn, dnl) => {\n const dnx = +dn.attr('x');\n const text_swing = (2 * spacing) + (2 * Math.sqrt(point_size));\n let dnlx2;\n let line_swing;\n if (handle_lines) {\n dnlx2 = +dnl.attr('x2');\n line_swing = spacing + (2 * Math.sqrt(point_size));\n }\n if (dn.style('text-anchor') === 'start') {\n dn.style('text-anchor', 'end');\n dn.attr('x', dnx - text_swing);\n if (handle_lines) {\n dnl.attr('x2', dnlx2 - line_swing);\n }\n } else {\n dn.style('text-anchor', 'start');\n dn.attr('x', dnx + text_swing);\n if (handle_lines) {\n dnl.attr('x2', dnlx2 + line_swing);\n }\n }\n };\n // Flip any going over the right edge from the right side to the left side\n // (all labels start on the right side)\n data_layer.label_texts.each(function (d, i) {\n const a = this;\n const da = d3.select(a);\n const dax = +da.attr('x');\n const abound = da.node().getBoundingClientRect();\n if (dax + abound.width + spacing > max_x) {\n const dal = handle_lines ? d3.select(data_layer.label_lines.nodes()[i]) : null;\n flip(da, dal);\n }\n });\n // Second pass to flip any others that haven't flipped yet if they collide with another label\n data_layer.label_texts.each(function (d, i) {\n const a = this;\n const da = d3.select(a);\n if (da.style('text-anchor') === 'end') {\n return;\n }\n let dax = +da.attr('x');\n const abound = da.node().getBoundingClientRect();\n const dal = handle_lines ? d3.select(data_layer.label_lines.nodes()[i]) : null;\n data_layer.label_texts.each(function () {\n const b = this;\n const db = d3.select(b);\n const bbound = db.node().getBoundingClientRect();\n const collision = abound.left < bbound.left + bbound.width + (2 * spacing) &&\n abound.left + abound.width + (2 * spacing) > bbound.left &&\n abound.top < bbound.top + bbound.height + (2 * spacing) &&\n abound.height + abound.top + (2 * spacing) > bbound.top;\n if (collision) {\n flip(da, dal);\n // Double check that this flip didn't push the label past min_x. If it did, immediately flip back.\n dax = +da.attr('x');\n if (dax - abound.width - spacing < min_x) {\n flip(da, dal);\n }\n }\n });\n });\n }\n\n // Recursive function to space labels apart immediately after initial render\n // Adapted from thudfactor's fiddle here: https://jsfiddle.net/thudfactor/HdwTH/\n // TODO: Make labels also aware of data elements\n separate_labels() {\n this.seperate_iterations++;\n const data_layer = this;\n const alpha = 0.5;\n if (!this.layout.label) {\n // Guard against layout changing in the midst of iterative rerender\n return;\n }\n const spacing = this.layout.label.spacing;\n let again = false;\n data_layer.label_texts.each(function () {\n // TODO: O(n2) algorithm; revisit performance?\n const a = this;\n const da = d3.select(a);\n const y1 = da.attr('y');\n data_layer.label_texts.each(function () {\n const b = this;\n // a & b are the same element and don't collide.\n if (a === b) {\n return;\n }\n const db = d3.select(b);\n // a & b are on opposite sides of the chart and\n // don't collide\n if (da.attr('text-anchor') !== db.attr('text-anchor')) {\n return;\n }\n // Determine if the bounding rects for the two text elements collide\n const abound = da.node().getBoundingClientRect();\n const bbound = db.node().getBoundingClientRect();\n const collision = abound.left < bbound.left + bbound.width + (2 * spacing) &&\n abound.left + abound.width + (2 * spacing) > bbound.left &&\n abound.top < bbound.top + bbound.height + (2 * spacing) &&\n abound.height + abound.top + (2 * spacing) > bbound.top;\n if (!collision) {\n return;\n }\n again = true;\n // If the labels collide, we'll push each\n // of the two labels up and down a little bit.\n const y2 = db.attr('y');\n const sign = abound.top < bbound.top ? 1 : -1;\n const adjust = sign * alpha;\n let new_a_y = +y1 - adjust;\n let new_b_y = +y2 + adjust;\n // Keep new values from extending outside the data layer\n const min_y = 2 * spacing;\n const max_y = data_layer.parent.layout.height - data_layer.parent.layout.margin.top - data_layer.parent.layout.margin.bottom - (2 * spacing);\n let delta;\n if (new_a_y - (abound.height / 2) < min_y) {\n delta = +y1 - new_a_y;\n new_a_y = +y1;\n new_b_y += delta;\n } else if (new_b_y - (bbound.height / 2) < min_y) {\n delta = +y2 - new_b_y;\n new_b_y = +y2;\n new_a_y += delta;\n }\n if (new_a_y + (abound.height / 2) > max_y) {\n delta = new_a_y - +y1;\n new_a_y = +y1;\n new_b_y -= delta;\n } else if (new_b_y + (bbound.height / 2) > max_y) {\n delta = new_b_y - +y2;\n new_b_y = +y2;\n new_a_y -= delta;\n }\n da.attr('y', new_a_y);\n db.attr('y', new_b_y);\n });\n });\n if (again) {\n // Adjust lines to follow the labels\n if (data_layer.layout.label.lines) {\n const label_elements = data_layer.label_texts.nodes();\n data_layer.label_lines.attr('y2', (d, i) => {\n const label_line = d3.select(label_elements[i]);\n return label_line.attr('y');\n });\n }\n // After ~150 iterations we're probably beyond diminising returns, so stop recursing\n if (this.seperate_iterations < 150) {\n setTimeout(() => {\n this.separate_labels();\n }, 1);\n }\n }\n }\n\n // Implement the main render function\n render() {\n const data_layer = this;\n const x_scale = 'x_scale';\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n\n if (this.layout.label) {\n // Apply filters to generate a filtered data set\n let filtered_data;\n const filters = data_layer.layout.label.filters || [];\n if (!filters.length) {\n filtered_data = this.data;\n } else {\n filtered_data = this.data.filter((d) => {\n // Start by assuming a match (base case = no filters).\n // Test each filters: ALL must be satisfied for match to occur.\n let match = true;\n filters.forEach((filter) => {\n const extra = this.layer_state.extra_fields[this.getElementId(d)];\n const field_value = (new Field(filter.field)).resolve(d, extra);\n\n if (!['!=', '='].includes(filter.operator) && isNaN(field_value)) {\n // If the filter can only be used with numbers, then the value must be numeric.\n match = false;\n } else {\n switch (filter.operator) {\n case '<':\n if (!(field_value < filter.value)) {\n match = false;\n }\n break;\n case '<=':\n if (!(field_value <= filter.value)) {\n match = false;\n }\n break;\n case '>':\n if (!(field_value > filter.value)) {\n match = false;\n }\n break;\n case '>=':\n if (!(field_value >= filter.value)) {\n match = false;\n }\n break;\n case '=':\n if (!(field_value === filter.value)) {\n match = false;\n }\n break;\n case '!=':\n // Deliberately allow weak comparisons to test for \"anything with a value present\" (null or undefined)\n // eslint-disable-next-line eqeqeq\n if (field_value == filter.value) {\n match = false;\n }\n break;\n default:\n // If we got here the operator is not valid, so the filter should fail\n match = false;\n break;\n }\n }\n });\n return match;\n });\n }\n\n // Render label groups\n this.label_groups = this.svg.group\n .selectAll(`g.lz-data_layer-${this.layout.type}-label`)\n .data(filtered_data, (d) => `${d[this.layout.id_field]}_label`);\n\n const groups_enter = this.label_groups.enter()\n .append('g')\n .attr('class', `lz-data_layer-${this.layout.type}-label`);\n\n // Render label texts\n if (this.label_texts) {\n this.label_texts.remove();\n }\n this.label_texts = this.label_groups.merge(groups_enter)\n .append('text')\n .attr('class', `lz-data_layer-${this.layout.type}-label`)\n .text((d) => parseFields(d, data_layer.layout.label.text || ''))\n .attr('x', (d) => {\n let x = data_layer.parent[x_scale](d[data_layer.layout.x_axis.field])\n + Math.sqrt(data_layer.resolveScalableParameter(data_layer.layout.point_size, d))\n + data_layer.layout.label.spacing;\n if (isNaN(x)) {\n x = -1000;\n }\n return x;\n })\n .attr('y', (d) => {\n let y = data_layer.parent[y_scale](d[data_layer.layout.y_axis.field]);\n if (isNaN(y)) {\n y = -1000;\n }\n return y;\n })\n .attr('text-anchor', 'start')\n .call(applyStyles, data_layer.layout.label.style || {});\n\n // Render label lines\n if (data_layer.layout.label.lines) {\n if (this.label_lines) {\n this.label_lines.remove();\n }\n this.label_lines = this.label_groups.merge(groups_enter)\n .append('line')\n .attr('class', `lz-data_layer-${this.layout.type}-label`)\n .attr('x1', (d) => {\n let x = data_layer.parent[x_scale](d[data_layer.layout.x_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n return x;\n })\n .attr('y1', (d) => {\n let y = data_layer.parent[y_scale](d[data_layer.layout.y_axis.field]);\n if (isNaN(y)) {\n y = -1000;\n }\n return y;\n })\n .attr('x2', (d) => {\n let x = data_layer.parent[x_scale](d[data_layer.layout.x_axis.field])\n + Math.sqrt(data_layer.resolveScalableParameter(data_layer.layout.point_size, d))\n + (data_layer.layout.label.spacing / 2);\n if (isNaN(x)) {\n x = -1000;\n }\n return x;\n })\n .attr('y2', (d) => {\n let y = data_layer.parent[y_scale](d[data_layer.layout.y_axis.field]);\n if (isNaN(y)) {\n y = -1000;\n }\n return y;\n })\n .call(applyStyles, data_layer.layout.label.lines.style || {});\n }\n // Remove labels when they're no longer in the filtered data set\n this.label_groups.exit()\n .remove();\n } else {\n // If the layout definition has changed (& no longer specifies labels), strip any previously rendered\n if (this.label_groups) {\n this.label_groups.remove();\n }\n if (this.label_lines) {\n this.label_lines.remove();\n }\n }\n\n // Generate main scatter data elements\n const selection = this.svg.group\n .selectAll(`path.lz-data_layer-${this.layout.type}`)\n .data(this.data, (d) => d[this.layout.id_field]);\n\n // Create elements, apply class, ID, and initial position\n const initial_y = isNaN(this.parent.layout.height) ? 0 : this.parent.layout.height;\n\n // Generate new values (or functions for them) for position, color, size, and shape\n const transform = (d) => {\n let x = this.parent[x_scale](d[this.layout.x_axis.field]);\n let y = this.parent[y_scale](d[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n return `translate(${x}, ${y})`;\n };\n\n const shape = d3.symbol()\n .size((d, i) => this.resolveScalableParameter(this.layout.point_size, d, i))\n .type((d, i) => nameToSymbol(this.resolveScalableParameter(this.layout.point_shape, d, i)));\n\n selection.enter()\n .append('path')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n .attr('id', (d) => this.getElementId(d))\n .attr('transform', `translate(0, ${initial_y})`)\n .merge(selection)\n .attr('transform', transform)\n .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))\n .attr('fill-opacity', (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i))\n .attr('d', shape)\n // Apply default event emitters & mouse behaviors to selection\n .on('click.event_emitter', (element) => this.parent.emit('element_clicked', element, true))\n .call(this.applyBehaviors.bind(this));\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n // Apply method to keep labels from overlapping each other\n if (this.layout.label) {\n this.flip_labels();\n this.seperate_iterations = 0;\n this.separate_labels();\n // Apply default event emitters to selection, and extend mouse behaviors to labels\n this.label_texts\n .on('click.event_emitter', (element) => this.parent.emit('element_clicked', element, true))\n .call(this.applyBehaviors.bind(this));\n }\n }\n\n // Method to set a passed element as the LD reference in the plot-level state\n makeLDReference(element) {\n let ref = null;\n if (typeof element == 'undefined') {\n throw new Error('makeLDReference requires one argument of any type');\n } else if (typeof element == 'object') {\n if (this.layout.id_field && typeof element[this.layout.id_field] != 'undefined') {\n ref = element[this.layout.id_field].toString();\n } else if (typeof element['id'] != 'undefined') {\n ref = element['id'].toString();\n } else {\n ref = element.toString();\n }\n } else {\n ref = element.toString();\n }\n this.parent_plot.applyState({ ldrefvar: ref });\n }\n}\n\n/**\n * A scatter plot in which the x-axis represents categories, rather than individual positions.\n * For example, this can be used by PheWAS plots to show related groups. This plot allows the categories to be\n * determined dynamically when data is first loaded.\n *\n */\nclass CategoryScatter extends Scatter {\n constructor(layout) {\n super(...arguments);\n /**\n * Define category names and extents (boundaries) for plotting.\n * @member {Object.} Category names and extents, in the form {category_name: [min_x, max_x]}\n */\n this._categories = {};\n }\n\n /**\n * This plot layer makes certain assumptions about the data passed in. Transform the raw array of records from\n * the datasource to prepare it for plotting, as follows:\n * 1. The scatter plot assumes that all records are given in sequence (pre-grouped by `category_field`)\n * 2. It assumes that all records have an x coordinate for individual plotting\n * @private\n */\n _prepareData() {\n const xField = this.layout.x_axis.field || 'x';\n // The (namespaced) field from `this.data` that will be used to assign datapoints to a given category & color\n const category_field = this.layout.x_axis.category_field;\n if (!category_field) {\n throw new Error(`Layout for ${this.layout.id} must specify category_field`);\n }\n // Sort the data so that things in the same category are adjacent (case-insensitive by specified field)\n const sourceData = this.data\n .sort((a, b) => {\n const ak = a[category_field];\n const bk = b[category_field];\n const av = (typeof ak === 'string') ? ak.toLowerCase() : ak;\n const bv = (typeof bk === 'string') ? bk.toLowerCase() : bk;\n return (av === bv) ? 0 : (av < bv ? -1 : 1);\n });\n sourceData.forEach((d, i) => {\n // Implementation detail: Scatter plot requires specifying an x-axis value, and most datasources do not\n // specify plotting positions. If a point is missing this field, fill in a synthetic value.\n d[xField] = d[xField] || i;\n });\n return sourceData;\n }\n\n /**\n * Identify the unique categories on the plot, and update the layout with an appropriate color scheme.\n * Also identify the min and max x value associated with the category, which will be used to generate ticks\n * @private\n * @returns {Object.} Series of entries used to build category name ticks {category_name: [min_x, max_x]}\n */\n _generateCategoryBounds() {\n // TODO: API may return null values in category_field; should we add placeholder category label?\n // The (namespaced) field from `this.data` that will be used to assign datapoints to a given category & color\n const category_field = this.layout.x_axis.category_field;\n const xField = this.layout.x_axis.field || 'x';\n const uniqueCategories = {};\n this.data.forEach((item) => {\n const category = item[category_field];\n const x = item[xField];\n const bounds = uniqueCategories[category] || [x, x];\n uniqueCategories[category] = [Math.min(bounds[0], x), Math.max(bounds[1], x)];\n });\n\n const categoryNames = Object.keys(uniqueCategories);\n this._setDynamicColorScheme(categoryNames);\n\n return uniqueCategories;\n }\n\n /**\n * This layer relies on defining its own category-based color scheme. Find the correct color config object to\n * be modified.\n * @param [from_source]\n * @returns {Object} A mutable reference to the layout configuration object\n * @private\n */\n _getColorScale(from_source) {\n from_source = from_source || this.layout;\n // If the layout does not use a supported coloring scheme, or is already complete, this method should do nothing\n\n // For legacy reasons, layouts can specify color as an object (only one way to set color), as opposed to the\n // preferred mechanism of array (multiple coloring options)\n let color_params = from_source.color || []; // Object or scalar, no other options allowed\n if (Array.isArray(color_params)) {\n color_params = color_params.find((item) => item.scale_function === 'categorical_bin');\n }\n if (!color_params || color_params.scale_function !== 'categorical_bin') {\n throw new Error('This layer requires that color options be provided as a `categorical_bin`');\n }\n return color_params;\n }\n\n /**\n * Automatically define a color scheme for the layer based on data returned from the server.\n * If part of the color scheme has been specified, it will fill in remaining missing information.\n *\n * There are three scenarios:\n * 1. The layout does not specify either category names or (color) values. Dynamically build both based on\n * the data and update the layout.\n * 2. The layout specifies colors, but not categories. Use that exact color information provided, and dynamically\n * determine what categories are present in the data. (cycle through the available colors, reusing if there\n * are a lot of categories)\n * 3. The layout specifies exactly what colors and categories to use (and they match the data!). This is useful to\n * specify an explicit mapping between color scheme and category names, when you want to be sure that the\n * plot matches a standard color scheme.\n * (If the layout specifies categories that do not match the data, the user specified categories will be ignored)\n *\n * This method will only act if the layout defines a `categorical_bin` scale function for coloring. It may be\n * overridden in a subclass to suit other types of coloring methods.\n *\n * @param {String[]} categoryNames\n * @private\n */\n _setDynamicColorScheme(categoryNames) {\n const colorParams = this._getColorScale(this.layout).parameters;\n const baseParams = this._getColorScale(this._base_layout).parameters;\n\n if (baseParams.categories.length && baseParams.values.length) {\n // If there are preset category/color combos, make sure that they apply to the actual dataset\n const parameters_categories_hash = {};\n baseParams.categories.forEach((category) => {\n parameters_categories_hash[category] = 1;\n });\n if (categoryNames.every((name) => Object.prototype.hasOwnProperty.call(parameters_categories_hash, name))) {\n // The layout doesn't have to specify categories in order, but make sure they are all there\n colorParams.categories = baseParams.categories;\n } else {\n colorParams.categories = categoryNames;\n }\n } else {\n colorParams.categories = categoryNames;\n }\n // Prefer user-specified colors if provided. Make sure that there are enough colors for all the categories.\n let colors;\n if (baseParams.values.length) {\n colors = baseParams.values;\n } else {\n // Originally from d3v3 category20\n colors = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'];\n }\n while (colors.length < categoryNames.length) {\n colors = colors.concat(colors);\n }\n colors = colors.slice(0, categoryNames.length); // List of hex values, should be of same length as categories array\n colorParams.values = colors;\n }\n\n /**\n *\n * @param dimension\n * @param {Object} [config] Parameters that customize how ticks are calculated (not style)\n * @param {('left'|'center'|'right')} [config.position='left'] Align ticks with the center or edge of category\n * @returns {Array}\n */\n getTicks(dimension, config) { // Overrides parent method\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error('Invalid dimension identifier');\n }\n const position = config.position || 'left';\n if (!['left', 'center', 'right'].includes(position)) {\n throw new Error('Invalid tick position');\n }\n\n const categoryBounds = this._categories;\n if (!categoryBounds || !Object.keys(categoryBounds).length) {\n return [];\n }\n\n if (dimension === 'y') {\n return [];\n }\n\n if (dimension === 'x') {\n // If colors have been defined by this layer, use them to make tick colors match scatterplot point colors\n const colors = this._getColorScale(this.layout);\n const knownCategories = colors.parameters.categories || [];\n const knownColors = colors.parameters.values || [];\n\n return Object.keys(categoryBounds).map((category, index) => {\n const bounds = categoryBounds[category];\n let xPos;\n\n switch (position) {\n case 'left':\n xPos = bounds[0];\n break;\n case 'center':\n // Center tick under one or many elements as appropriate\n // eslint-disable-next-line no-case-declarations\n const diff = bounds[1] - bounds[0];\n xPos = bounds[0] + (diff !== 0 ? diff : bounds[0]) / 2;\n break;\n case 'right':\n xPos = bounds[1];\n break;\n }\n return {\n x: xPos,\n text: category,\n style: {\n 'fill': knownColors[knownCategories.indexOf(category)] || '#000000',\n },\n };\n });\n }\n }\n\n applyCustomDataMethods() {\n this.data = this._prepareData();\n this._categories = this._generateCategoryBounds();\n return this;\n }\n}\n\n\nexport { Scatter as scatter, CategoryScatter as category_scatter };\n","/**\n * @module\n * @private\n */\nimport {ClassRegistry} from './base';\nimport * as layers from '../components/data_layer';\n\nconst registry = new ClassRegistry();\nfor (let [name, type] of Object.entries(layers)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n","/**\n * Transformation functions: used to transform a raw value from the API. For example, a template or axis label\n * can convert from pvalue to -log10pvalue\n * @module\n */\n\n/**\n * Return the -log (base 10)\n * @function neglog10\n */\nexport function neglog10 (value) {\n if (isNaN(value) || value <= 0) {\n return null;\n }\n return -Math.log(value) / Math.LN10;\n}\n\n/**\n * Convert a number from logarithm to scientific notation. Useful for, eg, a datasource that returns -log(p) by default\n * @function logtoscinotation\n */\nexport function logtoscinotation (value) {\n if (isNaN(value)) {\n return 'NaN';\n }\n if (value === 0) {\n return '1';\n }\n const exp = Math.ceil(value);\n const diff = exp - value;\n const base = Math.pow(10, diff);\n if (exp === 1) {\n return (base / 10).toFixed(4);\n } else if (exp === 2) {\n return (base / 100).toFixed(3);\n } else {\n return `${base.toFixed(2)} × 10^-${exp}`;\n }\n}\n\n/**\n * Represent a number in scientific notation\n * @function scinotation\n * @param {Number} value\n * @returns {String}\n */\nexport function scinotation (value) {\n if (isNaN(value)) {\n return 'NaN';\n }\n if (value === 0) {\n return '0';\n }\n\n const abs = Math.abs(value);\n let log;\n if (abs > 1) {\n log = Math.ceil(Math.log(abs) / Math.LN10);\n } else { // 0...1\n log = Math.floor(Math.log(abs) / Math.LN10);\n }\n if (Math.abs(log) <= 3) {\n return value.toFixed(3);\n } else {\n return value.toExponential(2).replace('+', '').replace('e', ' × 10^');\n }\n}\n\n/**\n * HTML-escape user entered values for use in constructed HTML fragments\n *\n * For example, this filter can be used on tooltips with custom HTML display\n * @function htmlescape\n * @param {String} value HTML-escape the provided value\n */\nexport function htmlescape (value) {\n if (!value) {\n return '';\n }\n value = `${value}`;\n\n return value.replace(/['\"<>&`]/g, function (s) {\n switch (s) {\n case \"'\":\n return ''';\n case '\"':\n return '"';\n case '<':\n return '<';\n case '>':\n return '>';\n case '&':\n return '&';\n case '`':\n return '`';\n }\n });\n}\n\n/**\n * URL-encode the provided text, eg for constructing hyperlinks\n * @function urlencode\n * @param {String} value\n */\nexport function urlencode (value) {\n return encodeURIComponent(value);\n}\n","/**\n * @module\n * @private\n */\nimport {RegistryBase} from './base';\nimport * as transforms from '../helpers/transforms';\n\n/**\n * Registry of transformation functions that may be applied to template values.\n * Provides syntactic sugar atop a standard registry.\n * @private\n */\nclass TransformationFunctions extends RegistryBase {\n _collectTransforms(template_string) {\n // Helper function that turns a sequence of function names into a single callable\n const funcs = template_string\n .match(/\\|([^|]+)/g)\n .map((item) => super.get(item.substring(1)));\n\n return (value) => {\n return funcs.reduce(\n (acc, func) => func(acc),\n value\n );\n };\n }\n\n /**\n * In templates, we often use a single concatenated string to ask for several transformation functions at once:\n * `value|func1|func2`\n * This class offers syntactical sugar to retrieve the entire sequence of transformations as a single callable\n * @param name\n */\n get(name) {\n if (!name) {\n // This function is sometimes called with no value, and the expected behavior is to return null instead of\n // a callable\n return null;\n }\n if (name.substring(0, 1) === '|') {\n // Legacy artifact of how this function is called- if a pipe is present, this is the template string\n // (`|func1|func2...`), rather than any one single transformation function.\n // A sequence of transformation functions is expected\n return this._collectTransforms(name);\n } else {\n // If not a template string, then user is asking for an item by name directly\n return super.get(name);\n }\n }\n}\n\nconst registry = new TransformationFunctions();\nfor (let [name, type] of Object.entries(transforms)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n// Export helper class for unit testing\nexport { TransformationFunctions as _TransformationFunctions };\n","/** @module */\nimport * as d3 from 'd3';\n\nimport {positionIntToString} from '../../helpers/display';\nimport {applyStyles} from '../../helpers/common';\nimport {deepCopy} from '../../helpers/layouts';\n\n// FIXME: Button creation should occur in the constructors, not in update functions\n\n/**\n *\n * A widget is an empty div rendered on a toolbar that can display custom\n * html of user interface elements.\n * @param {Object} layout A JSON-serializable object of layout configuration parameters\n * @param {('left'|'right')} [layout.position='left'] Whether to float the widget left or right.\n * @param {('start'|'middle'|'end')} [layout.group_position] Buttons can optionally be gathered into a visually\n * distinctive group whose elements are closer together. If a button is identified as the start or end of a group,\n * it will be drawn with rounded corners and an extra margin of spacing from any button not part of the group.\n * For example, the region_nav_plot toolbar is a defined as a group.\n * @param {('gray'|'red'|'orange'|'yellow'|'green'|'blue'|'purple')} [layout.color='gray'] Color scheme for the\n * widget. Applies to buttons and menus.\n * @param {Toolbar} parent The toolbar that contains this widget\n */\nclass BaseWidget {\n constructor(layout, parent) {\n /** @member {Object} */\n this.layout = layout || {};\n if (!this.layout.color) {\n this.layout.color = 'gray';\n }\n\n /** @member {Toolbar|*} */\n this.parent = parent || null;\n /**\n * Some widgets are attached to a panel, rather than directly to a plot\n * @member {Panel|null}\n */\n this.parent_panel = null;\n /** @member {Plot} */\n this.parent_plot = null;\n /**\n * This is a reference to either the panel or the plot, depending on what the toolbar is\n * tied to. Useful when absolutely positioning toolbar widgets relative to their SVG anchor.\n * @member {Plot|Panel}\n */\n this.parent_svg = null;\n if (this.parent) {\n if (this.parent.type === 'panel') {\n this.parent_panel = this.parent.parent;\n this.parent_plot = this.parent.parent.parent;\n this.parent_svg = this.parent_panel;\n } else {\n this.parent_plot = this.parent.parent;\n this.parent_svg = this.parent_plot;\n }\n }\n /** @member {d3.selection} */\n this.selector = null;\n /**\n * If this is an interactive widget, it will contain a button or menu instance that handles the interactivity.\n * There is a 1-to-1 relationship of toolbar widget to button\n * @member {null|Button}\n */\n this.button = null;\n /**\n * If any single widget is marked persistent, it will bubble up to prevent automatic hide behavior on a\n * widget's parent toolbar. Check via `shouldPersist`\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n if (!this.layout.position) {\n this.layout.position = 'left';\n }\n }\n\n /**\n * Perform all rendering of widget, including toggling visibility to true. Will initialize and create SVG element\n * if necessary, as well as updating with new data and performing layout actions.\n */\n show() {\n if (!this.parent || !this.parent.selector) {\n return;\n }\n if (!this.selector) {\n const group_position = (['start', 'middle', 'end'].includes(this.layout.group_position) ? ` lz-toolbar-group-${this.layout.group_position}` : '');\n this.selector = this.parent.selector.append('div')\n .attr('class', `lz-toolbar-${this.layout.position}${group_position}`);\n if (this.layout.style) {\n applyStyles(this.selector, this.layout.style);\n }\n if (typeof this.initialize == 'function') {\n this.initialize();\n }\n }\n if (this.button && this.button.status === 'highlighted') {\n this.button.menu.show();\n }\n this.selector.style('visibility', 'visible');\n this.update();\n return this.position();\n }\n\n /**\n * Update the toolbar widget with any new data or plot state as appropriate. This method performs all\n * necessary rendering steps.\n */\n update() { /* stub */\n }\n\n /**\n * Place the widget correctly in the plot\n * @returns {BaseWidget}\n */\n position() {\n if (this.button) {\n this.button.menu.position();\n }\n return this;\n }\n\n /**\n * Determine whether the widget should persist (will bubble up to parent toolbar)\n * @returns {boolean}\n */\n shouldPersist() {\n if (this.persist) {\n return true;\n }\n return !!(this.button && this.button.persist);\n }\n\n /**\n * Toggle visibility to hidden, unless marked as persistent\n * @returns {BaseWidget}\n */\n hide() {\n if (!this.selector || this.shouldPersist()) {\n return this;\n }\n if (this.button) {\n this.button.menu.hide();\n }\n this.selector.style('visibility', 'hidden');\n return this;\n }\n\n /**\n * Completely remove widget and button. (may be overridden by persistence settings)\n * @param {Boolean} [force=false] If true, will ignore persistence settings and always destroy the toolbar\n * @returns {Toolbar}\n */\n destroy(force) {\n if (typeof force == 'undefined') {\n force = false;\n }\n if (!this.selector) {\n return this;\n }\n if (this.shouldPersist() && !force) {\n return this;\n }\n if (this.button && this.button.menu) {\n this.button.menu.destroy();\n }\n this.selector.remove();\n this.selector = null;\n this.button = null;\n return this;\n }\n}\n\n/**\n * Plots and panels may have a \"toolbar\" element suited for showing HTML widgets that may be interactive.\n * When widgets need to incorporate a generic button, or additionally a button that generates a menu, this\n * class provides much of the necessary framework.\n * @param {BaseWidget} parent\n */\nclass Button {\n constructor(parent) {\n if (!(parent instanceof BaseWidget)) {\n throw new Error('Unable to create toolbar widget button, invalid parent');\n }\n /** @member {BaseWidget} */\n this.parent = parent;\n /** @member {Panel} */\n this.parent_panel = this.parent.parent_panel;\n /** @member {Plot} */\n this.parent_plot = this.parent.parent_plot;\n /** @member {Plot|Panel} */\n this.parent_svg = this.parent.parent_svg;\n\n /** @member {Toolbar|null|*} */\n this.parent_toolbar = this.parent.parent;\n /** @member {d3.selection} */\n this.selector = null;\n\n /**\n * Tag to use for the button (default: a)\n * @member {String}\n */\n this.tag = 'a';\n\n /**\n * HTML for the button to show.\n * @protected\n * @member {String}\n */\n this.html = '';\n\n /**\n * Mouseover title text for the button to show\n * @protected\n * @member {String}\n */\n this.title = '';\n\n /**\n * Color of the button\n * @member {String}\n */\n this.color = 'gray';\n\n /**\n * Hash of arbitrary button styles to apply as {name: value} entries\n * @protected\n * @member {Object}\n */\n this.style = {};\n\n // Permanence\n /**\n * Track internal state on whether to keep showing the button/ menu contents at the moment\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n /**\n * Configuration when defining a button: track whether this widget should be allowed to keep open\n * menu/button contents in response to certain events\n * @protected\n * @member {Boolean}\n */\n this.permanent = false;\n\n /**\n * Button status (highlighted / disabled/ etc)\n * @protected\n * @member {String}\n */\n this.status = '';\n\n /**\n * Button Menu Object\n * The menu is an HTML overlay that can appear below a button. It can contain arbitrary HTML and\n * has logic to be automatically positioned and sized to behave more or less like a dropdown menu.\n * @member {Object}\n */\n this.menu = {\n outer_selector: null,\n inner_selector: null,\n scroll_position: 0,\n hidden: true,\n /**\n * Show the button menu, including setting up any DOM elements needed for first rendering\n */\n show: () => {\n if (!this.menu.outer_selector) {\n this.menu.outer_selector = d3.select(this.parent_plot.svg.node().parentNode).append('div')\n .attr('class', `lz-toolbar-menu lz-toolbar-menu-${this.color}`)\n .attr('id', `${this.parent_svg.getBaseId()}.toolbar.menu`);\n this.menu.inner_selector = this.menu.outer_selector.append('div')\n .attr('class', 'lz-toolbar-menu-content');\n this.menu.inner_selector.on('scroll', () => {\n this.menu.scroll_position = this.menu.inner_selector.node().scrollTop;\n });\n }\n this.menu.outer_selector.style('visibility', 'visible');\n this.menu.hidden = false;\n return this.menu.update();\n },\n /**\n * Update the rendering of the menu\n */\n update: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.populate(); // This function is stubbed for all buttons by default and custom implemented in widget definition\n if (this.menu.inner_selector) {\n this.menu.inner_selector.node().scrollTop = this.menu.scroll_position;\n }\n return this.menu.position();\n },\n position: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n // Unset any explicitly defined outer selector height so that menus dynamically shrink if content is removed\n this.menu.outer_selector.style('height', null);\n const padding = 3;\n const scrollbar_padding = 20;\n const menu_height_padding = 14; // 14: 2x 6px padding, 2x 1px border\n const page_origin = this.parent_svg._getPageOrigin();\n const page_scroll_top = document.documentElement.scrollTop || document.body.scrollTop;\n const container_offset = this.parent_plot.getContainerOffset();\n const toolbar_client_rect = this.parent_toolbar.selector.node().getBoundingClientRect();\n const button_client_rect = this.selector.node().getBoundingClientRect();\n const menu_client_rect = this.menu.outer_selector.node().getBoundingClientRect();\n const total_content_height = this.menu.inner_selector.node().scrollHeight;\n let top;\n let left;\n if (this.parent_toolbar.type === 'panel') {\n top = (page_origin.y + toolbar_client_rect.height + (2 * padding));\n left = Math.max(page_origin.x + this.parent_svg.layout.width - menu_client_rect.width - padding, page_origin.x + padding);\n } else {\n top = button_client_rect.bottom + page_scroll_top + padding - container_offset.top;\n left = Math.max(button_client_rect.left + button_client_rect.width - menu_client_rect.width - container_offset.left, page_origin.x + padding);\n }\n const base_max_width = Math.max(this.parent_svg.layout.width - (2 * padding) - scrollbar_padding, scrollbar_padding);\n const container_max_width = base_max_width;\n const content_max_width = (base_max_width - (4 * padding));\n const base_max_height = Math.max(this.parent_svg.layout.height - (10 * padding) - menu_height_padding, menu_height_padding);\n const height = Math.min(total_content_height, base_max_height);\n this.menu.outer_selector\n .style('top', `${top.toString()}px`)\n .style('left', `${left.toString()}px`)\n .style('max-width', `${container_max_width.toString()}px`)\n .style('max-height', `${base_max_height.toString()}px`)\n .style('height', `${height.toString()}px`);\n this.menu.inner_selector\n .style('max-width', `${content_max_width.toString()}px`);\n this.menu.inner_selector.node().scrollTop = this.menu.scroll_position;\n return this.menu;\n },\n hide: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.outer_selector.style('visibility', 'hidden');\n this.menu.hidden = true;\n return this.menu;\n },\n destroy: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.inner_selector.remove();\n this.menu.outer_selector.remove();\n this.menu.inner_selector = null;\n this.menu.outer_selector = null;\n return this.menu;\n },\n /**\n * Internal method definition\n * By convention populate() does nothing and should be reimplemented with each toolbar button definition\n * Reimplement by way of Toolbar.BaseWidget.Button.menu.setPopulate to define the populate method and hook\n * up standard menu click-toggle behavior prototype.\n * @protected\n */\n populate: () => {\n throw new Error('Method must be implemented');\n },\n /**\n * Define how the menu is populated with items, and set up click and display properties as appropriate\n * @public\n */\n setPopulate: (menu_populate_function) => {\n if (typeof menu_populate_function == 'function') {\n this.menu.populate = menu_populate_function;\n this.setOnclick(() => {\n if (this.menu.hidden) {\n this.menu.show();\n this.highlight().update();\n this.persist = true;\n } else {\n this.menu.hide();\n this.highlight(false).update();\n if (!this.permanent) {\n this.persist = false;\n }\n }\n });\n } else {\n this.setOnclick();\n }\n return this;\n },\n };\n }\n\n /**\n * Set the color associated with this button\n * @param {('gray'|'red'|'orange'|'yellow'|'green'|'blue'|'purple')} color Any selection not in the preset list\n * will be replaced with gray.\n * @returns {Button}\n */\n setColor (color) {\n if (typeof color != 'undefined') {\n if (['gray', 'red', 'orange', 'yellow', 'green', 'blue', 'purple'].includes(color)) {\n this.color = color;\n } else {\n this.color = 'gray';\n }\n }\n return this;\n }\n\n\n /**\n * Allow code to change whether the button is allowed to be `permanent`\n * @param {boolean} bool\n * @returns {Button}\n */\n setPermanent (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n this.permanent = bool;\n if (this.permanent) {\n this.persist = true;\n }\n return this;\n }\n /**\n * Determine whether the button/menu contents should persist in response to a specific event\n * @returns {Boolean}\n */\n shouldPersist () {\n return this.permanent || this.persist;\n }\n\n /**\n * Set a collection of custom styles to be used by the button\n * @param {Object} style Hash of {name:value} entries\n * @returns {Button}\n */\n setStyle (style) {\n if (typeof style != 'undefined') {\n this.style = style;\n }\n return this;\n }\n\n //\n /**\n * Method to generate a CSS class string\n * @returns {string}\n */\n getClass () {\n const group_position = (['start', 'middle', 'end'].includes(this.parent.layout.group_position) ? ` lz-toolbar-button-group-${this.parent.layout.group_position}` : '');\n return `lz-toolbar-button lz-toolbar-button-${this.color}${this.status ? `-${this.status}` : ''}${group_position}`;\n }\n\n\n /**\n * Change button state\n * @param {('highlighted'|'disabled'|'')} status\n */\n setStatus (status) {\n if (typeof status != 'undefined' && ['', 'highlighted', 'disabled'].includes(status)) {\n this.status = status;\n }\n return this.update();\n }\n\n /**\n * Toggle whether the button is highlighted\n * @param {boolean} bool If provided, explicitly set highlighted state\n * @returns {Button}\n */\n highlight (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n if (bool) {\n return this.setStatus('highlighted');\n } else if (this.status === 'highlighted') {\n return this.setStatus('');\n }\n return this;\n }\n\n /**\n * Toggle whether the button is disabled\n * @param {boolean} bool If provided, explicitly set disabled state\n * @returns {Button}\n */\n disable (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n if (bool) {\n return this.setStatus('disabled');\n } else if (this.status === 'disabled') {\n return this.setStatus('');\n }\n return this;\n }\n\n // Mouse events\n /** @member {function} */\n onmouseover () {\n }\n setOnMouseover (onmouseover) {\n if (typeof onmouseover == 'function') {\n this.onmouseover = onmouseover;\n } else {\n this.onmouseover = function () {};\n }\n return this;\n }\n /** @member {function} */\n onmouseout () {\n }\n setOnMouseout (onmouseout) {\n if (typeof onmouseout == 'function') {\n this.onmouseout = onmouseout;\n } else {\n this.onmouseout = function () {};\n }\n return this;\n }\n /** @member {function} */\n onclick () {\n }\n setOnclick (onclick) {\n if (typeof onclick == 'function') {\n this.onclick = onclick;\n } else {\n this.onclick = function () {};\n }\n return this;\n }\n\n /**\n * Set the mouseover title text for the button (if any)\n * @param {String} title Simple text to display\n * @returns {Button}\n */\n setTitle(title) {\n if (typeof title != 'undefined') {\n this.title = title.toString();\n }\n return this;\n }\n\n /**\n * Specify the HTML content of this button.\n * WARNING: The string provided will be inserted into the document as raw markup; XSS mitigation is the\n * responsibility of each button implementation.\n * @param {String} html\n * @returns {Button}\n */\n setHtml(html) {\n if (typeof html != 'undefined') {\n this.html = html.toString();\n }\n return this;\n }\n\n // Primary behavior functions\n /**\n * Show the button, including creating DOM elements if necessary for first render\n */\n show () {\n if (!this.parent) {\n return;\n }\n if (!this.selector) {\n this.selector = this.parent.selector.append(this.tag)\n .attr('class', this.getClass());\n }\n return this.update();\n }\n\n /**\n * Hook for any actions or state cleanup to be performed before rerendering\n * @returns {Button}\n */\n preUpdate () {\n return this;\n }\n\n /**\n * Update button state and contents, and fully rerender\n * @returns {Button}\n */\n update () {\n if (!this.selector) {\n return this;\n }\n this.preUpdate();\n this.selector\n .attr('class', this.getClass())\n .attr('title', this.title)\n .on('mouseover', (this.status === 'disabled') ? null : this.onmouseover)\n .on('mouseout', (this.status === 'disabled') ? null : this.onmouseout)\n .on('click', (this.status === 'disabled') ? null : this.onclick)\n .html(this.html)\n .call(applyStyles, this.style);\n\n this.menu.update();\n this.postUpdate();\n return this;\n }\n\n /**\n * Hook for any behavior to be added/changed after the button has been re-rendered\n * @returns {Button}\n */\n postUpdate () {\n return this;\n }\n\n /**\n * Hide the button by removing it from the DOM (may be overridden by current persistence setting)\n * @returns {Button}\n */\n hide() {\n if (this.selector && !this.shouldPersist()) {\n this.selector.remove();\n this.selector = null;\n }\n return this;\n }\n\n}\n\n/**\n * Renders arbitrary text with title formatting\n * @param {object} layout\n * @param {string} layout.title Text to render\n */\nclass Title extends BaseWidget {\n show() {\n if (!this.div_selector) {\n this.div_selector = this.parent.selector.append('div')\n .attr('class', `lz-toolbar-title lz-toolbar-${this.layout.position}`);\n this.title_selector = this.div_selector.append('h3');\n }\n return this.update();\n }\n\n update() {\n let title = this.layout.title.toString();\n if (this.layout.subtitle) {\n title += ` ${this.layout.subtitle}`;\n }\n this.title_selector.html(title);\n return this;\n }\n}\n\n/**\n * Renders text to display the current dimensions of the plot. Automatically updated as plot dimensions change\n */\nclass Dimensions extends BaseWidget {\n update() {\n const display_width = !this.parent_plot.layout.width.toString().includes('.') ? this.parent_plot.layout.width : this.parent_plot.layout.width.toFixed(2);\n const display_height = !this.parent_plot.layout.height.toString().includes('.') ? this.parent_plot.layout.height : this.parent_plot.layout.height.toFixed(2);\n this.selector.html(`${display_width}px × ${display_height}px`);\n if (this.layout.class) {\n this.selector.attr('class', this.layout.class);\n }\n if (this.layout.style) {\n applyStyles(this.selector, this.layout.style);\n }\n return this;\n }\n}\n\n/**\n * Display the current scale of the genome region displayed in the plot, as defined by the difference between\n * `state.end` and `state.start`.\n */\nclass RegionScale extends BaseWidget {\n update() {\n if (!isNaN(this.parent_plot.state.start) && !isNaN(this.parent_plot.state.end)\n && this.parent_plot.state.start !== null && this.parent_plot.state.end !== null) {\n this.selector.style('display', null);\n this.selector.html(positionIntToString(this.parent_plot.state.end - this.parent_plot.state.start, null, true));\n } else {\n this.selector.style('display', 'none');\n }\n if (this.layout.class) {\n this.selector.attr('class', this.layout.class);\n }\n if (this.layout.style) {\n applyStyles(this.selector, this.layout.style);\n }\n return this;\n }\n}\n\n/**\n * Button to export current plot to an SVG image\n */\nclass DownloadSVG extends BaseWidget {\n /**\n * @param {string} [layout.button_html=\"Download SVG\"]\n * @param {string} [layout.button_title=\"Download image of the current plot as locuszoom.svg\"]\n * @param {string} [layout.filename=\"locuszoom.svg\"] The default filename to use when saving the image\n */\n constructor(layout, parent) {\n super(layout, parent);\n this._filename = this.layout.filename || 'locuszoom.svg';\n this._button_html = this.layout.button_html || 'Save as SVG';\n this._button_title = this.layout.button_title || 'Download hi-res image';\n }\n\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this._button_html)\n .setTitle(this._button_title)\n .setOnMouseover(() => {\n this.button.selector\n .classed('lz-toolbar-button-gray-disabled', true)\n .html('Preparing Image');\n this._getBlobUrl().then((url) => {\n const old = this.button.selector.attr('href');\n if (old) {\n // Clean up old url instance to prevent memory leaks\n URL.revokeObjectURL(old);\n }\n this.button.selector\n .attr('href', url)\n .classed('lz-toolbar-button-gray-disabled', false)\n .classed('lz-toolbar-button-gray-highlighted', true)\n .html(this._button_html);\n });\n })\n .setOnMouseout(() => {\n this.button.selector.classed('lz-toolbar-button-gray-highlighted', false);\n });\n this.button.show();\n this.button.selector\n .attr('href-lang', 'image/svg+xml')\n .attr('download', this._filename);\n return this;\n }\n\n /**\n * Extract all CSS rules whose selectors directly reference elements under the root node\n * @param {Element} root\n * @return {string}\n * @private\n */\n _getCSS(root) {\n // Hack: this method is based on text matching the rules on a given node; it doesn't handle, eg ancestors.\n // Since all LZ cssRules are written as \"svg .classname\", we need to strip the parent selector prefix in order\n // to extract CSS.\n const ancestor_pattern = /^svg\\.lz-locuszoom\\s*/;\n\n // Extract all relevant CSS Rules by iterating through all available stylesheets\n let extractedCSSText = '';\n for (let i = 0; i < document.styleSheets.length; i++) {\n const s = document.styleSheets[i];\n try {\n if (!s.cssRules) {\n continue;\n }\n } catch ( e ) {\n if (e.name !== 'SecurityError') {\n throw e;\n } // for Firefox\n continue;\n }\n let cssRules = s.cssRules;\n for (let i = 0; i < cssRules.length; i++) {\n // FIXME: We could write smaller SVGs by extracting only the exact CSS rules for this plot. However,\n // extracting rules (including parent selectors) is a finicky process\n // Instead just fetch all LZ plot rules, under a known hardcoded parent selector.\n const rule = cssRules[i];\n const is_match = (rule.selectorText && rule.selectorText.match(ancestor_pattern));\n if (is_match) {\n extractedCSSText += rule.cssText;\n }\n }\n }\n return extractedCSSText;\n }\n\n _appendCSS( cssText, element ) {\n // Append styles to the constructed SVG DOM node\n var styleElement = document.createElement('style');\n styleElement.setAttribute('type', 'text/css');\n styleElement.innerHTML = cssText;\n var refNode = element.hasChildNodes() ? element.children[0] : null;\n element.insertBefore( styleElement, refNode );\n }\n\n /**\n * Get the target dimensions for the rendered image.\n *\n * For non-vector displays, these dimensions will yield ~300 DPI image for an 8\" wide print figure.\n * @return {number[]}\n * @private\n */\n _getDimensions() {\n let { width, height } = this.parent_plot.svg.node().getBoundingClientRect();\n const target_width = 2400;\n const rescale = target_width / width;\n return [rescale * width, rescale * height];\n }\n\n _generateSVG () {\n return new Promise((resolve) => {\n // Copy the DOM node so that we can modify the image for publication\n let copy = this.parent_plot.svg.node().cloneNode(true);\n copy.setAttribute('xlink', 'http://www.w3.org/1999/xlink');\n copy = d3.select(copy);\n\n // Remove unnecessary elements\n copy.selectAll('g.lz-curtain').remove();\n copy.selectAll('g.lz-mouse_guide').remove();\n // Convert units on axis tick dy attributes from ems to pixels\n copy.selectAll('g.tick text').each(function() {\n const dy = +(d3.select(this).attr('dy').substring(-2).slice(0, -2)) * 10;\n d3.select(this).attr('dy', dy);\n });\n // Pull the svg into a string and add the contents of the locuszoom stylesheet\n // Don't add this with d3 because it will escape the CDATA declaration incorrectly\n const serializer = new XMLSerializer();\n\n copy = copy.node();\n\n // Firefox has issues saving the SVG in certain contexts (esp rendering to canvas) unless a width is given.\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=700533\n const [width, height] = this._getDimensions();\n copy.setAttribute('width', width);\n copy.setAttribute('height', height);\n\n // Add CSS to the node\n this._appendCSS(this._getCSS(copy), copy);\n let svg_markup = serializer.serializeToString(copy);\n resolve(svg_markup);\n });\n }\n\n /**\n * Converts the SVG string into a downloadable binary object\n * @return {Promise}\n */\n _getBlobUrl() {\n return this._generateSVG().then((markup) => {\n const blob = new Blob([markup], { type: 'image/svg+xml' });\n return URL.createObjectURL(blob);\n });\n }\n}\n\nclass DownloadPNG extends DownloadSVG {\n constructor(layout, parent) {\n super(...arguments);\n this._filename = this.layout.filename || 'locuszoom.png';\n this._button_html = this.layout.button_html || 'Save as PNG';\n this._button_title = this.layout.button_title || 'Download image';\n }\n\n _getBlobUrl() {\n return super._getBlobUrl().then((svg_url) => {\n const canvas = document.createElement('canvas');\n const context = canvas.getContext('2d');\n\n const [width, height] = this._getDimensions();\n\n canvas.width = width;\n canvas.height = height;\n\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => {\n context.drawImage(image, 0, 0, width, height);\n // Once canvas rendered, revoke svg blob to avoid memory leaks, and create new url for the canvas\n URL.revokeObjectURL(svg_url);\n canvas.toBlob((png) => {\n resolve(URL.createObjectURL(png));\n });\n };\n image.src = svg_url;\n });\n });\n }\n}\n\n/**\n * Button to remove panel from plot.\n * NOTE: Will only work on panel widgets.\n * @param {Boolean} [layout.suppress_confirm=false] If true, removes the panel without prompting user for confirmation\n */\nclass RemovePanel extends BaseWidget {\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('×')\n .setTitle('Remove panel')\n .setOnclick(() => {\n if (!this.layout.suppress_confirm && !confirm('Are you sure you want to remove this panel? This cannot be undone!')) {\n return false;\n }\n const panel = this.parent_panel;\n panel.toolbar.hide(true);\n d3.select(panel.parent.svg.node().parentNode).on(`mouseover.${panel.getBaseId()}.toolbar`, null);\n d3.select(panel.parent.svg.node().parentNode).on(`mouseout.${panel.getBaseId()}.toolbar`, null);\n return panel.parent.removePanel(panel.id);\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to move panel up relative to other panels (in terms of y-index on the page)\n * NOTE: Will only work on panel widgets.\n */\nclass MovePanelUp extends BaseWidget {\n update () {\n if (this.button) {\n const is_at_top = (this.parent_panel.layout.y_index === 0);\n this.button.disable(is_at_top);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('▴')\n .setTitle('Move panel up')\n .setOnclick(() => {\n this.parent_panel.moveUp();\n this.update();\n });\n this.button.show();\n return this.update();\n }\n}\n\n/**\n * Button to move panel down relative to other panels (in terms of y-index on the page)\n * NOTE: Will only work on panel widgets.\n */\nclass MovePanelDown extends BaseWidget {\n update () {\n if (this.button) {\n const is_at_bottom = (this.parent_panel.layout.y_index === this.parent_plot.panel_ids_by_y_index.length - 1);\n this.button.disable(is_at_bottom);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('▾')\n .setTitle('Move panel down')\n .setOnclick(() => {\n this.parent_panel.moveDown();\n this.update();\n });\n this.button.show();\n return this.update();\n }\n}\n\n/**\n * Button to shift plot region forwards or back by a `step` increment provided in the layout\n * @param {object} layout\n * @param {number} [layout.step=50000] The stepsize to change the region by\n * @param {string} [layout.button_html]\n * @param {string} [layout.button_title]\n */\nclass ShiftRegion extends BaseWidget {\n constructor(layout, parent) {\n if (isNaN(layout.step) || layout.step === 0) {\n layout.step = 50000;\n }\n if (typeof layout.button_html !== 'string') {\n layout.button_html = layout.step > 0 ? '>' : '<';\n }\n\n if (typeof layout.button_title !== 'string') {\n layout.button_title = `Shift region by ${layout.step > 0 ? '+' : '-'}${positionIntToString(Math.abs(layout.step), null, true)}`;\n }\n super(layout, parent);\n if (isNaN(this.parent_plot.state.start) || isNaN(this.parent_plot.state.end)) {\n throw new Error('Unable to add shift_region toolbar widget: plot state does not have region bounds');\n }\n\n\n }\n\n update () {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n this.parent_plot.applyState({\n start: Math.max(this.parent_plot.state.start + this.layout.step, 1),\n end: this.parent_plot.state.end + this.layout.step,\n });\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Zoom in or out on the plot, centered on the middle of the plot region, by the specified amount\n * @param {object} layout\n * @param {number} [layout.step=0.2] The amount to zoom in by (where 1 indicates 100%)\n */\nclass ZoomRegion extends BaseWidget {\n constructor(layout, parent) {\n if (isNaN(layout.step) || layout.step === 0) {\n layout.step = 0.2;\n }\n if (typeof layout.button_html != 'string') {\n layout.button_html = layout.step > 0 ? 'z–' : 'z+';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = `Zoom region ${layout.step > 0 ? 'out' : 'in'} by ${(Math.abs(layout.step) * 100).toFixed(1)}%`;\n }\n\n super(layout, parent);\n if (isNaN(this.parent_plot.state.start) || isNaN(this.parent_plot.state.end)) {\n throw new Error('Unable to add zoom_region toolbar widget: plot state does not have region bounds');\n }\n }\n\n update () {\n if (this.button) {\n let can_zoom = true;\n const current_region_scale = this.parent_plot.state.end - this.parent_plot.state.start;\n if (this.layout.step > 0 && !isNaN(this.parent_plot.layout.max_region_scale) && current_region_scale >= this.parent_plot.layout.max_region_scale) {\n can_zoom = false;\n }\n if (this.layout.step < 0 && !isNaN(this.parent_plot.layout.min_region_scale) && current_region_scale <= this.parent_plot.layout.min_region_scale) {\n can_zoom = false;\n }\n this.button.disable(!can_zoom);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n const current_region_scale = this.parent_plot.state.end - this.parent_plot.state.start;\n const zoom_factor = 1 + this.layout.step;\n let new_region_scale = current_region_scale * zoom_factor;\n if (!isNaN(this.parent_plot.layout.max_region_scale)) {\n new_region_scale = Math.min(new_region_scale, this.parent_plot.layout.max_region_scale);\n }\n if (!isNaN(this.parent_plot.layout.min_region_scale)) {\n new_region_scale = Math.max(new_region_scale, this.parent_plot.layout.min_region_scale);\n }\n const delta = Math.floor((new_region_scale - current_region_scale) / 2);\n this.parent_plot.applyState({\n start: Math.max(this.parent_plot.state.start - delta, 1),\n end: this.parent_plot.state.end + delta,\n });\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Renders button with arbitrary text that, when clicked, shows a dropdown containing arbitrary HTML\n * NOTE: Trusts content exactly as given. XSS prevention is the responsibility of the implementer.\n * @param {object} layout\n * @param {string} layout.button_html The HTML to render inside the button\n * @param {string} layout.button_title Text to display as a tooltip when hovering over the button\n * @param {string} layout.menu_html The HTML content of the dropdown menu\n */\nclass Menu extends BaseWidget {\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title);\n this.button.menu.setPopulate(() => {\n this.button.menu.inner_selector.html(this.layout.menu_html);\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to resize panel height to fit available data (eg when showing a list of tracks)\n * @param {string} [layout.button_html=\"Resize to Data\"]\n * @param {string} [layout.button_title]\n */\nclass ResizeToData extends BaseWidget {\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html || 'Resize to Data')\n .setTitle(this.layout.button_title || 'Automatically resize this panel to show all data available')\n .setOnclick(() => {\n this.parent_panel.scaleHeightToData();\n this.update();\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to toggle legend\n */\nclass ToggleLegend extends BaseWidget {\n update() {\n const html = this.parent_panel.legend.layout.hidden ? 'Show Legend' : 'Hide Legend';\n if (this.button) {\n this.button.setHtml(html).show();\n this.parent.position();\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setTitle('Show or hide the legend for this panel')\n .setOnclick(() => {\n this.parent_panel.legend.layout.hidden = !this.parent_panel.legend.layout.hidden;\n this.parent_panel.legend.render();\n this.update();\n });\n return this.update();\n }\n}\n\n/**\n * Dropdown menu allowing the user to choose between different display options for a single specific data layer\n * within a panel.\n *\n * This allows controlling how points on a datalayer can be displayed- any display options supported via the layout for the target datalayer. This includes point\n * size/shape, coloring, etc.\n *\n * This button intentionally limits display options it can control to those available on common plot types.\n * Although the list of options it sets can be overridden (to control very special custom plot types), this\n * capability should be used sparingly if at all.\n *\n * @param {object} layout\n * @param {String} [layout.button_html=\"Display options...\"] Text to display on the toolbar button\n * @param {String} [layout.button_title=\"Control how plot items are displayed\"] Hover text for the toolbar button\n * @param {string} layout.layer_name Specify the datalayer that this button should affect\n * @param {string} [layout.default_config_display_name] Store the default configuration for this datalayer\n * configuration, and show a button to revert to the \"default\" (listing the human-readable display name provided)\n * @param {Array} [layout.fields_whitelist='see code'] The list of presentation fields that this button can control.\n * This can be overridden if this button needs to be used on a custom layer type with special options.\n * @typedef {{display_name: string, display: Object}} DisplayOptionsButtonConfigField\n * @param {DisplayOptionsButtonConfigField[]} layout.options Specify a label and set of layout directives associated\n * with this `display` option. Display field should include all changes to datalayer presentation options.\n */\nclass DisplayOptions extends BaseWidget {\n constructor(layout, parent) {\n if (typeof layout.button_html != 'string') {\n layout.button_html = 'Display options...';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = 'Control how plot items are displayed';\n }\n super(...arguments);\n\n // List of layout fields that this button is allowed to control. This ensures that we don't override any other\n // information (like plot height etc) while changing point rendering\n const allowed_fields = layout.fields_whitelist || ['color', 'fill_opacity', 'filters', 'label', 'legend',\n 'point_shape', 'point_size', 'tooltip', 'tooltip_positioning'];\n\n const dataLayer = this.parent_panel.data_layers[layout.layer_name];\n if (!dataLayer) {\n throw new Error(`Display options could not locate the specified layer_name: '${layout.layer_name}'`);\n }\n const dataLayerLayout = dataLayer.layout;\n\n // Store default configuration for the layer as a clean deep copy, so we may revert later\n const defaultConfig = {};\n allowed_fields.forEach((name) => {\n const configSlot = dataLayerLayout[name];\n if (configSlot !== undefined) {\n defaultConfig[name] = deepCopy(configSlot);\n }\n });\n\n /**\n * Which item in the menu is currently selected. (track for rerendering menu)\n * @member {String}\n * @private\n */\n this._selected_item = 'default';\n\n // Define the button + menu that provides the real functionality for this toolbar widget\n\n this.button = new Button(this)\n .setColor(layout.color)\n .setHtml(layout.button_html)\n .setTitle(layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n this.button.menu.setPopulate(() => {\n // Multiple copies of this button might be used on a single LZ page; append unique IDs where needed\n const uniqueID = Math.floor(Math.random() * 1e4).toString();\n\n this.button.menu.inner_selector.html('');\n const table = this.button.menu.inner_selector.append('table');\n\n const menuLayout = this.layout;\n\n const renderRow = (display_name, display_options, row_id) => { // Helper method\n const row = table.append('tr');\n const radioId = `${uniqueID}${row_id}`;\n row.append('td')\n .append('input')\n .attr('id', radioId)\n .attr('type', 'radio')\n .attr('name', `display-option-${uniqueID}`)\n .attr('value', row_id)\n .style('margin', 0) // Override css libraries (eg skeleton) that style form inputs\n .property('checked', (row_id === this._selected_item))\n .on('click', () => {\n // If an option is not specified in these display options, use the original defaults\n allowed_fields.forEach((field_name) => {\n dataLayer.layout[field_name] = display_options[field_name] || defaultConfig[field_name];\n });\n\n this._selected_item = row_id;\n this.parent_panel.render();\n const legend = this.parent_panel.legend;\n if (legend) {\n legend.render();\n }\n });\n row.append('td').append('label')\n .style('font-weight', 'normal')\n .attr('for', radioId)\n .text(display_name);\n };\n // Render the \"display options\" menu: default and special custom options\n const defaultName = menuLayout.default_config_display_name || 'Default style';\n renderRow(defaultName, defaultConfig, 'default');\n menuLayout.options.forEach((item, index) => renderRow(item.display_name, item.display, index));\n return this;\n });\n }\n\n update() {\n this.button.show();\n return this;\n }\n}\n\n/**\n * Dropdown menu allowing the user to set the value of a specific `state_field` in plot.state\n * This is useful for things (like datasources) that allow dynamic configuration based on global information in state\n *\n * For example, the LDServer data source can use it to change LD reference population (for all panels) after render\n *\n * @param {object} layout\n * @param {String} [layout.button_html=\"Set option...\"] Text to display on the toolbar button\n * @param {String} [layout.button_title=\"Choose an option to customize the plot\"] Hover text for the toolbar button\n * @param {bool} [layout.show_selected=false] Whether to append the selected value to the button label\n * @param {string} [layout.state_field] The name of the field in plot.state that will be set by this button\n * @typedef {{display_name: string, value: *}} SetStateOptionsConfigField\n * @param {SetStateOptionsConfigField[]} layout.options Specify human labels and associated values for the dropdown menu\n */\nclass SetState extends BaseWidget {\n constructor(layout, parent) {\n if (typeof layout.button_html != 'string') {\n layout.button_html = 'Set option...';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = 'Choose an option to customize the plot';\n }\n\n super(layout, parent);\n\n if (this.parent_panel) {\n throw new Error('This widget is designed to set global options, so it can only be used at the top (plot) level');\n }\n if (!layout.state_field) {\n throw new Error('Must specify the `state_field` that this widget controls');\n }\n\n /**\n * Which item in the menu is currently selected. (track for rerendering menu)\n * @member {String}\n * @private\n */\n // The first option listed is automatically assumed to be the default, unless a value exists in plot.state\n this._selected_item = this.parent_plot.state[layout.state_field] || layout.options[0].value;\n if (!layout.options.find((item) => {\n return item.value === this._selected_item;\n })) {\n // Check only gets run at widget creation, but generally this widget is assumed to be an exclusive list of options\n throw new Error('There is an existing state value that does not match the known values in this widget');\n }\n\n // Define the button + menu that provides the real functionality for this toolbar widget\n this.button = new Button(this)\n .setColor(layout.color)\n .setHtml(layout.button_html + (layout.show_selected ? this._selected_item : ''))\n .setTitle(layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n this.button.menu.setPopulate(() => {\n // Multiple copies of this button might be used on a single LZ page; append unique IDs where needed\n const uniqueID = Math.floor(Math.random() * 1e4).toString();\n\n this.button.menu.inner_selector.html('');\n const table = this.button.menu.inner_selector.append('table');\n\n const renderRow = (display_name, value, row_id) => { // Helper method\n const row = table.append('tr');\n const radioId = `${uniqueID}${row_id}`;\n row.append('td')\n .append('input')\n .attr('id', radioId)\n .attr('type', 'radio')\n .attr('name', `set-state-${uniqueID}`)\n .attr('value', row_id)\n .style('margin', 0) // Override css libraries (eg skeleton) that style form inputs\n .property('checked', (value === this._selected_item))\n .on('click', () => {\n const new_state = {};\n new_state[layout.state_field] = value;\n this._selected_item = value;\n this.parent_plot.applyState(new_state);\n this.button.setHtml(layout.button_html + (layout.show_selected ? this._selected_item : ''));\n });\n row.append('td').append('label')\n .style('font-weight', 'normal')\n .attr('for', radioId)\n .text(display_name);\n };\n layout.options.forEach((item, index) => renderRow(item.display_name, item.value, index));\n return this;\n });\n }\n\n update() {\n this.button.show();\n return this;\n }\n}\n\n\nexport {\n BaseWidget, // This is used to create subclasses\n Button as _Button, // This is used to create Widgets that contain a button. It actually shouldn't be in the registry because it's not usable directly..\n Dimensions as dimensions,\n DisplayOptions as display_options,\n DownloadSVG as download,\n DownloadPNG as download_png,\n Menu as menu,\n MovePanelDown as move_panel_down,\n MovePanelUp as move_panel_up,\n RegionScale as region_scale,\n ResizeToData as resize_to_data,\n SetState as set_state,\n ShiftRegion as shift_region,\n RemovePanel as remove_panel,\n Title as title,\n ToggleLegend as toggle_legend,\n ZoomRegion as zoom_region,\n};\n","/**\n * @module\n * @private\n */\nimport {ClassRegistry} from './base';\nimport * as widgets from '../components/toolbar/widgets';\n\nconst registry = new ClassRegistry();\n\nfor (let [name, type] of Object.entries(widgets)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n","/**\n * Define functions used by Scalable Layout Directives.\n *\n * These \"scaling functions\" are used during rendering to return output (eg color) based on input value\n * @module\n */\n\nimport * as d3 from 'd3';\n\n/**\n * Basic conditional function to evaluate the value of the input field and return based on equality.\n * @param {Object} parameters\n * @param {*} parameters.field_value The value against which to test the input value.\n * @param {*} parameters.then The value to return if the input value matches the field value\n * @param {*} parameters.else The value to return if the input value does not match the field value. Optional. If not\n * defined this scale function will return null (or value of null_value parameter, if defined) when input value fails\n * to match field_value.\n * @param {*} input value\n */\nconst if_value = (parameters, input) => {\n if (typeof input == 'undefined' || parameters.field_value !== input) {\n if (typeof parameters.else != 'undefined') {\n return parameters.else;\n } else {\n return null;\n }\n } else {\n return parameters.then;\n }\n};\n\n/**\n * Function to sort numerical values into bins based on numerical break points. Will only operate on numbers and\n * return null (or value of null_value parameter, if defined) if provided a non-numeric input value. Parameters:\n * @function numerical_bin\n * @param {Object} parameters\n * @param {Number[]} parameters.breaks Array of numerical break points against which to evaluate the input value.\n * Must be of equal length to values parameter. If the input value is greater than or equal to break n and less than\n * or equal to break n+1 (or break n+1 doesn't exist) then returned value is the nth entry in the values parameter.\n * @param {Array} parameters.values Array of values to return given evaluations against break points. Must be of\n * equal length to breaks parameter. Each entry n represents the value to return if the input value is greater than\n * or equal to break n and less than or equal to break n+1 (or break n+1 doesn't exist).\n * @param {*} parameters.null_value\n * @param {*} input value\n * @returns {*}\n */\nconst numerical_bin = (parameters, input) => {\n const breaks = parameters.breaks || [];\n const values = parameters.values || [];\n if (typeof input == 'undefined' || input === null || isNaN(+input)) {\n return (parameters.null_value ? parameters.null_value : null);\n }\n const threshold = breaks.reduce(function (prev, curr) {\n if (+input < prev || (+input >= prev && +input < curr)) {\n return prev;\n } else {\n return curr;\n }\n });\n return values[breaks.indexOf(threshold)];\n};\n\n/**\n * Function to sort values of any type into bins based on direct equality testing with a list of categories.\n * Will return null if provided an input value that does not match to a listed category.\n * @function categorical_bin\n * @param {Object} parameters\n * @param {Array} parameters.categories Array of values against which to evaluate the input value. Must be of equal\n * length to values parameter. If the input value is equal to category n then returned value is the nth entry in the\n * values parameter.\n * @param {Array} parameters.values Array of values to return given evaluations against categories. Must be of equal\n * length to categories parameter. Each entry n represents the value to return if the input value is equal to the nth\n * value in the categories parameter.\n * @param {*} parameters.null_value Value to return if the input value fails to match to any categories. Optional.\n */\nconst categorical_bin = (parameters, value) => {\n if (typeof value == 'undefined' || !parameters.categories.includes(value)) {\n return (parameters.null_value ? parameters.null_value : null);\n } else {\n return parameters.values[parameters.categories.indexOf(value)];\n }\n};\n/**\n * Cycle through a set of options, so that the each element in a set of data receives a value different than the\n * element before it. For example: \"use this palette of 10 colors to visually distinguish 100 adjacent items\"\n * @param {Object} parameters\n * @param {Array} parameters.values A list of option values\n * @return {*}\n */\nconst ordinal_cycle = (parameters, value, index) => {\n var options = parameters.values;\n return options[index % options.length];\n};\n/**\n * Function for continuous interpolation of numerical values along a gradient with arbitrarily many break points.\n * @function interpolate\n * @parameters {Object} parameters\n * @parameters {Number[]} parameters.breaks Array of numerical break points against which to evaluate the input value.\n * Must be of equal length to values parameter and contain at least two elements. Input value will be evaluated for\n * relative position between two break points n and n+1 and the returned value will be interpolated at a relative\n * position between values n and n+1.\n * @parameters {*[]} parameters.values Array of values to interpolate and return given evaluations against break\n * points. Must be of equal length to breaks parameter and contain at least two elements. Each entry n represents\n * the value to return if the input value matches the nth entry in breaks exactly. Note that this scale function\n * uses d3.interpolate to provide for effective interpolation of many different value types, including numbers,\n * colors, shapes, etc.\n * @parameters {*} parameters.null_value\n */\nconst interpolate = (parameters, input) => {\n var breaks = parameters.breaks || [];\n var values = parameters.values || [];\n var nullval = (parameters.null_value ? parameters.null_value : null);\n if (breaks.length < 2 || breaks.length !== values.length) {\n return nullval;\n }\n if (typeof input == 'undefined' || input === null || isNaN(+input)) {\n return nullval;\n }\n if (+input <= parameters.breaks[0]) {\n return values[0];\n } else if (+input >= parameters.breaks[parameters.breaks.length - 1]) {\n return values[breaks.length - 1];\n } else {\n var upper_idx = null;\n breaks.forEach(function (brk, idx) {\n if (!idx) {\n return;\n }\n if (breaks[idx - 1] <= +input && breaks[idx] >= +input) {\n upper_idx = idx;\n }\n });\n if (upper_idx === null) {\n return nullval;\n }\n const normalized_input = (+input - breaks[upper_idx - 1]) / (breaks[upper_idx] - breaks[upper_idx - 1]);\n if (!isFinite(normalized_input)) {\n return nullval;\n }\n return d3.interpolate(values[upper_idx - 1], values[upper_idx])(normalized_input);\n }\n};\n\n\nexport { categorical_bin, if_value, interpolate, numerical_bin, ordinal_cycle };\n","/**\n * @module\n * @private\n */\nimport {RegistryBase} from './base';\nimport * as scalable from '../helpers/scalable';\n\nconst registry = new RegistryBase();\nfor (let [name, type] of Object.entries(scalable)) {\n registry.add(name, type);\n}\n\n// Alias for the \"if_value\" function (can't export reserved language keywords directly)\nregistry.add('if', scalable.if_value);\n\n\nexport default registry;\n","/** @module */\nimport {RegistryBase} from '../registry/base';\nimport { ADAPTERS } from '../registry';\n\n/**\n * Create and coordinate an ensemble of (namespaced) data source instances\n * This is the mechanism by which users create data sources for a specific plot, and should be considered part of the\n * public interface for LocusZoom.\n *\n * @public\n */\nclass DataSources extends RegistryBase {\n /**\n * @param {RegistryBase} [registry] Primarily used for unit testing. When creating sources by name, specify where to\n * find the registry of known sources.\n */\n constructor(registry) {\n super();\n // This both acts as a registry (of the instantiated sources for this plot), and references a registry\n // (to locate adapter classes by name, when creating from config)\n this._registry = registry || ADAPTERS;\n }\n\n /**\n * For data sources, there is a special behavior of \"create item from config, then add\"\n * @param {String} namespace Uniquely identify this datasource\n * @param {BaseAdapter|Array} item An instantiated datasource, or an array of arguments that can be used to\n * create a known datasource type.\n * @param [override=false] Whether to allow existing sources to be redefined\n * @return {DataSources} Most registries return the created instance, but this registry returns a reference to\n * itself (to support chaining)\n */\n add(namespace, item, override = false) {\n if (this._registry.has(namespace)) {\n throw new Error(`The namespace ${namespace} is already in use by another source`);\n }\n\n if (namespace.match(/[^A-Za-z0-9_]/)) {\n throw new Error(`Data source namespace names can only contain alphanumeric characters or underscores`);\n }\n if (Array.isArray(item)) {\n const [type, options] = item;\n item = this._registry.create(type, options);\n }\n // Each datasource in the chain should be aware of its assigned namespace\n item.source_id = namespace;\n\n super.add(namespace, item, override);\n return this;\n }\n}\n\n\nexport default DataSources;\n","module.exports = raremetal;","/** @module */\n/*\n * LocusZoom extensions used to calculate and render aggregation test results. Because these calculations depend on an\n * external library, the special data sources are defined here, rather than in LocusZoom core code.\n *\n * The page must incorporate and load all libraries before this file can be used, including:\n * - Vendor assets\n * - LocusZoom\n * - raremetal.js (available via NPM or a related CDN)\n */\n// This is defined as a UMD module, to work with multiple different module systems / bundlers\n// Arcane build note: everything defined here gets registered globally. This is not a \"pure\" module, and some build\n// systems may require being told that this file has side effects.\n\nimport {helpers} from 'raremetal.js';\nimport {RemoteAdapter} from '../data';\nimport {deepCopy} from '../helpers/layouts';\n\n\nfunction install (LocusZoom) {\n /**\n * Data Source that calculates gene or region-based tests based on provided data\n * It will rarely be used by itself, but rather using a connector that attaches the results to data from\n * another source (like genes). Using a separate connector allows us to add caching and run this front-end\n * calculation only once, while using it in many different places\n * @public\n */\n const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter');\n const ConnectorSource = LocusZoom.Adapters.get('ConnectorSource');\n\n class AggregationTestSource extends RemoteAdapter {\n getURL(state, chain, fields) {\n // Unlike most sources, calculations may require access to plot state data even after the initial request\n // This example source REQUIRES that the external UI widget would store the needed test definitions in a plot state\n // field called `aggregation_tests` (an object {masks: [], calcs: {})\n const required_info = state.aggregation_tests || {};\n\n if (!chain.header) {\n chain.header = {};\n }\n // All of these fields are required in order to use this datasource. TODO: Add validation?\n chain.header.aggregation_genoset_id = required_info.genoset_id || null; // Number\n chain.header.aggregation_genoset_build = required_info.genoset_build || null; // String\n chain.header.aggregation_phenoset_id = required_info.phenoset_id || null; // Number\n chain.header.aggregation_pheno = required_info.pheno || null; // String\n chain.header.aggregation_calcs = required_info.calcs || {}; // String[]\n const mask_data = required_info.masks || [];\n chain.header.aggregation_masks = mask_data; // {name:desc}[]\n chain.header.aggregation_mask_ids = mask_data.map(function (item) {\n return item.name;\n }); // Number[]\n return this.url;\n }\n\n getCacheKey(state, chain, fields) {\n this.getURL(state, chain, fields); // TODO: This just sets the chain.header fields\n return JSON.stringify({\n chrom: state.chr,\n start: state.start,\n stop: state.end,\n genotypeDataset: chain.header.aggregation_genoset_id,\n phenotypeDataset: chain.header.aggregation_phenoset_id,\n phenotype: chain.header.aggregation_pheno,\n samples: 'ALL',\n genomeBuild: chain.header.aggregation_genoset_build,\n masks: chain.header.aggregation_mask_ids,\n });\n }\n\n fetchRequest(state, chain, fields) {\n const url = this.getURL(state, chain, fields);\n const body = this.getCacheKey(state, chain, fields);\n const headers = {\n 'Content-Type': 'application/json',\n };\n\n return fetch(url, {method: 'POST', body: body, headers: headers}).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n }).then(function (resp) {\n const json = typeof resp == 'string' ? JSON.parse(resp) : resp;\n if (json.error) {\n // RAREMETAL-server quirk: The API sometimes returns a 200 status code for failed requests,\n // with a human-readable error description as a key\n // For now, this should be treated strictly as an error\n throw new Error(json.error);\n }\n return json;\n });\n }\n\n annotateData(records, chain) {\n // Operate on the calculated results. The result of this method will be added to chain.discrete\n\n // In a page using live API data, the UI would only request the masks it needs from the API.\n // But in our demos, sometimes boilerplate JSON has more masks than the UI asked for. Limit what calcs we run (by\n // type, and to the set of groups requested by the user)\n\n // The Raremetal-server API has a quirk: it returns a different payload structure if no groups are defined\n // for the request region. Detect when that happens and end the calculation immediately in that case\n if (!records.groups) {\n return { groups: [], variants: [] };\n }\n\n records.groups = records.groups.filter(function (item) {\n return item.groupType === 'GENE';\n });\n\n const parsed = helpers.parsePortalJSON(records);\n let groups = parsed[0];\n const variants = parsed[1];\n // Some APIs may return more data than we want (eg simple sites that are just serving up premade scorecov json files).\n // Filter the response to just what the user has chosen to analyze.\n groups = groups.byMask(chain.header.aggregation_mask_ids);\n\n // Determine what calculations to run\n const calcs = chain.header.aggregation_calcs;\n if (!calcs || Object.keys(calcs).length === 0) {\n // If no calcs have been requested, then return a dummy placeholder immediately\n return { variants: [], groups: [], results: [] };\n }\n const runner = new helpers.PortalTestRunner(groups, variants, calcs);\n\n return runner.toJSON()\n .then(function (res) {\n // Internally, raremetal helpers track how the calculation is done, but not any display-friendly values\n // We will annotate each mask name (id) with a human-friendly description for later use\n const mask_id_to_desc = chain.header.aggregation_masks.reduce(function (acc, val) {\n acc[val.name] = val.description;\n return acc;\n }, {});\n res.data.groups.forEach(function (group) {\n group.mask_name = mask_id_to_desc[group.mask];\n });\n return res.data;\n })\n .catch(function (e) {\n console.error(e);\n throw new Error('Failed to calculate aggregation test results');\n });\n }\n\n normalizeResponse(data) {\n return data;\n }\n\n combineChainBody(records, chain) {\n // aggregation tests are a bit unique, in that the data is rarely used directly- instead it is used to annotate many\n // other layers in different ways. The calculated result has been added to `chain.discrete`, but will not be returned\n // as part of the response body built up by the chain\n return chain.body;\n }\n\n }\n\n class AssocFromAggregationLZ extends BaseAdapter {\n constructor(config) {\n if (!config || !config.from) {\n throw 'Must specify the name of the source that contains association data';\n }\n super(...arguments);\n }\n parseInit(config) {\n super.parseInit(config);\n this._from = config.from;\n }\n\n getRequest(state, chain, fields) {\n // Does not actually make a request. Just pick off the specific bundle of data from a known payload structure.\n if (chain.discrete && !chain.discrete[this._from]) {\n throw `${this.constructor.SOURCE_NAME} cannot be used before loading required data for: ${this._from}`;\n }\n // Copy the data so that mutations (like sorting) don't affect the original\n return Promise.resolve(deepCopy(chain.discrete[this._from]['variants']));\n }\n\n normalizeResponse(data) {\n // The payload structure of the association source is slightly different than the one required by association\n // plots. For example, we need to parse variant names and convert to log_pvalue\n const REGEX_EPACTS = new RegExp('(?:chr)?(.+):(\\\\d+)_?(\\\\w+)?/?([^_]+)?_?(.*)?'); // match API variant strings\n return data.map((one_variant) => {\n const match = one_variant.variant.match(REGEX_EPACTS);\n return {\n variant: one_variant.variant,\n chromosome: match[1],\n position: +match[2],\n ref_allele: match[3],\n ref_allele_freq: 1 - one_variant.altFreq,\n log_pvalue: -Math.log10(one_variant.pvalue),\n };\n }).sort((a, b) => {\n a = a.variant;\n b = b.variant;\n if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n // names must be equal\n return 0;\n }\n });\n }\n }\n\n /**\n * A sample connector that aligns calculated aggregation test data with corresponding gene information. Returns a body\n * suitable for use with the genes datalayer.\n *\n * To use this source, one must specify a fields array that calls first the genes source, then a dummy field from\n * this source. The output will be to transparently add several new fields to the genes data.\n * @public\n */\n class GeneAggregationConnectorLZ extends ConnectorSource {\n _getRequiredSources() {\n return ['gene_ns', 'aggregation_ns'];\n }\n\n combineChainBody(data, chain) {\n // The genes layer receives all results, and displays only the best pvalue for each gene\n\n // Tie the calculated group-test results to genes with a matching name\n const aggregation_source_id = this._source_name_mapping['aggregation_ns'];\n const gene_source_id = this._source_name_mapping['gene_ns'];\n // This connector assumes that genes are the main body of records from the chain, and that aggregation tests are\n // a standalone source that has not acted on genes data yet\n const aggregationData = chain.discrete[aggregation_source_id];\n const genesData = chain.discrete[gene_source_id];\n\n const groupedAggregation = {}; // Group together all tests done on that gene- any mask, any test\n\n aggregationData.groups.forEach(function (result) {\n if (!Object.prototype.hasOwnProperty.call(groupedAggregation, result.group)) {\n groupedAggregation[result.group] = [];\n }\n groupedAggregation[result.group].push(result.pvalue);\n });\n\n // Annotate any genes that have test results\n genesData.forEach(function (gene) {\n const gene_id = gene.gene_name;\n const tests = groupedAggregation[gene_id];\n if (tests) {\n gene.aggregation_best_pvalue = Math.min.apply(null, tests);\n }\n });\n return genesData;\n }\n }\n\n\n LocusZoom.Adapters.add('AggregationTestSourceLZ', AggregationTestSource);\n LocusZoom.Adapters.add('AssocFromAggregationLZ', AssocFromAggregationLZ);\n LocusZoom.Adapters.add('GeneAggregationConnectorLZ', GeneAggregationConnectorLZ);\n}\n\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/./esm/ext/lz-aggregation-tests.js","webpack://[name]/./esm/data/adapters.js","webpack://[name]/external \"raremetal\""],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","install","LocusZoom","BaseAdapter","Adapters","ConnectorSource","AggregationTestSource","state","chain","fields","required_info","aggregation_tests","header","aggregation_genoset_id","genoset_id","aggregation_genoset_build","genoset_build","aggregation_phenoset_id","phenoset_id","aggregation_pheno","pheno","aggregation_calcs","calcs","mask_data","masks","aggregation_masks","aggregation_mask_ids","map","item","this","url","getURL","JSON","stringify","chrom","chr","start","stop","end","genotypeDataset","phenotypeDataset","phenotype","samples","genomeBuild","body","getCacheKey","fetch","method","headers","then","response","ok","Error","statusText","text","resp","json","parse","error","records","groups","variants","filter","groupType","parsed","helpers","parsePortalJSON","byMask","keys","length","PortalTestRunner","toJSON","res","mask_id_to_desc","reduce","acc","val","description","data","forEach","group","mask_name","mask","e","console","results","RemoteAdapter","AssocFromAggregationLZ","config","from","arguments","_from","discrete","constructor","SOURCE_NAME","Promise","resolve","REGEX_EPACTS","RegExp","one_variant","match","variant","chromosome","position","ref_allele","ref_allele_freq","altFreq","log_pvalue","Math","log10","pvalue","sort","a","b","GeneAggregationConnectorLZ","aggregation_source_id","_source_name_mapping","gene_source_id","aggregationData","genesData","groupedAggregation","result","push","gene","gene_id","gene_name","tests","aggregation_best_pvalue","min","apply","add","use","validateBuildSource","class_name","build","source","includes","_enableCache","_cachedKey","__dependentSource","parseInit","params","req","cacheKey","_cachedResponse","fetchRequest","Array","isArray","N","every","record","j","outnames","trans","fieldFound","k","output_record","v","source_id","normalizeResponse","standardized","annotateData","extractFields","one_source_body","combineChainBody","new_body","preGetData","pre","getRequest","parseResponse","AssociationLZ","id_field","x","unshift","analysis","LDServer","join","arr","dataFields","id","position_field","pvalue_field","_names_","names","nameMatch","regexes","regex","id_match","obj","isrefvarin","isrefvarout","ldin","ldout","refVar","findRequestedFields","ldrefvar","findMergeFields","columns","pval_field","cmp","test","extremeVal","extremeIdx","findExtremeValue","genome_build","ld_source","population","ld_pop","getRefvar","encodeURIComponent","reqFields","corrField","rsquare","left","right","lfield","rfield","position2","leftJoin","refvar","idfield","outrefname","outldname","tagRefVariant","combined","chainRequests","payload","concat","next","GwasCatalogLZ","build_option","default_source","posMatch","find","decider_out","indexOf","n_matches","fn","outn","chainNames","catNames","pos","GeneLZ","GeneConstraintLZ","unique_gene_names","query","alias","replace","constraint","toString","parseFloat","toFixed","RecombLZ","StaticSource","_data","PheWASLZ","sources","specified_ids","_getRequiredSources","chain_source_id","raremetal"],"mappings":"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","file":"ext/lz-aggregation-tests.min.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 12);\n","/** @module */\n/*\n * LocusZoom extensions used to calculate and render aggregation test results. Because these calculations depend on an\n * external library, the special data sources are defined here, rather than in LocusZoom core code.\n *\n * The page must incorporate and load all libraries before this file can be used, including:\n * - Vendor assets\n * - LocusZoom\n * - raremetal.js (available via NPM or a related CDN)\n */\n// This is defined as a UMD module, to work with multiple different module systems / bundlers\n// Arcane build note: everything defined here gets registered globally. This is not a \"pure\" module, and some build\n// systems may require being told that this file has side effects.\n\nimport {helpers} from 'raremetal.js';\nimport {RemoteAdapter} from '../data/adapters';\n\n\nfunction install (LocusZoom) {\n /**\n * Data Source that calculates gene or region-based tests based on provided data\n * It will rarely be used by itself, but rather using a connector that attaches the results to data from\n * another source (like genes). Using a separate connector allows us to add caching and run this front-end\n * calculation only once, while using it in many different places\n * @public\n */\n const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter');\n const ConnectorSource = LocusZoom.Adapters.get('ConnectorSource');\n\n class AggregationTestSource extends RemoteAdapter {\n getURL(state, chain, fields) {\n // Unlike most sources, calculations may require access to plot state data even after the initial request\n // This example source REQUIRES that the external UI widget would store the needed test definitions in a plot state\n // field called `aggregation_tests` (an object {masks: [], calcs: {})\n const required_info = state.aggregation_tests || {};\n\n if (!chain.header) {\n chain.header = {};\n }\n // All of these fields are required in order to use this datasource. TODO: Add validation?\n chain.header.aggregation_genoset_id = required_info.genoset_id || null; // Number\n chain.header.aggregation_genoset_build = required_info.genoset_build || null; // String\n chain.header.aggregation_phenoset_id = required_info.phenoset_id || null; // Number\n chain.header.aggregation_pheno = required_info.pheno || null; // String\n chain.header.aggregation_calcs = required_info.calcs || {}; // String[]\n const mask_data = required_info.masks || [];\n chain.header.aggregation_masks = mask_data; // {name:desc}[]\n chain.header.aggregation_mask_ids = mask_data.map(function (item) {\n return item.name;\n }); // Number[]\n return this.url;\n }\n\n getCacheKey(state, chain, fields) {\n this.getURL(state, chain, fields); // TODO: This just sets the chain.header fields\n return JSON.stringify({\n chrom: state.chr,\n start: state.start,\n stop: state.end,\n genotypeDataset: chain.header.aggregation_genoset_id,\n phenotypeDataset: chain.header.aggregation_phenoset_id,\n phenotype: chain.header.aggregation_pheno,\n samples: 'ALL',\n genomeBuild: chain.header.aggregation_genoset_build,\n masks: chain.header.aggregation_mask_ids,\n });\n }\n\n fetchRequest(state, chain, fields) {\n const url = this.getURL(state, chain, fields);\n const body = this.getCacheKey(state, chain, fields);\n const headers = {\n 'Content-Type': 'application/json',\n };\n\n return fetch(url, {method: 'POST', body: body, headers: headers}).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n }).then(function (resp) {\n const json = typeof resp == 'string' ? JSON.parse(resp) : resp;\n if (json.error) {\n // RAREMETAL-server quirk: The API sometimes returns a 200 status code for failed requests,\n // with a human-readable error description as a key\n // For now, this should be treated strictly as an error\n throw new Error(json.error);\n }\n return json;\n });\n }\n\n annotateData(records, chain) {\n // Operate on the calculated results. The result of this method will be added to chain.discrete\n\n // In a page using live API data, the UI would only request the masks it needs from the API.\n // But in our demos, sometimes boilerplate JSON has more masks than the UI asked for. Limit what calcs we run (by\n // type, and to the set of groups requested by the user)\n\n // The Raremetal-server API has a quirk: it returns a different payload structure if no groups are defined\n // for the request region. Detect when that happens and end the calculation immediately in that case\n if (!records.groups) {\n return { groups: [], variants: [] };\n }\n\n records.groups = records.groups.filter(function (item) {\n return item.groupType === 'GENE';\n });\n\n const parsed = helpers.parsePortalJSON(records);\n let groups = parsed[0];\n const variants = parsed[1];\n // Some APIs may return more data than we want (eg simple sites that are just serving up premade scorecov json files).\n // Filter the response to just what the user has chosen to analyze.\n groups = groups.byMask(chain.header.aggregation_mask_ids);\n\n // Determine what calculations to run\n const calcs = chain.header.aggregation_calcs;\n if (!calcs || Object.keys(calcs).length === 0) {\n // If no calcs have been requested, then return a dummy placeholder immediately\n return { variants: [], groups: [], results: [] };\n }\n const runner = new helpers.PortalTestRunner(groups, variants, calcs);\n\n return runner.toJSON()\n .then(function (res) {\n // Internally, raremetal helpers track how the calculation is done, but not any display-friendly values\n // We will annotate each mask name (id) with a human-friendly description for later use\n const mask_id_to_desc = chain.header.aggregation_masks.reduce(function (acc, val) {\n acc[val.name] = val.description;\n return acc;\n }, {});\n res.data.groups.forEach(function (group) {\n group.mask_name = mask_id_to_desc[group.mask];\n });\n return res.data;\n })\n .catch(function (e) {\n console.error(e);\n throw new Error('Failed to calculate aggregation test results');\n });\n }\n\n normalizeResponse(data) {\n return data;\n }\n\n combineChainBody(records, chain) {\n // aggregation tests are a bit unique, in that the data is rarely used directly- instead it is used to annotate many\n // other layers in different ways. The calculated result has been added to `chain.discrete`, but will not be returned\n // as part of the response body built up by the chain\n return chain.body;\n }\n\n }\n\n class AssocFromAggregationLZ extends BaseAdapter {\n constructor(config) {\n if (!config || !config.from) {\n throw 'Must specify the name of the source that contains association data';\n }\n super(...arguments);\n }\n parseInit(config) {\n super.parseInit(config);\n this._from = config.from;\n }\n\n getRequest(state, chain, fields) {\n // Does not actually make a request. Just pick off the specific bundle of data from a known payload structure.\n if (chain.discrete && !chain.discrete[this._from]) {\n throw `${this.constructor.SOURCE_NAME} cannot be used before loading required data for: ${this._from}`;\n }\n // Copy the data so that mutations (like sorting) don't affect the original\n return Promise.resolve(JSON.parse(JSON.stringify(chain.discrete[this._from]['variants'])));\n }\n\n normalizeResponse(data) {\n // The payload structure of the association source is slightly different than the one required by association\n // plots. For example, we need to parse variant names and convert to log_pvalue\n const REGEX_EPACTS = new RegExp('(?:chr)?(.+):(\\\\d+)_?(\\\\w+)?/?([^_]+)?_?(.*)?'); // match API variant strings\n return data.map((one_variant) => {\n const match = one_variant.variant.match(REGEX_EPACTS);\n return {\n variant: one_variant.variant,\n chromosome: match[1],\n position: +match[2],\n ref_allele: match[3],\n ref_allele_freq: 1 - one_variant.altFreq,\n log_pvalue: -Math.log10(one_variant.pvalue),\n };\n }).sort((a, b) => {\n a = a.variant;\n b = b.variant;\n if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n // names must be equal\n return 0;\n }\n });\n }\n }\n\n /**\n * A sample connector that aligns calculated aggregation test data with corresponding gene information. Returns a body\n * suitable for use with the genes datalayer.\n *\n * To use this source, one must specify a fields array that calls first the genes source, then a dummy field from\n * this source. The output will be to transparently add several new fields to the genes data.\n * @public\n */\n class GeneAggregationConnectorLZ extends ConnectorSource {\n _getRequiredSources() {\n return ['gene_ns', 'aggregation_ns'];\n }\n\n combineChainBody(data, chain) {\n // The genes layer receives all results, and displays only the best pvalue for each gene\n\n // Tie the calculated group-test results to genes with a matching name\n const aggregation_source_id = this._source_name_mapping['aggregation_ns'];\n const gene_source_id = this._source_name_mapping['gene_ns'];\n // This connector assumes that genes are the main body of records from the chain, and that aggregation tests are\n // a standalone source that has not acted on genes data yet\n const aggregationData = chain.discrete[aggregation_source_id];\n const genesData = chain.discrete[gene_source_id];\n\n const groupedAggregation = {}; // Group together all tests done on that gene- any mask, any test\n\n aggregationData.groups.forEach(function (result) {\n if (!Object.prototype.hasOwnProperty.call(groupedAggregation, result.group)) {\n groupedAggregation[result.group] = [];\n }\n groupedAggregation[result.group].push(result.pvalue);\n });\n\n // Annotate any genes that have test results\n genesData.forEach(function (gene) {\n const gene_id = gene.gene_name;\n const tests = groupedAggregation[gene_id];\n if (tests) {\n gene.aggregation_best_pvalue = Math.min.apply(null, tests);\n }\n });\n return genesData;\n }\n }\n\n\n LocusZoom.Adapters.add('AggregationTestSourceLZ', AggregationTestSource);\n LocusZoom.Adapters.add('AssocFromAggregationLZ', AssocFromAggregationLZ);\n LocusZoom.Adapters.add('GeneAggregationConnectorLZ', GeneAggregationConnectorLZ);\n}\n\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n","/**\n * Define standard data adapters used to retrieve data (usually from REST APIs)\n * @module\n */\n\nfunction validateBuildSource(class_name, build, source) {\n // Build OR Source, not both\n if ((build && source) || !(build || source)) {\n throw new Error(`${class_name} must provide a parameter specifying either \"build\" or \"source\". It should not specify both.`);\n }\n // If the build isn't recognized, our APIs can't transparently select a source to match\n if (build && !['GRCh37', 'GRCh38'].includes(build)) {\n throw new Error(`${class_name} must specify a valid genome build number`);\n }\n}\n\n\n/**\n * Base class for LocusZoom data sources (any). See also: RemoteAdapter\n * @public\n */\nclass BaseAdapter {\n constructor(config) {\n /**\n * Whether this source should enable caching\n * @member {Boolean}\n */\n this._enableCache = true;\n this._cachedKey = null;\n\n /**\n * Whether this data source type is dependent on previous requests- for example, the LD source cannot annotate\n * association data if no data was found for that region.\n * @member {boolean}\n */\n this.__dependentSource = false;\n\n // Parse configuration options\n this.parseInit(config);\n }\n\n /**\n * Parse configuration used to create the data source. Many custom sources will override this method to suit their\n * needs (eg specific config options, or for sources that do not retrieve data from a URL)\n * @protected\n * @param {String|Object} config Basic configuration- either a url, or a config object\n * @param {String} [config.url] The datasource URL\n * @param {String} [config.params] Initial config params for the datasource\n */\n parseInit(config) {\n /** @member {Object} */\n this.params = config.params || {};\n }\n\n /**\n * A unique identifier that indicates whether cached data is valid for this request. For most sources using GET\n * requests to a REST API, this is usually the URL.\n * @protected\n * @param {Object} state Information available in plot.state (chr, start, end). Sometimes used to inject globally\n * available information that influences the request being made.\n * @param {Object} chain The data chain from previous requests made in a sequence.\n * @param fields\n * @returns {String|undefined}\n */\n getCacheKey(state, chain, fields) {\n return this.getURL(state, chain, fields);\n }\n\n /**\n * Stub: build the URL for any requests made by this source.\n * @protected\n */\n getURL(state, chain, fields) {\n return this.url;\n }\n\n /**\n * Perform a network request to fetch data for this source. This is usually the method that is used to override\n * when defining how to retrieve data.\n * @protected\n * @param {Object} state The state of the parent plot\n * @param chain\n * @param fields\n * @returns {Promise}\n */\n fetchRequest(state, chain, fields) {\n const url = this.getURL(state, chain, fields);\n return fetch(url).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n });\n }\n\n /**\n * Gets the data for just this source, typically via a network request (but using cache where possible)\n *\n * For most use cases, it is better to override `fetchRequest` instead, to avoid bypassing the cache mechanism\n * by accident.\n * @protected\n */\n getRequest(state, chain, fields) {\n let req;\n const cacheKey = this.getCacheKey(state, chain, fields);\n if (this._enableCache && typeof(cacheKey) !== 'undefined' && cacheKey === this._cachedKey) {\n req = Promise.resolve(this._cachedResponse); // Resolve to the value of the current promise\n } else {\n req = this.fetchRequest(state, chain, fields);\n if (this._enableCache) {\n this._cachedKey = cacheKey;\n this._cachedResponse = req;\n }\n }\n return req;\n }\n\n /**\n * Ensure the server response is in a canonical form, an array of one object per record. [ {field: oneval} ].\n * If the server response contains columns, reformats the response from {column1: [], column2: []} to the above.\n *\n * Does not apply namespacing, transformations, or field extraction.\n *\n * May be overridden by data sources that inherently return more complex payloads, or that exist to annotate other\n * sources (eg, if the payload provides extra data rather than a series of records).\n * @protected\n * @param {Object[]|Object} data The original parsed server response\n */\n normalizeResponse(data) {\n if (Array.isArray(data)) {\n // Already in the desired form\n return data;\n }\n // Otherwise, assume the server response is an object representing columns of data.\n // Each array should have the same length (verify), and a given array index corresponds to a single row.\n const keys = Object.keys(data);\n const N = data[keys[0]].length;\n const sameLength = keys.every(function (key) {\n const item = data[key];\n return item.length === N;\n });\n if (!sameLength) {\n throw new Error(`${this.constructor.name} expects a response in which all arrays of data are the same length`);\n }\n\n // Go down the rows, and create an object for each record\n const records = [];\n const fields = Object.keys(data);\n for (let i = 0; i < N; i++) {\n const record = {};\n for (let j = 0; j < fields.length; j++) {\n record[fields[j]] = data[fields[j]][i];\n }\n records.push(record);\n }\n return records;\n }\n\n /**\n * Hook to post-process the data returned by this source with new, additional behavior.\n * (eg cleaning up API values or performing complex calculations on the returned data)\n *\n * @protected\n * @param {Object[]} records The parsed data from the source (eg standardized api response)\n * @param {Object} chain The data chain object. For example, chain.headers may provide useful annotation metadata\n * @returns {Object[]|Promise} The modified set of records\n */\n annotateData(records, chain) {\n // Default behavior: no transformations\n return records;\n }\n\n /**\n * Clean up the server records for use by datalayers: extract only certain fields, with the specified names.\n * Apply per-field transformations as appropriate.\n *\n * This hook can be overridden, eg to create a source that always returns all records and ignores the \"fields\" array.\n * This is particularly common for sources at the end of a chain- many \"dependent\" sources do not allow\n * cherry-picking individual fields, in which case by **convention** the fields array specifies \"last_source_name:all\"\n *\n * @protected\n * @param {Object[]} data One record object per element\n * @param {String[]} fields The names of fields to extract (as named in the source data). Eg \"afield\"\n * @param {String[]} outnames How to represent the source fields in the output. Eg \"namespace:afield|atransform\"\n * @param {function[]} trans An array of transformation functions (if any). One function per data element, or null.\n * @protected\n */\n extractFields (data, fields, outnames, trans) {\n //intended for an array of objects\n // [ {\"id\":1, \"val\":5}, {\"id\":2, \"val\":10}]\n // Since a number of sources exist that do not obey this format, we will provide a convenient pass-through\n if (!Array.isArray(data)) {\n return data;\n }\n\n if (!data.length) {\n // Sometimes there are regions that just don't have data- this should not trigger a missing field error message!\n return data;\n }\n\n const fieldFound = [];\n for (let k = 0; k < fields.length; k++) {\n fieldFound[k] = 0;\n }\n\n const records = data.map(function (item) {\n const output_record = {};\n for (let j = 0; j < fields.length; j++) {\n let val = item[fields[j]];\n if (typeof val != 'undefined') {\n fieldFound[j] = 1;\n }\n if (trans && trans[j]) {\n val = trans[j](val);\n }\n output_record[outnames[j]] = val;\n }\n return output_record;\n });\n fieldFound.forEach(function(v, i) {\n if (!v) {\n throw new Error(`field ${fields[i]} not found in response for ${outnames[i]}`);\n }\n });\n return records;\n }\n\n /**\n * Combine records from this source with others in the chain to yield final chain body.\n * Handles merging this data with other sources (if applicable).\n *\n * @protected\n * @param {Object[]} data The data That would be returned from this source alone\n * @param {Object} chain The data chain built up during previous requests\n * @param {String[]} fields\n * @param {String[]} outnames\n * @param {String[]} trans\n * @return {Promise|Object[]} The new chain body\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n return data;\n }\n\n /**\n * Coordinates the work of parsing a response and returning records. This is broken into 4 steps, which may be\n * overridden separately for fine-grained control. Each step can return either raw data or a promise.\n *\n * @protected\n *\n * @param {String|Object} resp The raw data associated with the response\n * @param {Object} chain The combined parsed response data from this and all other requests made in the chain\n * @param {String[]} fields Array of requested field names (as they would appear in the response payload)\n * @param {String[]} outnames Array of field names as they will be represented in the data returned by this source,\n * including the namespace. This must be an array with the same length as `fields`\n * @param {Function[]} trans The collection of transformation functions to be run on selected fields.\n * This must be an array with the same length as `fields`\n * @returns {Promise} A promise that resolves to an object containing\n * request metadata (`headers: {}`), the consolidated data for plotting (`body: []`), and the individual responses that would be\n * returned by each source in the chain in isolation (`discrete: {}`)\n */\n parseResponse (resp, chain, fields, outnames, trans) {\n const source_id = this.source_id || this.constructor.name;\n if (!chain.discrete) {\n chain.discrete = {};\n }\n\n const json = typeof resp == 'string' ? JSON.parse(resp) : resp;\n\n // Perform the 4 steps of parsing the payload and return a combined chain object\n return Promise.resolve(this.normalizeResponse(json.data || json))\n .then((standardized) => {\n // Perform calculations on the data from just this source\n return Promise.resolve(this.annotateData(standardized, chain));\n }).then((data) => {\n return Promise.resolve(this.extractFields(data, fields, outnames, trans));\n }).then((one_source_body) => {\n // Store a copy of the data that would be returned by parsing this source in isolation (and taking the\n // fields array into account). This is useful when we want to re-use the source output in many ways.\n chain.discrete[source_id] = one_source_body;\n return Promise.resolve(this.combineChainBody(one_source_body, chain, fields, outnames, trans));\n }).then((new_body) => {\n return { header: chain.header || {}, discrete: chain.discrete, body: new_body };\n });\n }\n\n /**\n * Fetch the data from the specified data source, and apply transformations requested by an external consumer.\n * This is the public-facing datasource method that will most be called by the plot, but custom data sources will\n * almost never want to override this method directly- more specific hooks are provided to control individual pieces\n * of the request lifecycle.\n *\n * @private\n * @param {Object} state The current \"state\" of the plot, such as chromosome and start/end positions\n * @param {String[]} fields Array of field names that the plot has requested from this data source. (without the \"namespace\" prefix)\n * @param {String[]} outnames Array describing how the output data should refer to this field. This represents the\n * originally requested field name, including the namespace. This must be an array with the same length as `fields`\n * @param {Function[]} trans The collection of transformation functions to be run on selected fields.\n * This must be an array with the same length as `fields`\n * @returns {function} A callable operation that can be used as part of the data chain\n */\n getData(state, fields, outnames, trans) {\n if (this.preGetData) { // TODO try to remove this method if at all possible\n const pre = this.preGetData(state, fields, outnames, trans);\n if (this.pre) {\n state = pre.state || state;\n fields = pre.fields || fields;\n outnames = pre.outnames || outnames;\n trans = pre.trans || trans;\n }\n }\n\n return (chain) => {\n if (this.__dependentSource && chain && chain.body && !chain.body.length) {\n // A \"dependent\" source should not attempt to fire a request if there is no data for it to act on.\n // Therefore, it should simply return the previous data chain.\n return Promise.resolve(chain);\n }\n\n return this.getRequest(state, chain, fields).then((resp) => {\n return this.parseResponse(resp, chain, fields, outnames, trans);\n });\n };\n }\n}\n\n/**\n * Base source for LocusZoom data sources that receive their data over the web. Adds default config parameters\n * (and potentially other behavior) that are relevant to URL-based requests.\n */\nclass RemoteAdapter extends BaseAdapter {\n parseInit(config) {\n super.parseInit(config);\n\n /** @member {String} */\n this.url = config.url;\n if (!this.url) {\n throw new Error('Source not initialized with required URL');\n }\n }\n}\n\n/**\n * Data Source for Association Data from the LocusZoom/ Portaldev API (or compatible). Defines how to make a requesr\n * @public\n */\nclass AssociationLZ extends RemoteAdapter {\n preGetData (state, fields, outnames, trans) {\n // TODO: Modify internals to see if we can go without this method\n const id_field = this.params.id_field || 'id';\n [id_field, 'position'].forEach(function(x) {\n if (!fields.includes(x)) {\n fields.unshift(x);\n outnames.unshift(x);\n trans.unshift(null);\n }\n });\n return {fields: fields, outnames:outnames, trans:trans};\n }\n\n getURL (state, chain, fields) {\n const analysis = chain.header.analysis || this.params.source || this.params.analysis; // Old usages called this param \"analysis\"\n if (typeof analysis == 'undefined') {\n throw new Error('Association source must specify an analysis ID to plot');\n }\n return `${this.url}results/?filter=analysis in ${analysis} and chromosome in '${state.chr}' and position ge ${state.start} and position le ${state.end}`;\n }\n\n normalizeResponse (data) {\n // Some association sources do not sort their data in a predictable order, which makes it hard to reliably\n // align with other sources (such as LD). For performance reasons, sorting is an opt-in argument.\n // TODO: Consider more fine grained sorting control in the future. This was added as a very specific\n // workaround for the original T2D portal.\n data = super.normalizeResponse(data);\n if (this.params && this.params.sort && data.length && data[0]['position']) {\n data.sort(function (a, b) {\n return a['position'] - b['position'];\n });\n }\n return data;\n }\n}\n\n/**\n * Fetch linkage disequilibrium information from a UMich LDServer-compatible API\n *\n * This source is designed to connect its results to association data, and therefore depends on association data having\n * been loaded by a previous request in the data chain.\n *\n * In older versions of LocusZoom, this was known as \"LDServer\". A prior source (targeted at older APIs) has been removed.\n */\nclass LDServer extends RemoteAdapter {\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n preGetData(state, fields) {\n if (fields.length > 1) {\n if (fields.length !== 2 || !fields.includes('isrefvar')) {\n throw new Error(`LD does not know how to get all fields: ${fields.join(', ')}`);\n }\n }\n }\n\n findMergeFields(chain) {\n // Find the fields (as provided by a previous step in the chain, like an association source) that will be needed to\n // combine LD data with existing information\n\n // Since LD information may be shared across multiple assoc sources with different namespaces,\n // we use regex to find columns to join on, rather than requiring exact matches\n const exactMatch = function (arr) {\n return function () {\n const regexes = arguments;\n for (let i = 0; i < regexes.length; i++) {\n const regex = regexes[i];\n const m = arr.filter(function (x) {\n return x.match(regex);\n });\n if (m.length) {\n return m[0];\n }\n }\n return null;\n };\n };\n let dataFields = {\n id: this.params.id_field,\n position: this.params.position_field,\n pvalue: this.params.pvalue_field,\n _names_:null,\n };\n if (chain && chain.body && chain.body.length > 0) {\n const names = Object.keys(chain.body[0]);\n const nameMatch = exactMatch(names);\n // Internally, fields are generally prefixed with the name of the source they come from.\n // If the user provides an id_field (like `variant`), it should work across data sources( `assoc1:variant`,\n // assoc2:variant), but not match fragments of other field names (assoc1:variant_thing)\n // Note: these lookups hard-code a couple of common fields that will work based on known APIs in the wild\n const id_match = dataFields.id && nameMatch(new RegExp(`${dataFields.id}\\\\b`));\n dataFields.id = id_match || nameMatch(/\\bvariant\\b/) || nameMatch(/\\bid\\b/);\n dataFields.position = dataFields.position || nameMatch(/\\bposition\\b/i, /\\bpos\\b/i);\n dataFields.pvalue = dataFields.pvalue || nameMatch(/\\bpvalue\\b/i, /\\blog_pvalue\\b/i);\n dataFields._names_ = names;\n }\n return dataFields;\n }\n\n findRequestedFields (fields, outnames) {\n // Assumption: all usages of this source will only ever ask for \"isrefvar\" or \"state\". This maps to output names.\n let obj = {};\n for (let i = 0; i < fields.length; i++) {\n if (fields[i] === 'isrefvar') {\n obj.isrefvarin = fields[i];\n obj.isrefvarout = outnames && outnames[i];\n } else {\n obj.ldin = fields[i];\n obj.ldout = outnames && outnames[i];\n }\n }\n return obj;\n }\n\n normalizeResponse (data) {\n // The LD API payload does not obey standard format conventions; do not try to transform it.\n return data;\n }\n\n /**\n * Get the LD reference variant, which by default will be the most significant hit in the assoc results\n * This will be used in making the original query to the LD server for pairwise LD information\n * @returns {*|string} The marker id (expected to be in `chr:pos_ref/alt` format) of the reference variant\n */\n getRefvar(state, chain, fields) {\n let findExtremeValue = function(records, pval_field) {\n // Finds the most significant hit (smallest pvalue, or largest -log10p). Will try to auto-detect the appropriate comparison.\n pval_field = pval_field || 'log_pvalue'; // The official LZ API returns log_pvalue\n const is_log = /log/.test(pval_field);\n let cmp;\n if (is_log) {\n cmp = function(a, b) {\n return a > b;\n };\n } else {\n cmp = function(a, b) {\n return a < b;\n };\n }\n let extremeVal = records[0][pval_field], extremeIdx = 0;\n for (let i = 1; i < records.length; i++) {\n if (cmp(records[i][pval_field], extremeVal)) {\n extremeVal = records[i][pval_field];\n extremeIdx = i;\n }\n }\n return extremeIdx;\n };\n\n let reqFields = this.findRequestedFields(fields);\n let refVar = reqFields.ldin;\n if (refVar === 'state') {\n refVar = state.ldrefvar || chain.header.ldrefvar || 'best';\n }\n if (refVar === 'best') {\n if (!chain.body) {\n throw new Error('No association data found to find best pvalue');\n }\n let keys = this.findMergeFields(chain);\n if (!keys.pvalue || !keys.id) {\n let columns = '';\n if (!keys.id) {\n columns += `${columns.length ? ', ' : ''}id`;\n }\n if (!keys.pvalue) {\n columns += `${columns.length ? ', ' : ''}pvalue`;\n }\n throw new Error(`Unable to find necessary column(s) for merge: ${columns} (available: ${keys._names_})`);\n }\n refVar = chain.body[findExtremeValue(chain.body, keys.pvalue)][keys.id];\n }\n return refVar;\n }\n\n getURL(state, chain, fields) {\n // Accept the following params in this.params:\n // - method (r, rsquare, cov)\n // - source (aka panel)\n // - population (ALL, AFR, EUR, etc)\n // - build\n // The LD source/pop can be overridden from plot.state for dynamic layouts\n const build = state.genome_build || this.params.build || 'GRCh37';\n let source = state.ld_source || this.params.source || '1000G';\n const population = state.ld_pop || this.params.population || 'ALL'; // LDServer panels will always have an ALL\n const method = this.params.method || 'rsquare';\n\n if (source === '1000G' && build === 'GRCh38') {\n // For build 38 (only), there is a newer/improved 1000G LD panel available that uses WGS data. Auto upgrade by default.\n source = '1000G-FRZ09';\n }\n\n validateBuildSource(this.constructor.name, build, null); // LD doesn't need to validate `source` option\n\n let refVar = this.getRefvar(state, chain, fields);\n // Some datasets, notably the Portal, use a different marker format.\n // Coerce it into one that will work with the LDServer API. (CHROM:POS_REF/ALT)\n const REGEX_MARKER = /^(?:chr)?([a-zA-Z0-9]+?)[_:-](\\d+)[_:|-]?(\\w+)?[/_:|-]?([^_]+)?_?(.*)?/;\n const match = refVar && refVar.match(REGEX_MARKER);\n\n if (!match) {\n throw new Error('Could not request LD for a missing or incomplete marker format');\n }\n refVar = [match[1], ':', match[2], '_', match[3], '/', match[4]].join('');\n chain.header.ldrefvar = refVar;\n\n return [\n this.url, 'genome_builds/', build, '/references/', source, '/populations/', population, '/variants',\n '?correlation=', method,\n '&variant=', encodeURIComponent(refVar),\n '&chrom=', encodeURIComponent(state.chr),\n '&start=', encodeURIComponent(state.start),\n '&stop=', encodeURIComponent(state.end),\n ].join('');\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n let keys = this.findMergeFields(chain);\n let reqFields = this.findRequestedFields(fields, outnames);\n if (!keys.position) {\n throw new Error(`Unable to find position field for merge: ${keys._names_}`);\n }\n const leftJoin = function (left, right, lfield, rfield) {\n let i = 0, j = 0;\n while (i < left.length && j < right.position2.length) {\n if (left[i][keys.position] === right.position2[j]) {\n left[i][lfield] = right[rfield][j];\n i++;\n j++;\n } else if (left[i][keys.position] < right.position2[j]) {\n i++;\n } else {\n j++;\n }\n }\n };\n const tagRefVariant = function (data, refvar, idfield, outrefname, outldname) {\n for (let i = 0; i < data.length; i++) {\n if (data[i][idfield] && data[i][idfield] === refvar) {\n data[i][outrefname] = 1;\n data[i][outldname] = 1; // For label/filter purposes, implicitly mark the ref var as LD=1 to itself\n } else {\n data[i][outrefname] = 0;\n }\n }\n };\n\n // LD servers vary slightly. Some report corr as \"rsquare\", others as \"correlation\"\n let corrField = data.rsquare ? 'rsquare' : 'correlation';\n leftJoin(chain.body, data, reqFields.ldout, corrField);\n if (reqFields.isrefvarin && chain.header.ldrefvar) {\n tagRefVariant(chain.body, chain.header.ldrefvar, keys.id, reqFields.isrefvarout, reqFields.ldout);\n }\n return chain.body;\n }\n\n fetchRequest(state, chain, fields) {\n // The API is paginated, but we need all of the data to render a plot. Depaginate and combine where appropriate.\n let url = this.getURL(state, chain, fields);\n let combined = { data: {} };\n let chainRequests = function (url) {\n return fetch(url).then().then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n }).then(function(payload) {\n payload = JSON.parse(payload);\n Object.keys(payload.data).forEach(function (key) {\n combined.data[key] = (combined.data[key] || []).concat(payload.data[key]);\n });\n if (payload.next) {\n return chainRequests(payload.next);\n }\n return combined;\n });\n };\n return chainRequests(url);\n }\n}\n\n/**\n * Data source for GWAS catalogs of known variants\n * @public\n * @class\n * @param {Object|String} init Configuration (URL or object)\n * @param {Object} [init.params] Optional configuration parameters\n * @param {Number} [init.params.source=2] The ID of the chosen catalog. Defaults to EBI GWAS catalog, GRCh37\n * @param {('strict'|'loose')} [init.params.match_type='strict'] Whether to match on exact variant, or just position.\n */\nclass GwasCatalogLZ extends RemoteAdapter {\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n getURL(state, chain, fields) {\n // This is intended to be aligned with another source- we will assume they are always ordered by position, asc\n // (regardless of the actual match field)\n const build_option = state.genome_build || this.params.build;\n validateBuildSource(this.constructor.name, build_option, null); // Source can override build- not mutually exclusive\n\n // Most of our annotations will respect genome build before any other option.\n // But there can be more than one GWAS catalog version available in the same API, for the same build- an\n // explicit config option will always take\n // precedence.\n const default_source = (build_option === 'GRCh38') ? 1 : 2; // EBI GWAS catalog\n const source = this.params.source || default_source;\n return `${this.url }?format=objects&sort=pos&filter=id eq ${source} and chrom eq '${state.chr}' and pos ge ${state.start} and pos le ${state.end}`;\n }\n\n findMergeFields(records) {\n // Data from previous sources is already namespaced. Find the alignment field by matching.\n const knownFields = Object.keys(records);\n // Note: All API endoints involved only give results for 1 chromosome at a time; match is implied\n const posMatch = knownFields.find(function (item) {\n return item.match(/\\b(position|pos)\\b/i);\n });\n\n if (!posMatch) {\n throw new Error('Could not find data to align with GWAS catalog results');\n }\n return { 'pos': posMatch };\n }\n\n extractFields (data, fields, outnames, trans) {\n // Skip the \"individual field extraction\" step; extraction will be handled when building chain body instead\n return data;\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n if (!data.length) {\n return chain.body;\n }\n\n // TODO: Better reuse options in the future. This source is very specifically tied to the PortalDev API, where\n // the field name is always \"log_pvalue\". Relatively few sites will write their own gwas-catalog endpoint.\n const decider = 'log_pvalue';\n const decider_out = outnames[fields.indexOf(decider)];\n\n function leftJoin(left, right, fields, outnames, trans) { // Add `fields` from `right` to `left`\n // Add a synthetic, un-namespaced field to all matching records\n const n_matches = left['n_catalog_matches'] || 0;\n left['n_catalog_matches'] = n_matches + 1;\n if (decider && left[decider_out] && left[decider_out] > right[decider]) {\n // There may be more than one GWAS catalog entry for the same SNP. This source is intended for a 1:1\n // annotation scenario, so for now it only joins the catalog entry that has the best -log10 pvalue\n return;\n }\n\n for (let j = 0; j < fields.length; j++) {\n const fn = fields[j];\n const outn = outnames[j];\n\n let val = right[fn];\n if (trans && trans[j]) {\n val = trans[j](val);\n }\n left[outn] = val;\n }\n }\n\n const chainNames = this.findMergeFields(chain.body[0]);\n const catNames = this.findMergeFields(data[0]);\n\n var i = 0, j = 0;\n while (i < chain.body.length && j < data.length) {\n var left = chain.body[i];\n var right = data[j];\n\n if (left[chainNames.pos] === right[catNames.pos]) {\n // There may be multiple catalog entries for each matching SNP; evaluate match one at a time\n leftJoin(left, right, fields, outnames, trans);\n j += 1;\n } else if (left[chainNames.pos] < right[catNames.pos]) {\n i += 1;\n } else {\n j += 1;\n }\n }\n return chain.body;\n }\n}\n\n/**\n * Data Source for Gene Data, as fetched from the LocusZoom/Portaldev API server (or compatible format)\n * @public\n */\nclass GeneLZ extends RemoteAdapter {\n getURL(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n let source = this.params.source;\n validateBuildSource(this.constructor.name, build, source);\n\n if (build) { // If build specified, choose a known Portal API dataset IDs (build 37/38)\n source = (build === 'GRCh38') ? 1 : 3;\n }\n return `${this.url}?filter=source in ${source} and chrom eq '${state.chr}' and start le ${state.end} and end ge ${state.start}`;\n }\n\n normalizeResponse(data) {\n // Genes have a very complex internal data format. Bypass any record parsing, and provide the data layer with\n // the exact information returned by the API. (ignoring the fields array in the layout)\n return data;\n }\n\n extractFields(data, fields, outnames, trans) {\n return data;\n }\n}\n\n/**\n * Data Source for Gene Constraint Data, as fetched from the gnomAD server (or compatible)\n *\n * This is intended to be the second request in a chain, with special logic that connects it to Genes data\n * already fetched.\n *\n * @public\n*/\nclass GeneConstraintLZ extends RemoteAdapter {\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n getURL() {\n // GraphQL API: request details are encoded in the body, not the URL\n return this.url;\n }\n getCacheKey(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n // GraphQL API: request not defined solely by the URL\n // Gather the state params that govern constraint query for a given region.\n return `${this.url} ${state.chr} ${state.start} ${state.end} ${build}`;\n }\n\n normalizeResponse(data) {\n return data;\n }\n\n fetchRequest(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n if (!build) {\n throw new Error(`Data source ${this.constructor.name} must specify a 'genome_build' option`);\n }\n\n const unique_gene_names = chain.body.reduce(\n // In rare cases, the same gene symbol may appear at multiple positions. (issue #179) We de-duplicate the\n // gene names to avoid issuing a malformed GraphQL query.\n function (acc, gene) {\n acc[gene.gene_name] = null;\n return acc;\n },\n {}\n );\n let query = Object.keys(unique_gene_names).map(function (gene_name) {\n // GraphQL alias names must match a specific set of allowed characters: https://stackoverflow.com/a/45757065/1422268\n const alias = `_${gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`;\n // Each gene symbol is a separate graphQL query, grouped into one request using aliases\n return `${alias}: gene(gene_symbol: \"${gene_name}\", reference_genome: ${build}) { gnomad_constraint { exp_syn obs_syn syn_z oe_syn oe_syn_lower oe_syn_upper exp_mis obs_mis mis_z oe_mis oe_mis_lower oe_mis_upper exp_lof obs_lof pLI oe_lof oe_lof_lower oe_lof_upper } } `;\n });\n\n if (!query.length) {\n // If there are no genes, skip the network request\n return Promise.resolve({ data: null });\n }\n\n query = `{${query.join(' ')} }`; // GraphQL isn't quite JSON; items are separated by spaces but not commas\n const url = this.getURL(state, chain, fields);\n // See: https://graphql.org/learn/serving-over-http/\n const body = JSON.stringify({ query: query });\n const headers = { 'Content-Type': 'application/json' };\n\n return fetch(url, { method: 'POST', body, headers }).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n });\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n if (!data) {\n return chain;\n }\n\n chain.body.forEach(function(gene) {\n // Find payload keys that match gene names in this response\n const alias = `_${gene.gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`; // aliases are modified gene names\n const constraint = data[alias] && data[alias]['gnomad_constraint']; // gnomad API has two ways of specifying missing data for a requested gene\n if (constraint) {\n // Add all fields from constraint data- do not override fields present in the gene source\n Object.keys(constraint).forEach(function (key) {\n let val = constraint[key];\n if (typeof gene[key] === 'undefined') {\n if (typeof val == 'number' && val.toString().includes('.')) {\n val = parseFloat(val.toFixed(2));\n }\n gene[key] = val; // These two sources are both designed to bypass namespacing\n }\n });\n }\n });\n return chain.body;\n }\n}\n\n/**\n * Data Source for Recombination Rate Data, as fetched from the LocusZoom API server (or compatible)\n * @public\n */\nclass RecombLZ extends RemoteAdapter {\n getURL(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n let source = this.params.source;\n validateBuildSource(this.constructor.SOURCE_NAME, build, source);\n\n if (build) { // If build specified, choose a known Portal API dataset IDs (build 37/38)\n source = (build === 'GRCh38') ? 16 : 15;\n }\n return `${this.url}?filter=id in ${source} and chromosome eq '${state.chr}' and position le ${state.end} and position ge ${state.start}`;\n }\n}\n\n/**\n * Data Source for static blobs of data as raw JS objects. This does not perform additional parsing, and it bypasses\n * namespaces. Therefore it is the responsibility of the user to pass information in a format that can be read and\n * understood by the chosen plot- a StaticJSON source is rarely a drop-in replacement.\n *\n * This source is largely here for legacy reasons. More often, a convenient way to serve static data is as separate\n * JSON files to an existing source (with the JSON url in place of an API).\n * @public\n */\nclass StaticSource extends BaseAdapter {\n parseInit(data) {\n // Does not receive any config; the only argument is the raw data, embedded when source is created\n this._data = data;\n }\n getRequest(state, chain, fields) {\n return Promise.resolve(this._data);\n }\n}\n\n\n/**\n * Data source for PheWAS data retrieved from a LocusZoom/PortalDev compatible API\n * @public\n * @param {String[]} init.params.build This datasource expects to be provided the name of the genome build that will\n * be used to provide pheWAS results for this position. Note positions may not translate between builds.\n */\nclass PheWASLZ extends RemoteAdapter {\n getURL(state, chain, fields) {\n const build = (state.genome_build ? [state.genome_build] : null) || this.params.build;\n if (!build || !Array.isArray(build) || !build.length) {\n throw new Error(['Data source', this.constructor.SOURCE_NAME, 'requires that you specify array of one or more desired genome build names'].join(' '));\n }\n const url = [\n this.url,\n \"?filter=variant eq '\", encodeURIComponent(state.variant), \"'&format=objects&\",\n build.map(function (item) {\n return `build=${encodeURIComponent(item)}`;\n }).join('&'),\n ];\n return url.join('');\n }\n}\n\n\n/**\n * Base class for \"connectors\"- this is meant to be subclassed, rather than used directly.\n *\n * A connector is a source that makes no server requests and caches no data of its own. Instead, it decides how to\n * combine data from other sources in the chain. Connectors are useful when we want to request (or calculate) some\n * useful piece of information once, but apply it to many different kinds of record types.\n *\n * Typically, a subclass will implement the field merging logic in `combineChainBody`.\n *\n * @public\n * @param {Object} init Configuration for this source\n * @param {Object} init.sources Specify how the hard-coded logic should find the data it relies on in the chain,\n * as {internal_name: chain_source_id} pairs. This allows writing a reusable connector that does not need to make\n * assumptions about what namespaces a source is using.\n * @type {*|Function}\n */\nclass ConnectorSource extends BaseAdapter {\n constructor(config) {\n super(config);\n\n if (!config || !config.sources) {\n throw new Error('Connectors must specify the data they require as init.sources = {internal_name: chain_source_id}} pairs');\n }\n\n /**\n * Tells the connector how to find the data it relies on\n *\n * For example, a connector that applies burden test information to the genes layer might specify:\n * {gene_ns: \"gene\", aggregation_ns: \"aggregation\"}\n *\n * @member {Object}\n */\n this._source_name_mapping = config.sources;\n\n // Validate that this source has been told how to find the required information\n const specified_ids = Object.keys(config.sources);\n /** @property {String[]} Specifies the sources that must be provided in the original config object */\n\n this._getRequiredSources().forEach((k) => {\n if (!specified_ids.includes(k)) {\n // TODO: Fix constructor.name usage in minified bundles\n throw new Error(`Configuration for ${this.constructor.name} must specify a source ID corresponding to ${k}`);\n }\n });\n }\n\n // Stub- connectors don't have their own url or data, so the defaults don't make sense\n parseInit() {}\n\n getRequest(state, chain, fields) {\n // Connectors do not request their own data by definition, but they *do* depend on other sources having been loaded\n // first. This method performs basic validation, and preserves the accumulated body from the chain so far.\n Object.keys(this._source_name_mapping).forEach((ns) => {\n const chain_source_id = this._source_name_mapping[ns];\n if (chain.discrete && !chain.discrete[chain_source_id]) {\n throw new Error(`${this.constructor.name} cannot be used before loading required data for: ${chain_source_id}`);\n }\n });\n return Promise.resolve(chain.body || []);\n }\n\n parseResponse(data, chain, fields, outnames, trans) {\n // A connector source does not update chain.discrete, but it may use it. It bypasses data formatting\n // and field selection (both are assumed to have been done already, by the previous sources this draws from)\n\n // Because of how the chain works, connectors are not very good at applying new transformations or namespacing.\n // Typically connectors are called with `connector_name:all` in the fields array.\n return Promise.resolve(this.combineChainBody(data, chain, fields, outnames, trans))\n .then(function(new_body) {\n return {header: chain.header || {}, discrete: chain.discrete || {}, body: new_body};\n });\n }\n\n combineChainBody(records, chain) {\n // Stub method: specifies how to combine the data\n throw new Error('This method must be implemented in a subclass');\n }\n\n /**\n * Helper method since ES6 doesn't support class fields\n * @private\n */\n _getRequiredSources() {\n throw new Error('Must specify an array that identifes the kind of data required by this source');\n }\n}\n\nexport { BaseAdapter, RemoteAdapter };\n\nexport {\n AssociationLZ,\n ConnectorSource,\n GeneConstraintLZ,\n GeneLZ,\n GwasCatalogLZ,\n LDServer,\n PheWASLZ,\n RecombLZ,\n StaticSource,\n};\n","module.exports = raremetal;"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/ext/lz-credible-sets.min.js b/dist/ext/lz-credible-sets.min.js index c4233456..1ddc5cd3 100644 --- a/dist/ext/lz-credible-sets.min.js +++ b/dist/ext/lz-credible-sets.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.12.0-beta.1 */ -var LzCredibleSets=function(e){var t={};function a(o){if(t[o])return t[o].exports;var n=t[o]={i:o,l:!1,exports:{}};return e[o].call(n.exports,n,n.exports,a),n.l=!0,n.exports}return a.m=e,a.c=t,a.d=function(e,t,o){a.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},a.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.t=function(e,t){if(1&t&&(e=a(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(a.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)a.d(o,n,function(t){return e[t]}.bind(null,n));return o},a.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return a.d(t,"a",t),t},a.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},a.p="",a(a.s=22)}({14:function(e,t){e.exports=gwasCredibleSets},22:function(e,t,a){"use strict";a.r(t);var o=a(14);function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var a=0;aPosterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}",t)),e.Layouts.add("tooltip","annotation_credible_set",{namespace:{assoc:"assoc",credset:"credset"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"{{{{namespace[assoc]}}variant|htmlescape}}
P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}

Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}"}),e.Layouts.add("data_layer","association_credible_set",((a=e.Layouts.get("data_layer","association_pvalues",{unnamespaced:!0,id:"associationcredibleset",namespace:{assoc:"assoc",credset:"credset",ld:"ld"},fill_opacity:.7,tooltip:e.Layouts.get("tooltip","association_credible_set",{unnamespaced:!0}),fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[assoc]}}log_pvalue|logtoscinotation","{{namespace[assoc]}}ref_allele","{{namespace[credset]}}posterior_prob","{{namespace[credset]}}contrib_fraction","{{namespace[credset]}}is_member","{{namespace[ld]}}state","{{namespace[ld]}}isrefvar"],match:{send:"{{namespace[assoc]}}variant",receive:"{{namespace[assoc]}}variant"}})).color.unshift({field:"lz_highlight_match",scale_function:"if",parameters:{field_value:!0,then:"#FFf000"}}),a)),e.Layouts.add("data_layer","annotation_credible_set",{namespace:{assoc:"assoc",credset:"credset"},id:"annotationcredibleset",type:"annotation_track",id_field:"{{namespace[assoc]}}variant",x_axis:{field:"{{namespace[assoc]}}position"},color:[{field:"lz_highlight_match",scale_function:"if",parameters:{field_value:!0,then:"#001cee"}},"#00CC00"],fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[credset]}}posterior_prob","{{namespace[credset]}}contrib_fraction","{{namespace[credset]}}is_member"],match:{send:"{{namespace[assoc]}}variant",receive:"{{namespace[assoc]}}variant"},filters:[["{{namespace[credset]}}is_member",!0]],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:e.Layouts.get("tooltip","annotation_credible_set",{unnamespaced:!0}),tooltip_positioning:"top"}),e.Layouts.add("panel","annotation_credible_set",{id:"annotationcredibleset",title:{text:"SNPs in 95% credible set",x:50,style:{"font-size":"14px"}},width:800,height:45,min_height:45,proportional_width:1,margin:{top:25,right:50,bottom:0,left:50},inner_border:"rgb(210, 210, 210)",toolbar:e.Layouts.get("toolbar","standard_panel",{unnamespaced:!0}),interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[e.Layouts.get("data_layer","annotation_credible_set",{unnamespaced:!0})]}),e.Layouts.add("panel","association_credible_set",function(){var t=e.Layouts.get("panel","association",{unnamespaced:!0,id:"associationcrediblesets",namespace:{assoc:"assoc",credset:"credset"},data_layers:[e.Layouts.get("data_layer","significance",{unnamespaced:!0}),e.Layouts.get("data_layer","recomb_rate",{unnamespaced:!0}),e.Layouts.get("data_layer","association_credible_set",{unnamespaced:!0})]});return t.toolbar.widgets.push({type:"display_options",position:"right",color:"blue",button_html:"Display options...",button_title:"Control how plot items are displayed",layer_name:"associationcredibleset",default_config_display_name:"Linkage Disequilibrium (default)",options:[{display_name:"95% credible set (boolean)",display:{point_shape:"circle",point_size:40,color:{field:"{{namespace[credset]}}is_member",scale_function:"if",parameters:{field_value:!0,then:"#00CC00",else:"#CCCCCC"}},legend:[{shape:"circle",color:"#00CC00",size:40,label:"In credible set",class:"lz-data_layer-scatter"},{shape:"circle",color:"#CCCCCC",size:40,label:"Not in credible set",class:"lz-data_layer-scatter"}]}},{display_name:"95% credible set (gradient by contribution)",display:{point_shape:"circle",point_size:40,color:[{field:"{{namespace[credset]}}contrib_fraction",scale_function:"if",parameters:{field_value:0,then:"#777777"}},{scale_function:"interpolate",field:"{{namespace[credset]}}contrib_fraction",parameters:{breaks:[0,1],values:["#fafe87","#9c0000"]}}],legend:[{shape:"circle",color:"#777777",size:40,label:"No contribution",class:"lz-data_layer-scatter"},{shape:"circle",color:"#fafe87",size:40,label:"Some contribution",class:"lz-data_layer-scatter"},{shape:"circle",color:"#9c0000",size:40,label:"Most contribution",class:"lz-data_layer-scatter"}]}}]}),t}()),e.Layouts.add("plot","association_credible_set",{state:{},width:800,height:450,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:e.Layouts.get("toolbar","region_nav_plot",{unnamespaced:!0}),panels:[e.Layouts.get("panel","association_credible_set",{unnamespaced:!0}),e.Layouts.get("panel","annotation_credible_set",{unnamespaced:!0}),e.Layouts.get("panel","genes",{unnamespaced:!0})]})}"undefined"!=typeof LocusZoom&&LocusZoom.use(d),t.default=d}}).default; +/*! Locuszoom 0.12.0-beta.3 */ +var LzCredibleSets=function(e){var t={};function a(o){if(t[o])return t[o].exports;var n=t[o]={i:o,l:!1,exports:{}};return e[o].call(n.exports,n,n.exports,a),n.l=!0,n.exports}return a.m=e,a.c=t,a.d=function(e,t,o){a.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},a.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.t=function(e,t){if(1&t&&(e=a(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(a.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)a.d(o,n,function(t){return e[t]}.bind(null,n));return o},a.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return a.d(t,"a",t),t},a.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},a.p="",a(a.s=10)}({10:function(e,t,a){"use strict";a.r(t);var o=a(3);function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var a=0;aPosterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}",t)),e.Layouts.add("tooltip","annotation_credible_set",{namespace:{assoc:"assoc",credset:"credset"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"{{{{namespace[assoc]}}variant|htmlescape}}
P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}

Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}"}),e.Layouts.add("data_layer","association_credible_set",((a=e.Layouts.get("data_layer","association_pvalues",{unnamespaced:!0,id:"associationcredibleset",namespace:{assoc:"assoc",credset:"credset",ld:"ld"},fill_opacity:.7,tooltip:e.Layouts.get("tooltip","association_credible_set",{unnamespaced:!0}),fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[assoc]}}log_pvalue|logtoscinotation","{{namespace[assoc]}}ref_allele","{{namespace[credset]}}posterior_prob","{{namespace[credset]}}contrib_fraction","{{namespace[credset]}}is_member","{{namespace[ld]}}state","{{namespace[ld]}}isrefvar"],match:{send:"{{namespace[assoc]}}variant",receive:"{{namespace[assoc]}}variant"}})).color.unshift({field:"lz_highlight_match",scale_function:"if",parameters:{field_value:!0,then:"#FFf000"}}),a)),e.Layouts.add("data_layer","annotation_credible_set",{namespace:{assoc:"assoc",credset:"credset"},id:"annotationcredibleset",type:"annotation_track",id_field:"{{namespace[assoc]}}variant",x_axis:{field:"{{namespace[assoc]}}position"},color:[{field:"lz_highlight_match",scale_function:"if",parameters:{field_value:!0,then:"#001cee"}},"#00CC00"],fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[credset]}}posterior_prob","{{namespace[credset]}}contrib_fraction","{{namespace[credset]}}is_member"],match:{send:"{{namespace[assoc]}}variant",receive:"{{namespace[assoc]}}variant"},filters:[{field:"{{namespace[credset]}}is_member",operator:"=",value:!0}],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:e.Layouts.get("tooltip","annotation_credible_set",{unnamespaced:!0}),tooltip_positioning:"top"}),e.Layouts.add("panel","annotation_credible_set",{id:"annotationcredibleset",title:{text:"SNPs in 95% credible set",x:50,style:{"font-size":"14px"}},width:800,height:45,min_height:45,proportional_width:1,margin:{top:25,right:50,bottom:0,left:50},inner_border:"rgb(210, 210, 210)",toolbar:e.Layouts.get("toolbar","standard_panel",{unnamespaced:!0}),interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[e.Layouts.get("data_layer","annotation_credible_set",{unnamespaced:!0})]}),e.Layouts.add("panel","association_credible_set",function(){var t=e.Layouts.get("panel","association",{unnamespaced:!0,id:"associationcrediblesets",namespace:{assoc:"assoc",credset:"credset"},data_layers:[e.Layouts.get("data_layer","significance",{unnamespaced:!0}),e.Layouts.get("data_layer","recomb_rate",{unnamespaced:!0}),e.Layouts.get("data_layer","association_credible_set",{unnamespaced:!0})]});return t.toolbar.widgets.push({type:"display_options",position:"right",color:"blue",button_html:"Display options...",button_title:"Control how plot items are displayed",layer_name:"associationcredibleset",default_config_display_name:"Linkage Disequilibrium (default)",options:[{display_name:"95% credible set (boolean)",display:{point_shape:"circle",point_size:40,color:{field:"{{namespace[credset]}}is_member",scale_function:"if",parameters:{field_value:!0,then:"#00CC00",else:"#CCCCCC"}},legend:[{shape:"circle",color:"#00CC00",size:40,label:"In credible set",class:"lz-data_layer-scatter"},{shape:"circle",color:"#CCCCCC",size:40,label:"Not in credible set",class:"lz-data_layer-scatter"}]}},{display_name:"95% credible set (gradient by contribution)",display:{point_shape:"circle",point_size:40,color:[{field:"{{namespace[credset]}}contrib_fraction",scale_function:"if",parameters:{field_value:0,then:"#777777"}},{scale_function:"interpolate",field:"{{namespace[credset]}}contrib_fraction",parameters:{breaks:[0,1],values:["#fafe87","#9c0000"]}}],legend:[{shape:"circle",color:"#777777",size:40,label:"No contribution",class:"lz-data_layer-scatter"},{shape:"circle",color:"#fafe87",size:40,label:"Some contribution",class:"lz-data_layer-scatter"},{shape:"circle",color:"#9c0000",size:40,label:"Most contribution",class:"lz-data_layer-scatter"}]}}]}),t}()),e.Layouts.add("plot","association_credible_set",{state:{},width:800,height:450,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:e.Layouts.get("toolbar","region_nav_plot",{unnamespaced:!0}),panels:[e.Layouts.get("panel","association_credible_set",{unnamespaced:!0}),e.Layouts.get("panel","annotation_credible_set",{unnamespaced:!0}),e.Layouts.get("panel","genes",{unnamespaced:!0})]})}"undefined"!=typeof LocusZoom&&LocusZoom.use(d),t.default=d},3:function(e,t){e.exports=gwasCredibleSets}}).default; //# sourceMappingURL=lz-credible-sets.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-credible-sets.min.js.map b/dist/ext/lz-credible-sets.min.js.map index 292788cf..adb3b5b6 100644 --- a/dist/ext/lz-credible-sets.min.js.map +++ b/dist/ext/lz-credible-sets.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/external \"gwasCredibleSets\"","webpack://[name]/./esm/ext/lz-credible-sets.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","gwasCredibleSets","install","LocusZoom","base","CredibleSetLZ","config","arguments","dependentSource","this","params","fields","log_pvalue","Error","constructor","SOURCE_NAME","threshold","state","chain","credible_set_threshold","chr","start","end","join","self","body","nlogpvals","map","item","credset_data","scores","scoring","bayesFactors","posteriorProbabilities","normalizeProbabilities","credibleSet","marking","findCredibleSet","credSetScaled","rescaleCredibleSet","credSetBool","markBoolean","length","push","posterior_prob","contrib_fraction","is_member","e","console","error","Promise","resolve","data","outnames","trans","src","dest","keys","forEach","attr","Adapters","add","Layouts","unnamespaced","html","namespace","closable","show","or","hide","and","id","fill_opacity","tooltip","match","send","receive","color","unshift","field","scale_function","parameters","field_value","then","type","id_field","x_axis","filters","behaviors","onmouseover","action","status","onmouseout","onclick","exclusive","onshiftclick","tooltip_positioning","title","text","x","style","width","height","min_height","proportional_width","margin","top","right","bottom","left","inner_border","toolbar","interaction","drag_background_to_pan","scroll_to_zoom","x_linked","data_layers","widgets","position","button_html","button_title","layer_name","default_config_display_name","options","display_name","display","point_shape","point_size","else","legend","shape","size","label","class","breaks","values","responsive_resize","min_region_scale","max_region_scale","panels","use"],"mappings":"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","file":"ext/lz-credible-sets.min.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 22);\n","module.exports = gwasCredibleSets;","/**\n Custom code used to power credible sets demonstration example. This is not part of the core LocusZoom library,\n but can be included as a standalone file.\n\n The page must incorporate and load all libraries before this file can be used, including:\n - Vendor assets\n - LocusZoom\n - gwas-credible-sets (available via NPM or a related CDN)\n @module\n*/\n\nimport {marking, scoring} from 'gwas-credible-sets';\n\nfunction install (LocusZoom) {\n const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter');\n /**\n * Custom data source that calculates the 95% credible set based on provided data.\n * This source must be requested as the second step in a chain, after a previous step that returns fields required\n * for the calculation.\n *\n * @param {Object} init.params\n * @param {Object} init.params.fields\n * @param {String} init.params.fields.log_pvalue The name of the field containing pvalue information\n * @param {Number} [init.params.threshold=0.95] The credible set threshold (eg 95%)\n *\n */\n class CredibleSetLZ extends BaseAdapter {\n constructor(config) {\n super(...arguments);\n this.dependentSource = true; // Don't do calcs for a region with no assoc data\n }\n\n parseInit(config) {\n super.parseInit(...arguments);\n if (!(this.params.fields && this.params.fields.log_pvalue)) {\n throw new Error(`Source config for ${this.constructor.SOURCE_NAME} must specify how to find 'fields.log_pvalue'`);\n }\n if (!this.params.threshold) {\n this.params.threshold = 0.95;\n }\n }\n\n getCacheKey (state, chain, fields) {\n const threshold = state.credible_set_threshold || this.params.threshold;\n return [threshold, state.chr, state.start, state.end].join('_');\n }\n\n fetchRequest(state, chain) {\n const self = this;\n // The threshold can be overridden dynamically via `plot.state`, or set when the source is created\n const threshold = state.credible_set_threshold || this.params.threshold;\n // Calculate raw bayes factors and posterior probabilities based on information returned from the API\n if (typeof chain.body[0][self.params.fields.log_pvalue] === 'undefined') {\n throw new Error('Credible set source could not locate the required fields from a previous request.');\n }\n const nlogpvals = chain.body.map(function (item) {\n return item[self.params.fields.log_pvalue];\n });\n const credset_data = [];\n try {\n const scores = scoring.bayesFactors(nlogpvals);\n const posteriorProbabilities = scoring.normalizeProbabilities(scores);\n\n // Use scores to mark the credible set in various ways (depending on your visualization preferences,\n // some of these may not be needed)\n const credibleSet = marking.findCredibleSet(scores, threshold);\n const credSetScaled = marking.rescaleCredibleSet(credibleSet);\n const credSetBool = marking.markBoolean(credibleSet);\n\n // Annotate each response record based on credible set membership\n for (let i = 0; i < chain.body.length; i++) {\n credset_data.push({\n posterior_prob: posteriorProbabilities[i],\n contrib_fraction: credSetScaled[i],\n is_member: credSetBool[i],\n });\n }\n } catch (e) {\n // If the calculation cannot be completed, return the data without annotation fields\n console.error(e);\n }\n return Promise.resolve(credset_data);\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n // At this point namespacing has been applied; add the calculated fields for this source to the chain\n for (let i = 0; i < data.length; i++) {\n const src = data[i];\n const dest = chain.body[i];\n Object.keys(src).forEach(function (attr) {\n dest[attr] = src[attr];\n });\n }\n return chain.body;\n }\n }\n\n\n LocusZoom.Adapters.add('CredibleSetLZ', CredibleSetLZ);\n\n // Add related layouts to the central global registry\n LocusZoom.Layouts.add('tooltip', 'association_credible_set', function () {\n // Extend a known tooltip with an extra row of info showing posterior probabilities\n const l = LocusZoom.Layouts.get('tooltip', 'standard_association', { unnamespaced: true });\n l.html += '
Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}';\n return l;\n }());\n\n LocusZoom.Layouts.add('tooltip', 'annotation_credible_set', {\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{{{namespace[assoc]}}variant|htmlescape}}
'\n + 'P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
' +\n '
Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}',\n });\n\n LocusZoom.Layouts.add('data_layer', 'association_credible_set', function () {\n const base = LocusZoom.Layouts.get('data_layer', 'association_pvalues', {\n unnamespaced: true,\n id: 'associationcredibleset',\n namespace: { 'assoc': 'assoc', 'credset': 'credset', 'ld': 'ld' },\n fill_opacity: 0.7,\n tooltip: LocusZoom.Layouts.get('tooltip', 'association_credible_set', { unnamespaced: true }),\n fields: [\n '{{namespace[assoc]}}variant', '{{namespace[assoc]}}position',\n '{{namespace[assoc]}}log_pvalue', '{{namespace[assoc]}}log_pvalue|logtoscinotation',\n '{{namespace[assoc]}}ref_allele',\n '{{namespace[credset]}}posterior_prob', '{{namespace[credset]}}contrib_fraction',\n '{{namespace[credset]}}is_member',\n '{{namespace[ld]}}state', '{{namespace[ld]}}isrefvar',\n ],\n match: { send: '{{namespace[assoc]}}variant', receive: '{{namespace[assoc]}}variant' },\n });\n base.color.unshift({\n field: 'lz_highlight_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#FFf000',\n },\n });\n return base;\n }());\n\n LocusZoom.Layouts.add('data_layer', 'annotation_credible_set', {\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n id: 'annotationcredibleset',\n type: 'annotation_track',\n id_field: '{{namespace[assoc]}}variant',\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n color: [\n {\n field: 'lz_highlight_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#001cee',\n },\n },\n '#00CC00',\n ],\n fields: ['{{namespace[assoc]}}variant', '{{namespace[assoc]}}position', '{{namespace[assoc]}}log_pvalue', '{{namespace[credset]}}posterior_prob', '{{namespace[credset]}}contrib_fraction', '{{namespace[credset]}}is_member'],\n match: { send: '{{namespace[assoc]}}variant', receive: '{{namespace[assoc]}}variant' },\n filters: [\n // Specify which points to show on the track. Any selection must satisfy ALL filters\n ['{{namespace[credset]}}is_member', true],\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: LocusZoom.Layouts.get('tooltip', 'annotation_credible_set', { unnamespaced: true }),\n tooltip_positioning: 'top',\n });\n\n LocusZoom.Layouts.add('panel', 'annotation_credible_set', {\n id: 'annotationcredibleset',\n title: { text: 'SNPs in 95% credible set', x: 50, style: { 'font-size': '14px' } },\n width: 800,\n height: 45,\n min_height: 45,\n proportional_width: 1,\n margin: { top: 25, right: 50, bottom: 0, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_panel', { unnamespaced: true }),\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n LocusZoom.Layouts.get('data_layer', 'annotation_credible_set', { unnamespaced: true }),\n ],\n });\n\n LocusZoom.Layouts.add('panel', 'association_credible_set', function () {\n const l = LocusZoom.Layouts.get('panel', 'association', {\n unnamespaced: true,\n id: 'associationcrediblesets',\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n data_layers: [\n LocusZoom.Layouts.get('data_layer', 'significance', { unnamespaced: true }),\n LocusZoom.Layouts.get('data_layer', 'recomb_rate', { unnamespaced: true }),\n LocusZoom.Layouts.get('data_layer', 'association_credible_set', { unnamespaced: true }),\n ],\n });\n // Add \"display options\" button to control how credible set coloring is overlaid on the standard association plot\n l.toolbar.widgets.push(\n {\n type: 'display_options',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Display options...',\n button_title: 'Control how plot items are displayed',\n layer_name: 'associationcredibleset',\n default_config_display_name: 'Linkage Disequilibrium (default)', // display name for the default plot color option (allow user to revert to plot defaults)\n\n options: [\n {\n // First dropdown menu item\n display_name: '95% credible set (boolean)', // Human readable representation of field name\n display: { // Specify layout directives that control display of the plot for this option\n point_shape: 'circle',\n point_size: 40,\n color: {\n field: '{{namespace[credset]}}is_member',\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#00CC00',\n else: '#CCCCCC',\n },\n },\n legend: [ // Tells the legend how to represent this display option\n {\n shape: 'circle',\n color: '#00CC00',\n size: 40,\n label: 'In credible set',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#CCCCCC',\n size: 40,\n label: 'Not in credible set',\n class: 'lz-data_layer-scatter',\n },\n ],\n },\n },\n {\n // Second option. The same plot- or even the same field- can be colored in more than one way.\n display_name: '95% credible set (gradient by contribution)',\n display: {\n point_shape: 'circle',\n point_size: 40,\n color: [\n {\n field: '{{namespace[credset]}}contrib_fraction',\n scale_function: 'if',\n parameters: {\n field_value: 0,\n then: '#777777',\n },\n },\n {\n scale_function: 'interpolate',\n field: '{{namespace[credset]}}contrib_fraction',\n parameters: {\n breaks: [0, 1],\n values: ['#fafe87', '#9c0000'],\n },\n },\n ],\n legend: [\n {\n shape: 'circle',\n color: '#777777',\n size: 40,\n label: 'No contribution',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#fafe87',\n size: 40,\n label: 'Some contribution',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#9c0000',\n size: 40,\n label: 'Most contribution',\n class: 'lz-data_layer-scatter',\n },\n ],\n },\n },\n ],\n }\n );\n return l;\n }());\n\n LocusZoom.Layouts.add('plot', 'association_credible_set', {\n state: {},\n width: 800,\n height: 450,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: LocusZoom.Layouts.get('toolbar', 'region_nav_plot', { unnamespaced: true }),\n panels: [\n LocusZoom.Layouts.get('panel', 'association_credible_set', { unnamespaced: true }),\n LocusZoom.Layouts.get('panel', 'annotation_credible_set', { unnamespaced: true }),\n LocusZoom.Layouts.get('panel', 'genes', { unnamespaced: true }),\n ],\n });\n\n}\n\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/./esm/ext/lz-credible-sets.js","webpack://[name]/external \"gwasCredibleSets\""],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","install","LocusZoom","base","CredibleSetLZ","config","arguments","dependentSource","this","params","fields","log_pvalue","Error","constructor","SOURCE_NAME","threshold","state","chain","credible_set_threshold","chr","start","end","join","self","body","nlogpvals","map","item","credset_data","scores","scoring","bayesFactors","posteriorProbabilities","normalizeProbabilities","credibleSet","marking","findCredibleSet","credSetScaled","rescaleCredibleSet","credSetBool","markBoolean","length","push","posterior_prob","contrib_fraction","is_member","e","console","error","Promise","resolve","data","outnames","trans","src","dest","keys","forEach","attr","Adapters","add","Layouts","unnamespaced","html","namespace","closable","show","or","hide","and","id","fill_opacity","tooltip","match","send","receive","color","unshift","field","scale_function","parameters","field_value","then","type","id_field","x_axis","filters","operator","behaviors","onmouseover","action","status","onmouseout","onclick","exclusive","onshiftclick","tooltip_positioning","title","text","x","style","width","height","min_height","proportional_width","margin","top","right","bottom","left","inner_border","toolbar","interaction","drag_background_to_pan","scroll_to_zoom","x_linked","data_layers","widgets","position","button_html","button_title","layer_name","default_config_display_name","options","display_name","display","point_shape","point_size","else","legend","shape","size","label","class","breaks","values","responsive_resize","min_region_scale","max_region_scale","panels","use","gwasCredibleSets"],"mappings":"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","file":"ext/lz-credible-sets.min.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 10);\n","/**\n Custom code used to power credible sets demonstration example. This is not part of the core LocusZoom library,\n but can be included as a standalone file.\n\n The page must incorporate and load all libraries before this file can be used, including:\n - Vendor assets\n - LocusZoom\n - gwas-credible-sets (available via NPM or a related CDN)\n @module\n*/\n\nimport {marking, scoring} from 'gwas-credible-sets';\n\nfunction install (LocusZoom) {\n const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter');\n /**\n * Custom data source that calculates the 95% credible set based on provided data.\n * This source must be requested as the second step in a chain, after a previous step that returns fields required\n * for the calculation.\n *\n * @param {Object} init.params\n * @param {Object} init.params.fields\n * @param {String} init.params.fields.log_pvalue The name of the field containing pvalue information\n * @param {Number} [init.params.threshold=0.95] The credible set threshold (eg 95%)\n *\n */\n class CredibleSetLZ extends BaseAdapter {\n constructor(config) {\n super(...arguments);\n this.dependentSource = true; // Don't do calcs for a region with no assoc data\n }\n\n parseInit(config) {\n super.parseInit(...arguments);\n if (!(this.params.fields && this.params.fields.log_pvalue)) {\n throw new Error(`Source config for ${this.constructor.SOURCE_NAME} must specify how to find 'fields.log_pvalue'`);\n }\n if (!this.params.threshold) {\n this.params.threshold = 0.95;\n }\n }\n\n getCacheKey (state, chain, fields) {\n const threshold = state.credible_set_threshold || this.params.threshold;\n return [threshold, state.chr, state.start, state.end].join('_');\n }\n\n fetchRequest(state, chain) {\n const self = this;\n // The threshold can be overridden dynamically via `plot.state`, or set when the source is created\n const threshold = state.credible_set_threshold || this.params.threshold;\n // Calculate raw bayes factors and posterior probabilities based on information returned from the API\n if (typeof chain.body[0][self.params.fields.log_pvalue] === 'undefined') {\n throw new Error('Credible set source could not locate the required fields from a previous request.');\n }\n const nlogpvals = chain.body.map(function (item) {\n return item[self.params.fields.log_pvalue];\n });\n const credset_data = [];\n try {\n const scores = scoring.bayesFactors(nlogpvals);\n const posteriorProbabilities = scoring.normalizeProbabilities(scores);\n\n // Use scores to mark the credible set in various ways (depending on your visualization preferences,\n // some of these may not be needed)\n const credibleSet = marking.findCredibleSet(scores, threshold);\n const credSetScaled = marking.rescaleCredibleSet(credibleSet);\n const credSetBool = marking.markBoolean(credibleSet);\n\n // Annotate each response record based on credible set membership\n for (let i = 0; i < chain.body.length; i++) {\n credset_data.push({\n posterior_prob: posteriorProbabilities[i],\n contrib_fraction: credSetScaled[i],\n is_member: credSetBool[i],\n });\n }\n } catch (e) {\n // If the calculation cannot be completed, return the data without annotation fields\n console.error(e);\n }\n return Promise.resolve(credset_data);\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n // At this point namespacing has been applied; add the calculated fields for this source to the chain\n for (let i = 0; i < data.length; i++) {\n const src = data[i];\n const dest = chain.body[i];\n Object.keys(src).forEach(function (attr) {\n dest[attr] = src[attr];\n });\n }\n return chain.body;\n }\n }\n\n\n LocusZoom.Adapters.add('CredibleSetLZ', CredibleSetLZ);\n\n // Add related layouts to the central global registry\n LocusZoom.Layouts.add('tooltip', 'association_credible_set', function () {\n // Extend a known tooltip with an extra row of info showing posterior probabilities\n const l = LocusZoom.Layouts.get('tooltip', 'standard_association', { unnamespaced: true });\n l.html += '
Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}';\n return l;\n }());\n\n LocusZoom.Layouts.add('tooltip', 'annotation_credible_set', {\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{{{namespace[assoc]}}variant|htmlescape}}
'\n + 'P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
' +\n '
Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}',\n });\n\n LocusZoom.Layouts.add('data_layer', 'association_credible_set', function () {\n const base = LocusZoom.Layouts.get('data_layer', 'association_pvalues', {\n unnamespaced: true,\n id: 'associationcredibleset',\n namespace: { 'assoc': 'assoc', 'credset': 'credset', 'ld': 'ld' },\n fill_opacity: 0.7,\n tooltip: LocusZoom.Layouts.get('tooltip', 'association_credible_set', { unnamespaced: true }),\n fields: [\n '{{namespace[assoc]}}variant', '{{namespace[assoc]}}position',\n '{{namespace[assoc]}}log_pvalue', '{{namespace[assoc]}}log_pvalue|logtoscinotation',\n '{{namespace[assoc]}}ref_allele',\n '{{namespace[credset]}}posterior_prob', '{{namespace[credset]}}contrib_fraction',\n '{{namespace[credset]}}is_member',\n '{{namespace[ld]}}state', '{{namespace[ld]}}isrefvar',\n ],\n match: { send: '{{namespace[assoc]}}variant', receive: '{{namespace[assoc]}}variant' },\n });\n base.color.unshift({\n field: 'lz_highlight_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#FFf000',\n },\n });\n return base;\n }());\n\n LocusZoom.Layouts.add('data_layer', 'annotation_credible_set', {\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n id: 'annotationcredibleset',\n type: 'annotation_track',\n id_field: '{{namespace[assoc]}}variant',\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n color: [\n {\n field: 'lz_highlight_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#001cee',\n },\n },\n '#00CC00',\n ],\n fields: ['{{namespace[assoc]}}variant', '{{namespace[assoc]}}position', '{{namespace[assoc]}}log_pvalue', '{{namespace[credset]}}posterior_prob', '{{namespace[credset]}}contrib_fraction', '{{namespace[credset]}}is_member'],\n match: { send: '{{namespace[assoc]}}variant', receive: '{{namespace[assoc]}}variant' },\n filters: [\n // Specify which points to show on the track. Any selection must satisfy ALL filters\n { field: '{{namespace[credset]}}is_member', operator: '=', value: true },\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: LocusZoom.Layouts.get('tooltip', 'annotation_credible_set', { unnamespaced: true }),\n tooltip_positioning: 'top',\n });\n\n LocusZoom.Layouts.add('panel', 'annotation_credible_set', {\n id: 'annotationcredibleset',\n title: { text: 'SNPs in 95% credible set', x: 50, style: { 'font-size': '14px' } },\n width: 800,\n height: 45,\n min_height: 45,\n proportional_width: 1,\n margin: { top: 25, right: 50, bottom: 0, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_panel', { unnamespaced: true }),\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n LocusZoom.Layouts.get('data_layer', 'annotation_credible_set', { unnamespaced: true }),\n ],\n });\n\n LocusZoom.Layouts.add('panel', 'association_credible_set', function () {\n const l = LocusZoom.Layouts.get('panel', 'association', {\n unnamespaced: true,\n id: 'associationcrediblesets',\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n data_layers: [\n LocusZoom.Layouts.get('data_layer', 'significance', { unnamespaced: true }),\n LocusZoom.Layouts.get('data_layer', 'recomb_rate', { unnamespaced: true }),\n LocusZoom.Layouts.get('data_layer', 'association_credible_set', { unnamespaced: true }),\n ],\n });\n // Add \"display options\" button to control how credible set coloring is overlaid on the standard association plot\n l.toolbar.widgets.push(\n {\n type: 'display_options',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Display options...',\n button_title: 'Control how plot items are displayed',\n layer_name: 'associationcredibleset',\n default_config_display_name: 'Linkage Disequilibrium (default)', // display name for the default plot color option (allow user to revert to plot defaults)\n\n options: [\n {\n // First dropdown menu item\n display_name: '95% credible set (boolean)', // Human readable representation of field name\n display: { // Specify layout directives that control display of the plot for this option\n point_shape: 'circle',\n point_size: 40,\n color: {\n field: '{{namespace[credset]}}is_member',\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#00CC00',\n else: '#CCCCCC',\n },\n },\n legend: [ // Tells the legend how to represent this display option\n {\n shape: 'circle',\n color: '#00CC00',\n size: 40,\n label: 'In credible set',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#CCCCCC',\n size: 40,\n label: 'Not in credible set',\n class: 'lz-data_layer-scatter',\n },\n ],\n },\n },\n {\n // Second option. The same plot- or even the same field- can be colored in more than one way.\n display_name: '95% credible set (gradient by contribution)',\n display: {\n point_shape: 'circle',\n point_size: 40,\n color: [\n {\n field: '{{namespace[credset]}}contrib_fraction',\n scale_function: 'if',\n parameters: {\n field_value: 0,\n then: '#777777',\n },\n },\n {\n scale_function: 'interpolate',\n field: '{{namespace[credset]}}contrib_fraction',\n parameters: {\n breaks: [0, 1],\n values: ['#fafe87', '#9c0000'],\n },\n },\n ],\n legend: [\n {\n shape: 'circle',\n color: '#777777',\n size: 40,\n label: 'No contribution',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#fafe87',\n size: 40,\n label: 'Some contribution',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#9c0000',\n size: 40,\n label: 'Most contribution',\n class: 'lz-data_layer-scatter',\n },\n ],\n },\n },\n ],\n }\n );\n return l;\n }());\n\n LocusZoom.Layouts.add('plot', 'association_credible_set', {\n state: {},\n width: 800,\n height: 450,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: LocusZoom.Layouts.get('toolbar', 'region_nav_plot', { unnamespaced: true }),\n panels: [\n LocusZoom.Layouts.get('panel', 'association_credible_set', { unnamespaced: true }),\n LocusZoom.Layouts.get('panel', 'annotation_credible_set', { unnamespaced: true }),\n LocusZoom.Layouts.get('panel', 'genes', { unnamespaced: true }),\n ],\n });\n\n}\n\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n","module.exports = gwasCredibleSets;"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/ext/lz-dynamic-urls.min.js b/dist/ext/lz-dynamic-urls.min.js index 658b3118..4f0d1939 100644 --- a/dist/ext/lz-dynamic-urls.min.js +++ b/dist/ext/lz-dynamic-urls.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.12.0-beta.1 */ -var LzDynamicUrls=function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=19)}({19:function(t,e,n){"use strict";function r(t){var e={};if(t)for(var n=("?"===t[0]?t.substr(1):t).split("&"),r=0;r tag mode.\nconst all = {\n paramsFromUrl,\n extractValues: _extractValues,\n plotUpdatesUrl,\n plotWatchesUrl,\n};\n\nexport default all;\nexport { paramsFromUrl, _extractValues as extractValues, plotUpdatesUrl, plotWatchesUrl };\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/./esm/ext/lz-dynamic-urls.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","_parseQueryParams","queryString","query","pairs","substr","split","length","pair","decodeURIComponent","_extractValues","data","mapping","reverse","ret","newMapping","keys","forEach","k","asName","_setStateFromUrlHandler","plot","stateData","applyState","_setUrlFromStateHandler","state","paramsFromUrl","window","location","search","plotWatchesUrl","callback","listener","event","urlData","addEventListener","trackExternalListener","plotUpdatesUrl","eventContext","paramsObj","oldParams","serializedPlotData","newParams","assign","some","map","encodeURIComponent","join","history","pushState","document","title","replaceState","on","all","extractValues"],"mappings":"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","file":"ext/lz-dynamic-urls.min.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 7);\n","/**\n * Optional LocusZoom extension: must be included separately, and after LocusZoom has been loaded\n *\n * This plugin exports helper functions, but does not modify the global registry. It does not require `LocusZoom.use`.\n *\n * Demonstrates a mechanism by which the plot can be loaded to a specific initial state based on the URL query string\n * (and, optionally, to update the URL bar when the plot state changes, with back button support)\n *\n * This makes it possible to create \"direct links\" to a particular plot of interest (and go back to a previous state\n * as the user interacts with the page). Optionally, there is support for custom callbacks to connect the URL to\n * arbitrarily complex plot behaviors.\n * @module\n */\n\nfunction _serializeQueryParams(paramsObj) {\n // Serialize an object of parameter values into a query string\n // TODO: Improve support for array values v[]=1&v[]=2\n return `?${\n Object.keys(paramsObj).map(function(key) {\n return `${encodeURIComponent(key)}=${encodeURIComponent(paramsObj[key])}`;\n }).join('&')}`;\n}\n\nfunction _parseQueryParams(queryString) {\n // Parse a query string into an object of parameter values.\n // Does not attempt any type coercion; all values are, therefore, strings.\n // TODO future: Support arrays / params that specify more than one value\n const query = {};\n if (queryString) {\n const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');\n for (let i = 0; i < pairs.length; i++) {\n const pair = pairs[i].split('=');\n query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');\n }\n }\n return query;\n}\n\n// A useful helper function for serializing values from a provided object\nfunction _extractValues(data, mapping, reverse) {\n // Use the mapping to convert between {stateField: urlParam} (or the reverse). Any fields not referenced in\n // the \"key\" side of the mapping will be omitted from the return value.\n // Likewise, will omit any requested keys that the source side of the mapping has no information for\n reverse = reverse || false;\n\n const ret = {};\n let newMapping = mapping;\n if (reverse) {\n newMapping = {};\n Object.keys(mapping).forEach(function(k) {\n newMapping[mapping[k]] = k;\n });\n }\n\n Object.keys(newMapping).forEach(function(k) {\n const asName = newMapping[k];\n if (Object.prototype.hasOwnProperty.call(data, k)) {\n ret[asName] = data[k];\n }\n\n });\n return ret;\n}\n\nfunction _setStateFromUrlHandler(plot, stateData) {\n // A default way to deal with URL changes: push all the params as state into plot and rerender\n // More complex handlers are possible- example, URL parameters could be used to add or remove data layers\n plot.applyState(stateData);\n}\n\nfunction _setUrlFromStateHandler(plot, mapping) {\n // Serialize and return basic query params based solely on information from plot.state\n // More complex handlers are possible- the serializer can extract any information desired because it is given\n // a direct reference to the plot object\n\n // This default method does not use the eventContext data, because so many things change plot.state without\n // officially triggering an event.\n return _extractValues(plot.state, mapping);\n}\n\n/**\n * Extract plot parameters from the URL query string. Very useful for setting up the plot on initial page load.\n * @param {object} mapping How to map elements of plot state to URL param fields. Hash of\n * {plotFieldName: urlParamName} entries (both values should be unique)\n * @param {string} [queryString='window.location.search'] The query string to parse\n * @returns {object} Plot parameter values\n */\nfunction paramsFromUrl(mapping, queryString) {\n // Internal helper function: second argument only used for unit testing\n queryString = queryString || window.location.search;\n const queryParams = _parseQueryParams(queryString);\n return _extractValues(queryParams, mapping, true);\n}\n\n/**\n * Allows the plot to monitor changes in the URL and take action when the URL changes.\n *\n * For example, this enables using the browser back button to jump to a previous plot after user interaction.\n *\n * @param {Plot} plot A reference to the LZ plot\n * @param {object} mapping How to map elements of plot state to URL param fields. Hash of\n * {plotFieldName: urlParamName} entries (both values should be unique)\n * @param {function} [callback] Specify how the plot acts on information read in from query params.\n * The default behavior is to push the data into `plot.state`\n * Signature is function(plot, plotDataFromQueryString)\n * @returns {function} The function handle for the new listener (allows cleanup if plot is removed later)\n */\nfunction plotWatchesUrl(plot, mapping, callback) {\n callback = callback || _setStateFromUrlHandler;\n\n const listener = function (event) {\n const urlData = paramsFromUrl(mapping);\n // Tell the plot what to do with the params extracted from the URL\n callback(plot, urlData);\n };\n window.addEventListener('popstate', listener);\n plot.trackExternalListener(window, 'popstate', listener);\n return listener;\n}\n\n/**\n * Update the URL whenever the plot state changes\n * @param {Plot} plot A reference to the LZ plot\n * @param {object} mapping How to map elements of plot state to URL param fields. Hash of\n * {plotFieldName: urlParamName} entries (both values should be unique)\n * @param {function} [callback] Specify how plot data will be serialized into query params\n * The default behavior is to extract all the URL params from plot.state as the only source.\n * Signature is function(plot, mapping, eventContext)\n * @returns {function} The function handle for the new listener (allows cleanup if plot is removed later)\n */\nfunction plotUpdatesUrl(plot, mapping, callback) {\n callback = callback || _setUrlFromStateHandler;\n // Note: this event only fires when applyState receives *new* information that would trigger a rerender.\n // Plot state is sometimes changed without the event being fired.\n const listener = function (eventContext) {\n const oldParams = _parseQueryParams(window.location.search);\n // Apply custom serialization to convert plot data to URL params\n const serializedPlotData = callback(plot, mapping, eventContext);\n const newParams = Object.assign({}, oldParams, serializedPlotData);\n\n const update = Object.keys(newParams).some(function (k) {\n // Not every state change would affect the URL. Allow type coercion since query is a string.\n // eslint-disable-next-line eqeqeq\n return (oldParams[k] != newParams[k]);\n });\n if (update) {\n const queryString = _serializeQueryParams(newParams);\n\n if (Object.keys(oldParams).length) {\n history.pushState({}, document.title, queryString);\n } else {\n // Prevent broken back behavior on first page load: the first time query params are set,\n // we don't generate a separate history entry\n history.replaceState({}, document.title, queryString);\n }\n\n }\n };\n plot.on('state_changed', listener);\n return listener;\n}\n\n// Slight build quirk: we use a single webpack file for all modules, but `libraryTarget` expects the entire\n// module to be exported as `default` in - + - + LocusZoom.js ~ Covariates Model Example @@ -35,7 +35,7 @@

LocusZoom.js

Covariates Model Example

-
< return home
+
< return home

diff --git a/examples/covariates_model.png b/examples/misc/covariates_model.png similarity index 100% rename from examples/covariates_model.png rename to examples/misc/covariates_model.png diff --git a/index.html b/index.html index d72ca91d..7f1784c7 100644 --- a/index.html +++ b/index.html @@ -76,7 +76,7 @@

Get LocusZoom.js

CSS
@@ -96,7 +96,7 @@
Dependencies
Javascript
@@ -173,12 +173,6 @@
Chromatin coaccessibility
Chromatin co-accessibility -
Multiple Phenotypes (Layered)
diff --git a/package-lock.json b/package-lock.json index cda8d70d..47f352bb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "locuszoom", - "version": "0.12.0-beta.1", + "version": "0.12.0-beta.3", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -3275,9 +3275,9 @@ "dev": true }, "elliptic": { - "version": "6.5.2", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.2.tgz", - "integrity": "sha512-f4x70okzZbIQl/NSRLkI/+tteV/9WqL98zx+SQ69KbXxmVrmjwsNUPn/gYJJ0sHvEak24cZgHIPegRePAtA/xw==", + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.3.tgz", + "integrity": "sha512-IMqzv5wNQf+E6aHeIqATs0tOLeOTwj1QKbRcS3jBbYkl5oLAserA8yJTT7/VyHUYG91PRmPyeQDObKLPpeS4dw==", "dev": true, "requires": { "bn.js": "^4.4.0", diff --git a/package.json b/package.json index 001b7418..3a81e132 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "locuszoom", - "version": "0.12.0-beta.1", + "version": "0.12.0-beta.3", "main": "dist/locuszoom.app.min.js", "module": "esm/index.js", "sideEffects": true, @@ -23,7 +23,7 @@ "Andy Boughton " ], "engines": { - "node": ">=8.9.0" + "node": ">=10.13.0" }, "repository": { "type": "git", @@ -34,7 +34,7 @@ "test:coverage": "nyc --reporter=text mocha --recursive test/**/*.js", "css": "sass --style compressed ./css/locuszoom.scss ./dist/locuszoom.css", "dev": "npm run css && webpack --watch --config webpack.dev.cjs", - "prod": "npm run css && webpack --config webpack.prod.cjs", + "build": "npm run test && npm run css && webpack --config webpack.prod.cjs", "docs": "jsdoc --recurse --readme ./README.md --destination jsdoc esm/ && pandoc -s --toc --css css/pandoc.css assets/docs/layout_tutorial.md -o docs/layout_tutorial.html" }, "dependencies": { diff --git a/test/unit/components/test_datalayer.js b/test/unit/components/test_datalayer.js index a059e8b1..284a9c2f 100644 --- a/test/unit/components/test_datalayer.js +++ b/test/unit/components/test_datalayer.js @@ -39,21 +39,21 @@ describe('LocusZoom.DataLayer', function () { it('should have a chainable method for moving layers up that stops at the top', function () { assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerB', 'layerC', 'layerD']); - this.plot.panels.panel0.data_layers.layerB.moveUp(); + this.plot.panels.panel0.data_layers.layerB.moveForward(); assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerB', 'layerD']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 2); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 3); - this.plot.panels.panel0.data_layers.layerB.moveUp(); + this.plot.panels.panel0.data_layers.layerB.moveForward(); assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerD', 'layerB']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 3); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 2); - this.plot.panels.panel0.data_layers.layerB.moveUp().moveUp(); + this.plot.panels.panel0.data_layers.layerB.moveForward().moveForward(); assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerD', 'layerB']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 3); @@ -63,21 +63,21 @@ describe('LocusZoom.DataLayer', function () { it('should have a chainable method for moving layers down that stops at the bottom', function () { assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerB', 'layerC', 'layerD']); - this.plot.panels.panel0.data_layers.layerC.moveDown(); + this.plot.panels.panel0.data_layers.layerC.moveBack(); assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerB', 'layerD']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 2); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 3); - this.plot.panels.panel0.data_layers.layerC.moveDown(); + this.plot.panels.panel0.data_layers.layerC.moveBack(); assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerC', 'layerA', 'layerB', 'layerD']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 2); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 3); - this.plot.panels.panel0.data_layers.layerC.moveDown().moveDown(); + this.plot.panels.panel0.data_layers.layerC.moveBack().moveBack(); assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerC', 'layerA', 'layerB', 'layerD']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 2); @@ -420,72 +420,6 @@ describe('LocusZoom.DataLayer', function () { }); }); - describe('Layout mutation helpers (public interface)', function () { - describe('addField', function () { - beforeEach(function () { - this.layer = new BaseDataLayer(); - }); - afterEach(function () { - this.layer = null; - }); - - it('should require field and namespace to be specified', function () { - // TODO: Should there be validation to ensure this is a known namespace? - const self = this; - assert.throws(function () { - self.layer.addField(); - }, /Must specify field name and namespace to use when adding field/); - - assert.throws(function () { - self.layer.addField('afield'); - }, /Must specify field name and namespace to use when adding field/); - }); - - it('should check type of the transformations argument', function () { - const self = this; - assert.ok( - this.layer.addField('aman', 'aplan'), - 'Transformations are optional' - ); - assert.ok( - this.layer.addField('aman', 'aplan', 'acanal'), - 'Transformation can be a string' - ); - assert.ok( - this.layer.addField('aman', 'aplan', ['acanal', 'panama']), - 'Transformation can be an array' - ); - assert.throws(function () { - self.layer.addField('aman', 'aplan', 42); - }, /Must provide transformations as either a string or array of strings/); - }); - it('should construct an appropriate field name and add it to the internal fields array', function () { - const e1 = 'namespace:field'; - assert.equal( - this.layer.addField('field', 'namespace'), - e1 - ); - - const e2 = 'namespace:field|transformation'; - assert.equal( - this.layer.addField('field', 'namespace', 'transformation'), - e2 - ); - - const e3 = 'namespace:field|t1|t2'; - assert.equal( - this.layer.addField('field', 'namespace', ['t1', 't2']), - e3 - ); - - const fields = this.layer.layout.fields; - assert.ok(fields.indexOf(e1) !== -1); - assert.ok(fields.indexOf(e2) !== -1); - assert.ok(fields.indexOf(e3) !== -1); - }); - }); - }); - describe('Highlight functions', function () { beforeEach(function () { this.plot = null; @@ -775,6 +709,123 @@ describe('LocusZoom.DataLayer', function () { }); }); + describe('Filtering operations', function () { + it('can filter numeric data', function () { + const layer = new BaseDataLayer({id_field: 'a'}); + const options = [{ field: 'a', operator: '>', value: 12 }]; + const data = [{ a: 12 }, { a: 11 }, { a: 13 }]; + + const result = data.filter(layer.filter.bind(layer, options)); + assert.equal(result.length, 1); + assert.deepEqual(result, [{ a: 13 }]); + }); + + it('can apply two filters and both must match', function () { + const layer = new BaseDataLayer({id_field: 'a'}); + const options = [{ field: 'a', operator: '>', value: 12 }, { field: 'a', operator: '<=', value: 14 }]; + const data = [{ a: 12 }, { a: 11 }, { a: 13 }, { a: 15 }, { a: 14 }]; + + const result = data.filter(layer.filter.bind(layer, options)); + assert.equal(result.length, 2); + assert.deepEqual(result, [{ a: 13 }, { a: 14 }]); + }); + + it('can filter text data', function () { + const layer = new BaseDataLayer({id_field: 'a'}); + const options = [{ field: 'a', operator: '=', value: 'exact' }]; + const data = [{ a: 'inexact' }, { a: 'exactly' }, { a: 'exact' }]; + + const result = data.filter(layer.filter.bind(layer, options)); + assert.equal(result.length, 1); + assert.deepEqual(result, [{ a: 'exact' }]); + }); + + describe('interaction with data fetching', function () { + beforeEach(function () { + this.plot = null; + const data_sources = new DataSources() + .add('d', ['StaticJSON', [{ id: 1, a: 12 }, { id: 2, a: 11 }, { id: 3, a: 13 }, { id: 4, a: 15 }, { id: 5, a: 14 }]]); + const layout = { + panels: [ + { + id: 'p', + data_layers: [ + { + id: 'd', + fields: ['d:id', 'd:a'], + id_field: 'd:id', + type: 'scatter', + filters: null, + }, + ], + }, + ], + }; + d3.select('body').append('div').attr('id', 'plot'); + this.plot = populate('#plot', data_sources, layout); + }); + + afterEach(function () { + d3.select('#plot').remove(); + delete this.plot; + }); + + it('passes all data when no filters are defined', function () { + const layer = this.plot.panels.p.data_layers.d; + return layer.parent.reMap() + .then(() => assert.equal(layer.data.length, 5)); + }); + + it('passes modified data when layout filters are used', function () { + const filters = [{ field: 'd:a', operator: '>', value: 12 }, { field: 'd:a', operator: '<=', value: 14 }]; + const layer = this.plot.panels.p.data_layers.d; + layer.layout.filters = filters; + + return layer.parent.reMap() // ensures data has been fetched + .then(() => { + const result = layer._applyFilters(); + assert.equal(result.length, 2); + }); + }); + + it('passes modified data when explicit filter function is used', function () { + const layer = this.plot.panels.p.data_layers.d; + layer.setFilter((item) => item['d:a'] === 12); + return layer.parent.reMap() + .then(() => { + const result = layer._applyFilters(); + assert.equal(result.length, 1); + }); + }); + + it('allows explicit filter function to take precedence over layout-defined filters', function () { + const filters = [{ field: 'd:a', operator: '>', value: 12 }, { field: 'd:a', operator: '<=', value: 14 }]; + const layer = this.plot.panels.p.data_layers.d; + layer.layout.filters = filters; + layer.setFilter((item) => item['d:a'] === 12); + return layer.parent.reMap() + .then(() => { + const result = layer._applyFilters(); + assert.equal(result.length, 1); + }); + }); + + it('respects element annotation cache when applying declarative filters to data', function () { + const layer = this.plot.panels.p.data_layers.d; + const filters = [{ field: 'custom_field', operator: '=', value: 'some_value' }]; + const inner_datum = { 'd:id': 1, 'd:a': 12 }; + layer.setElementAnnotation(inner_datum, 'custom_field', 'some_value'); + layer.layout.filters = filters; + return layer.parent.reMap() + .then(() => { + const result = layer._applyFilters(); + assert.equal(result.length, 1); + assert.deepEqual(result[0]['d:a'], 12); + }); + }); + }); + }); + describe('Persistent annotations', function () { beforeEach(function () { this.plot = null; diff --git a/test/unit/components/test_panel.js b/test/unit/components/test_panel.js index fb61b5c4..90f4ad84 100644 --- a/test/unit/components/test_panel.js +++ b/test/unit/components/test_panel.js @@ -454,7 +454,7 @@ describe('Panel', function() { this.plot = populate('#plot', this.datasources, this.layout); return Promise.all(this.plot.remap_promises).then(() => { assert.isDefined(this.plot.panels.p.svg.container.node().__on - .find((item) => item.type === 'mousedown' && item.name === 'zoom')); + .find((item) => item.type === 'wheel' && item.name === 'zoom')); }); }); diff --git a/test/unit/components/test_plot.js b/test/unit/components/test_plot.js index 6d89741e..b5620d1d 100644 --- a/test/unit/components/test_plot.js +++ b/test/unit/components/test_plot.js @@ -552,7 +552,7 @@ describe('LocusZoom.Plot', function() { }); describe('fires off various events in response to actions', function () { - describe('region_changed event describes exact region change', function () { + it('region_changed event describes exact region change', function () { d3.select('body').append('div').attr('id', 'plot'); const layout = { panels: [{ id: 'panel0' }], @@ -569,11 +569,11 @@ describe('LocusZoom.Plot', function() { plot.on('region_changed', region_spy); return plot.applyState(requested_state).then(function() { - assert(state_spy.called); - assert(state_spy.calledWith(requested_state)); + assert.ok(state_spy.called); + assert.ok(state_spy.calledWith({sourceID: 'plot', data: requested_state})); - assert(region_spy.called); - assert(region_spy.calledWith(expected_state)); + assert.ok(region_spy.called); + assert.ok(region_spy.calledWith({sourceID: 'plot', data: expected_state})); }); }); diff --git a/test/unit/components/test_dashboard.js b/test/unit/components/test_toolbar.js similarity index 69% rename from test/unit/components/test_dashboard.js rename to test/unit/components/test_toolbar.js index 55fd83c5..86877eab 100644 --- a/test/unit/components/test_dashboard.js +++ b/test/unit/components/test_toolbar.js @@ -111,65 +111,4 @@ describe('LocusZoom.Toolbar', function() { assert.equal(d3.select('#plot\\.toolbar').empty(), false); }); }); - - describe('Dimensions Widget', function() { - beforeEach(function() { - var datasources = new DataSources(); - var layout = { - toolbar: { - widgets: [ - { type: 'dimensions' }, - ], - }, - panels: [ - { id: 'test', width: 100, height: 100 }, - ], - }; - d3.select('body').append('div').attr('id', 'plot'); - this.plot = populate('#plot', datasources, layout); - }); - afterEach(function() { - d3.select('#plot').remove(); - this.plot = null; - }); - it('Should show initial plot dimensions', function() { - assert.equal(this.plot.toolbar.widgets[0].selector.html(), '100px × 100px'); - }); - it('Should show updated plot dimensions automatically as dimensions change', function() { - this.plot.setDimensions(220, 330); - assert.equal(this.plot.toolbar.widgets[0].selector.html(), '220px × 330px'); - }); - }); - - describe('Region Scale Widget', function() { - beforeEach(function() { - var datasources = new DataSources(); - var layout = { - state: { - chr: 1, - start: 126547453, - end: 126847453, - }, - toolbar: { - widgets: [ - { type: 'region_scale' }, - ], - }, - }; - d3.select('body').append('div').attr('id', 'plot'); - this.plot = populate('#plot', datasources, layout); - }); - afterEach(function() { - d3.select('#plot').remove(); - this.plot = null; - }); - it('Should show initial region scale from state', function() { - assert.equal(this.plot.toolbar.widgets[0].selector.html(), '300.00 Kb'); - }); - it('Should show updated region scale from state as state region boundaries change', function() { - return this.plot.applyState({ chr: 1, start: 126547453, end: 126947453 }).then(() => { - assert.equal(this.plot.toolbar.widgets[0].selector.html(), '400.00 Kb'); - }); - }); - }); }); diff --git a/test/unit/components/test_widgets.js b/test/unit/components/test_widgets.js new file mode 100644 index 00000000..00dfb048 --- /dev/null +++ b/test/unit/components/test_widgets.js @@ -0,0 +1,173 @@ +import DataSources from '../../../esm/data'; +import * as d3 from 'd3'; +import {populate} from '../../../esm/helpers/display'; +import {assert} from 'chai'; + + +describe('Toolbar widgets', function () { + describe('Dimensions Widget', function() { + beforeEach(function() { + var datasources = new DataSources(); + var layout = { + toolbar: { + widgets: [ + { type: 'dimensions' }, + ], + }, + panels: [ + { id: 'test', width: 100, height: 100 }, + ], + }; + d3.select('body').append('div').attr('id', 'plot'); + this.plot = populate('#plot', datasources, layout); + }); + afterEach(function() { + d3.select('#plot').remove(); + this.plot = null; + }); + it('Should show initial plot dimensions', function() { + assert.equal(this.plot.toolbar.widgets[0].selector.html(), '100px × 100px'); + }); + it('Should show updated plot dimensions automatically as dimensions change', function() { + this.plot.setDimensions(220, 330); + assert.equal(this.plot.toolbar.widgets[0].selector.html(), '220px × 330px'); + }); + }); + + describe('Region Scale Widget', function() { + beforeEach(function() { + var datasources = new DataSources(); + var layout = { + state: { + chr: 1, + start: 126547453, + end: 126847453, + }, + toolbar: { + widgets: [ + { type: 'region_scale' }, + ], + }, + }; + d3.select('body').append('div').attr('id', 'plot'); + this.plot = populate('#plot', datasources, layout); + }); + afterEach(function() { + d3.select('#plot').remove(); + this.plot = null; + }); + it('Should show initial region scale from state', function() { + assert.equal(this.plot.toolbar.widgets[0].selector.html(), '300.00 Kb'); + }); + it('Should show updated region scale from state as state region boundaries change', function() { + return this.plot.applyState({ chr: 1, start: 126547453, end: 126947453 }).then(() => { + assert.equal(this.plot.toolbar.widgets[0].selector.html(), '400.00 Kb'); + }); + }); + }); + + describe('Filter fields Widget', function () { + beforeEach(function() { + const datasources = new DataSources() + .add('d', ['StaticJSON', [{ id: 1, a: 12 }]]); + const layout = { + panels: [{ + id: 'p', + toolbar: { + widgets: [ + { + type: 'filter_field', + position: 'right', + layer_name: 'd', + field: 'd:a', + field_display_html: 'Some Name', + operator: '!=', + data_type: 'number', + }, + ], + }, + data_layers: [ + { + id: 'd', + fields: ['d:id', 'd:a'], + id_field: 'd:id', + type: 'scatter', + }, + ], + }], + }; + d3.select('body').append('div').attr('id', 'plot'); + this.plot = populate('#plot', datasources, layout); + this.data_layer = this.plot.panels['p'].data_layers['d']; + this.widget = this.data_layer.parent.toolbar.widgets[0]; + }); + afterEach(function() { + d3.select('#plot').remove(); + this.plot = null; + }); + + it('creates a filter if none is present in config', function() { + assert.equal(this.data_layer.layout.filters, null, 'No filters at start'); + + const target = this.widget._getTarget(); + assert.deepEqual(target, {field: 'd:a', operator: '!=', value: null}, 'Auto-create blank filter'); + }); + + it('updates an existing filter if already present', function() { + this.data_layer.layout.filters = [{field: 'd:a', operator: '!=', value: 1}]; + + this.widget._setFilter(5); + const target = this.widget._getTarget(); + assert.equal(this.data_layer.layout.filters.length, 1, 'No second filter created'); + assert.deepEqual(target, {field: 'd:a', operator: '!=', value: 5}, 'Updates filter with new value'); + }); + + it('finds a specific filter (by id field) when more than one with same operation is used', function() { + this.widget._filter_id = 'target'; + this.data_layer.layout.filters = [ + {field: 'd:a', operator: '!=', value: null}, + {field: 'd:a', operator: '!=', value: 'squid', id: 'target'}, + {field: 'd:a', operator: '!=', value: 'cephalopod', id: 'detroit'}, + ]; + + this.widget._setFilter('al'); + // assert.equal(this.data_layer.layout.filters.length, 3, '3 filters at end'); + assert.deepEqual( + this.data_layer.layout.filters, + [ + {field: 'd:a', operator: '!=', value: null}, + {field: 'd:a', operator: '!=', value: 'al', id: 'target'}, + {field: 'd:a', operator: '!=', value: 'cephalopod', id: 'detroit'}, + ], 'Updates filter with new value'); + }); + + it('validates values and coerces types', function() { + const scenarios = [ + ['0', 0], + ['', null], + ['notanumber', null], + ]; + // This test requires the widget actually be rendered + this.widget.parent.show(); + this.widget.update(); + scenarios.forEach(([input, output]) => { + this.widget._value_selector.property('value', input); + assert.equal( + this.widget._getValue(), + output, + `Number conversion should convert input ${input} to output ${output}` + ); + }); + }); + + it('clears the filter if no valid option is provided', function() { + this.widget.parent.show(); + this.widget.update(); + this.widget._setFilter(12); + assert.equal(this.data_layer.layout.filters.length, 1, 'Filter has been created'); + + this.widget._setFilter(null); + assert.equal(this.data_layer.layout.filters.length, 0, 'Filter has been removed'); + }); + }); +}); diff --git a/test/unit/data/test_adapters.js b/test/unit/data/test_adapters.js index ed225eda..8ee2dc21 100644 --- a/test/unit/data/test_adapters.js +++ b/test/unit/data/test_adapters.js @@ -501,6 +501,30 @@ describe('Data adapters', function () { ); assert.ok(request_url.includes(encodeURIComponent(ldserver_format))); }); + + it('chooses best 1000G panel for the given build', function () { + const source37 = new LDServer({ url: 'www.fake.test', params: { source: '1000G', build: 'GRCh37' } }); + let request_url = source37.getURL({ ldrefvar: '1:2_A/B' }, { + header: {}, + body: [], + }, ['isrefvar', 'state']); + assert.equal( + request_url, + 'www.fake.testgenome_builds/GRCh37/references/1000G/populations/ALL/variants?correlation=rsquare&variant=1%3A2_A%2FB&chrom=undefined&start=undefined&stop=undefined', + 'Build 37 uses 1000G panel (old)' + ); + + const source38 = new LDServer({ url: 'www.fake.test', params: { source: '1000G', build: 'GRCh38' } }); + request_url = source38.getURL({ ldrefvar: '1:2_A/B' }, { + header: {}, + body: [], + }, ['isrefvar', 'state']); + assert.equal( + request_url, + 'www.fake.testgenome_builds/GRCh38/references/1000G-FRZ09/populations/ALL/variants?correlation=rsquare&variant=1%3A2_A%2FB&chrom=undefined&start=undefined&stop=undefined', + 'Build 38 uses 1000G panel (upgraded)' + ); + }); }); describe('Static Data Source', function () { diff --git a/test/unit/test_registry.js b/test/unit/test_registry.js index fbee88fe..0bcc9f6c 100644 --- a/test/unit/test_registry.js +++ b/test/unit/test_registry.js @@ -60,6 +60,37 @@ describe('Registries', function() { const instance = registry.create('fake', 12); assert.equal(instance.a, 12); }); + + it('.extend shortcut for quasi-subclassing', function () { + const registry = new ClassRegistry(); + const fake = class { + constructor(a) { + this.a = a; + } + + b() { + return this.a + 1; + } + }; + registry.add('fake', fake); + + const NewChild = registry.extend( + 'fake', + 'new_child', + { + b() { + return this.a + 2; + }, + c() { + return this.a * 2; + }, + }); + const child = new NewChild(12); + assert.equal(child.a, 12, 'Inherits constructor'); + assert.equal(child.b(), 14, 'Subclass overrides parent method'); + assert.equal(child.c(), 24, 'Subclass adds its own methods'); + assert.ok(registry.get('new_child')); + }); }); describe('Transformation registry special behaviors', function() {