diff --git a/igv.min.js b/igv.min.js index 49b8fa4..440d1fb 100644 --- a/igv.min.js +++ b/igv.min.js @@ -61,7 +61,7 @@ function(e){var t,i,n,r,s,o,a,A,c,l,h,d,u,f,p,g,w,m,F,b="sizzle"+1*new Date,v=e. * * Copyright 2017-2021 Andreas Borgen (https://github.com/Sphinxxxx), Adam Brooks (https://github.com/dissimulate) * Released under the ISC license. - */var eF=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},tF=function(){function e(e,t){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:1;return(t>0?e.toFixed(t).replace(/0+$/,"").replace(/\.$/,""):e.toString())||"0"}var sF=function(){function e(t,i,n,r){eF(this,e);var s=this;if(void 0===t);else if(Array.isArray(t))this.rgba=t;else if(void 0===n){var o=t&&""+t;o&&function(t){if(t.startsWith("hsl")){var i=t.match(/([\-\d\.e]+)/g).map(Number),n=iF(i,4),r=n[0],o=n[1],a=n[2],A=n[3];void 0===A&&(A=1),r/=360,o/=100,a/=100,s.hsla=[r,o,a,A]}else if(t.startsWith("rgb")){var c=t.match(/([\-\d\.e]+)/g).map(Number),l=iF(c,4),h=l[0],d=l[1],u=l[2],f=l[3];void 0===f&&(f=1),s.rgba=[h,d,u,f]}else t.startsWith("#")?s.rgba=e.hexToRgb(t):s.rgba=e.nameToRgb(t)||e.hexToRgb(t)}(o.toLowerCase())}else this.rgba=[t,i,n,void 0===r?1:r]}return tF(e,[{key:"printRGB",value:function(e){var t=(e?this.rgba:this.rgba.slice(0,3)).map((function(e,t){return rF(e,3===t?3:0)}));return e?"rgba("+t+")":"rgb("+t+")"}},{key:"printHSL",value:function(e){var t=[360,100,100,1],i=["","%","%",""],n=(e?this.hsla:this.hsla.slice(0,3)).map((function(e,n){return rF(e*t[n],3===n?3:1)+i[n]}));return e?"hsla("+n+")":"hsl("+n+")"}},{key:"printHex",value:function(e){var t=this.hex;return e?t:t.substring(0,7)}},{key:"rgba",get:function(){if(this._rgba)return this._rgba;if(!this._hsla)throw new Error("No color is set");return this._rgba=e.hslToRgb(this._hsla)},set:function(e){3===e.length&&(e[3]=1),this._rgba=e,this._hsla=null}},{key:"rgbString",get:function(){return this.printRGB()}},{key:"rgbaString",get:function(){return this.printRGB(!0)}},{key:"hsla",get:function(){if(this._hsla)return this._hsla;if(!this._rgba)throw new Error("No color is set");return this._hsla=e.rgbToHsl(this._rgba)},set:function(e){3===e.length&&(e[3]=1),this._hsla=e,this._rgba=null}},{key:"hslString",get:function(){return this.printHSL()}},{key:"hslaString",get:function(){return this.printHSL(!0)}},{key:"hex",get:function(){var e=this.rgba.map((function(e,t){return t<3?e.toString(16):Math.round(255*e).toString(16)}));return"#"+e.map((function(e){return e.padStart(2,"0")})).join("")},set:function(t){this.rgba=e.hexToRgb(t)}}],[{key:"hexToRgb",value:function(e){var t=(e.startsWith("#")?e.slice(1):e).replace(/^(\w{3})$/,"$1F").replace(/^(\w)(\w)(\w)(\w)$/,"$1$1$2$2$3$3$4$4").replace(/^(\w{6})$/,"$1FF");if(!t.match(/^([0-9a-fA-F]{8})$/))throw new Error("Unknown hex color; "+e);var i=t.match(/^(\w\w)(\w\w)(\w\w)(\w\w)$/).slice(1).map((function(e){return parseInt(e,16)}));return i[3]=i[3]/255,i}},{key:"nameToRgb",value:function(t){var i=t.toLowerCase().replace("at","T").replace(/[aeiouyldf]/g,"").replace("ght","L").replace("rk","D").slice(-5,4),n=nF[i];return void 0===n?n:e.hexToRgb(n.replace(/\-/g,"00").padStart(6,"f"))}},{key:"rgbToHsl",value:function(e){var t=iF(e,4),i=t[0],n=t[1],r=t[2],s=t[3];i/=255,n/=255,r/=255;var o=Math.max(i,n,r),a=Math.min(i,n,r),A=void 0,c=void 0,l=(o+a)/2;if(o===a)A=c=0;else{var h=o-a;switch(c=l>.5?h/(2-o-a):h/(o+a),o){case i:A=(n-r)/h+(n1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e},l=r<.5?r*(1+n):r+n-r*n,h=2*r-l;o=c(h,l,i+1/3),a=c(h,l,i),A=c(h,l,i-1/3)}var d=[255*o,255*a,255*A].map(Math.round);return d[3]=s,d}}]),e}(),oF=function(){function e(){eF(this,e),this._events=[]}return tF(e,[{key:"add",value:function(e,t,i){e.addEventListener(t,i,!1),this._events.push({target:e,type:t,handler:i})}},{key:"remove",value:function(t,i,n){this._events=this._events.filter((function(r){var s=!0;return t&&t!==r.target&&(s=!1),i&&i!==r.type&&(s=!1),n&&n!==r.handler&&(s=!1),s&&e._doRemove(r.target,r.type,r.handler),!s}))}},{key:"destroy",value:function(){this._events.forEach((function(t){return e._doRemove(t.target,t.type,t.handler)})),this._events=[]}}],[{key:"_doRemove",value:function(e,t,i){e.removeEventListener(t,i,!1)}}]),e}();function aF(e,t,i){var n=!1;function r(e,t,i){return Math.max(t,Math.min(e,i))}function s(e,s,o){if(o&&(n=!0),n){e.preventDefault();var a=t.getBoundingClientRect(),A=a.width,c=a.height,l=s.clientX,h=s.clientY,d=r(l-a.left,0,A),u=r(h-a.top,0,c);i(d/A,u/c)}}function o(e,t){1===(void 0===e.buttons?e.which:e.buttons)?s(e,e,t):n=!1}function a(e,t){1===e.touches.length?s(e,e.touches[0],t):n=!1}e.add(t,"mousedown",(function(e){o(e,!0)})),e.add(t,"touchstart",(function(e){a(e,!0)})),e.add(window,"mousemove",o),e.add(t,"touchmove",a),e.add(window,"mouseup",(function(e){n=!1})),e.add(t,"touchend",(function(e){n=!1})),e.add(t,"touchcancel",(function(e){n=!1}))}var AF="keydown",cF="mousedown",lF="focusin";function hF(e,t){return(t||document).querySelector(e)}function dF(e){e.preventDefault(),e.stopPropagation()}function uF(e,t,i,n,r){e.add(t,AF,(function(e){i.indexOf(e.key)>=0&&(r&&dF(e),n(e))}))}var fF=function(){function e(t){eF(this,e),this.settings={popup:"right",layout:"default",alpha:!0,editor:!0,editorFormat:"hex",cancelButton:!1,defaultColor:"#0cf"},this._events=new oF,this.onChange=null,this.onDone=null,this.onOpen=null,this.onClose=null,this.setOptions(t)}return tF(e,[{key:"setOptions",value:function(e){var t=this;if(e){var i=this.settings;if(e instanceof HTMLElement)i.parent=e;else{i.parent&&e.parent&&i.parent!==e.parent&&(this._events.remove(i.parent),this._popupInited=!1),function(e,t,i){for(var n in e)i&&i.indexOf(n)>=0||(t[n]=e[n])}(e,i),e.onChange&&(this.onChange=e.onChange),e.onDone&&(this.onDone=e.onDone),e.onOpen&&(this.onOpen=e.onOpen),e.onClose&&(this.onClose=e.onClose);var n=e.color||e.colour;n&&this._setColor(n)}var r=i.parent;if(r&&i.popup&&!this._popupInited){var s=function(e){return t.openHandler(e)};this._events.add(r,"click",s),uF(this._events,r,[" ","Spacebar","Enter"],s),this._popupInited=!0}else e.parent&&!i.popup&&this.show()}}},{key:"openHandler",value:function(e){if(this.show()){e&&e.preventDefault(),this.settings.parent.style.pointerEvents="none";var t=e&&e.type===AF?this._domEdit:this.domElement;setTimeout((function(){return t.focus()}),100),this.onOpen&&this.onOpen(this.colour)}}},{key:"closeHandler",value:function(e){var t=e&&e.type,i=!1;if(e)if(t===cF||t===lF){var n=(this.__containedEvent||0)+100;e.timeStamp>n&&(i=!0)}else dF(e),i=!0;else i=!0;i&&this.hide()&&(this.settings.parent.style.pointerEvents="",t!==cF&&this.settings.parent.focus(),this.onClose&&this.onClose(this.colour))}},{key:"movePopup",value:function(e,t){this.closeHandler(),this.setOptions(e),t&&this.openHandler()}},{key:"setColor",value:function(e,t){this._setColor(e,{silent:t})}},{key:"_setColor",value:function(e,t){if("string"==typeof e&&(e=e.trim()),e){t=t||{};var i=void 0;try{i=new sF(e)}catch(e){if(t.failSilently)return;throw e}if(!this.settings.alpha){var n=i.hsla;n[3]=1,i.hsla=n}this.colour=this.color=i,this._setHSLA(null,null,null,null,t)}}},{key:"setColour",value:function(e,t){this.setColor(e,t)}},{key:"show",value:function(){if(!this.settings.parent)return!1;if(this.domElement){var e=this._toggleDOM(!0);return this._setPosition(),e}var t=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstElementChild}(this.settings.template||'
');return this.domElement=t,this._domH=hF(".picker_hue",t),this._domSL=hF(".picker_sl",t),this._domA=hF(".picker_alpha",t),this._domEdit=hF(".picker_editor input",t),this._domSample=hF(".picker_sample",t),this._domOkay=hF(".picker_done button",t),this._domCancel=hF(".picker_cancel button",t),t.classList.add("layout_"+this.settings.layout),this.settings.alpha||t.classList.add("no_alpha"),this.settings.editor||t.classList.add("no_editor"),this.settings.cancelButton||t.classList.add("no_cancel"),this._ifPopup((function(){return t.classList.add("popup")})),this._setPosition(),this.colour?this._updateUI():this._setColor(this.settings.defaultColor),this._bindEvents(),!0}},{key:"hide",value:function(){return this._toggleDOM(!1)}},{key:"destroy",value:function(){this._events.destroy(),this.domElement&&this.settings.parent.removeChild(this.domElement)}},{key:"_bindEvents",value:function(){var e=this,t=this,i=this.domElement,n=this._events;function r(e,t,i){n.add(e,t,i)}r(i,"click",(function(e){return e.preventDefault()})),aF(n,this._domH,(function(e,i){return t._setHSLA(e)})),aF(n,this._domSL,(function(e,i){return t._setHSLA(null,e,1-i)})),this.settings.alpha&&aF(n,this._domA,(function(e,i){return t._setHSLA(null,null,null,1-i)}));var s=this._domEdit;r(s,"input",(function(e){t._setColor(this.value,{fromEditor:!0,failSilently:!0})})),r(s,"focus",(function(e){var t=this;t.selectionStart===t.selectionEnd&&t.select()})),this._ifPopup((function(){var t=function(t){return e.closeHandler(t)};r(window,cF,t),r(window,lF,t),uF(n,i,["Esc","Escape"],t);var s=function(t){e.__containedEvent=t.timeStamp};r(i,cF,s),r(i,lF,s),r(e._domCancel,"click",t)}));var o=function(t){e._ifPopup((function(){return e.closeHandler(t)})),e.onDone&&e.onDone(e.colour)};r(this._domOkay,"click",o),uF(n,i,["Enter"],o)}},{key:"_setPosition",value:function(){var e=this.settings.parent,t=this.domElement;e!==t.parentNode&&e.appendChild(t),this._ifPopup((function(i){"static"===getComputedStyle(e).position&&(e.style.position="relative");var n=!0===i?"popup_right":"popup_"+i;["popup_top","popup_bottom","popup_left","popup_right"].forEach((function(e){e===n?t.classList.add(e):t.classList.remove(e)})),t.classList.add(n)}))}},{key:"_setHSLA",value:function(e,t,i,n,r){r=r||{};var s=this.colour,o=s.hsla;[e,t,i,n].forEach((function(e,t){(e||0===e)&&(o[t]=e)})),s.hsla=o,this._updateUI(r),this.onChange&&!r.silent&&this.onChange(s)}},{key:"_updateUI",value:function(e){if(this.domElement){e=e||{};var t=this.colour,i=t.hsla,n="hsl("+360*i[0]+", 100%, 50%)",r=t.hslString,s=t.hslaString,o=this._domH,a=this._domSL,A=this._domA,c=hF(".picker_selector",o),l=hF(".picker_selector",a),h=hF(".picker_selector",A);m(0,c,i[0]),this._domSL.style.backgroundColor=this._domH.style.color=n,m(0,l,i[1]),F(0,l,1-i[2]),a.style.color=r,F(0,h,1-i[3]);var d=r,u=d.replace("hsl","hsla").replace(")",", 0)"),f="linear-gradient("+[d,u]+")";if(this._domA.style.background=f+", linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0 / 2em 2em,\n linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em / 2em 2em",!e.fromEditor){var p=this.settings.editorFormat,g=this.settings.alpha,w=void 0;switch(p){case"rgb":w=t.printRGB(g);break;case"hsl":w=t.printHSL(g);break;default:w=t.printHex(g)}this._domEdit.value=w}this._domSample.style.color=s}function m(e,t,i){t.style.left=100*i+"%"}function F(e,t,i){t.style.top=100*i+"%"}}},{key:"_ifPopup",value:function(e,t){this.settings.parent&&this.settings.popup?e&&e(this.settings.popup):t&&t()}},{key:"_toggleDOM",value:function(e){var t=this.domElement;if(!t)return!1;var i=e?"":"none",n=t.style.display!==i;return n&&(t.style.display=i),n}}]),e}(),pF=document.createElement("style");function gF(e){if(wF[e])return wF[e];if(wF["chr"+e]){const t=wF["chr"+e];return wF[e]=t,t}{const r=(t=Math.round(255*Math.random()).toString(10),i=Math.round(255*Math.random()).toString(10),n=Math.round(255*Math.random()).toString(10),"rgb("+t+","+i+","+n+")");return wF[e]=r,r}var t,i,n}pF.textContent='.picker_wrapper.no_alpha .picker_alpha{display:none}.picker_wrapper.no_editor .picker_editor{position:absolute;z-index:-1;opacity:0}.picker_wrapper.no_cancel .picker_cancel{display:none}.layout_default.picker_wrapper{display:flex;flex-flow:row wrap;justify-content:space-between;align-items:stretch;font-size:10px;width:25em;padding:.5em}.layout_default.picker_wrapper input,.layout_default.picker_wrapper button{font-size:1rem}.layout_default.picker_wrapper>*{margin:.5em}.layout_default.picker_wrapper::before{content:"";display:block;width:100%;height:0;order:1}.layout_default .picker_slider,.layout_default .picker_selector{padding:1em}.layout_default .picker_hue{width:100%}.layout_default .picker_sl{flex:1 1 auto}.layout_default .picker_sl::before{content:"";display:block;padding-bottom:100%}.layout_default .picker_editor{order:1;width:6.5rem}.layout_default .picker_editor input{width:100%;height:100%}.layout_default .picker_sample{order:1;flex:1 1 auto}.layout_default .picker_done,.layout_default .picker_cancel{order:1}.picker_wrapper{box-sizing:border-box;background:#f2f2f2;box-shadow:0 0 0 1px silver;cursor:default;font-family:sans-serif;color:#444;pointer-events:auto}.picker_wrapper:focus{outline:none}.picker_wrapper button,.picker_wrapper input{box-sizing:border-box;border:none;box-shadow:0 0 0 1px silver;outline:none}.picker_wrapper button:focus,.picker_wrapper button:active,.picker_wrapper input:focus,.picker_wrapper input:active{box-shadow:0 0 2px 1px #1e90ff}.picker_wrapper button{padding:.4em .6em;cursor:pointer;background-color:#f5f5f5;background-image:linear-gradient(0deg, gainsboro, transparent)}.picker_wrapper button:active{background-image:linear-gradient(0deg, transparent, gainsboro)}.picker_wrapper button:hover{background-color:#fff}.picker_selector{position:absolute;z-index:1;display:block;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);border:2px solid #fff;border-radius:100%;box-shadow:0 0 3px 1px #67b9ff;background:currentColor;cursor:pointer}.picker_slider .picker_selector{border-radius:2px}.picker_hue{position:relative;background-image:linear-gradient(90deg, red, yellow, lime, cyan, blue, magenta, red);box-shadow:0 0 0 1px silver}.picker_sl{position:relative;box-shadow:0 0 0 1px silver;background-image:linear-gradient(180deg, white, rgba(255, 255, 255, 0) 50%),linear-gradient(0deg, black, rgba(0, 0, 0, 0) 50%),linear-gradient(90deg, #808080, rgba(128, 128, 128, 0))}.picker_alpha,.picker_sample{position:relative;background:linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0/2em 2em,linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em/2em 2em;box-shadow:0 0 0 1px silver}.picker_alpha .picker_selector,.picker_sample .picker_selector{background:none}.picker_editor input{font-family:monospace;padding:.2em .4em}.picker_sample::before{content:"";position:absolute;display:block;width:100%;height:100%;background:currentColor}.picker_arrow{position:absolute;z-index:-1}.picker_wrapper.popup{position:absolute;z-index:2;margin:1.5em}.picker_wrapper.popup,.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{background:#f2f2f2;box-shadow:0 0 10px 1px rgba(0,0,0,.4)}.picker_wrapper.popup .picker_arrow{width:3em;height:3em;margin:0}.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{content:"";display:block;position:absolute;top:0;left:0;z-index:-99}.picker_wrapper.popup .picker_arrow::before{width:100%;height:100%;-webkit-transform:skew(45deg);transform:skew(45deg);-webkit-transform-origin:0 100%;transform-origin:0 100%}.picker_wrapper.popup .picker_arrow::after{width:150%;height:150%;box-shadow:none}.popup.popup_top{bottom:100%;left:0}.popup.popup_top .picker_arrow{bottom:0;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.popup.popup_bottom{top:100%;left:0}.popup.popup_bottom .picker_arrow{top:0;left:0;-webkit-transform:rotate(90deg) scale(1, -1);transform:rotate(90deg) scale(1, -1)}.popup.popup_left{top:0;right:100%}.popup.popup_left .picker_arrow{top:0;right:0;-webkit-transform:scale(-1, 1);transform:scale(-1, 1)}.popup.popup_right{top:0;left:100%}.popup.popup_right .picker_arrow{top:0;left:0}',document.documentElement.firstElementChild.appendChild(pF),fF.StyleElement=pF;const wF={chrX:"rgb(204, 153, 0)",chrY:"rgb(153, 204, 0",chrUn:"rgb(50, 50, 50)",chr1:"rgb(80, 80, 255)",chrI:"rgb(139, 155, 187)",chr2:"rgb(206, 61, 50)",chrII:"rgb(206, 61, 50)",chr2a:"rgb(216, 71, 60)",chr2b:"rgb(226, 81, 70)",chr3:"rgb(116, 155, 88)",chrIII:"rgb(116, 155, 88)",chr4:"rgb(240, 230, 133)",chrIV:"rgb(240, 230, 133)",chr5:"rgb(70, 105, 131)",chr6:"rgb(186, 99, 56)",chr7:"rgb(93, 177, 221)",chr8:"rgb(128, 34, 104)",chr9:"rgb(107, 215, 107)",chr10:"rgb(213, 149, 167)",chr11:"rgb(146, 72, 34)",chr12:"rgb(131, 123, 141)",chr13:"rgb(199, 81, 39)",chr14:"rgb(213, 143, 92)",chr15:"rgb(122, 101, 165)",chr16:"rgb(228, 175, 105)",chr17:"rgb(59, 27, 83)",chr18:"rgb(205, 222, 183)",chr19:"rgb(97, 42, 121)",chr20:"rgb(174, 31, 99)",chr21:"rgb(231, 199, 111)",chr22:"rgb(90, 101, 94)",chr23:"rgb(204, 153, 0)",chr24:"rgb(153, 204, 0)",chr25:"rgb(51, 204, 0)",chr26:"rgb(0, 204, 51)",chr27:"rgb(0, 204, 153)",chr28:"rgb(0, 153, 204)",chr29:"rgb(10, 71, 255)",chr30:"rgb(71, 117, 255)",chr31:"rgb(255, 194, 10)",chr32:"rgb(255, 209, 71)",chr33:"rgb(153, 0, 51)",chr34:"rgb(153, 26, 0)",chr35:"rgb(153, 102, 0)",chr36:"rgb(128, 153, 0)",chr37:"rgb(51, 153, 0)",chr38:"rgb(0, 153, 26)",chr39:"rgb(0, 153, 102)",chr40:"rgb(0, 128, 153)",chr41:"rgb(0, 51, 153)",chr42:"rgb(26, 0, 153)",chr43:"rgb(102, 0, 153)",chr44:"rgb(153, 0, 128)",chr45:"rgb(214, 0, 71)",chr46:"rgb(255, 20, 99)",chr47:"rgb(0, 214, 143)",chr48:"rgb(20, 255, 177)"};class mF{constructor(e){this.tracks=[],this.chordSets=[]}addChordSet(e){this.chordSets=this.chordSets.filter((t=>t.name!==e.name)),this.chordSets.push(e);let t=this.tracks.find((t=>e.trackName===t.name));t&&(t.chordSets=t.chordSets.filter((t=>t.name!==e.name)),t.chordSets.push(e)),t||(t=new FF(e),this.tracks.push(t))}clearChords(){this.tracks=[],this.chordSets=[]}getTrack(e){return this.tracks.find((t=>e===t.name))}getChordSet(e){return this.chordSets.find((t=>e===t.name))}}class FF{constructor(e){this.name=e.trackName,this.color=e.trackColor,this.visible=!0,this.chordSets=[e],this.id=("0000"+(Math.random()*Math.pow(36,4)<<0).toString(36)).slice(-4)}get chords(){if(1===this.chordSets.length)return this.chordSets[0].chords;const e=[];for(let t of this.chordSets)for(let i of t.chords)e.push(i);return e}}const bF=Math.exp(5);class vF{static isInstalled(){return void 0!==window.JBrowseReactCircularGenomeView&&void 0!==window.React&&void 0!==window.ReactDOM}constructor(e,t){if(t=t||{},this.config=t,vF.isInstalled()){this.parent=e,this.groupByTrack=!0===t.groupByTrack,this.chordManager=new mF(t);const i=document.createElement("div");i.className="igv-circview-container",e.appendChild(i),this.createControls(i),this.resetControlPanel();const n=document.createElement("div");n.className="igv-circview-circular-genome-view",i.appendChild(n),this.container=n,t.assembly&&this.setAssembly(t.assembly),this.width=t.width||500,this.height=t.height||500,this.setSize(this.width,this.height)}else console.error("JBrowse circular view is not installed")}createControls(e){const t=document.createElement("div");t.className="igv-circview-toolbar",e.appendChild(t),this.toolbar=t;const i=document.createElement("div");i.className="igv-circview-track-panel",e.appendChild(i),this.controlPanel=i,this.controlPanel.style.display="none";const n=document.createElement("div");n.className="igv-circview-toolbar-button-container",this.toolbar.appendChild(n),this.showControlsButton=document.createElement("div"),this.showControlsButton.className="igv-circview-button",n.appendChild(this.showControlsButton),this.showControlsButton.innerText="none"===this.controlPanel.style.display?"Show Controls":"Hide Controls",this.showControlsButton.addEventListener("click",(e=>{this.controlPanel.querySelectorAll("div").length>0&&("none"===this.controlPanel.style.display?(this.controlPanel.style.display="flex",e.target.innerText="Hide Controls"):(this.controlPanel.style.display="none",e.target.innerText="Show Controls"))}));let r=document.createElement("div");r.className="igv-circview-button",n.appendChild(r),r.innerText="Clear All",r.addEventListener("click",(()=>{this.clearChords()})),!1!==this.config.showCloseButton&&(r=document.createElement("div"),r.className="igv-circview-button",n.appendChild(r),r.innerText="Close",r.addEventListener("click",(()=>{this.visible=!1})))}resetControlPanel(){this.controlPanel.innerHTML="",this.controlPanel.appendChild(this.createGroupByCB());const e=this.groupByTrack?this.chordManager.tracks:this.chordManager.chordSets;for(let t of e)this.addToControlPanel(t)}createGroupByCB(){const e=document.createElement("input");e.type="checkbox",e.id="groupByCB",e.style.width="1.4em",e.style.height="1.4em",e.checked=this.groupByTrack,e.onclick=e=>{this.groupByTrack=e.target.checked,this.resetControlPanel(),this.render()};const t=document.createElement("label");t.for="groupByCB",t.innerText="Group by track",t.style.color="black",t.style.paddingLeft="10px";const i=document.createElement("div");return i.style.width="100%",i.style.paddingTop="5px",i.style.paddingBottom="5px",i.style.background="rgb(216, 230, 234)",i.appendChild(e),i.appendChild(t),i}addToControlPanel(e){const t=document.createElement("div");this.controlPanel.appendChild(t);const i=document.createElement("div");i.className="igv-circview-button",t.appendChild(i),i.innerText=!0===e.visible?"Hide":"Show",i.addEventListener("click",(t=>{!0===e.visible?(this.hideChordSet(e.name),t.target.innerText="Show"):(this.showChordSet(e.name),t.target.innerText="Hide")}));const n=document.createElement("input"),r=e=>200*Math.log(e*bF),s=document.createElement("div");s.className="igv-circview-button",s.innerHTML="    ",t.appendChild(s),s.style.backgroundColor=BF(e.color,1);const o={parent:s,popup:"right",editorFormat:"rgb",color:e.color,onChange:({rgbaString:t})=>{s.style.backgroundColor=BF(t,1),this.setColor(e.name,t),n.value=r(yF(e.color))}},a=new fF(o);n.setAttribute("title","Adjust transparency of arcs"),n.type="range",n.style.width="100px",n.style.marginRight="10px",n.setAttribute("class","range"),n.setAttribute("min","0"),n.setAttribute("max","1000"),n.value=r(yF(e.color)),n.oninput=()=>{const t=(i=n.value,Math.exp(i/200)/bF);var i;this.setColor(e.name,BF(e.color,t)),a.setColor(e.color)},t.appendChild(n);const A=document.createElement("div");A.style.color="black",t.appendChild(A),A.innerText=A.title=e.name}setAssembly(e){const t=this.genomeId||xF();if(this.genomeId===t)return;this.chordManager.clearChords(),this.genomeId=t,this.chrNames=new Set(e.chromosomes.map((e=>CF(e.name))));const i=[],n=[];for(let t of e.chromosomes){const e=CF(t.name);n.push(t.color||gF(e)),i.push({refName:e,uniqueId:e,start:0,end:t.bpLength})}this.assembly={name:e.name,sequence:{trackId:t,type:"ReferenceSequenceTrack",adapter:{type:"FromConfigSequenceAdapter",features:i}},refNameColors:n},this.render()}addChords(e,t={}){const i=t.name||t.track||"*",n=i.split(" ")[0].replaceAll("%20"," "),r={name:i.replaceAll("%20"," "),trackName:n,chords:e,color:t.color||"black",trackColor:t.trackColor||t.color||"black",visible:!0,id:t.id||xF()};this.chordManager.addChordSet(r),this.resetControlPanel(),this.render()}setSize(e,t){if(t=t||e,this.width=e,this.height=t,this.viewState){const i=this.viewState.session.view;i.setWidth(e),i.setHeight(t),i.setBpPerPx(i.minBpPerPx)}}getSize(){return Math.min(this.width,this.height)}clearChords(){this.chordManager.clearChords(),this.resetControlPanel(),this.render()}clearSelection(){this.viewState.pluginManager.rootModel.session.clearSelection()}show(){this.parent.style.display="block"}hide(){this.parent.style.display="none"}get visible(){return"none"!==this.parent.style.display}set visible(e){this.parent.style.display=e?"block":"none"}hideChordSet(e){let t=this.getChordSet(e);t?(t.visible=!1,this.render()):console.warn(`No track with name: ${name}`)}showChordSet(e){let t=this.getChordSet(e);t?(t.visible=!0,this.render()):console.warn(`No track with name: ${e}`)}deleteTrack(e){let t=this.tracks.findIndex((t=>e===t.name));t>=0&&this.tracks.splice(t,1),this.render()}getChordSet(e){return this.groupByTrack?this.chordManager.getTrack(e):this.chordManager.getChordSet(e)}setColor(e,t){const i=this.getChordSet(e);if(i){i.color=t;const e=i.id;for(let i of this.viewState.config.tracks)if(e===i.trackId){i.displays[0].renderer.strokeColor.set(t);break}}}render(){const{createViewState:e,JBrowseCircularGenomeView:t}=JBrowseReactCircularGenomeView;ReactDOM.unmountComponentAtNode(this.container);const i=(this.groupByTrack?this.chordManager.tracks:this.chordManager.chordSets).filter((e=>e.visible)),n=[],r=[];for(let e of i)n.push({trackId:e.id,name:e.name,assemblyNames:["forIGV"],type:"VariantTrack",adapter:{type:"FromConfigAdapter",features:e.chords}}),r.push(e.color);this.viewState=e({assembly:this.assembly,tracks:n});for(let e=0;e div {\n margin: 4px;\n}\n\n.igv-circview-track-panel {\n z-index: 1024;\n position: absolute;\n top: 33px;\n left: 0;\n width: 100%;\n height: fit-content;\n border-bottom-style: solid;\n border-bottom-color: dimgray;\n border-bottom-width: thin;\n background-color: white;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n}\n.igv-circview-track-panel > div {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-circview-track-panel > div > div {\n margin: 4px;\n}\n\n.igv-circview-swatch-button {\n cursor: pointer;\n padding: 5px;\n width: 8px;\n height: 8px;\n border: 1px solid #8d8b8b;\n border-radius: 16px;\n}\n\n.igv-circview-button {\n cursor: pointer;\n padding: 5px;\n color: #444;\n vertical-align: middle;\n text-align: center;\n font-family: "Open Sans", sans-serif;\n font-size: 12px;\n border: 1px solid #8d8b8b;\n border-radius: 4px;\n background: #efefef;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.2);\n}\n\n.igv-circview-button:hover {\n background: #efefef;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.6);\n}\n\n.igv-circview-button:active {\n color: #007bff;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.6);\n}\n\n/*# sourceMappingURL=circular-view.css.map */\n',document.head.insertBefore(e,document.head.childNodes[document.head.childNodes.length-1])}()}const kF=e=>e.startsWith("chr")?e.substring(3):e;function EF(e){const t=[],i=[];for(let n of e.wgChromosomeNames){const r=e.getChromosome(n);i.push(lb(r.name)),t.push({name:r.name,bpLength:r.bpLength})}return t}function IF(e,t,i,n){const r=t.color||"rgb(0,0,255)",s=Ts.addAlpha("all"===i.chr?r:lb(i.chr),n),o=Ts.addAlpha(r,n),a=t.name.replaceAll(" ","%20"),A="all"===i.chr?a:`${a} ${i.chr}:${i.start}-${i.end}`;t.browser.circularView.addChords(e,{track:A,color:s,trackColor:o}),t.browser.circularViewVisible||(t.browser.circularViewVisible=!0)}class UF{constructor(e,{minTLENPercentile:t,maxTLENPercentile:i}){this.totalCount=0,this.frCount=0,this.rfCount=0,this.ffCount=0,this.sumF=0,this.sumF2=0,this.lp=void 0===t?.1:t,this.up=void 0===i?99.5:i,this.isizes=[],this.compute(e)}compute(e){for(let n of e)if(n.isProperPair()){var t=Math.abs(n.fragmentLength);this.sumF+=t,this.sumF2+=t*t,this.isizes.push(t);var i=n.pairOrientation;if("string"==typeof i&&4===i.length)switch(""+i.charAt(0)+i.charAt(2)){case"FF":case"RR":this.ffCount++;break;case"FR":this.frCount++;break;case"RF":this.rfCount++}this.totalCount++}this.ffCount/this.totalCount>.9?this.orienation="ff":this.frCount/this.totalCount>.9?this.orienation="fr":this.rfCount/this.totalCount>.9&&(this.orienation="rf"),this.minTLEN=0===this.lp?0:QF(this.isizes,this.lp),this.maxTLEN=QF(this.isizes,this.up)}}function QF(e,t){if(0!==e.length){var i=Math.floor(e.length*(t/100));return e.sort((function(e,t){return e-t})),e[i]}}const SF={getTissueInfo:function(e,t){let i=(t=t||"https://gtexportal.org/rest/v1")+"/dataset/tissueInfo?datasetId="+(e=e||"gtex_v8");return io.loadJson(i,{})},trackConfiguration:function(e,t){return{type:"eqtl",sourceType:"gtex-ws",url:(t=t||"https://gtexportal.org/rest/v1")+"/association/singleTissueEqtlByLocation",tissueSiteDetailId:e.tissueSiteDetailId,name:e.tissueSiteDetailId.split("_").join(" "),visibilityWindow:25e4}}};function HF(e,t,i){let n=(e.start-t)/i,r=(e.end-t)/i,s=r-n;return s<3&&(s=3,n-=1.5),{px:n,px1:r,pw:s}}function NF(e,t,i,n,r,s){try{r.save(),r.fillStyle=this.color,r.strokeStyle=this.color;const n=this.getColorForFeature(e);let o,a;r.fillStyle=n,r.strokeStyle=n,"SQUISHED"===this.displayMode&&void 0!==e.row?(o=this.featureHeight/2,a=this.margin+this.squishedRowHeight*e.row):"EXPANDED"===this.displayMode&&void 0!==e.row?(o=this.featureHeight,a=this.margin+this.expandedRowHeight*e.row):(o=this.featureHeight,a=this.margin);const A=s.pixelWidth,c=a+o/2,l=o/2,h=c-l/2,d=e.exons?e.exons.length:0,u=HF(e,t,i),f=this.arrowSpacing,p="+"===e.strand?1:"-"===e.strand?-1:0;if(0===d){const e=Math.max(0,u.px),t=Math.min(A,u.px1),i=t-e;if(r.fillRect(e,a,i,o),0!==p){r.fillStyle="white",r.strokeStyle="white";for(let i=e+f/2;iA)break;if(d.utr)r.fillRect(g,h,m,l);else if(d.cdStart&&(u=Math.round((d.cdStart-t)/i),r.fillRect(g,h,u-g,l),m-=u-g,g=u),d.cdEnd&&(u=Math.round((d.cdEnd-t)/i),r.fillRect(u,h,w-u,l),m-=w-u,w=u),m=Math.max(m,1),r.fillRect(g,a,m,o),m>f+5&&0!==p){r.fillStyle="white",r.strokeStyle="white";for(let e=g+f/2;eb||p)&&(o.rowLastLabelX[t.row]=F,"y"===o.axis?(e.save(),Eo.labelTransformWithContext(e,h),Eo.fillText(e,a,h,d,g,l),e.restore()):Eo.fillText(e,a,h,d,g,l))}finally{e.restore()}}const LF=new Set(["nonsense","missense","stop-loss","frameshift","cds-indel"]),DF=new Set(["coding-synon"]),TF=new Set(["splice-3","splice-5"]),RF=new Set(["untranslated-5","untranslated-3"]);function zF(e,t,i,n,r){var s,o,a,A,c=HF(e,t,i),l=this.margin,h=this.snpColors.length;switch(s="squished"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight,this.colorBy){case"function":A=e.func,o=A.split(",").map((function(e){return LF.has(e)||TF.has(e)?h-1:DF.has(e)?h-2:RF.has(e)?h-3:0})).reduce((function(e,t){return Math.max(e,t)}));break;case"class":o="deletion"===(a=e.class)?h-1:"mnp"===a?h-2:"microsatellite"===a||"named"===a?h-3:0}r.fillStyle=this.snpColors[o],r.fillRect(c.px,l,c.pw,s)}function OF(e,t,i,n,r){const s="EXPANDED"===this.displayMode?this.expandedRowHeight:this.squishedRowHeight;let o=this.margin;"COLLAPSED"!==this.displayMode&&void 0!==e.row&&(o+=e.row*s);const a=o+.5*s,A=a-.5*s,c=a+.5*s,l=Math.round((e.junction_left-t)/i),h=Math.round((e.junction_right-t)/i);r.beginPath(),r.moveTo(l,a),r.bezierCurveTo(l,A,h,A,h,a),r.lineWidth=1+Math.log(e.num_junction_reads)/Math.log(2),r.strokeStyle="blue",r.stroke();const d=e.spanning_frag_coords;for(let e=0;et&&(t=i.row);return this.margin+(t+1)*("SQUISHED"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight)}}draw(e){const t=e.features,i=e.context,n=e.bpPerPixel,r=e.bpStart,s=e.pixelWidth,o=e.pixelHeight,a=r+s*n+1;if(this.config.isMergedTrack||Eo.fillRect(i,0,e.pixelTop,s,o,{fillStyle:"rgb(255, 255, 255)"}),t){const A=[];e.rowLastX=[],e.rowLastLabelX=[];for(let i of t)if(i.start>r&&i.enda)break;const t="COLLAPSED"===this.displayMode?0:s.row;e.drawLabel=e.labelAllFeatures||c>10;const A=Math.ceil((s.end-r)/n),h=l[t];if(!h||A>h){this.render.call(this,s,r,n,o,i,e);const a=Math.floor((s.start-r)/n);h&&a-h<=0&&(i.globalAlpha=.5,Eo.strokeLine(i,a,0,a,o,{strokeStyle:"rgb(255, 255, 255)"}),i.globalAlpha=1),l[t]=A}}}else console.log("No feature list")}clickedFeatures(e){const t=e.y-this.margin,i=super.clickedFeatures(e);let n;switch(this.displayMode){case"SQUISHED":n=Math.floor(t/this.squishedRowHeight);break;case"EXPANDED":n=Math.floor(t/this.expandedRowHeight);break;default:n=void 0}return i.filter((function(e){return void 0===n||void 0===e.row||n===e.row}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,n=[];for(let e of t){const t=e._f||e,r="function"==typeof t.popupData?t.popupData(i):this.extractPopupData(t);if(r){n.length>0&&n.push("

");const s=this.infoURL||this.config.infoURL;for(let t of r)if(n.push(t),s&&t.name&&"name"===t.name.toLowerCase()&&t.value&&$t(t.value)&&!t.value.startsWith("<")){const i=s.replace("$$",e.name);t.value=`${t.value}`}const o="gff"===this.config.format||"gff3"===this.config.format||"gtf"===this.config.format;if(t.exons)for(let e=0;e=r.start&&i<=r.end){const i=o?r.number:"-"===t.strand?t.exons.length-e:e+1;i&&(n.push("
"),n.push({name:"Exon Number",value:i}));break}}}}return n}menuItemList(){const e=[];if(this.render===zF){e.push("
");for(let t of["function","class"])e.push({object:ut(Kt("Color by "+t,t===this.colorBy)),click:()=>{this.colorBy=t,this.trackView.repaintViews()}})}e.push("
");for(let t of["COLLAPSED","SQUISHED","EXPANDED"]){const i={COLLAPSED:"Collapse",SQUISHED:"Squish",EXPANDED:"Expand"};e.push({object:ut(Kt(i[t],t===this.displayMode)),click:()=>{this.displayMode=t,this.config.displayMode=t,this.trackView.checkContentHeight(),this.trackView.repaintViews()}})}return e}contextMenuItemList(e){const t=this.clickedFeatures(e);if(void 0===t||0===t.length)return;t.length>1&&t.sort(((e,t)=>t.end-t.start-(e.end-e.start)));const i=t[0];if(i.end-i.start<=1e6){const e=[{label:"View feature sequence",click:async()=>{let e=await this.browser.genome.getSequence(i.chr,i.start,i.end);e?"-"===i.strand&&(e=kf(e)):e="Unknown sequence",this.browser.alert.present(e)}}];return hf()&&void 0!==navigator.clipboard&&e.push({label:"Copy feature sequence",click:async()=>{let e=await this.browser.genome.getSequence(i.chr,i.start,i.end);e?"-"===i.strand&&(e=kf(e)):e="Unknown sequence";try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),e.push("
"),e}}description(){if(zF===this.render){let e=""+this.name+"
";return e+="Color By Function:
",e+='Red: Coding-Non-Synonymous, Splice Site
',e+='Green: Coding-Synonymous
',e+='Blue: Untranslated
',e+='Black: Intron, Locus, Unknown

',e+="Color By Class:
",e+='Red: Deletion
',e+='Green: MNP
',e+='Blue: Microsatellite, Named
',e+='Black: Indel, Insertion, SNP',e+="",e}return super.description()}getColorForFeature(e){const t=e._f||e;let i;if(this.altColor&&"-"===t.strand)i="function"==typeof this.altColor?this.altColor(t):this.altColor;else if(this.color)i="function"==typeof this.color?this.color(t):this.color;else if(this.colorBy){const e=t.getAttributeValue?t.getAttributeValue(this.colorBy):t[this.colorBy];i=this.colorTable.getColor(e)}else t.color&&(i=t.color);if(i||(i="rgb(0, 0, 150)"),t.alpha&&1!==t.alpha)i=Ts.addAlpha(i,t.alpha);else if(this.useScore&&t.score&&!Number.isNaN(t.score)){const e=function(e,t,i){const n=(t-e)/9,r=Math.floor((i-e)/n);return Math.min(1,.2+.8*r/9)}(this.config.min?this.config.min:this.viewLimitMin?this.viewLimitMin:0,this.config.max?this.config.max:this.viewLimitMax?this.viewLimitMax:1e3,t.score);t.alpha=e,i=Ts.addAlpha(i,e)}return i}dispose(){this.trackView=void 0}}class VF{constructor(e){this.config=e,this.browser=e.browser,this.columnFormat=e.columnFormat,this.tableRowSelectionList=[],this.tableDOM=vt.div({class:"igv-roi-table"}),e.parent.appendChild(this.tableDOM),this.headerDOM=e,this.tableColumnTitles=this.tableDOM,this.tableRowContainer=this.tableDOM,this.footerDOM=e.gotoButtonHandler}set headerDOM({browser:e,parent:t,headerTitle:i,dismissHandler:n}){const r=vt.div();this.tableDOM.appendChild(r);const s=vt.div();r.appendChild(s),s.innerHTML=i;const o=vt.div();r.appendChild(o),o.appendChild(xt.createIcon("times")),this.boundDismissHandler=function(e){e.stopPropagation(),n()}.bind(this),o.addEventListener("click",this.boundDismissHandler);const{y:a}=e.root.getBoundingClientRect(),{y:A}=t.getBoundingClientRect(),c=-(A-a);Ut(this.tableDOM,r,{minX:0,minY:c}),this.tableDOM.style.display="none",this._headerDOM=r}set tableColumnTitles(e){const t=vt.div({class:"igv-roi-table-column-titles"});e.appendChild(t);for(const{label:e,width:i}of this.columnFormat){const n=vt.div();t.appendChild(n),n.style.width=i,n.innerText=e}this._tableColumnTitlesDOM=t}get tableColumnTitles(){return this._tableColumnTitlesDOM}set tableRowContainer(e){const t=vt.div({class:"igv-roi-table-row-container"});e.appendChild(t),this._tableRowContainerDOM=t}get tableRowContainer(){return this._tableRowContainerDOM}set footerDOM(e){const t=vt.div();this.tableDOM.appendChild(t);const i=vt.div({class:"igv-roi-table-button"});t.appendChild(i),i.id="igv-roi-table-view-button",i.textContent="Go To",i.style.pointerEvents="none",this._footerDOM=t,this.gotoButton=i,this.boundGotoButtonHandler=e.bind(this),this.gotoButton.addEventListener("click",this.boundGotoButtonHandler)}tableRowDOMHelper(e){e.addEventListener("mousedown",(t=>{t.stopPropagation(),e.classList.toggle("igv-roi-table-row-selected"),e.classList.contains("igv-roi-table-row-selected")?e.classList.remove("igv-roi-table-row-hover"):e.classList.add("igv-roi-table-row-hover"),this.setTableRowSelectionState(e.classList.contains("igv-roi-table-row-selected"))})),e.addEventListener("mouseover",(t=>{e.classList.contains("igv-roi-table-row-selected")?e.classList.remove("igv-roi-table-row-hover"):e.classList.add("igv-roi-table-row-hover")})),e.addEventListener("mouseout",(t=>{e.classList.remove("igv-roi-table-row-hover")}))}clearTable(){const e=this.tableRowContainer.querySelectorAll(".igv-roi-table-row");for(let t of e)t.remove()}setTableRowSelectionState(e){e?this.tableRowSelectionList.push(1):this.tableRowSelectionList.pop(),this.gotoButton.style.pointerEvents=this.tableRowSelectionList.length>0?"auto":"none"}present(){this.tableDOM.style.left="0px";const{y:e}=this.browser.root.getBoundingClientRect(),{y:t}=this.config.parent.getBoundingClientRect();this.tableDOM.style.top=e-t+"px",this.tableDOM.style.display="flex"}dismiss(){this.tableDOM.style.display="none"}dispose(){this.tableDOM.innerHTML="",this.tableDOM.remove();for(const e of Object.keys(this))this[e]=void 0;document.removeEventListener("click",this.boundDismissHandler)}}class KF extends VF{constructor(e){super(Object.assign({width:"1024px"},e)),this.descriptionDOM=e}set descriptionDOM(e){if(e.description){let t;t=vt.div({class:"igv-roi-table-description"}),this.tableDOM.insertBefore(t,this.tableColumnTitles),t.style.height="auto",t.innerHTML="BLAT result for query sequence:",t=vt.div({class:"igv-roi-table-description"}),this.tableDOM.insertBefore(t,this.tableColumnTitles),t.style.height="auto",t.style.maxHeight="128px",t.innerHTML=e.description,t=vt.div({class:"igv-roi-table-goto-explainer"}),this.tableDOM.insertBefore(t,this.tableColumnTitles),t.innerHTML="Select one or more rows and click Go To to view the regions"}}tableRowDOM(e){const t=vt.div({class:"igv-roi-table-row"}),i=e.map((e=>isFinite(e)?Xt(e):e));for(let e=0;ee.remove())),e.length>0)for(let t of e){const e=this.tableRowDOM(t);this.tableRowContainer.appendChild(e)}}static getColumnFormatConfiguration(){return[{label:"chr",width:"7%"},{label:"start",width:"12%"},{label:"end",width:"12%"},{label:"strand",width:"5%"},{label:"score",width:"5%"},{label:"match",width:"5%"},{label:"mis-match",width:"7%"},{label:"rep. match",width:"7%"},{label:"N's",width:"3%"},{label:"Q gap count",width:"9%"},{label:"Q gap bases",width:"9%"},{label:"T gap count",width:"9%"},{label:"T gap bases",width:"9%"}]}static gotoButtonHandler(e){e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected"),i=[];for(const e of t){const t=[];e.querySelectorAll("div").forEach((e=>t.push(e.innerText)));const[n,r,s]=t;i.push(`${n}:${r}-${s}`)}for(const e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");this.setTableRowSelectionState(!1),this.browser.search(i.join(" "))}}const GF="https://igv.org/services/blatUCSC.php";async function qF({url:e,userSeq:t,db:i}){e=e||GF;const n=await async function(e="",t,i){const n=new URLSearchParams;n.append("userSeq",t),n.append("db",i);const r=await fetch(e,{method:"post",body:n});return r.json()}(e,t,i);n.fields;return n.blat.map(Vp)}const jF=25e3;class WF extends PF{constructor(e,t){super(e,t),this.name||(this.name="Blat Results"),this.sequence=e.sequence,this.table=void 0}openTableView(){if(void 0===this.table){const e=this.config.features.map((e=>[e.chr,e.start+1,e.end,e.strand,e.score,e.matches,e.misMatches,e.repMatches,e.nCount,e.qNumInsert,e.qBaseInsert,e.tNumInsert,e.tBaseInsert])),t={browser:this.browser,parent:this.browser.parent,headerTitle:this.config.title,description:this.sequence,dismissHandler:()=>{this.table.dismiss(),this.table.dispose(),this.table=void 0},columnFormat:KF.getColumnFormatConfiguration(),gotoButtonHandler:KF.gotoButtonHandler};this.table=new KF(t),this.table.renderTable(e)}this.table.present()}menuItemList(){const e=super.menuItemList();return e.push("
"),e.push({label:"Open table view",click:()=>this.openTableView()}),e}dispose(){super.dispose(),this.table&&this.table.popover.parentElement.removeChild(this.table.popover)}}async function $F({sequence:e,browser:t,name:i,title:n}){if(e.length>jF)return void t.alert.present(`Sequence size exceeds maximum allowed length (${e.length} > ${jF})`);const r=t.genome.id,s=t.config.blatServerURL;try{const o={type:"blat",name:i||"blat results",title:n||"blat results",sequence:e,altColor:"rgb(176, 176, 236)",color:"rgb(236, 176, 176)",features:await qF({url:s,userSeq:e,db:r})};(await t.loadTrack(o)).openTableView()}catch(e){t.alert.present(`Error performing blat search: ${e}`)}}const XF="rgb(255,0,255)",ZF="rgb(0,0,255)",JF="rgb(132, 178, 158)",YF=new Map;YF.set("m","rgb(255,0,0)"),YF.set("h",XF),YF.set("o","rgb(111, 78, 129)"),YF.set("f","rgb(246, 200, 95)"),YF.set("c","rgb(157, 216, 102)"),YF.set("g","rgb(255, 160, 86)"),YF.set("e","rgb(141, 221, 208)"),YF.set("b","rgb(202, 71, 47)"),YF.set("h",XF),YF.set("a","rgb(51,0,111)"),YF.set("NONE_A",ZF),YF.set("NONE_C",ZF),YF.set("NONE_T",ZF),YF.set("NONE_G",ZF),YF.set("NONE_N",ZF);const eb=new Map;function tb(e,t,i){let n=function(e,t){return YF.has(e)?YF.get(e):JF}(e),r=rm(t);if(r>255)return n;const s=e+r+i;if(r<0&&(r=0),!eb.has(s)){const e="basemod2"===i?Math.max(20,Math.min(255,r*r/50-4*r+200+20)):Math.max(20,Math.min(255,.006127*r*r)),[t,o,a]=Ts.rgbComponents(n);eb.set(s,`rgba(${t},${o},${a},${e/255})`)}return eb.get(s)}function ib(e,t,i,n,r,s,o,a,A){const c=o.baseModCounts,l=o.coverageMap;if(c){const o=Array.from(c.allModifications);o.sort(sm.compare);const h=l.getTotalCount(s);for(let d of o){if(d.modification.startsWith("NONE_")&&"basemod2"!==a)continue;const o=d.base,u=xf(o),f=l.getCount(s,o)+l.getCount(s,u),p=c.simplexModifications.has(d.modification)?l.getPosCount(s,o)+l.getNegCount(s,u):f;if(0==p)continue;const g=c.getCount(s,d,A,"basemod2"===a);if(0==g)continue;const w=f/h*(g/p),m=Math.round(w*r),F=c.getLikelihoodSum(s,d,A,"basemod2")/g,b=i-m,v=tb(d.modification,F,a);e.fillStyle=v,e.fillRect(t,b,n,m),i=b}}}class nb{constructor(e){this.alignmentTrack=e}updateContext(e){this.context=e}drawModifications(e,t,i,n,r){const{ctx:s,pixelEnd:o,bpStart:a,bpPerPixel:A}=n,c=e.getBaseModificationSets();if(c)for(let n of e.blocks){if("S"===n.type)continue;const e=t,l=i;let h=Math.max(1,1/A);for(let t=n.seqOffset;to)break;if(i+h<0)continue;let d,u=-1,f=255,p=0;for(let e of c)if(e.containsPosition(t)){const i=rm(e.likelihoods.get(t));f-=i,(!d||i>u)&&(d=e.modification,p=e.canonicalBase,u=i)}if(d){const t=127.5;let n;f>u&&"basemod2"===r&&f>=t?n=tb("NONE_"+p,f,r):u>=t&&(n=tb(d,u,r)),s.fillStyle=n,h<3&&(h=3,i--),s.fillRect(i,e,h,Math.max(1,l-2))}}}}}const rb="rgb(185, 185, 185)";class sb extends ag{static defaults={alleleFreqThreshold:.2,visibilityWindow:3e4,showCoverage:!0,showAlignments:!0,viewAsPairs:!1,pairsSupported:!0,showSoftClips:!1,showAllBases:!1,showInsertions:!0,showMismatches:!0,height:300,coverageTrackHeight:50,colorBy:void 0};constructor(e,t){super(e,t)}init(e){this.type="alignment",this.featureSource=new Zm(e,this.browser),this.coverageTrack=new ob(e,this),this.alignmentTrack=new ab(e,this),super.init(e),this.alignmentTrack.setTop(this.coverageTrack,this.showCoverage),this.showAlignments||(this._height=this.coverageTrackHeight),e.sort&&(Array.isArray(e.sort)?this.assignSort(e.sort[0]):this.assignSort(e.sort))}setHighlightedReads(e){this.alignmentTrack.setHighlightedReads(e),this.updateViews()}set height(e){this._height=e,this.showAlignments&&(this.alignmentTrack.height=this.showCoverage?e-this.coverageTrackHeight:e)}get height(){return this._height}get minTemplateLength(){const e=void 0!==this.config.minTLEN?this.config.minTLEN:this.config.minFragmentLength;return void 0!==e?e:this._pairedEndStats?this._pairedEndStats.minTLEN:0}get maxTemplateLength(){const e=void 0!==this.config.maxTLEN?this.config.maxTLEN:this.config.maxFragmentLength;return void 0!==e?e:this._pairedEndStats?this._pairedEndStats.maxTLEN:1e3}sort(e){e=this.assignSort(e);for(let t of this.trackView.viewports)if(t.containsPosition(e.chr,e.position)){const i=t.cachedFeatures;i&&(i.sortRows(e),t.repaint())}}assignSort(e){if(e.locus){const t=function(e){const t=e.split(":"),i=t[1].split("-"),n={chr:t[0],start:Number.parseInt(i[0].replace(/,/g,""))-1};return i.length>1?n.end=Number.parseInt(i[1].replace(/,/g,"")):n.end=n.start+1,n}(e.locus);e.chr=t.chr,e.position=t.start}else e.position--;return e.direction="ASC"===e.direction||!0===e.direction,e.chr=this.browser.genome.getChromosomeName(e.chr),this.sortObject=e,this.sortObject}async getFeatures(e,t,i,n,r){const s=await this.featureSource.getAlignments(e,t,i);if(s.paired&&!this._pairedEndStats&&!this.config.maxFragmentLength){const e=new UF(s.alignments,this.config);e.totalCount>99&&(this._pairedEndStats=e)}s.alignments=void 0;const o=this.sortObject;return o&&o.chr===e&&o.position>=t&&o.position<=i&&s.sortRows(o),s}computePixelHeight(e){return(this.showCoverage?this.coverageTrackHeight:0)+(this.showAlignments?this.alignmentTrack.computePixelHeight(e):0)}draw(e){Eo.fillRect(e.context,0,e.pixelTop,e.pixelWidth,e.pixelHeight,{fillStyle:"rgb(255, 255, 255)"}),!0===this.showCoverage&&this.coverageTrackHeight>0?(this.trackView.axisCanvas.style.display="block",this.coverageTrack.draw(e)):this.trackView.axisCanvas.style.display="none",!0===this.showAlignments&&(this.alignmentTrack.setTop(this.coverageTrack,this.showCoverage),this.alignmentTrack.draw(e))}paintAxis(e,t,i){this.coverageTrack.paintAxis(e,t,this.coverageTrackHeight)}contextMenuItemList(e){return this.alignmentTrack.contextMenuItemList(e)}popupData(e){return!0===this.showCoverage&&e.y>=this.coverageTrack.top&&e.y=this.coverageTrack.top&&e.y=this.coverageTrack.top&&e.y");const t=ut('
');t.text("Color by:"),e.push({name:void 0,object:t,click:void 0,init:void 0});const i=[{key:"strand",label:"read strand"}];this.alignmentTrack.hasPairs&&(i.push({key:"firstOfPairStrand",label:"first-of-pair strand"}),i.push({key:"pairOrientation",label:"pair orientation"}),i.push({key:"tlen",label:"insert size (TLEN)"}),i.push({key:"unexpectedPair",label:"pair orientation & insert size (TLEN)"}));const n="tag"+(this.alignmentTrack.colorByTag?" ("+this.alignmentTrack.colorByTag+")":"");i.push({key:"tag",label:n});for(let t of i){const i=this.alignmentTrack.colorBy===t.key;e.push(this.colorByCB(t,i))}const r=()=>{if(!this.autoHeight){const e=(this.showCoverage?this.coverageTrackHeight:0)+(this.showAlignments?this.alignmentTrack.height:0);this.trackView.setTrackHeight(e)}};e.push("
"),e.push({object:ut(Kt("Show Coverage",this.showCoverage)),click:()=>{this.showCoverage=!this.showCoverage,r(),this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e.push({object:ut(Kt("Show Alignments",this.showAlignments)),click:()=>{this.showAlignments=!this.showAlignments,r(),this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e.push("
"),e.push({object:ut(Kt("Show all bases",this.showAllBases)),click:()=>{this.showAllBases=!this.showAllBases,this.config.showAllBases=this.showAllBases,this.trackView.repaintViews()}}),e.push("
"),e.push({object:ut(Kt("Show mismatches",this.showMismatches)),click:()=>{this.showMismatches=!this.showMismatches,this.config.showMismatches=this.showMismatches,this.trackView.repaintViews()}}),e.push({object:ut(Kt("Show insertions",this.showInsertions)),click:()=>{this.showInsertions=!this.showInsertions,this.config.showInsertions=this.showInsertions,this.getCachedAlignmentContainers(),this.trackView.repaintViews()}}),e.push({object:ut(Kt("Show soft clips",this.showSoftClips)),click:()=>{this.showSoftClips=!this.showSoftClips,this.config.showSoftClips=this.showSoftClips,this.featureSource.setShowSoftClips(this.showSoftClips);const e=this.getCachedAlignmentContainers();for(let t of e)t.setShowSoftClips(this.showSoftClips);this.trackView.repaintViews()}}),this.pairsSupported&&this.alignmentTrack.hasPairs&&(e.push("
"),e.push({object:ut(Kt("View as pairs",this.viewAsPairs)),click:()=>{this.viewAsPairs=!this.viewAsPairs,this.config.viewAsPairs=this.viewAsPairs,this.featureSource.setViewAsPairs(this.viewAsPairs);const e=this.getCachedAlignmentContainers();for(let t of e)t.setViewAsPairs(this.viewAsPairs);this.trackView.repaintViews()}})),this.browser.circularView&&(this.alignmentTrack.hasPairs||this.alignmentTrack.hasSupplemental)&&(e.push("
"),this.alignmentTrack.hasPairs&&e.push({label:"Add discordant pairs to circular view",click:()=>{for(let e of this.trackView.viewports)this.addPairedChordsForViewport(e)}}),this.alignmentTrack.hasSupplemental&&e.push({label:"Add split reads to circular view",click:()=>{for(let e of this.trackView.viewports)this.addSplitChordsForViewport(e)}})),e.push("
");const s=ut('
');return s.text("Display mode:"),e.push({name:void 0,object:s,click:void 0,init:void 0}),e.push({object:ut(Kt("expand","EXPANDED"===this.alignmentTrack.displayMode)),click:()=>{this.alignmentTrack.displayMode="EXPANDED",this.config.displayMode="EXPANDED",this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e.push({object:ut(Kt("squish","SQUISHED"===this.alignmentTrack.displayMode)),click:()=>{this.alignmentTrack.displayMode="SQUISHED",this.config.displayMode="SQUISHED",this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e}colorByCB(e,t){return{name:void 0,object:ut(Kt(e.label,t)),click:t=>{"tag"!==e.key?e.key===this.alignmentTrack.colorBy?(this.alignmentTrack.colorBy="none",this.config.colorBy="none",this.trackView.repaintViews()):(this.alignmentTrack.colorBy=e.key,this.config.colorBy=e.key,this.trackView.repaintViews()):this.browser.inputDialog.present({label:"Tag Name",value:this.alignmentTrack.colorByTag?this.alignmentTrack.colorByTag:"",callback:e=>{e?(this.alignmentTrack.colorBy="tag",this.alignmentTrack.colorByTag=e,this.alignmentTrack.tagColors||(this.alignmentTrack.tagColors=new bo("Set1"))):(this.alignmentTrack.colorBy="none",this.alignmentTrack.colorByTag=""),this.trackView.repaintViews()}},t)},init:void 0}}getState(){const e=super.getState();return this.sortObject&&(e.sort={chr:this.sortObject.chr,position:this.sortObject.position+1,option:this.sortObject.option,direction:this.sortObject.direction?"ASC":"DESC"}),this.alignmentTrack.highlightedReads&&(e.highlightedReads=Array.from(this.alignmentTrack.highlightedReads)),e}getCachedAlignmentContainers(){return this.trackView.viewports.map((e=>e.cachedFeatures))}get dataRange(){return this.coverageTrack.dataRange}set dataRange(e){this.coverageTrack.dataRange=e}get logScale(){return this.coverageTrack.logScale}set logScale(e){this.coverageTrack.logScale=e}get autoscale(){return this.coverageTrack.autoscale}set autoscale(e){this.coverageTrack.autoscale=e}addPairedChordsForViewport(e){const t=this.maxTemplateLength,i=[],n=e.referenceFrame;for(let r of e.cachedFeatures.allAlignments())r.end>=n.start&&r.start<=n.end&&(r.paired?r.end-r.start>t&&i.push(r):r.mate&&r.mate.chr&&(r.mate.chr!==r.chr||Math.max(r.fragmentLength)>t)&&i.push(r));const r=(e=>{const t=[];for(let i of e)if(i.paired)i.firstAlignment&&i.secondAlignment&&t.push({uniqueId:i.readName,refName:kF(i.firstAlignment.chr),start:i.firstAlignment.start,end:i.firstAlignment.end,mate:{refName:kF(i.secondAlignment.chr),start:i.secondAlignment.start,end:i.secondAlignment.end}});else{const e=i.mate;e&&e.chr&&e.position&&t.push({uniqueId:i.readName,refName:kF(i.chr),start:i.start,end:i.end,mate:{refName:kF(e.chr),start:e.position-1,end:e.position}})}return t})(i);IF(r,this,n,.02)}addSplitChordsForViewport(e){const t=[],i=e.referenceFrame;for(let n of e.cachedFeatures.allAlignments()){const e=n.hasTag("SA");n.end>=i.start&&n.start<=i.end&&e&&t.push(n)}const n=(e=>{const t=e=>{const t=fm(e.tags().SA);let n=0;for(let r of t)r.start!==e.start&&i.push({uniqueId:`${e.readName}_${n++}`,refName:kF(e.chr),start:e.start,end:e.end,mate:{refName:kF(r.chr),start:r.start,end:r.start+r.lenOnRef}})},i=[];for(let i of e)i.paired?(t(i.firstAlignment),i.secondAlignment&&t(i.secondAlignment)):t(i);return i})(t);IF(n,this,i,.02)}}class ob{constructor(e,t){this.parent=t,this.featureSource=t.featureSource,this.paintAxis=Jm,this.top=0,this.autoscale=e.autoscale||void 0===e.max,this.autoscale||(this.dataRange={min:e.min||0,max:e.max})}get height(){return this.parent.coverageTrackHeight}draw(e){const t=e.pixelTop;e.pixelHeight;const i=this.parent.browser.nucleotideColors;if(t>this.height)return;const n=e.context,r=e.features,s=r.coverageMap;let o;s.refSeq&&(o=s.refSeq.toUpperCase());const a=e.bpPerPixel,A=e.bpStart,c=A+e.pixelWidth*a+1;let l;l=this.parent.coverageColor?this.parent.coverageColor:this.parent.color&&"function"!=typeof this.parent.color?Ts.darkenLighten(this.parent.color,-35):"rgb(150, 150, 150)",Eo.setProperties(n,{fillStyle:l,strokeStyle:l});const h=Math.max(1,Math.ceil(1/a));for(let e=0,t=s.coverage.length;ec)break;const i=s.coverage[e];if(!i)continue;const r=Math.round(i.total/this.dataRange.max*this.height),o=this.height-r,l=Math.floor((t-A)/a);Eo.fillRect(n,l,o,h,r)}if(o)for(let e=0,t=s.coverage.length;ec)break;const l=s.coverage[e];if(!l)continue;const d=l.total/this.dataRange.max*this.height;let u=this.height-d;const f=Math.floor((t-A)/a),p=o[e];if("basemod2"===this.parent.colorBy||"basemod"===this.parent.colorBy){const e=.5;ib(n,f,this.height,h,d,t,r,this.parent.colorBy,e)}else if(l.isMismatch(p)){Eo.setProperties(n,{fillStyle:i[p]}),Eo.fillRect(n,f,u,h,d);let e=0;for(let t of["A","C","T","G"]){const r=(l["pos"+t]+l["neg"+t])/this.dataRange.max*this.height;u=this.height-r-e,e+=r,Eo.setProperties(n,{fillStyle:i[t]}),Eo.fillRect(n,f,u,h,r)}}}}getClickedObject(e){let t=e.viewport.cachedFeatures;if(!t||0===t.length)return;const i=Math.floor(e.genomicLocation),n=t.coverageMap,r=Math.floor(i-n.bpStart);return n.coverage[r]}popupData(e){const t=[],i=this.getClickedObject(e);if(i){const n=Math.floor(e.genomicLocation),r=e.viewport.referenceFrame;t.push(r.chr+":"+Xt(1+n)),t.push({name:"Total Count",value:i.total});let s=i.posA+i.negA;s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posA+"+, "+i.negA+"- )"),t.push({name:"A",value:s}),s=i.posC+i.negC,s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posC+"+, "+i.negC+"- )"),t.push({name:"C",value:s}),s=i.posG+i.negG,s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posG+"+, "+i.negG+"- )"),t.push({name:"G",value:s}),s=i.posT+i.negT,s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posT+"+, "+i.negT+"- )"),t.push({name:"T",value:s}),s=i.posN+i.negN,s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posN+"+, "+i.negN+"- )"),t.push({name:"N",value:s}),t.push("
"),t.push({name:"DEL",value:i.del.toString()}),t.push({name:"INS",value:i.ins.toString()})}return t}}class ab{constructor(e,t){this.parent=t,this.browser=t.browser,this.featureSource=t.featureSource,this.top=0===e.coverageTrackHeight?0:e.coverageTrackHeight+5,this.displayMode=e.displayMode||"EXPANDED",this.alignmentRowHeight=e.alignmentRowHeight||14,this.squishedRowHeight=e.squishedRowHeight||3,this.negStrandColor=e.negStrandColor||"rgba(150, 150, 230, 0.75)",this.posStrandColor=e.posStrandColor||"rgba(230, 150, 150, 0.75)",this.insertionColor=e.insertionColor||"rgb(138, 94, 161)",this.insertionTextColor=e.insertionTextColor||"white",this.showInsertionText=void 0!==e.showInsertionText&&!!e.showInsertionText,this.deletionColor=e.deletionColor||"black",this.deletionTextColor=e.deletionTextColor||"black",this.showDeletionText=void 0!==e.showDeletionText&&!!e.showDeletionText,this.skippedColor=e.skippedColor||"rgb(150, 170, 170)",this.pairConnectorColor=e.pairConnectorColor,this.smallTLENColor=e.smallTLENColor||e.smallFragmentLengthColor||"rgb(0, 0, 150)",this.largeTLENColor=e.largeTLENColor||e.largeFragmentLengthColor||"rgb(200, 0, 0)",this.pairOrientation=e.pairOrienation||"fr",this.pairColors={},this.pairColors.RL=e.rlColor||"rgb(0, 150, 0)",this.pairColors.RR=e.rrColor||"rgb(20, 50, 200)",this.pairColors.LL=e.llColor||"rgb(0, 150, 150)",this.colorBy=e.colorBy||"unexpectedPair",this.colorByTag=e.colorByTag?e.colorByTag.toUpperCase():void 0,this.bamColorTag=void 0===e.bamColorTag?"YC":e.bamColorTag,this.hideSmallIndels=e.hideSmallIndels,this.indelSizeThreshold=e.indelSizeThreshold||1,e.highlightedReads&&this.setHighlightedReads(e.highlightedReads),e.highlightColor&&(this.highlightColor=e.highlightColor),this.hasPairs=!1,this.hasSupplemental=!1}get baseModRenderer(){return this._baseModRenderer||(this._baseModRenderer=new nb(this)),this._baseModRenderer}setTop(e,t){this.top=0===e.height||!1===t?0:5+e.height}setHighlightedReads(e){if(!Array.isArray(e)||!e.every((e=>"string"==typeof e)))throw new Error("AlignmentTrack.setHighlightedReads() only accept array of strings");this.highlightedReads=new Set(e)}computePixelHeight(e){if(e.packedAlignmentRows){return(e.hasDownsampledIntervals()?10:0)+("SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight)*e.packedAlignmentRows.length+5}return 0}draw(e){const t=e.features,i=e.context,n=e.bpPerPixel,r=e.bpStart,s=e.pixelWidth,o=r+s*n+1,a=this.parent.showSoftClips,A=this.parent.showAllBases,c=this.browser.nucleotideColors,l=t.packedAlignmentRows;i.save();let h=t.sequence;h&&(h=h.toUpperCase());let d=0,u=e.pixelTop;this.top&&i.translate(0,this.top);const f=u+e.pixelHeight;t.hasDownsampledIntervals()?(d=10,t.downsampledIntervals.forEach((function(e){var t=(e.start-r)/n,s=(e.end-r)/n;s-t>5&&(t+=1,s-=1),Eo.fillRect(i,t,2,s-t,3,{fillStyle:"black"})}))):d=0,this.alignmentsYOffset=d;const p="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight;if(l){const e=l.length;for(let t=0;tf)break;if(!(i+no)break;!0!==t.hidden&&(t instanceof $w?(g.call(this,t,i,n),w.call(this,t.firstAlignment,i,n),t.secondAlignment&&w.call(this,t.secondAlignment,i,n)):w.call(this,t,i,n))}}}function g(e,t,s){var a=this.getConnectorColor(e.firstAlignment),A=(e.connectingStart-r)/n,c=(e.connectingEnd-r)/n,l=t+s/2;e.connectingEndo||(e.mq<=0&&(a=Ts.addAlpha(a,.15)),Eo.setProperties(i,{fillStyle:a,strokeStyle:a}),Eo.strokeLine(i,A,l,c,l))}function w(e,l,d){if(e.start+e.lengthOnRefo)return;const u=a?e.blocks:e.blocks.filter((e=>"S"!==e.type));let f=this.getAlignmentColor(e);const g=f;e.mq<=0&&(f=Ts.addAlpha(f,.15)),Eo.setProperties(i,{fillStyle:f,strokeStyle:g});const w=[];for(let e=0;eo))break}if(e.gaps){const t=l+d/2;for(let s of e.gaps){const e=(s.start-r)/n,o=(s.start+s.len-r)/n,a=o-e,A=s.len.toString(),c=6*A.length,h=e+a/2,d="D"===s.type?this.deletionColor:this.skippedColor;if(Eo.strokeLine(i,e,t,o,t,{strokeStyle:d,lineWidth:2}),this.showDeletionText&&s.len>1&&a>=c+8){const e=h-c/2;Eo.fillRect(i,e-1,l-1,c+2,12,{fillStyle:"white"}),Eo.fillText(i,A,e,l+10,{font:"normal 10px monospace",fillStyle:this.deletionTextColor})}}}if(e.insertions&&this.parent.showInsertions){let t=-1;for(let s of e.insertions){if(this.hideSmallIndels&&s.len<=this.indelSizeThreshold)continue;if(s.starto)break;const e=s.start-r,a=s.len.toString(),A=2+6*a.length,c=this.showInsertionText&&1!==s.len?Math.round(s.len/n):2,h=Math.max(Math.min(A,c),2),u=e/n-h/2;if(u-t>2){const e={fillStyle:this.insertionColor};Eo.fillRect(i,u-2,l,h+4,2,e),Eo.fillRect(i,u,l+2,h,d-4,e),Eo.fillRect(i,u-2,l+d-2,h+4,2,e),this.showInsertionText&&s.len>1&&c>A&&Eo.fillText(i,a,u+1,l+10,{font:"normal 10px monospace",fillStyle:this.insertionTextColor}),t=u}}}for(let{bbox:e,baseColor:t,readChar:r}of w){if(n<=.1&&e.height>=8){const n=Math.min(10,e.height);i.font=n+"px sans-serif";const s=e.x+e.width/2;Eo.strokeText(i,r,s-i.measureText(r).width/2,n-1+e.y,{strokeStyle:t})}else Eo.fillRect(i,e.x,e.y,e.width,e.height,{fillStyle:t})}if("basemod2"===this.colorBy||"basemod"===this.parent.colorBy){const t={ctx:i,bpPerPixel:n,bpStart:r,bpEnd:o,pixelEnd:s};this.baseModRenderer.drawModifications(e,l,d,t,this.parent.colorBy)}function m(o,a){const w=[],m=o.start-t.start,F=(o.start-r)/n,b=(o.start+o.len-r)/n,v=Math.max(1,b-F),B=100/n,y=Math.min(p/2,B/6),C="S"===o.type,_=e.mq<=0||this.selectedReadName===e.readName||C||this.highlightedReads&&this.highlightedReads.has(e.readName);let x=g;this.selectedReadName===e.readName?x="red":C?x="rgb(50,50,50)":this.highlightedReads&&this.highlightedReads.has(e.readName)&&(x=this.highlightColor||"#00ff00");const k=!0===e.strand&&a===u.length-1,E=!1===e.strand&&0===a;if(k|E){let e,t;k?(e=[F,b,b+y,b,F,F],t=[l,l,l+d/2,l+d,l+d,l]):E&&(e=[b,F,F-y,F,b,b],t=[l,l,l+d/2,l+d,l+d,l]),Eo.fillPolygon(i,e,t,{fillStyle:f}),_&&Eo.strokePolygon(i,e,t,{strokeStyle:x})}else Eo.fillRect(i,F,l,v,d,{fillStyle:f}),_&&(i.save(),i.strokeStyle=x,i.strokeRect(F,l,v,d),i.restore());if(C||A||this.parent.showMismatches&&h&&e.seq&&"*"!==e.seq){const t=e.seq?e.seq.toUpperCase():void 0,i=e.qual,a=o.seqOffset,u=Math.max(1,1/n);for(let e=0,f=o.len;es)break;let p=t?t.charAt(a+e):"";const g=m+e>=0?h.charAt(m+e):"";if("="===p&&(p=g),"X"===p||g!==p||C||A){let t;if(!C&&void 0!==i&&i.length>a+e){t=Ab(i[a+e],c[p])}else t=c[p];t&&w.push({bbox:{x:f,y:l,width:u,height:d},baseColor:t,readChar:p})}}}return w}}i.restore()}popupData(e){const t=this.getClickedObject(e);return t?t.popupData(e.genomicLocation):void 0}contextMenuItemList(e){const t=e.viewport,i=[],n=i=>{const n=this.parent.sortObject,r=!n||n.position!==Math.floor(e.genomicLocation)||!n.direction,s={chr:t.referenceFrame.chr,position:Math.floor(e.genomicLocation),option:i,direction:r,sortAsPairs:t.trackView.track.viewAsPairs};this.parent.sortObject=s,t.cachedFeatures.sortRows(s),t.repaint()};i.push("Sort by..."),i.push({label:"  base",click:()=>n("BASE")}),i.push({label:"  read strand",click:()=>n("STRAND")}),i.push({label:"  start location",click:()=>n("START")}),i.push({label:"  insert size",click:()=>n("INSERT_SIZE")}),i.push({label:"  gap size",click:()=>n("GAP_SIZE")}),i.push({label:"  chromosome of mate",click:()=>n("MATE_CHR")}),i.push({label:"  mapping quality",click:()=>n("MQ")}),i.push({label:"  read name",click:()=>n("READ_NAME")}),i.push({label:"  aligned read length",click:()=>n("ALIGNED_READ_LENGTH")}),i.push({label:"  tag",click:()=>{const i=this.parent.sortObject,n=!i||i.position!==Math.floor(e.genomicLocation)||!i.direction,r={label:"Tag Name",value:this.sortByTag?this.sortByTag:"",callback:i=>{if(i){const r={chr:t.referenceFrame.chr,position:Math.floor(e.genomicLocation),option:"TAG",tag:i,direction:n};this.sortByTag=i,this.parent.sortObject=r,t.cachedFeatures.sortRows(r),t.repaint()}}};this.browser.inputDialog.present(r,e.event)}}),i.push("
");const r=this.getClickedObject(e);if(r){const t=this.parent.showSoftClips,n="function"==typeof r.alignmentContaining?r.alignmentContaining(e.genomicLocation,t):r;if(n){n.isPaired()&&n.isMateMapped()&&i.push({label:"View mate in split screen",click:()=>{if(n.mate){const t=e.viewport.referenceFrame,i=this.browser.genome.getChromosome(n.mate.chr);if(i){this.selectedReadName=n.readName;const e=t.end-t.start,r=n.mate.position-e/2,s=n.mate.position+e/2;this.browser.addMultiLocusPanel(i.name,r,s,t)}else this.browser.alert.present(`Reference does not contain chromosome: ${n.mate.chr}`)}},init:void 0}),i.push({label:"View read sequence",click:()=>{const e=n.seq;e&&"*"!==e?this.browser.alert.present(e):this.browser.alert.present("Read sequence: *")}}),hf()&&i.push({label:"Copy read sequence",click:async()=>{const e=n.seq;try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}});const t=n.seq;if(t&&"*"!=t){t.length{const e=n.isNegativeStrand()?kf(t):t,i=`${n.readName} - blat`,r=`${this.parent.name} - ${i}`;$F({sequence:e,browser:this.browser,name:i,title:r})}});const e=n.softClippedBlocks();e.left&&e.left.len>20&&e.left.len{const i=t.substr(e.left.seqOffset,e.left.len),r=n.isNegativeStrand()?kf(i):i,s=`${n.readName} - blat left clip`,o=`${this.parent.name} - ${s}`;$F({sequence:r,browser:this.browser,name:s,title:o})}}),e.right&&e.right.len>20&&e.right.len{const i=t.substr(e.right.seqOffset,e.right.len),r=n.isNegativeStrand()?kf(i):i,s=`${n.readName} - blat right clip`,o=`${this.parent.name} - ${s}`;$F({sequence:r,browser:this.browser,name:s,title:o})}})}i.push("
")}}return this.browser.circularView&&(this.hasPairs||this.hasSupplemental)&&(this.hasPairs&&i.push({label:"Add discordant pairs to circular view",click:()=>{this.parent.addPairedChordsForViewport(t)}}),this.hasSupplemental&&i.push({label:"Add split reads to circular view",click:()=>{this.parent.addSplitChordsForViewport(t)}}),i.push("
")),i}getClickedObject(e){const t=e.viewport,i=e.y,n=e.genomicLocation,r=this.parent.showSoftClips;let s=t.cachedFeatures;if(!s||0===s.length)return;let o=s.packedAlignmentRows,a=s.downsampledIntervals;const A="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight;let c=Math.floor((i-this.top-this.alignmentsYOffset)/A);if(c<0){for(let e=0;e=n)return a[e]}else if(ce.containsLocation(n,r)));if(e.length>0)return e[0]}}getConnectorColor(e){if(this.pairConnectorColor)return this.pairConnectorColor;switch(this.colorBy){case"strand":case"firstOfPairStrand":case"pairOrientation":case"tag":return this.parent.color?"function"==typeof this.parent.color?this.parent.color(e):this.parent.color:"rgb(200, 200, 200)";default:return this.getAlignmentColor(e)}}getAlignmentColor(e){let t=rb;t=this.parent.color?"function"==typeof this.parent.color?this.parent.color(e):this.parent.color:rb;const i=this.colorBy;switch(i){case"strand":t=e.strand?this.posStrandColor:this.negStrandColor;break;case"firstOfPairStrand":e instanceof $w?t=e.firstOfPairStrand()?this.posStrandColor:this.negStrandColor:e.isPaired()&&(e.isFirstOfPair()?t=e.strand?this.posStrandColor:this.negStrandColor:e.isSecondOfPair()?t=e.strand?this.negStrandColor:this.posStrandColor:console.error("ERROR. Paired alignments are either first or second."));break;case"unexpectedPair":case"pairOrientation":if(this.pairOrientation&&e.pairOrientation){const i=cb[this.pairOrientation];if(i){const n=this.pairColors[i[e.pairOrientation]];if(n){t=n;break}}}if("pairOrientation"===i)break;case"tlen":case"fragmentLength":e.mate&&e.isMateMapped()&&(e.mate.chr!==e.chr?t=lb(e.mate.chr):this.parent.minTemplateLength&&Math.abs(e.fragmentLength)this.parent.maxTemplateLength&&(t=this.largeTLENColor));break;case"tag":const n=e.tags()[this.colorByTag];void 0!==n&&(this.bamColorTag===this.colorByTag?t="rgb("+n+")":(this.tagColors||(this.tagColors=new bo("Set1")),t=this.tagColors.getColor(n)))}return t}get color(){return this.parent.color}get showSortClips(){return this.parent.showSoftClips}get showAllBases(){return this.parent.showAllBases}get nucleotideColors(){return this.browser.nucleotideColors}get minTemplateLength(){return this.parent.minTemplateLength}get maxTemplateLength(){return this.parent.maxTemplateLength}get colorBy(){return this.parent.colorBy}set colorBy(e){this.parent.colorBy=e}}function Ab(e,t){let i;return i=e<5?.1:Math.max(.1,Math.min(1,.1+.9*(e-5)/15)),i=Math.round(10*i)/10,i<1&&(t=Ts.addAlpha(t,i)),t}const cb={fr:{F1R2:"LR",F2R1:"LR",F1F2:"LL",F2F1:"LL",R1R2:"RR",R2R1:"RR",R1F2:"RL",R2F1:"RL"},rf:{R1F2:"LR",R2F1:"LR",R1R2:"LL",R2R1:"LL",F1F2:"RR",F2F1:"RR",F1R2:"RL",F2R1:"RL"},ff:{F2F1:"LR",R1R2:"LR",F2R1:"LL",R1F2:"LL",R2F1:"RR",F1R2:"RR",R2R1:"RL",F1F2:"RL"}};function lb(e){if(hb[e])return hb[e];if(hb["chr"+e]){const t=hb["chr"+e];return hb[e]=t,t}{const t=Ts.randomRGB(0,255);return hb[e]=t,t}}const hb={chrX:"rgb(204, 153, 0)",chrY:"rgb(153, 204, 0)",chrUn:"rgb(50, 50, 50)",chr1:"rgb(80, 80, 255)",chrI:"rgb(139, 155, 187)",chr2:"rgb(206, 61, 50)",chrII:"rgb(206, 61, 50)",chr2a:"rgb(216, 71, 60)",chr2b:"rgb(226, 81, 70)",chr3:"rgb(116, 155, 88)",chrIII:"rgb(116, 155, 88)",chr4:"rgb(240, 230, 133)",chrIV:"rgb(240, 230, 133)",chr5:"rgb(70, 105, 131)",chr6:"rgb(186, 99, 56)",chr7:"rgb(93, 177, 221)",chr8:"rgb(128, 34, 104)",chr9:"rgb(107, 215, 107)",chr10:"rgb(213, 149, 167)",chr11:"rgb(146, 72, 34)",chr12:"rgb(131, 123, 141)",chr13:"rgb(199, 81, 39)",chr14:"rgb(213, 143, 92)",chr15:"rgb(122, 101, 165)",chr16:"rgb(228, 175, 105)",chr17:"rgb(59, 27, 83)",chr18:"rgb(205, 222, 183)",chr19:"rgb(97, 42, 121)",chr20:"rgb(174, 31, 99)",chr21:"rgb(231, 199, 111)",chr22:"rgb(90, 101, 94)",chr23:"rgb(204, 153, 0)",chr24:"rgb(153, 204, 0)",chr25:"rgb(51, 204, 0)",chr26:"rgb(0, 204, 51)",chr27:"rgb(0, 204, 153)",chr28:"rgb(0, 153, 204)",chr29:"rgb(10, 71, 255)",chr30:"rgb(71, 117, 255)",chr31:"rgb(255, 194, 10)",chr32:"rgb(255, 209, 71)",chr33:"rgb(153, 0, 51)",chr34:"rgb(153, 26, 0)",chr35:"rgb(153, 102, 0)",chr36:"rgb(128, 153, 0)",chr37:"rgb(51, 153, 0)",chr38:"rgb(0, 153, 26)",chr39:"rgb(0, 153, 102)",chr40:"rgb(0, 128, 153)",chr41:"rgb(0, 51, 153)",chr42:"rgb(26, 0, 153)",chr43:"rgb(102, 0, 153)",chr44:"rgb(153, 0, 128)",chr45:"rgb(214, 0, 71)",chr46:"rgb(255, 20, 99)",chr47:"rgb(0, 214, 143)",chr48:"rgb(20, 255, 177)"};let db,ub;class fb extends up{constructor(e,t,i,n){super(e,t,i,n)}get contentDiv(){return this.$viewport.get(0)}initializationHelper(){let e;this.$multiLocusCloseButton=ut("
",{class:"igv-multi-locus-close-button"}),this.$viewport.append(this.$multiLocusCloseButton),this.$multiLocusCloseButton.get(0).appendChild(xt.createIcon("times-circle")),this.$multiLocusCloseButton.click((()=>{this.browser.removeMultiLocusPanel(this.referenceFrame)})),this.$rulerLabel=ut("
",{class:"igv-multi-locus-ruler-label"}),this.$viewport.append(this.$rulerLabel),e=document.createElement("div"),this.$rulerLabel.append(ut(e)),this.$rulerLabel.get(0).addEventListener("click",(async e=>{e.stopPropagation(),await this.browser.gotoMultilocusPanel(this.referenceFrame)})),this.$tooltip=ut("
",{class:"igv-ruler-tooltip"}),this.$tooltip.height(this.$viewport.height()),this.$viewport.append(this.$tooltip),this.$tooltipContent=ut("
"),this.$tooltip.append(this.$tooltipContent),this.rulerSweeper=new Ww(this,this.$viewport.get(0).parentElement,this.browser,this.referenceFrame),this.attachMouseHandlers(Ap.isWholeGenomeView(this.referenceFrame.chr)),this.$tooltip.hide(),this.dismissLocusLabel()}presentLocusLabel(e){this.$multiLocusCloseButton.show(),this.$rulerLabel.show(),this.$rulerLabel.get(0).style.backgroundColor=lb(this.referenceFrame.chr);const t=this.$rulerLabel.get(0).querySelector("div"),{width:i}=this.$rulerLabel.get(0).getBoundingClientRect();t.innerHTML=`${this.referenceFrame.getMultiLocusLabel(e)}`;const{width:n}=t.getBoundingClientRect();n/i>.5&&(t.innerHTML=`${this.referenceFrame.getMultiLocusLabelBPLengthOnly(e)}`)}dismissLocusLabel(){this.$rulerLabel.hide(),this.$multiLocusCloseButton.hide()}attachMouseHandlers(e){if(this.namespace=`.ruler_track_viewport_${this.browser.referenceFrameList.indexOf(this.referenceFrame)}`,this.$viewport.off(this.namespace),!0===e){const e=this.browser.referenceFrameList.indexOf(this.referenceFrame),t=`click${this.namespace}`;this.$viewport.on(t,(t=>{const{x:i}=vt.translateMouseCoordinates(t,this.$viewport.get(0)),n=Math.round(this.referenceFrame.start+this.referenceFrame.toBP(i));let r;const{chr:s}=this.browser.genome.getChromosomeCoordinate(n);if(1===this.browser.referenceFrameList.length)r=s;else{let t=this.browser.referenceFrameList.map((({locusSearchString:e})=>e));t[e]=s,r=t.join(" ")}this.browser.search(r)})),this.$viewport.get(0).style.cursor="pointer"}else this.$viewport.get(0).style.cursor="default"}mouseMove(e){if(!0===this.browser.cursorGuideVisible){void 0===ub?(ub=this,this.$tooltip.show()):ub.guid!==this.guid?(ub.$tooltip&&ub.$tooltip.hide(),this.$tooltip.show(),ub=this):this.$tooltip.show();if(this.browser.isMultiLocusWholeGenomeView()||Ap.isWholeGenomeView(this.referenceFrame.chr))return void this.$tooltip.hide();const{x:t}=vt.translateMouseCoordinates(e,this.$viewport.get(0)),{start:i,bpPerPixel:n}=this.referenceFrame,r=Math.round(.5+i+Math.max(0,t)*n);this.$tooltipContent.text(Xt(r));const{width:s}=this.$tooltipContent.get(0).getBoundingClientRect(),{width:o}=this.$viewport.get(0).getBoundingClientRect();this.$tooltip.css({left:`${Ms.clamp(t,0,o-s)}px`}),clearTimeout(db),db=setTimeout((()=>{this.$tooltip&&this.$tooltip.hide()}),1e4)}}startSpinner(){}stopSpinner(){}dispose(){this.rulerSweeper.dispose(),super.dispose()}}class pb extends up{constructor(e,t,i,n){super(e,t,i,n)}initializationHelper(){this.canvas=document.createElement("canvas"),this.canvas.className="igv-ideogram-canvas",this.$viewport.append(ut(this.canvas)),this.ideogram_ctx=this.canvas.getContext("2d"),this.addMouseHandlers()}addMouseHandlers(){this.addViewportClickHandler(this.$viewport.get(0))}addViewportClickHandler(e){this.boundClickHandler=function(e){const{xNormalized:t,width:i}=vt.translateMouseCoordinates(e,this.ideogram_ctx.canvas),{bpLength:n}=this.browser.genome.getChromosome(this.referenceFrame.chr),r=this.referenceFrame.bpPerPixel*i/n;let s=t;s-r/2<0&&(s=r/2);s+r/2>1&&(s=1-r/2);const o=Math.round((s-r/2)*n),a=Math.round((s+r/2)*n);this.referenceFrame.start=o,this.referenceFrame.end=a,this.referenceFrame.bpPerPixel=(a-o)/i,this.browser.updateViews(this.referenceFrame,this.browser.trackViews,!0)}.bind(this),e.addEventListener("click",this.boundClickHandler)}setWidth(e){this.$viewport.width(e)}drawSVGWithContext(e,t,i,n,r,s,o){e.saveWithTranslationAndClipRect(n,r,s,t,i,o),this.trackView.track.draw({context:e,referenceFrame:this.referenceFrame,pixelWidth:t,pixelHeight:i}),e.restore()}repaint(){this.draw({referenceFrame:this.referenceFrame})}draw({referenceFrame:e}){Eo.configureHighDPICanvas(this.ideogram_ctx,this.$viewport.width(),this.$viewport.height()),this.trackView.track.draw({context:this.ideogram_ctx,referenceFrame:e,pixelWidth:this.$viewport.width(),pixelHeight:this.$viewport.height()})}startSpinner(){}stopSpinner(){}}function gb(e,t,i,n){if("ruler"===e.track.type)return new fb(e,t,i,n);if("ideogram"===e.track.id)return new pb(e,t,i,n);return new up(e,t,i,n)}const wb=["rgb(255, 0, 0)","rgb(0, 255, 0)","rgb(0, 0, 255)","rgb(255, 0, 255)","rgb(0, 255, 255)","rgb(128, 0, 128)","rgb(255, 165, 0)","rgb(255, 105, 180)","rgb(255, 127, 80)","rgb(220, 20, 60)","rgb(255, 99, 71)","rgb(173, 216, 230)","rgb(144, 238, 144)","rgb(224, 255, 255)","rgb(250, 250, 210)","rgb(152, 251, 152)","rgb(70, 130, 180)","rgb(102, 205, 170)"].map((e=>{const[t,i,n]=e.split(","),[r,s]=t.split("("),[o,a]=n.split(")");return[s,i,o]}));let mb,Fb,bb,vb,Bb,yb={};const Cb="|",_b=mo("magnesium");class xb{constructor(e){this.sampleInfoFiles=[];e.findTracks((e=>"function"==typeof e.getSamples)).length>0&&e.sampleInfoControl.setButtonVisibility(!0),e.on("trackorderchanged",(t=>{if(this.isInitialized()){e.findTracks((e=>"function"==typeof e.getSamples)).length>0&&e.layoutChange()}}))}initialize(){vb=void 0}isInitialized(){return void 0!==vb}getAttributeNames(){return mb}getAttributes(e){const t=void 0===Bb?e:Bb[e]||e;return vb[t]}async loadSampleInfoFile(e,t){let i;try{i=await io.loadString(t),this.processSampleInfoFileAsString(e,i)}catch(e){console.error(e.message)}!1===ti(t)&&this.sampleInfoFiles.push(t),await Ib.update(e);e.findTracks((e=>"function"==typeof e.getSamples)).length>0&&e.sampleInfoControl.setButtonVisibility(!0)}processSampleInfoFileAsString(e,t){const i=t.split("#").filter((e=>e.length>0));!function(e){const t=e.split(/[\r\n]/);t.shift();const i=t.shift().split("\t");i.shift(),mb=i.map((e=>e.split(" ").join(Cb))),Fb=new Map(mb.map(((e,t)=>[e,t])));const n=t.filter((e=>e.length>0));for(const e of n){const t=e.split("\t"),i=t.shift();void 0===vb&&(vb={}),vb[i]={};for(let e=0;e"number"==typeof e,n=e=>"string"==typeof e;for(const e of Object.keys(t)){const r=t[e],s=new Set(r),o=Array.from(s);if(!0===o.some(n)&&!0===o.some(i)?t[e]=o.filter((e=>!n(e))):t[e]=o,!t[e].some(n)){const i=t[e].slice();t[e]=[Math.min(...i),Math.max(...i)]}}return t}(vb),i.length>1&&(function(e,t){let i;if("copynumber"===t&&(i=e.filter((e=>e.startsWith(t))),i.length>0)){let e=i[0];e=e.split(/[\r\n]/).filter((e=>e.length>0)),e.shift();for(const t of e){const[e,i]=t.split("\t");void 0===Bb&&(Bb={}),Bb[e]=i}}}(i,"copynumber"),function(e){const t=e.filter((e=>e.startsWith("colors")));if(t.length>0){let e=t[0];e=e.split(/[\r\n]/).filter((e=>e.length>0)),e.shift();const i=(e,t,i)=>{let n;switch(t){case 0:n=e.split(" ").join(Cb);break;case 1:n=e.includes(":")?e.split(":").map((e=>parseFloat(e))):e;break;case 2:case 3:n=`rgb(${e})`}return n},n=e.map((e=>e.split("\t").map(i))),r=n.filter((e=>3===e.length&&!e.includes("*"))).filter((([e,t,i])=>!Array.isArray(t))),s={};for(const e of r){const[t,i,n]=e;void 0===s[t]&&(s[t]={}),s[t][i.toUpperCase()]=n}for(const[e,t]of Object.entries(s)){const i=Object.assign({},t);yb[e]=e=>{const t=e.toUpperCase();return i[t]||mo("snow")}}const o=n.filter((e=>Array.isArray(e[1])));for(const e of o){const[t,i]=e[1],n=e[0];if(3===e.length){const[r,s,o]=_o(e[2]);yb[n]=e=>{e=Ms.clamp(e,t,i);return yo(r,s,o,(e-t)/(i-t))}}else if(4===e.length){const[t,i]=e[1],[n,r,s,o]=e;yb[n]=e=>{e=Ms.clamp(e,t,i);return ko(s,o,(e-t)/(i-t))}}}const a=n.filter((e=>3===e.length&&e.includes("*")));for(const e of a)if("*"===e[1]){const[t,i,n]=e;yb[t]=e=>{if("NA"===e)return _b;{const[i,r]=bb[t],s=(e-i)/(r-i),[o,a,A]=_o(n);return yo(o,a,A,s)}}}else if("*"===e[0]){const[t,i,n]=e;yb[i]=()=>n}}}(i))}getAttributeColor(e,t){let i;if("-"===t)i=mo("snow");else if("string"==typeof t&&yb[t])i=yb[t]();else if(yb[e])i=yb[e](t);else if("string"==typeof t)i="NA"===t?_b:function(e){let t=0;for(let i=0;i>8*e&255;i.push(n)}return`rgb(${i.join(", ")})`}(t);else{const[n,r]=bb[e],s=.2,o=Math.max((t-n)/(r-n),s),[a,A,c]=wb[Object.keys(bb).indexOf(e)];i=`rgba(${a},${A},${c},${o})`}return i}getSortedSampleKeysByAttribute(e,t,i){const n=e.filter((e=>"number"==typeof this.getAttributes(e)[t])),r=e.filter((e=>"string"==typeof this.getAttributes(e)[t])),s=(e,n)=>{const r=this.getAttributes(e)[t],s=this.getAttributes(n)[t];return"string"==typeof r&&"string"==typeof s?i*r.localeCompare(s):"number"==typeof r&&"number"==typeof s?i*(r-s):void 0};return n.sort(s),r.sort(s),-1===i?[...n,...r]:[...r,...n]}toJSON(e){for(const t of this.sampleInfoFiles)e.push({type:"sampleinfo",url:t})}}function kb(e){const t=Object.assign({},e);for(const[e,i]of Object.entries(t))"string"!=typeof i||isNaN(i)||(t[e]=Number(i));return t}class Eb{constructor(e,t,i){this.guid=vt.guid(),this.trackView=e,this.browser=e.browser,this.viewport=vt.div({class:"igv-viewport"}),t.appendChild(this.viewport),this.viewport.style.height=`${e.track.height}px`,this.canvas=document.createElement("canvas"),this.viewport.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.contentTop=0,this.hitList=void 0,this.sortDirection=1,this.setWidth(i),this.addMouseHandlers()}static getSampleInfoColumnWidth(e){return e.findTracks((e=>"function"==typeof e.getSamples)).length>0&&e.sampleInfo.isInitialized()&&!0===e.sampleInfoControl.showSampleInfo?8+16*e.sampleInfo.getAttributeNames().length:0}checkCanvas(){const e=window.devicePixelRatio,t=this.viewport.clientHeight,i=this.browser.getSampleInfoViewportWidth();if(this.canvas.width!==i*e||this.canvas.height!==t*e){const n=this.canvas;n.width=i*e,n.height=t*e,n.style.width=`${i}px`,n.style.height=`${t}px`,this.ctx=this.canvas.getContext("2d"),this.ctx.scale(e,e)}}setTop(e){if("function"==typeof this.trackView.track.getSamples){this.contentTop=e;const t=this.trackView.track.getSamples();this.repaint(t)}}setWidth(e){this.viewport.innerWidth=e,this.checkCanvas()}static async update(e){for(const{sampleNameViewport:t}of e.trackViews)t.setWidth(Eb.getSampleInfoColumnWidth(e));await e.layoutChange()}async repaint(e){this.checkCanvas(),this.draw({context:this.ctx,samples:e})}draw({context:e,samples:t}){if(e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillStyle=mo("snow"),e.fillRect(0,0,e.canvas.width,e.canvas.height),vb&&t&&t.names.length>0){this.browser.sampleInfo.getAttributeNames();const i=this.viewport.getBoundingClientRect().height;let n=1;const r=t.height;n=r-2*n<=1?0:1;let s=this.contentTop;this.hitList={};for(const o of t.names){if(s>i)break;if(s+r>0){const t=this.browser.sampleInfo.getAttributes(o);if(t){const i=Object.entries(t);for(const t of i){const[i,o]=t;e.fillStyle=this.browser.sampleInfo.getAttributeColor(i,o);const a=8+16*Fb.get(i),A=s+n,c=r-2*n;e.fillRect(a,A,16,c);const l=`${Math.floor(a)}#${Math.floor(A)}#16#${Math.ceil(c)}`;this.hitList[l]=`${i}#${o}`}}}s+=r}}}renderSVGContext(e,{deltaX:t,deltaY:i}){if("function"==typeof this.trackView.track.getSamples){const n=this.trackView.track.getSamples(),r=0,{width:s,height:o}=this.viewport.getBoundingClientRect(),a=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_sample_names_guid_${vt.guid()}`;e.saveWithTranslationAndClipRect(a,t,i+r,s,o,-r),this.draw({context:e,samples:n}),e.restore()}}addMouseHandlers(){this.addMouseMoveHandler()}addMouseMoveHandler(){this.boundMouseMoveHandler=function(e){if(e.stopPropagation(),this.hitList){const t=Object.entries(this.hitList),{x:i,y:n}=vt.translateMouseCoordinates(e,this.viewport);this.viewport.setAttribute("title","");for(const[e,r]of t){const[t,s,o,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+o||ns+a)){const[e,t]=r.split("#");this.viewport.setAttribute("title",`${e.split(Cb).join(" ")}: ${"-"===t?"":t}`);break}}}}.bind(this),this.viewport.addEventListener("mousemove",this.boundMouseMoveHandler)}removeMouseHandlers(){this.viewport.removeEventListener("mousemove",this.boundMouseMoveHandler)}show(){this.viewport.style.display="block"}hide(){this.viewport.style.display="none"}dispose(){this.removeMouseHandlers(),this.viewport.remove()}}var Ib=Eb;const Ub={textAlign:"start",textBaseline:"bottom",strokeStyle:"black",fillStyle:"black"};class Qb{constructor(e,t,i,n){this.guid=vt.guid(),this.trackView=e,this.browser=e.browser,this.viewport=vt.div({class:"igv-viewport"}),t.appendChild(this.viewport),e.track.height&&(this.viewport.style.height=`${e.track.height}px`),this.canvas=document.createElement("canvas"),this.viewport.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.trackScrollDelta=0,this.contentTop=0,this.hitList=void 0,this.sortDirection=1,this.setWidth(n),!1===this.browser.showSampleNames&&this.hide(),this.addMouseHandlers()}checkCanvas(){const e=this.browser.sampleNameViewportWidth||0;this.ctx.canvas.width=e*window.devicePixelRatio,this.ctx.canvas.style.width=`${e}px`,this.ctx.canvas.height=this.viewport.clientHeight*window.devicePixelRatio,this.ctx.canvas.style.height=`${this.viewport.clientHeight}px`,this.ctx.scale(window.devicePixelRatio,window.devicePixelRatio)}setTop(e){if("function"==typeof this.trackView.track.getSamples){this.contentTop=e;const t=this.trackView.track.getSamples();this.repaint(t)}}setWidth(e){this.viewport.innerWidth=e,this.checkCanvas()}show(){this.viewport.style.display="block"}hide(){this.viewport.style.display="none"}async repaint(e){if(e.names.length>0&&!0===this.browser.showSampleNames&&(this.checkCanvas(),this.draw({context:this.ctx,samples:e}),void 0===this.browser.sampleNameViewportWidth)){const t=e.names.map((e=>this.ctx.measureText(e).width));this.browser.sampleNameViewportWidth=Math.min(200,4+Math.ceil(Math.max(...t))),this.browser.layoutChange()}}draw({context:e,samples:t}){if(!t||0===t.names.length)return;!function(e,{textAlign:t,textBaseline:i,strokeStyle:n,fillStyle:r},s){const o=Math.min(s,10);e.font=`${o}px sans-serif`,e.textAlign=t,e.textBaseline=i,e.fillStyle=r}(e,Ub,t.height);e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillStyle=mo("lead");const i=this.viewport.getBoundingClientRect().height;let n=(t.yOffset||0)+this.contentTop;this.hitList={};for(let r of t.names){if(n>i)break;if(n+t.height>0){const i=r,s=Sb(e,i,n,t.height);e.fillText(i,4,s);const o=`${Math.floor(4)}#${Math.floor(n)}#${e.canvas.width}#${Math.ceil(t.height)}`;this.hitList[o]=`${r}`}n+=t.height}}renderSVGContext(e,{deltaX:t,deltaY:i}){if("function"==typeof this.trackView.track.getSamples){const n=this.trackView.track.getSamples(),r=0,{width:s,height:o}=this.viewport.getBoundingClientRect(),a=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_sample_names_guid_${vt.guid()}`;e.saveWithTranslationAndClipRect(a,t,i+r,s,o,-r),this.draw({context:e,samples:n}),e.restore()}}addMouseHandlers(){this.boundClickHandler=function(e){e.preventDefault(),e.stopPropagation();const t={label:"Name Panel Width",value:this.browser.sampleNameViewportWidth,callback:e=>{this.browser.sampleNameViewportWidth=parseInt(e),this.browser.layoutChange()}};this.browser.inputDialog.present(t,e)}.bind(this),this.viewport.addEventListener("contextmenu",this.boundClickHandler),this.boundMouseMoveHandler=function(e){if(e.stopPropagation(),this.hitList){const t=Object.entries(this.hitList),{x:i,y:n}=vt.translateMouseCoordinates(e,this.viewport);this.viewport.setAttribute("title","");for(const[e,r]of t){const[t,s,o,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+o||ns+a)){this.viewport.setAttribute("title",`${r}`);break}}}}.bind(this),this.viewport.addEventListener("mousemove",this.boundMouseMoveHandler)}removeMouseHandlers(){this.viewport.removeEventListener("contextmenu",this.boundClickHandler),this.viewport.removeEventListener("mousemove",this.boundMouseMoveHandler)}dispose(){this.removeMouseHandlers(),this.viewport.remove()}}function Sb(e,t,i,n){return Hb(e,t,n),i+n-Hb(e,t,n)}function Hb(e,t,i){const{actualBoundingBoxAscent:n,actualBoundingBoxDescent:r}=e.measureText(t);return(i-(n+r))/2}const Nb=function(e){this.popover=vt.div({class:"igv-menu-popup"}),e.appendChild(this.popover);const t=vt.div({class:"igv-menu-popup-header"});this.popover.appendChild(t),Et.attachDialogCloseHandlerWithParent(t,(()=>this.hide())),this.popoverContent=vt.div(),this.popover.appendChild(this.popoverContent),Ut(this.popover,t),t.addEventListener("click",(e=>{e.stopPropagation(),e.preventDefault()})),this.hide()};Nb.prototype.hide=function(){this.popover.style.display="none"},Nb.prototype.presentMenuList=function(e){if(Mb(),e.length>0){this.popoverContent.innerHTML="",e=Gt.trackMenuItemListHelper(e,this);for(let t of e){t.init&&t.init();let i=t.object;0===e.indexOf(t)&&i.removeClass("igv-track-menu-border-top"),i.hasClass("igv-track-menu-border-top")||i.hasClass("igv-menu-popup-check-container")||i.is("div")&&i.addClass("igv-menu-popup-shim"),this.popoverContent.appendChild(i.get(0))}this.popover.style.display="flex";const{width:t}=this.popover.getBoundingClientRect();this.popover.style.left=-t+"px",this.popover.style.top="0px"}},Nb.prototype.presentTrackContextMenu=function(e,t){this.popoverContent.innerHTML="";const i=(n=t,r=this.popover,n.map((e=>{let t;if("string"==typeof e&&"
"===e)t=document.createElement("hr");else if("string"==typeof e)t=vt.div({class:"context-menu"}),t.innerHTML=e;else if("Node"==typeof e)t=e;else{if("function"==typeof e.init&&e.init(),"checkbox"===e.type)t=Kt("Show all bases",e.value);else if("color"===e.type){const i=new Vt({parent:r.parentElement,width:364});i.configure(void 0,{color:t=>e.click(t)}),t=vt.div({class:"context-menu"}),"string"==typeof e.label&&(t.innerHTML=e.label);const n=e=>{i.show(),vt.hide(r),e.preventDefault(),e.stopPropagation()};t.addEventListener("click",n),t.addEventListener("touchend",n),t.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}else t=vt.div({class:"context-menu"}),"string"==typeof e.label&&(t.innerHTML=e.label);if(e.click&&"color"!==e.type){function s(t){e.click(),vt.hide(r),t.preventDefault(),t.stopPropagation()}t.addEventListener("click",s),t.addEventListener("touchend",s),t.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}}return{el:t,init:e.init}})));var n,r;for(let{el:e}of i)this.popoverContent.appendChild(e);!function(e,t){t.style.display="flex";const{x:i,y:n}=vt.translateMouseCoordinates(e,t.parentNode),{width:r}=t.getBoundingClientRect(),s=i+r,{width:o}=t.parentNode.getBoundingClientRect();t.style.left=`${s>o?i-(s-o):i}px`,t.style.top=`${n}px`}(e,this.popover)},Nb.prototype.dispose=function(){this.popoverContent.innerHTML="",this.popover.innerHTML="",Object.keys(this).forEach((function(e){this[e]=void 0}))};const Mb=()=>{const e=document.querySelectorAll(".igv-menu-popup");for(let t=0;t0&&this.viewports[0].startSpinner()}stopSpinner(){this.viewports&&this.viewports.length>0&&this.viewports[0].stopSpinner()}addDOMToColumnContainer(e,t,i){this.axis=this.createAxis(e,this.track),this.viewports=[];const n=e.calculateViewportWidth(i.length),r=t.querySelectorAll(".igv-column");for(let e=0;e{e.dataRangeDialog.configure(this),e.dataRangeDialog.present(ut(e.columnContainer))}));const{width:n,height:r}=i.getBoundingClientRect();this.axisCanvas=document.createElement("canvas"),this.axisCanvas.style.width=`${n}px`,this.axisCanvas.style.height=`${r}px`,i.appendChild(this.axisCanvas)}return i}resizeAxisCanvas(e,t){this.axis.style.width=`${e}px`,this.axis.style.height=`${t}px`,"function"==typeof this.track.paintAxis&&(this.axisCanvas.style.width=`${e}px`,this.axisCanvas.style.height=`${t}px`)}renderSVGContext(e,{deltaX:t,deltaY:i}){!function(e,t,i,n,r){if("function"==typeof t.paintAxis){const{y:s,width:o,height:a}=i.getBoundingClientRect(),A=`${(t.name||t.id).replace(/\W/g,"")}_axis_guid_${vt.guid()}`;e.saveWithTranslationAndClipRect(A,n,s+r,o,a,0),t.paintAxis(e,o,a),e.restore()}}(e,this.track,this.axisCanvas,t,i);const{width:n}=this.axis.getBoundingClientRect(),{y:r}=this.viewports[0].$viewport.get(0).getBoundingClientRect();let s={deltaX:n+t,deltaY:r+i};for(let t of this.viewports){t.renderSVGContext(e,s);const{width:i}=t.$viewport.get(0).getBoundingClientRect();s.deltaX+=i}if(!0===this.browser.sampleInfo.isInitialized()&&!0===this.browser.sampleInfoControl.showSampleInfo){this.sampleInfoViewport.renderSVGContext(e,s);const{width:t}=this.sampleInfoViewport.viewport.getBoundingClientRect();s.deltaX+=t}!0===this.browser.showSampleNames&&this.sampleNameViewport.renderSVGContext(e,s)}dataRange(){return this.track.dataRange?this.track.dataRange:void 0}setDataRange(e,t){void 0!==e&&(this.track.dataRange.min=e),void 0!==t&&(this.track.dataRange.max=t),this.track.autoscale=!1,this.repaintViews()}presentColorPicker(e){if(!1===Db.has(this.track.type)){const t=[],i=this.track.color||this.track.defaultColor;$t(i)&&t.push(i),this.track.altColor&&$t(this.track.altColor)&&t.push(this.track.altColor);const n=t.map((e=>e.startsWith("#")?e:e.startsWith("rgb(")?Ts.rgbToHex(e):Ts.colorNameToHex(e))),r={color:e=>{this.track.color=e,this.repaintViews()},altColor:e=>{this.track.altColor=e,this.repaintViews()}};this.browser.genericColorPicker.configure(n,r),this.browser.genericColorPicker.setActiveColorHandler(e),this.browser.genericColorPicker.show()}}setTrackHeight(e,t){t||(this.track.minHeight&&(e=Math.max(this.track.minHeight,e)),this.track.maxHeight&&(e=Math.min(this.track.maxHeight,e))),this.track.height=e,this.resizeAxisCanvas(this.axis.clientWidth,this.track.height),"function"==typeof this.track.paintAxis&&this.paintAxis();for(let{$viewport:t}of this.viewports)t.height(e);if(this.sampleInfoViewport.viewport.style.height=`${e}px`,this.sampleNameViewport.viewport.style.height=`${e}px`,"function"!=typeof this.track.computePixelHeight)for(let t of this.viewports)t.setContentHeight(e);this.repaintViews(),!1===Lb.has(this.track.type)&&this.updateScrollbar(),this.dragHandle.style.height=`${e}px`,this.gearContainer.style.height=`${e}px`}updateScrollbar(){const e=this.viewports[0].$viewport.height();this.outerScroll.style.height=`${e}px`;const t=this.maxViewportContentHeight(),i=Math.round(e/t*e);t>e?(this.innerScroll.style.display="block",this.innerScroll.style.height=`${i}px`):this.innerScroll.style.display="none"}moveScroller(e){const t=ut(this.innerScroll).position().top+e,i=Math.min(Math.max(0,t),this.outerScroll.clientHeight-this.innerScroll.clientHeight);ut(this.innerScroll).css("top",`${i}px`);const n=this.maxViewportContentHeight(),r=-Math.round(i*(n/this.viewports[0].$viewport.height()));for(let e of this.viewports)e.setTop(r);this.sampleInfoViewport.setTop(r),this.sampleNameViewport.trackScrollDelta=e,this.sampleNameViewport.setTop(r)}isLoading(){for(let e of this.viewports)if(e.isLoading())return!0}repaintViews(){for(let e of this.viewports)e.isVisible()&&e.repaint();"function"==typeof this.track.paintAxis&&this.paintAxis(),this.repaintSampleInfo(),this.repaintSamples()}repaintSampleInfo(){if("function"==typeof this.track.getSamples){const e=this.track.getSamples();this.sampleInfoViewport.repaint(e)}}repaintSamples(){if("function"==typeof this.track.getSamples){const e=this.track.getSamples();this.sampleNameViewport.repaint(e)}}setTrackLabelName(e){this.viewports.forEach((t=>t.setTrackLabel(e)))}resize(e){for(let t of this.viewports)t.setWidth(e)}async updateViews(){if(!this.browser||!this.browser.referenceFrameList)return;const e=this.viewports.filter((e=>e.isVisible()));if(e.forEach((e=>e.shift())),this.browser.dragObject)return;const t=e.filter((e=>e.needsRepaint())).filter((e=>e.checkZoomIn())),i=t.filter((e=>e.needsReload()));for(let e of i)await e.loadFeatures();if(this.disposed)return;if(this.track&&"function"==typeof this.track.variantRowCount&&i.length>0){let e=0;for(let t of this.viewports)t.featureCache&&t.featureCache.features&&(e=Math.max(e,t.featureCache.features.reduce(((e,t)=>Math.max(e,t.row||0)),0)));if(this.track.nVariantRows!==e+1){this.track.variantRowCount(e+1);for(let e of this.viewports)e.checkContentHeight()}}if(this.track.autoscale){let t=[];for(let i of e){const e=i.referenceFrame,n=e.start,r=n+e.toBP(i.getWidth());if(i.featureCache&&i.featureCache.features)if("function"==typeof i.featureCache.features.getMax){const e=i.featureCache.features.getMax(n,r);t.push({value:e})}else{const e=go(i.featureCache.features,n,r);for(let i of e)t.push(i)}}"function"==typeof this.track.doAutoscale?this.track.dataRange=this.track.doAutoscale(t):this.track.dataRange=nf(t)}const n=this.track.autoscale||this.track.autoscaleGroup||"ruler"===this.track.type;for(let i of e)t.includes(i)?i.repaint():n&&i.refresh();this.adjustTrackHeight(),this.repaintSampleInfo(),this.repaintSamples(),this.updateRulerViewportLabels()}clearCachedFeatures(){for(let e of this.viewports)e.clearCache()}updateRulerViewportLabels(){const e=this.browser.calculateViewportWidth(this.viewports.length);for(let t of this.viewports)"ruler"===this.track.type&&(this.viewports.length>1?t.presentLocusLabel(e):t.dismissLocusLabel())}async getInViewFeatures(){if(!this.browser||!this.browser.referenceFrameList)return[];let e=[];const t=this.viewports.filter((e=>e.isVisible()));for(let i of t){const t=i.referenceFrame,{chr:n,start:r,bpPerPixel:s}=i.referenceFrame,o=r+t.toBP(i.getWidth());if((!i.featureCache||!i.featureCache.containsRange(n,r,o,s))&&await i.loadFeatures(),i.featureCache&&i.featureCache.features)if("function"==typeof i.featureCache.features.getMax){const t=i.featureCache.features.getMax(r,o);e.push({value:t})}else{const t="function"==typeof i.featureCache.queryFeatures?i.featureCache.queryFeatures(n,r,o):go(i.featureCache.features,r,o);e=e.concat(t)}}return e}checkContentHeight(){for(let e of this.viewports)e.checkContentHeight();this.adjustTrackHeight()}adjustTrackHeight(){var e=this.maxViewportContentHeight();if(this.track.autoHeight?this.setTrackHeight(e,!1):this.track.paintAxis&&this.paintAxis(),!1===Lb.has(this.track.type)){const t=this.viewports[0].getContentTop(),i=this.viewports[0].$viewport.height(),n=Math.min(0,i-e);if(t{e.preventDefault(),void 0===t&&e.target.classList.remove("igv-track-drag-handle-hover")})),this.boundTrackDragMouseOutHandler=s.bind(this),this.dragHandle.addEventListener("mouseout",this.boundTrackDragMouseOutHandler)}}removeTrackDragMouseHandlers(){"ideogram"===this.track.id||"ruler"===this.track.id||(this.dragHandle.removeEventListener("mousedown",this.boundTrackDragMouseDownHandler),document.removeEventListener("mouseup",this.boundDocumentTrackDragMouseUpHandler),this.dragHandle.removeEventListener("mouseup",this.boundTrackDragMouseEnterHandler),this.dragHandle.removeEventListener("mouseout",this.boundTrackDragMouseOutHandler))}addTrackGearMouseHandlers(){if(!0===this.track.ignoreTrackMenu);else{function e(e){e.preventDefault(),e.stopPropagation(),this.trackGearPopup.presentMenuList(Gt.trackMenuItemList(this))}this.boundTrackGearClickHandler=e.bind(this),this.gear.addEventListener("click",this.boundTrackGearClickHandler)}}removeTrackGearMouseHandlers(){!0===this.track.ignoreTrackMenu||this.gear.removeEventListener("click",this.boundTrackGearClickHandler)}removeDOMFromColumnContainer(){this.boundAxisClickHander&&this.removeAxisEventListener(this.axis),this.axis.remove();for(let e of this.viewports)e.$viewport.remove();this.sampleInfoViewport.dispose(),this.sampleNameViewport.dispose(),this.removeTrackScrollMouseHandlers(),this.outerScroll.remove(),this.removeTrackDragMouseHandlers(),this.dragHandle.remove(),this.removeTrackGearMouseHandlers(),this.gearContainer.remove()}dispose(){this.removeAxisEventListener(this.axis),this.axis.remove();for(let e of this.viewports)e.dispose();this.sampleInfoViewport.dispose(),this.sampleNameViewport.dispose(),this.removeTrackScrollMouseHandlers(),this.outerScroll.remove(),this.removeTrackDragMouseHandlers(),this.dragHandle.remove(),this.removeTrackGearMouseHandlers(),this.gearContainer.remove(),"function"==typeof this.track.dispose&&this.track.dispose();for(let e of Object.keys(this))this[e]=void 0;this.alert&&this.alert.container.remove(),this.disposed=!0}paintAxis(){if("function"==typeof this.track.paintAxis){const{width:e,height:t}=this.axisCanvas.getBoundingClientRect(),i=window.devicePixelRatio||1;this.axisCanvas.height=i*t,this.axisCanvas.width=i*e;const n=this.axisCanvas.getContext("2d");n.scale(i,i),this.track.paintAxis(n,e,t)}}maxViewportContentHeight(){return Math.max(this.viewports.map((e=>e.getContentHeight())))}}const Rb="rgb(150, 150, 150)";class zb extends ag{static defaults={height:50,flipAxis:!1,logScale:!1,windowFunction:"mean",graphType:"bar",autoscale:!0,normalize:void 0,scaleFactor:void 0};constructor(e,t){super(e,t)}init(e){super.init(e),this.type="wig",this.featureType="numeric",this.paintAxis=Jm;const t=e.format?e.format.toLowerCase():e.format;e.featureSource?(this.featureSource=e.featureSource,delete e.featureSource):"bigwig"===t?(this.featureSource=new Uw(e,this.browser.genome),this.resolutionAware=!0):"tdf"===t?(this.featureSource=new Mw(e,this.browser.genome),this.resolutionAware=!0):(this.featureSource=Pw(e,this.browser.genome),this.resolutionAware=!1),void 0===e.max||!0===e.autoscale?this.autoscale=!0:this.dataRange={min:e.min||0,max:e.max}}async postInit(){const e=await this.getHeader();this.disposed||e&&this.setTrackProperties(e)}async getFeatures(e,t,i,n){const r=await this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:this.visibilityWindow,windowFunction:this.windowFunction});if(this.normalize&&this.featureSource.normalizationFactor){const e=this.featureSource.normalizationFactor;for(let t of r)t.value*=e}if(this.scaleFactor){const e=this.scaleFactor;for(let t of r)t.value*=e}return r}menuItemList(){let e=[];return void 0!==this.flipAxis&&(e.push("
"),e.push({label:"Flip y-axis",click:()=>{this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}})),e=e.concat(Gt.numericDataMenuItems(this.trackView)),e}async getHeader(){return"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader()),this.header}getScaleFactor(e,t,i,n){return n?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}computeYPixelValue(e,t){return(this.flipAxis?e-this.dataRange.min:this.dataRange.max-e)*t}computeYPixelValueInLogScale(e,t){let i=this.dataRange.max,n=this.dataRange.min;return i<=0?0:(n<=-1&&(n=0),n=n<=0?0:Math.log10(n+1),i=Math.log10(i+1),e=Math.log10(e+1),(this.flipAxis?e-n:i-e)*t)}draw(e){const t=e.features,i=e.context,n=e.bpPerPixel,r=e.bpStart,s=e.pixelWidth;e.pixelHeight;const o=r+s*n+1,a=this.color||Rb;let A;"string"==typeof a&&a.startsWith("rgb(")&&(A=Ts.addAlpha(a,.1));const c=this.getScaleFactor(this.dataRange.min,this.dataRange.max,e.pixelHeight,this.logScale),l=e=>this.logScale?this.computeYPixelValueInLogScale(e,c):this.computeYPixelValue(e,c);if(t&&t.length>0&&(void 0===this.dataRange.min&&(this.dataRange.min=0),this.dataRange.max>this.dataRange.min)){let s,a=-1;const c=l(0);for(let e of t){if(e.endo)break;const t=Math.floor((e.start-r)/n);if(isNaN(t))continue;let A=l(e.value);const h=Math.ceil((e.end-r)/n),d=Math.max(1,h-t),u=this.getColorForFeature(e);if("points"===this.graphType){const e=this.config.pointSize||3,n=t+d/2;Eo.fillCircle(i,n,A,e/2,{fillStyle:u,strokeStyle:u})}else if("line"===this.graphType)null!=s&&Eo.strokeLine(i,a,s,t,A,{fillStyle:u,strokeStyle:u}),Eo.strokeLine(i,t,A,t+d,A,{fillStyle:u,strokeStyle:u});else{const e=A-c;Eo.fillRect(i,t,c,d,e,{fillStyle:u})}a=t+d,s=A}if(this.dataRange.min<0){const t=this.dataRange.max/(this.dataRange.max-this.dataRange.min)*e.pixelHeight;Eo.strokeLine(i,0,t,e.pixelWidth,t,{strokeStyle:A})}}if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=l(t.y),n={strokeStyle:t.color,strokeWidth:2};t.dotted?Eo.dashedLine(e.context,0,i,e.pixelWidth,i,5,n):Eo.strokeLine(e.context,0,i,e.pixelWidth,i,n)}}popupData(e,t){if(void 0===t&&(t=this.clickedFeatures(e)),t&&t.length>0){const i=e.genomicLocation,n=[];t.sort((function(e,t){return Math.abs((e.start+e.end)/2-i)-Math.abs((t.start+t.end)/2-i)}));const r=t.length>10?t.slice(0,10):t;r.sort((function(e,t){return e.start-t.start}));for(let e of r)if(e){n.length>0&&n.push("
");let t=e.end-e.start==1?Xt(e.start+1):Xt(e.start+1)+"-"+Xt(e.end);n.push({name:"Position:",value:t}),n.push({name:"Value:     ",value:Xt(e.value)})}return r.length..."),n}return[]}get supportsWholeGenome(){return!this.config.indexURL&&!1!==this.config.supportsWholeGenome}getColorForFeature(e){let t=e.value<0&&this.altColor?this.altColor:this.color||Rb;return"function"==typeof t?t(e.value):t}dispose(){this.trackView=void 0}}function Ob(e){this.thresholds=e.thresholds,this.colors=e.colors}function Pb(e){this.scale=e,this.lowColor="rgb("+e.lowR+","+e.lowG+","+e.lowB+")",this.highColor="rgb("+e.highR+","+e.highG+","+e.highB+")",this.diff=e.high-e.low}Ob.prototype.getColor=function(e){for(let t of this.thresholds)if(e=i.high?this.highColor:(t=(e-i.low)/this.diff,"rgb("+Math.floor(i.lowR+t*(i.highR-i.lowR))+","+Math.floor(i.lowG+t*(i.highG-i.lowG))+","+Math.floor(i.lowB+t*(i.highB-i.lowB))+")")};class Vb{constructor(e){this.color=e}getColor(){return this.color}}const Kb={threshold:2e3,r:0,g:0,b:255};class Gb{constructor(e){e=e||Kb,this.threshold=e.threshold,this.r=e.r,this.g=e.g,this.b=e.b,this.cache=[],this.nbins=2e3,this.binsize=this.threshold/this.nbins}setThreshold(e){this.threshold=e,this.cache=[],this.binsize=this.threshold/this.nbins}getThreshold(){return this.threshold}setColorComponents(e){this.r=e.r,this.g=e.g,this.b=e.b,this.cache=[]}getColorComponents(){return{r:this.r,g:this.g,b:this.b}}equals(e){return JSON.stringify(this)===JSON.stringify(e)}getColor(e){const t=Math.floor(Math.min(this.threshold,e)/this.binsize);if(void 0===this.cache[t]){const i=(Ms.clamp(e,0,this.threshold)-0)/(this.threshold-0);this.cache[t]=`rgba(${this.r},${this.g},${this.b}, ${i})`}return this.cache[t]}stringify(){return this.threshold+","+this.r+","+this.g+","+this.b}static parse(e){var t,i;return e.startsWith("R:")?(t=e.substring(2).split(":"),(i=new RatioColorScale(Number.parseFloat(t[0]))).positiveScale=n(t[1]),i.negativeScale=n(t[2]),i):n(e);function n(e){var t,i;return t={threshold:(i=e.split(","))[0],r:i[1],g:i[2],b:i[3]},new Gb(t)}}}class qb{constructor(e){this.config=e,this.url=e.path||e.url}async read(e,t){const i={start:e,size:t};return io.loadArrayBuffer(this.url,{range:i})}}class jb{constructor(e){this.file=e}async read(e,t){const i=this.file;return void 0!==e?i.slice(e,e+t).arrayBuffer():i.arrayBuffer()}}class Wb{constructor(e,t){this.file=e,this.rateLimiter=t}async read(e,t){const i=this.file,n=this.rateLimiter;return new Promise((function(r,s){n.limiter((async function(i){try{const n=await i.read(e,t);r(n)}catch(e){s(e)}}))(i)}))}}var $b=function(e,t){var i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer};const Xb=function(e,t){this.littleEndian=void 0===t||t,this.position=0,this.view=e,this.length=e.byteLength};function Zb(e,t){this.block=e,this.offset=t}Xb.prototype.available=function(){return this.length-this.position},Xb.prototype.remLength=function(){return this.length-this.position},Xb.prototype.hasNext=function(){return this.position=0;i--)t=256*t+e[i];else for(i=0;i0&&(n+=String.fromCharCode(i));return n},Xb.prototype.getFixedLengthTrimmedString=function(e){var t,i,n="";for(t=0;t32&&(n+=String.fromCharCode(i));return n},Xb.prototype.getFloat=function(){var e=this.view.getFloat32(this.position,this.littleEndian);return this.position+=4,e},Xb.prototype.getDouble=function(){var e=this.view.getFloat64(this.position,this.littleEndian);return this.position+=8,e},Xb.prototype.skip=function(e){return this.position+=e,this.position},Xb.prototype.getVPointer=function(){var e=this.position,t=this.view.getUint8(e+1)<<8|this.view.getUint8(e),i=4294967296*(255&this.view.getUint8(e+6))+16777216*(255&this.view.getUint8(e+5))+65536*(255&this.view.getUint8(e+4))+256*(255&this.view.getUint8(e+3))+(255&this.view.getUint8(e+2));return this.position+=8,new Zb(i,t)},Zb.prototype.isLessThan=function(e){return this.blocke.block||this.block===e.block&&this.offset>e.offset},Zb.prototype.print=function(){return this.block+":"+this.offset};class Jb{constructor(e,t){this.chr1=e,this.chr2=t}getKey(){return this.chr1.name+"_"+this.chr2.name+"_"+this.zoom.unit+"_"+this.zoom.binSize}getBlockNumbers(e,t,i){if(e.chr==this.chr2&&t.chr===this.chr1){const i=e;e=t,t=i}const n=this.chr1===this.chr2,r=this.zoom.binSize,s=this.blockBinCount,o=this.blockColumnCount;return i<9||!n?function(){const i=e.start/r,a=e.end/r,A=t.start/r,c=t.end/r,l=Math.floor(i/s),h=Math.floor((a-1)/s),d=Math.floor(A/s),u=Math.floor((c-1)/s),f=[];for(let e=d;e<=u;e++)for(let t=l;t<=h;t++){let i;i=n&&e0;){const e=t.getInt(),i=t.getLong(),n=t.getInt();this.blockIndex[e]={filePosition:i,size:n}}}getBlockIndexEntry(e){return this.blockIndex[e]}}class ev{constructor(e,t,i){this.chr1=e,this.chr2=t,this.bpZoomData=[],this.fragZoomData=[];for(let e of i)"BP"===e.zoom.unit?this.bpZoomData.push(e):this.fragZoomData.push(e)}findZoomForResolution(e,t){const i="FRAG"===t?this.fragZoomData:this.bpZoomData;for(let t=1;tt){const i=e;e=t,t=i}return`${e}_${t}`}static parseMatrix(e,t){const i=new Xb(new DataView(e)),n=i.getInt(),r=i.getInt(),s=t[n],o=t[r];let a=i.getInt();const A=[];for(;a-- >0;){const e=Jb.parseMatrixZoomData(s,o,i);A.push(e)}return new ev(n,r,A)}}class tv{constructor(e,t,i){this.bin1=e,this.bin2=t,this.counts=i}getKey(){return this.bin1+"_"+this.bin2}}class iv{constructor(e=10){this.max=e,this.map=new Map}get(e){let t=this.map.get(e);return t&&(this.map.delete(e),this.map.set(e,t)),t}set(e,t){this.map.has(e)?this.map.delete(e):this.map.size===this.max&&this.map.delete(this.first()),this.map.set(e,t)}has(e){return this.map.has(e)}clear(){this.map.clear()}first(){return this.map.keys().next().value}}class nv{constructor(e,t,i,n){this.file=e,this.filePosition=t,this.nValues=i,this.dataType=n,this.cache=void 0}async getValues(e,t){if(!this.cache||ethis.cache.end){const i=Math.max(0,e-1e3),n=Math.min(this.nValues,t+1e3),r=this.filePosition+i*this.dataType,s=n-i,o=s*this.dataType,a=await this.file.read(r,o);if(!a)return;const A=new Xb(new DataView(a)),c=[];for(let e=0;e=0||t.indexOf("www.googleapis.com/drive")>0?this.file=new Wb(i,ov):this.file=i}}var t}async init(){this.initialized||(await this.readHeaderAndFooter(),this.initialized=!0)}async getVersion(){if(void 0===this.version){const e=await this.file.read(0,128);if(!e)return;const t=new Xb(new DataView(e));return this.magic=t.getString(),this.version=t.getInt(),this.version}return this.version}async getMetaData(){return await this.init(),this.meta}async readHeaderAndFooter(){let e=await this.file.read(0,16);if(!e||0===e.byteLength)throw Error("File content is empty");let t=new Xb(new DataView(e));if(this.magic=t.getString(),this.version=t.getInt(),this.version<5)throw Error("Unsupported hic version: "+this.version);this.footerPosition=t.getLong(),await this.readFooter();const i=Object.values(this.masterIndex).reduce(((e,t)=>Math.min(e,t.start)),Number.MAX_VALUE)-16;e=await this.file.read(16,i),t=new Xb(new DataView(e)),this.genomeId=t.getString(),this.version>=9&&(this.normVectorIndexPosition=t.getLong(),this.normVectorIndexSize=t.getLong()),this.attributes={};let n=t.getInt();for(;n-- >0;)this.attributes[t.getString()]=t.getString();this.chromosomes=[],this.chromosomeIndexMap={};let r=t.getInt(),s=0;for(;r-- >0;){const e={index:s,name:t.getString(),size:this.version<9?t.getInt():t.getLong()};"all"===e.name.toLowerCase()&&(this.wholeGenomeChromosome=e,this.wholeGenomeResolution=Math.round(2*e.size)),this.chromosomes.push(e),this.chromosomeIndexMap[e.name]=e.index,s++}this.bpResolutions=[];let o=t.getInt();for(;o-- >0;)this.bpResolutions.push(t.getInt());if(this.loadFragData){this.fragResolutions=[];let e=t.getInt();if(e>0)for(;e-- >0;)this.fragResolutions.push(t.getInt())}this.chrAliasTable={};for(let e of Object.keys(this.chromosomeIndexMap))e.startsWith("chr")?this.chrAliasTable[e.substr(3)]=e:"MT"===e?this.chrAliasTable.chrM=e:this.chrAliasTable["chr"+e]=e;this.meta={version:this.version,genome:this.genomeId,chromosomes:this.chromosomes,resolutions:this.bpResolutions}}async readFooter(){const e=this.version<9?8:12;let t=await this.file.read(this.footerPosition,e);if(!t)return null;let i=new Xb(new DataView(t));const n=this.version<9?i.getInt():i.getLong();let r=i.getInt();const s=196*r;for(t=await this.file.read(this.footerPosition+e,Math.min(s,n)),i=new Xb(new DataView(t)),this.masterIndex={};r-- >0;){const e=i.getString(),t=i.getLong(),n=i.getInt();this.masterIndex[e]={start:t,size:n}}if(this.expectedValueVectors={},this.version>5){const e=this.version<9?4:8;this.normExpectedValueVectorsPosition=this.footerPosition+e+n}return this}async printIndexStats(){let e,t=0,i=0;await await this.init();for(let n of Object.keys(this.masterIndex)){const r=this.masterIndex[n];t+=r.size,r.size>i&&(i=r.size,e=n)}console.log(`${i} ${e} ${this.config.url}`)}async getMatrix(e,t){const i=ev.getKey(e,t);if(this.matrixCache.has(i))return this.matrixCache.get(i);{const n=await this.readMatrix(e,t);return this.matrixCache.set(i,n),n}}async readMatrix(e,t){if(await this.init(),e>t){const i=e;e=t,t=i}const i=ev.getKey(e,t),n=this.masterIndex[i];if(!n)return;const r=await this.file.read(n.start,n.size);return r?ev.parseMatrix(r,this.chromosomes):void 0}async getContactRecords(e,t,i,n,r,s=!1){await this.init();const o=this.chromosomeIndexMap[this.getFileChrName(t.chr)],a=this.chromosomeIndexMap[this.getFileChrName(i.chr)];if(o>a||o===a&&t.start>=i.end){const e=t;t=i,i=e}const A=await this.getBlocks(t,i,n,r);if(!A||0===A.length)return[];const c=[],l=t.start/r,h=t.end/r,d=i.start/r,u=i.end/r,f=Math.floor(l),p=Math.ceil(h),g=Math.floor(d),w=Math.ceil(u);for(let o of A)if(o){let a,A,m=e&&"NONE"!==e;const F=this.getFileChrName(t.chr),b=this.getFileChrName(i.chr);if(m){const t=await this.getNormalizationVector(e,F,n,r),i=F===b?t:await this.getNormalizationVector(e,b,n,r);t&&i?(a=await t.getValues(f,p),A=await i.getValues(g,w)):m=!1}for(let e of o.records)if(s||e.bin1>=l&&e.bin1=d&&e.bin210&&(this.percentile95=hv(o.records,95))}return c}async getBlocks(e,t,i,n){const r=(e,t)=>`${t.getKey()}_${e}`;await this.init();const s=this.getFileChrName(e.chr),o=this.getFileChrName(t.chr),a=this.chromosomeIndexMap[s],A=this.chromosomeIndexMap[o];if(void 0===a)return console.log("No chromosome named: "+e.chr),[];if(void 0===A)return console.log("No chromosome named: "+t.chr),[];const c=await this.getMatrix(a,A);if(!c)return console.log("No matrix for "+e.chr+"-"+t.chr),[];const l=c.getZoomData(n,i);if(!l){let i=`No data avalailble for resolution: ${n} for map ${e.chr}-${t.chr}`;throw new Error(i)}const h=l.getBlockNumbers(e,t,this.version),d=[],u=[];for(let e of h){const t=r(e,l);this.blockCache.has(n,t)?d.push(this.blockCache.get(n,t)):u.push(e)}const f=u.map((e=>this.readBlock(e,l))),p=await Promise.all(f);for(let e of p)e&&this.blockCache.set(n,r(e.blockNumber,l),e);return d.concat(p)}async readBlock(e,t){const i=await t.blockIndex.getBlockIndexEntry(e);if(i){let n=await this.file.read(i.filePosition,i.size);if(!n)return;n=new _s(new Uint8Array(n)).buffer;const r=new Xb(new DataView(n)),s=r.getInt(),o=[];if(this.version<7)for(let e=0;e0;)this.parseNormVectorEntry(i);return this.normVectorIndex}async readNormExpectedValuesAndNormVectorIndex(){if(await this.init(),void 0===this.normExpectedValueVectorsPosition)return;const e=await this.skipExpectedValues(this.normExpectedValueVectorsPosition);let t=4,i=await this.file.read(e,4);if(0===i.byteLength)return;const n=new Xb(new DataView(i)).getInt(),r={start:e+t,size:30*n};i=await this.file.read(r.start,r.size),this.normalizedExpectedValueVectors={},this.normVectorIndex={},await async function i(n,r){const s=new Xb(new DataView(r));for(;n-- >0;){if(s.available()<100){n++,t+=s.position;const r=Math.max(1e3,30*n),o={start:e+t,size:r},a=await this.file.read(o.start,o.size);return i.call(this,n,a)}this.parseNormVectorEntry(s)}t+=s.position}.call(this,n,i),this.config.nvi=e.toString()+","+t}async skipExpectedValues(e){const t=this.version,i=new class{constructor(e){this.file=e.file,this.size=e.size||64e3,this.position=0,this.bufferStart=0,this.bufferLength=0,this.buffer=void 0}async read(e,t){const i=e,n=e+t,r=this.bufferStart,s=this.bufferStart+this.bufferLength;if(t>this.size)return this.buffer=void 0,this.bufferStart=0,this.bufferLength=0,this.file.read(e,t);if(i>=r&&n<=s){const e=i-r,n=e+t;return this.buffer.slice(e,n)}if(ir){const n=r-i,s=await this.file.read(e,n),o=t-n;if(o>0){const e=this.buffer.slice(0,o);return $b(s,e)}return s}if(!(is))return this.buffer=await this.file.read(e,this.size),this.bufferStart=e,this.bufferLength=this.buffer.byteLength,this.buffer.slice(0,t);{const e=s-i,n=this.bufferLength-e,r=this.buffer.slice(n,this.bufferLength),o=t-e;if(!(o>0))return r;try{this.buffer=await this.file.read(s,this.size),this.bufferStart=s,this.bufferLength=this.buffer.byteLength;const e=this.buffer.slice(0,o);return $b(r,e)}catch(e){if(e.code&&416===e.code)return r;throw e}}}}({file:this.file,size:256e3}),n={start:e,size:4},r=await i.read(n.start,n.size),s=new Xb(new DataView(r)).getInt();return 0===s?e+4:async function e(n,r){let s={start:n,size:500},o=0,a=n,A=await i.read(s.start,s.size),c=new Xb(new DataView(A));c.getString(),c.getString(),c.getInt();const l=t<9?c.getInt():c.getLong();o+=c.position+l*(t<9?8:4),s={start:n+o,size:4},A=await i.read(s.start,s.size),c=new Xb(new DataView(A));const h=c.getInt();return o+=4+h*(4+(t<9?8:4)),r--,0===r?a+o:e(a+o,r)}(e+4,s)}getZoomIndexForBinSize(e,t){let i;if("BP"===(t=t||"BP"))i=this.bpResolutions;else{if("FRAG"!==t)throw new Error("Invalid unit: "+t);i=this.fragResolutions}for(let t=0;te.counts));i.sort((function(e,t){return e-t}));return i[Math.floor(t/100*e.length)]}class dv{constructor(e,t){this.config=e,this.genome=t,this.hicFile=e._hicFile?e._hicFile:new av(e),e._hicFile=void 0}async getHeader(){return await this.hicFile.init(),this.hicFile}async getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:r}){this.hicFile.initialized||await this.hicFile.init();const s=this.hicFile.bpResolutions,o=s[s.length-1];return(await this.hicFile.getContactRecords(void 0,{chr:e,start:t,end:i},{chr:"celltype",start:0,end:1e8},"BP",o)).map((t=>{const i=t.bin1*o;return{chr:e,start:i,end:i+o,value:t.counts,sample:t.bin2.toString()}}))}supportsWholeGenome(){return!1}}class uv extends ag{constructor(e,t){super(e,t)}init(e){if(super.init(e),this.type=e.type||"seg","maf"===this.type&&(this.type="mut"),this.isLog=e.isLog,this.displayMode=e.displayMode||"EXPANDED",this.height=e.height||300,this.maxHeight=e.maxHeight||500,this.squishedRowHeight=e.sampleSquishHeight||e.squishedRowHeight||2,this.expandedRowHeight=e.sampleExpandHeight||e.expandedRowHeight||13,this.sampleHeight=this.squishedRowHeight,this.sampleKeys=[],this.sampleNames=new Map,e.samples){for(let t of e.samples)this.sampleKeys.push(t),this.sampleNames.set(t,t);this.explicitSamples=!0}if(e.color)this.color=e.color;else if(e.colorTable)this.colorTable=new vo(e.colorTable);else switch(this.type){case"mut":this.colorTable=new vo(wv);break;case"shoebox":e.colorScale&&(this.sbColorScale=Gb.parse(e.colorScale));break;default:this.posColorScale=new Pb(e.posColorScale||pv),this.negColorScale=new Pb(e.negColorScale||gv)}const t=Object.assign({},this.config);t.maxWGCount=t.maxWGCount||Number.MAX_SAFE_INTEGER,"shoebox"===this.type?(this.featureSource=new dv(t,this.browser.genome),this.height=e.height||500,this.maxHeight=e.maxHeight||800,this.isLog=!1,this.squishedRowHeight=e.squishedRowHeight||1,this.displayMode=e.displayMode||"SQUISHED",this.visibilityWindow=void 0===e.visibilityWindow?1e6:e.visibilityWindow):this.featureSource=Pw(t,this.browser.genome),this.initialSort=e.sort}async postInit(){"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader(),this.disposed)||this.header&&this.setTrackProperties(this.header)}menuItemList(){const e=[];if(e.push("
"),e.push(function(e){const t=ut("
");t.text("Sort by sample names");const i=()=>{e.track.sampleKeys.sort(((t,i)=>e.sampleNameViewport.sortDirection*t.localeCompare(i))),e.repaintViews(),e.sampleNameViewport.sortDirection*=-1};return{object:t,click:i}}(this.trackView)),vb){e.push("
"),e.push("Sort by attribute:");for(const t of this.browser.sampleInfo.getAttributeNames())e.push(fv(this.trackView,t))}const t={SQUISHED:"Squish",EXPANDED:"Expand",FILL:"Fill"};"shoebox"===this.type&&this.sbColorScale&&(e.push("
"),e.push({object:ut("
Set color scale threshold
"),click:e=>{this.browser.inputDialog.present({label:"Color Scale Threshold",value:this.sbColorScale.threshold,callback:()=>{const e=Number(this.browser.inputDialog.input.value,10);e&&(this.sbColorScale.setThreshold(e),this.trackView.repaintViews())}},e)}})),e.push("
"),e.push("DisplayMode:");const i="seg"===this.type||"shoebox"===this.type?["SQUISHED","EXPANDED","FILL"]:["SQUISHED","EXPANDED"];for(let n of i){const i=Kt(t[n],n===this.displayMode);e.push({object:ut(i),click:()=>{this.displayMode=n,this.config.displayMode=n,this.trackView.checkContentHeight(),this.trackView.repaintViews(),this.trackView.moveScroller(this.trackView.sampleNameViewport.trackScrollDelta)}})}return e}hasSamples(){return!0}getSamples(){return{names:this.sampleKeys.map((e=>this.sampleNames.get(e))),height:this.sampleHeight,yOffset:0}}async getFeatures(e,t,i){const n=await this.featureSource.getFeatures({chr:e,start:t,end:i});if(this.initialSort){const e=this.initialSort;this.sortSamples(e.chr,e.start,e.end,e.direction,n),this.initialSort=void 0}return n}draw({context:e,renderSVG:t,pixelTop:i,pixelWidth:n,pixelHeight:r,features:s,bpPerPixel:o,bpStart:a}){if(Eo.fillRect(e,0,i,n,r,{fillStyle:"rgb(255, 255, 255)"}),s&&s.length>0){if(this.checkForLog(s),"shoebox"===this.type&&!this.sbColorScale){const e=this.featureSource.hicFile.percentile95||2e3;this.sbColorScale=new Gb({threshold:e,r:0,g:0,b:255})}this.updateSampleKeys(s);const t={};let A;switch(this.sampleKeys.forEach((function(e,i){t[e]=i})),this.displayMode){case"FILL":this.sampleHeight=r/this.sampleKeys.length,A=0;break;case"SQUISHED":this.sampleHeight=this.squishedRowHeight,A=0;break;default:this.sampleHeight=this.expandedRowHeight,A=1}const c=this.sampleHeight;for(let e of s)e.pixelRect=void 0;const l=i+r,h=a+n*o+1,d=o;this.sampleYStart=void 0;for(let n of s){if(n.endh)continue;const r=n.sampleKey||n.sample;n.row=t[r];const s=n.row*c+A;void 0===this.sampleYStart&&(this.sampleYStart=s);if(s+cl)continue;const o=Math.max(n.start,a);let u=Math.round((o-a)/d);const f=Math.min(n.end,h),p=Math.round((f-a)/d);let g,w,m=Math.max(1,p-u);if(this.color?g="function"==typeof this.color?this.color(n):this.color:this.colorTable&&(g=this.colorTable.getColor(n.value.toLowerCase())),"mut"===this.type)w=c-2*A,m<3&&(m=3,u-=1);else if("shoebox"===this.type){g=this.sbColorScale.getColor(n.value);let e=c;if(c<.25){const t=.1+2*Math.abs(t.value);e=Math.min(1,t*c)}w=e-2*A}else{let e=n.value;this.isLog||(e=Ms.log2(e/2)),g=e<-.1?this.negColorScale.getColor(e):e>.1?this.posColorScale.getColor(e):"white";let t=c;if(c<.25){const i=.1+2*Math.abs(e);t=Math.min(1,i*c)}w=t-2*A}n.pixelRect={x:u,y:s,w:m,h:w},e.fillStyle=g,e.fillRect(u,s,m,w)}}}checkForLog(e){if(void 0===this.isLog){this.isLog=!1;for(let t of e)if(t.value<0)return void(this.isLog=!0)}}computePixelHeight(e){if(!e)return 0;const t="SQUISHED"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight;return this.updateSampleKeys(e),this.sampleKeys.length*t}async sortSamples(e,t,i,n,r){if(r||(r=await this.featureSource.getFeatures({chr:e,start:t,end:i})),!r)return;this.updateSampleKeys(r);const s={},o="ASC"===n?1:-1,a=()=>{const e=i-t+1;for(let n of r){if(n.endi)break;const r=Math.max(t,n.start),o=(Math.min(i,n.end)-r)/e,a=n.sampleKey||n.sample,A=s[a]||0;s[a]=A+o*n.value}this.sampleKeys.sort((function(e,t){let i=s[e],n=s[t];return i||(i=o*Number.MAX_VALUE),n||(n=o*Number.MAX_VALUE),i===n?0:i>n?o:-1*o}))},A=()=>{for(let e of r){if(e.endi)break;const n=e.sampleKey||e.sample;(!s.hasOwnProperty(n)||e.value.localeCompare(s[n])>0)&&(s[n]=e.value)}this.sampleKeys.sort((function(e,t){let i=s[e]||"",n=s[t]||"";return o*i.localeCompare(n)}))};"mut"===this.type?A():a(),this.trackView.repaintViews()}clickedFeatures(e){const t=super.clickedFeatures(e),i=e.y;return t.filter((function(e){const t=e.pixelRect;return t&&i>=t.y&&i<=t.y+t.h}))}hoverText(e){const t=this.clickedFeatures(e);if(t&&t.length>0)return`${t[0].sample}: ${t[0].value}`}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){i.length>0&&(i.push("
"),i.push("
"));const t=e._f||e,n="function"==typeof t.popupData?t.popupData(this.type,this.browser.genome.id):this.extractPopupData(t);Array.prototype.push.apply(i,n)}return i}contextMenuItemList(e){const t=e.viewport.referenceFrame,i=e.genomicLocation,n=this.config.sort?"ASC"===this.config.sort.direction?"DESC":"ASC":"DESC",r=t.toBP(2.5),s=t=>{const i=e.viewport.cachedFeatures;this.sortSamples(t.chr,t.start,t.end,t.direction,i)};return[{label:"seg"===this.type||"shoebox"===this.type?"Sort by value":"Sort by type",click:t=>{const o={direction:n,chr:e.viewport.referenceFrame.chr,start:i-r,end:i+r};s(o),this.config.sort=o}}]}get supportsWholeGenome(){return(!1===this.config.indexed||!this.config.indexURL)&&!1!==this.config.supportsWholeGenome}updateSampleKeys(e){if(!this.explicitSamples)for(let t of e){const e=t.sampleKey||t.sample;this.sampleNames.has(e)||(this.sampleNames.set(e,t.sample),this.sampleKeys.push(e))}}}function fv(e,t){const i=ut("
");i.html(`  ${t.split(Cb).join(" ")}`);return{object:i,click:()=>{e.track.sampleKeys=e.browser.sampleInfo.getSortedSampleKeysByAttribute(e.track.sampleKeys,t,e.sampleInfoViewport.sortDirection),e.repaintViews(),e.sampleInfoViewport.sortDirection*=-1}}}const pv={low:.1,lowR:255,lowG:255,lowB:255,high:1.5,highR:255,highG:0,highB:0},gv={low:-1.5,lowR:0,lowG:0,lowB:255,high:-.1,highR:255,highG:255,highB:255},wv={indel:"rgb(0,200,0)","targeted region":"rgb(236,155,43)",truncating:"rgb(\t150,0,0)","non-coding transcript":"rgb(0,0,150)",synonymous:"rgb(109,165,95)",silent:"rgb(109,135,80)",missense_mutation:"rgb(72,130,187)",missense:"rgb(72,130,187)","splice site":"rgb(143,83,155)",splice_region:"rgb(143,83,155)",nonsense:"rgb(216, 57,81)",nonsense_mutation:"rgb(216, 57,81)",frame_shift_del:"rgb(226,135,65)",frame_shift_ins:"rgb(226,135,65)",in_frame_del:"rgb(247,235,94)",in_frame_ins:"rgb(247,235,94)","*other*":"rgb(159,91,50)"};class mv extends ag{constructor(e,t){super(e,t),this.type="merged",this.featureType="numeric",this.paintAxis=Jm,this.graphType=e.graphType}init(e){if(!e.tracks)throw Error("Error: no tracks defined for merged track"+e);super.init(e)}async postInit(){this.tracks=[];const e=[];for(let t of this.config.tracks){t.isMergedTrack=!0;const i=await this.browser.createTrack(t);i?(i.autoscale=!1,this.tracks.push(i)):console.warn("Could not create track "+t),"function"==typeof i.postInit&&e.push(i.postInit())}this.flipAxis=!!this.config.flipAxis&&this.config.flipAxis,this.logScale=!!this.config.logScale&&this.config.logScale,this.autoscale=this.config.autoscale||void 0===this.config.max,this.autoscale||(this.dataRange={min:this.config.min||0,max:this.config.max});for(let e of this.tracks)e.autoscale=!1,e.dataRange=this.dataRange;return this.height=this.config.height||50,this.resolutionAware=this.tracks.some((e=>e.resolutionAware)),Promise.all(e)}get height(){return this._height}set height(e){if(this._height=e,this.tracks)for(let t of this.tracks)t.height=e,t.config.height=e}menuItemList(){let e=[];return void 0!==this.flipAxis&&e.push({label:"Flip y-axis",click:()=>{this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}}),e=e.concat(Gt.numericDataMenuItems(this.trackView)),e}async getFeatures(e,t,i,n){const r=this.tracks.map((r=>r.getFeatures(e,t,i,n))),s=await Promise.all(r);return new Fv(s)}draw(e){const t=e.features;for(let i=0,n=this.tracks.length;i0&&i.push("
"),i.push(`
${this.tracks[n].name}
`);const r=this.tracks[n].popupData(e,t[n]);i.push(...r)}return i}}}clickedFeatures(e){const t=e.viewport.cachedFeatures;if(!t)return[];const i=e.genomicLocation,n=[];for(let r of t.featureArrays){const t=e.referenceFrame.bpPerPixel>.2?3*e.referenceFrame.bpPerPixel:.2,s=go(r,i-t,i+t);for(let e of s)n.push(e)}return n}get supportsWholeGenome(){return this.tracks.every((e=>e.supportsWholeGenome))}}class Fv{constructor(e){this.featureArrays=e}getMax(e,t){let i=-Number.MAX_VALUE;for(let n of this.featureArrays)for(let r of n)if(void 0!==r.value&&!Number.isNaN(r.value)){if(r.endt)break;i=Math.max(i,r.value)}return i}}class bv extends ag{static defaults={height:250,theta:Math.PI/4,arcOrientation:!0,showBlocks:!0,blockHeight:3,thickness:1,alpha:.02,logScale:!0};constructor(e,t){super(e,t)}init(e){super.init(e),this.sinTheta=Math.sin(this.theta),this.cosTheta=Math.cos(this.theta),this.arcType=function(e){if(!e.arcType)return"nested";switch(e.arcType){case"chiapet":return"inView";case"chiapetoutbound":return"partialInView";default:return e.arcType}}(e),this.alpha=e.alpha||.02,this.painter={flipAxis:!this.arcOrientation,dataRange:this.dataRange,paintAxis:Jm},e.valueColumn?(this.valueColumn=e.valueColumn,this.hasValue=!0):e.useScore&&(this.hasValue=!0,this.valueColumn="score"),e.max?(this.dataRange={min:e.min||0,max:e.max},this.autoscale=!1):this.autoscale=!0,e.featureSource?(this.featureSource=e.featureSource,delete e._featureSource):(this.featureSource=Pw(e,this.browser.genome),this.featureSource.getWGFeatures=_v)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),void 0===this.visibilityWindow&&"function"==typeof this.featureSource.defaultVisibilityWindow&&(this.visibilityWindow=await this.featureSource.defaultVisibilityWindow(),this.featureSource.visibilityWindow=this.visibilityWindow),this}get supportsWholeGenome(){return!0}async getFeatures(e,t,i){const n=this.visibilityWindow,r=await this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:n});return void 0===this.hasValue&&r&&r.length>0&&(this.hasValue=void 0!==r[0].score),r}draw(e){"proportional"===this.arcType||"inView"===this.arcType||"partialInView"===this.arcType?this.drawProportional(e):this.drawNested(e)}drawNested(e){const t=e.context,i=e.pixelWidth,n=e.pixelHeight,r=e.viewportWidth,s=e.bpPerPixel,o=e.bpStart,a=s;Eo.fillRect(t,0,e.pixelTop,i,n,{fillStyle:"rgb(255, 255, 255)"});const A=e.features;if(A){(function(){let e=0;for(let t of A){let n=(t.start-o)/a,r=(t.end-o)/a;n>=0&&r<=i&&(e=Math.max(e,r-n))}let t=Math.min(r,e)/2;if(e>0){let e=(n-10)/t;this.theta=function(e){let t,i=[.01570925532366355,.15838444032453644,.3249196962329063,.5095254494944288,.7265425280053609,.9999999999999999],n=[.031415926535897934,.3141592653589793,.6283185307179586,.9424777960769379,1.2566370614359172,1.5707963267948966];for(t=0;te);t++);let r=0===t?0:i[t-1],s=ti)continue;let u=d-h;u<3&&(u=3,h--);const f=u/2,p=f/this.sinTheta,g=this.cosTheta*p,w=h+f;let m,F,b;if(l?(m=this.height+g,F=Math.PI+Math.PI/2-this.theta,b=Math.PI+Math.PI/2+this.theta):(m=-g,F=Math.PI/2-this.theta,b=Math.PI/2+this.theta),this.showBlocks&&"all"!==e.chr){const i=(e.start1-o)/a,n=(e.end1-o)/a,r=(e.start2-o)/a,A=(e.end2-o)/a,c=this.arcOrientation?-this.blockHeight:this.blockHeight;t.fillRect(i,s,n-i,c),t.fillRect(r,s,A-r,c)}n&&!this.config.useScore&&u>r&&(n=Cv(n,this.alpha)),t.strokeStyle=n,t.fillStyle=n,t.beginPath(),t.arc(w,m,p,F,b,!1),t.stroke(),e.drawState={xc:w,yc:m,r:p}}else{let r=Math.round((e.start-o)/a),s=Math.round((e.end-o)/a);if(s<0||r>i)continue;let A=s-r;A<3&&(A=3,r--);const c=e.chr===e.chr1?e.chr2:e.chr1;t.strokeStyle=n,t.fillStyle=Cv(lb(c),.5),l?(t.fillRect(r,this.height/2,A,this.height/2),t.fillText(c,r+A/2,this.height/2-5),e.drawState={x:r,y:this.height/2,w:A,h:this.height/2}):(t.fillRect(r,0,A,this.height/2),t.fillText(c,r+A/2,this.height/2+13),e.drawState={x:r,y:0,w:A,h:this.height/2})}}}var c}getScaleFactor(e,t,i,n){return n?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}drawProportional(e){const t=e.context,i=e.pixelWidth,n=e.pixelHeight,r=e.bpPerPixel,s=e.bpStart,o=r,a=e.referenceFrame.start,A=e.referenceFrame.end;Eo.fillRect(t,0,e.pixelTop,i,n,{fillStyle:"rgb(255, 255, 255)"});const c=e.features;if(c&&c.length>0){new Map;const n=0,r=this.getScaleFactor(n,this.dataRange.max,e.pixelHeight-1,this.logScale),l=this.arcOrientation?e.pixelHeight:0;for(let e of c){e.drawState=void 0;const n=this.valueColumn?e[this.valueColumn]:e.score;if(void 0===n||Number.isNaN(n))continue;const c=Math.round((this.logScale?Math.log10(n+1):n)*r);if(e.chr1===e.chr2||"all"===e.chr){const{m1:i,m2:r}=vv(e,this.browser.genome);let h=Math.round((i-s)/o),d=Math.round((r-s)/o)-h;if(d<3&&(d=3,h--),nthis.dataRange.max)continue;if("proportional"!==this.arcType){const e="partialInView"===this.arcType,t=i>=a&&r<=A;let n=!1,s=!1;if(!t&&e&&(n=a<=i&&i<=A,n||(s=a<=r&&r<=A)),!(t||n||s))continue}const u=d/2,f=h+d/2;e.drawState={xc:f,yc:l,radiusX:u,radiusY:c};const p=!!this.arcOrientation,g=e.color||this.color;if(t.strokeStyle=g,t.lineWidth=e.thickness||this.thickness||1,!0===t.isSVG?t.strokeEllipse(f,l,u,c,0,0,Math.PI,p):(t.beginPath(),t.ellipse(f,l,u,c,0,0,Math.PI,p),t.stroke()),this.alpha&&(t.fillStyle=Cv(g,this.alpha),!0===t.isSVG?t.fillEllipse(f,l,u,c,0,0,Math.PI,p):t.fill()),this.showBlocks&&"all"!==e.chr){t.fillStyle=g;const i=(e.start1-s)/o,n=(e.end1-s)/o,r=(e.start2-s)/o,a=(e.end2-s)/o,A=this.arcOrientation?-this.blockHeight:this.blockHeight;t.fillRect(i,l,n-i,A),t.fillRect(r,l,a-r,A)}}else{let r=Math.round((e.start-s)/o),a=Math.round((e.end-s)/o);if(a<0||r>i||nthis.dataRange.max)continue;const A=Math.min(c,this.height-13);let l=a-r;l<3&&(l=3,r--);const h=e.chr===e.chr1?e.chr2:e.chr1;if(t.font="8px sans-serif",t.textAlign="center",t.fillStyle=Cv(lb(h),.5),this.arcOrientation){const i=this.height-A;t.fillRect(r,i,l,A),t.fillText(h,r+l/2,i-5),e.drawState={x:r,y:i,w:l,h:A}}else t.fillRect(r,0,l,A),t.fillText(h,r+l/2,A+13),e.drawState={x:r,y:0,w:l,h:A}}}}}clearAxis(e,t,i){Eo.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"})}paintAxis(e,t,i){const n={min:0,max:this.dataRange.max};"proportional"===this.arcType||"inView"===this.arcType||"partialInView"===this.arcType?(this.painter.flipAxis=!this.arcOrientation,this.painter.dataRange=n,this.painter.paintAxis(e,t,i)):this.clearAxis(e,t,i)}menuItemList(){let e=[];if(this.hasValue){e.push("
");const t={nested:"Nested",proportional:"Proportional - All",inView:"Proportional - Both Ends in View",partialInView:"Proportional - One End in View"};e.push("Arc Type");for(let i of["nested","proportional","inView","partialInView"])e.push({object:ut(Kt(t[i],i===this.arcType)),click:()=>{this.arcType=i,this.trackView.repaintViews()}})}return e.push("
"),e.push({name:"Toggle arc direction",click:()=>{this.arcOrientation=!this.arcOrientation,this.trackView.repaintViews()}}),e.push({name:this.showBlocks?"Hide Blocks":"Show Blocks",click:()=>{this.showBlocks=!this.showBlocks,this.trackView.repaintViews()}}),"proportional"!==this.arcType&&"inView"!==this.arcType&&"partialInView"!==this.arcType||(e=e.concat(Gt.numericDataMenuItems(this.trackView))),this.browser.circularView&&(e.push("
"),e.push({label:"Add interactions to circular view",click:()=>{for(let e of this.trackView.viewports)this.addChordsForViewport(e.referenceFrame)}})),e}contextMenuItemList(e){if(this.browser.circularView){const t=e.viewport,i=[];return i.push({label:"Add interactions to circular view",click:()=>{const e=t.referenceFrame;this.addChordsForViewport(e)}}),i.push("
"),i}}addChordsForViewport(e){const t=("all"===e.chr?this.featureSource.getAllFeatures():this.featureSource.featureCache.queryFeatures(e.chr,e.start,e.end)).filter((e=>e.drawState));if(0===t.length)return;const i=t.map((e=>{const t=e._f||e;return{uniqueId:`${t.chr1}:${t.start1}-${t.end1}_${t.chr2}:${t.start2}-${t.end2}`,refName:kF(t.chr1),start:t.start1,end:t.end1,mate:{refName:kF(t.chr2),start:t.start2,end:t.end2}}}));IF(i,this,e,.5)}doAutoscale(e){let t=0;if(e)for(let i of e){const e=this.valueColumn?i[this.valueColumn]:i.score;Number.isNaN(e)||(t=Math.max(t,e))}return{min:0,max:t}}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){const t=e._||e;if(i.push({name:"Region 1",value:Bv(t.chr1,t.start1,t.end1,t.strand1)}),i.push({name:"Region 2",value:Bv(t.chr2,t.start2,t.end2,t.strand2)}),t.name&&i.push({name:"Name",value:t.name}),void 0!==t.value&&i.push({name:"Value",value:t.value}),void 0!==t.score&&i.push({name:"Score",value:t.score}),t.extras&&this.header&&this.header.columnNames){const e=this.header.columnNames,n=this.header.hiccups?6:10;for(let r=n;r=t-a&&e.canvasX<=t+s+a&&e.canvasY>=n&&e.canvasY<=n+o){const n=-Math.abs(e.canvasX-(t+s/2));i.push({score:n,feature:r});break}}}return i.length>1&&i.sort(((e,t)=>e.score-t.score)),i.map((e=>e.feature))}}function vv(e,t){let i=(e.start1+e.end1)/2,n=(e.start2+e.end2)/2;if("all"===e.chr&&(i=t.getGenomeCoordinate(e.chr1,i),n=t.getGenomeCoordinate(e.chr2,n)),i>n){const e=i;i=n,n=e}return{m1:i,m2:n}}function Bv(e,t,i,n){return n&&"."!==n?`${e}:${Xt(t+1)}-${Xt(i)} (${n})`:`${e}:${Xt(t+1)}-${Xt(i)}`}const yv=new Map;function Cv(e,t){const i=`${e}_${t}`;let n=yv.get(i);return n||(n=Ts.addAlpha(e,t),yv.set(i,n)),n}function _v(e){const t=e=>{const t=Object.assign({},e);return t.chr="all",t.start=i.getGenomeCoordinate(e.chr1,e.start1),t.end=i.getGenomeCoordinate(e.chr2,e.end2),t},i=this.genome;let n,r=0;for(let t of i.wgChromosomeNames){let i=e[t];if(i)for(let e of i)e.dup||(r++,e.score&&(!n||e.score>n.score)&&(n=e))}const s=this.maxWGCount,o=n&&n.score>0&&r>s?5:1,a=Math.floor(s/o),A=n&&n.score>0?Math.log(n.score)/o:Number.MAX_SAFE_INTEGER;let c,l=[],h=[];for(let e=0;ee.name)):[]}return this.header}getCallsetsLength(){return this.callSets?this.callSets.length:0}async getFeatures(e,t,i,n){return void 0===this.header&&(this.header=await this.getHeader()),this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:this.visibilityWindow})}hasSamples(){return this.getCallsetsLength()>0}getSamples(){return{yOffset:this.sampleYOffset,names:this.sampleNames,height:this.sampleHeight}}computePixelHeight(e){if(!e||0==e.length)return 10;const t="COLLAPSED"===this.displayMode?1:this.nVariantRows,i="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,n="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,r="SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight;return 10+t*(n+i)+i+((!1===this.showGenotypes?0:this.getCallsetsLength()*t)+1)*(r+i)}variantRowCount(e){this.nVariantRows=e}draw({context:e,pixelWidth:t,pixelHeight:i,bpPerPixel:n,bpStart:r,pixelTop:s,features:o}){Eo.fillRect(e,0,s,t,i,{fillStyle:"rgb(255, 255, 255)"});const a="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,A="COLLAPSED"===this.displayMode?1:this.nVariantRows,c="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight;this.variantBandHeight=10+A*(c+a);let l=this.callSets;!l&&this._f&&(l=this._f.callSets);const h=this.getCallsetsLength();if(l&&h>0&&!1!==this.showGenotypes&&Eo.strokeLine(e,0,this.variantBandHeight,t,this.variantBandHeight,{strokeStyle:"rgb(224,224,224) "}),o){const i="SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight,s="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,a=r+t*n+1;for(let t of o){if(t.enda)break;const o="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,A=10+("COLLAPSED"===this.displayMode?0:t.row*(o+s)),c=o;let d=Math.round((t.start-r)/n),u=Math.round((t.end-r)/n),f=Math.max(1,u-d);f<3?(f=3,d-=1):f>5&&(d+=1,f-=2),e.fillStyle=this.getColorForFeature(t),e.fillRect(d,A,f,c);let p=this.getVariantStrokecolor(t);if(p&&(e.strokeStyle=p,e.strokeRect(d,A,f,c)),this.callContextHook(t,e,d,A,f,c),t.pixelRect={x:d,y:A,w:f,h:c},h>0&&!1!==this.showGenotypes){const n="COLLAPSED"===this.displayMode?1:this.nVariantRows;this.sampleYOffset=this.variantBandHeight+s,this.sampleHeight=n*(i+s);let r=0;if(l&&t.calls)for(let n of l){const o=t.calls[n.id];if(o){const a="COLLAPSED"===this.displayMode?0:t.row,A=this.sampleYOffset+r*this.sampleHeight+a*(i+s);let c=!0,l=!0,h=!1;if(o.genotype)for(let e of o.genotype){if("."===e){h=!0;break}0!==e&&(l=!1),0===e&&(c=!1)}o.genotype?e.fillStyle=h?this.noCallColor:l?this.homrefColor:c?this.homvarColor:this.hetvarColor:e.fillStyle=this.noGenotypeColor,e.fillRect(d,A,f,i),n.pixelRect={x:d,y:A,w:f,h:i}}r++}}}}else console.log("No feature list")}getColorForFeature(e){const t=e._f||e;let i;if(this.colorBy){const e=this.colorBy;let n;if(t.info.hasOwnProperty(e))n=t.info[e];else if(Ev.has(e)){n=t[Ev.get(e)]}i=this.getVariantColorTable(e).getColor(n),i||(i="gray")}else i=this._color?"function"==typeof this._color?this._color(e):this._color:"NONVARIANT"===t.type?this.nonRefColor:"MIXED"===t.type?this.mixedColor:this.color;return i}getVariantStrokecolor(e){const t=e._f||e;let i;return i=this._strokecolor?"function"==typeof this._strokecolor?this._strokecolor(t):this._strokecolor:void 0,i}callContextHook(e,t,i,n,r,s){if(this._context_hook&&"function"==typeof this._context_hook){const o=e._f||e;t.save(),this._context_hook(o,t,i,n,r,s),t.restore()}}clickedFeatures(e){let t=super.clickedFeatures(e);const i="EXPANDED"===this.displayMode?this.expandedVGap:this.squishedVGap,n=i+("SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight),r=e.y;if(r<=this.variantBandHeight){const e="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,n=Math.floor((r-10)/(e+i));"COLLAPSED"!==this.displayMode&&(t=t.filter((e=>e.row===n)))}else if(this.callSets){const e=this.callSets,i=r-this.variantBandHeight,s=Math.floor(i/this.sampleHeight);if(s>=0&&se.row===r)),a=e[s];t=o.map((e=>{const t=e.calls[a.id];return function(e,t){if(e.genotype){let i="";if("."===t.alternateBases)i="No Call";else{const n=t.alternateBases.split(",");for(let r of e.genotype)if(i.length>0&&(i+="|"),"."===r)i+=".";else if(0===r)i+=t.referenceBases;else{i+=n[r-1].replace("<","<")}}e.genotypeName=i}}(t,e),t}))}}return t}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,n=this.browser.genome.id,r=this.browser.sampleInformation;let s=[];for(let e of t){const t=e._f||e;if(s.length>0&&s.push({html:'
'}),"function"==typeof t.popupData){const e=t.popupData(i,n);Array.prototype.push.apply(s,e)}else{const e=t;if(void 0!==e.callSetName&&s.push({name:"Name",value:e.callSetName}),e.genotypeName&&s.push({name:"Genotype",value:e.genotypeName}),void 0!==e.phaseset&&s.push({name:"Phase set",value:e.phaseset}),void 0!==e.genotypeLikelihood&&s.push({name:"genotypeLikelihood",value:e.genotypeLikelihood.toString()}),r){var o=r.getAttributes(e.callSetName);o&&Object.keys(o).forEach((function(e){var t=e.replace(/([A-Z])/g," $1");t=t.charAt(0).toUpperCase()+t.slice(1),s.push({name:t,value:o[e]})}))}var a=Object.keys(e.info);a.length&&s.push("
"),a.forEach((function(t){s.push({name:t,value:decodeURIComponent(e.info[t])})}))}}return s}menuItemList(){const e=[];if(this.header.INFO&&this.header.INFO){const t=this.header.INFO.SVTYPE?["SVTYPE"]:[];if(this._initColorBy&&"SVTYPE"!==this._initColorBy&&t.push(this._initColorBy),t.length>0){e.push("
");const i=ut('
');i.text("Color by:"),e.push({name:void 0,object:i,click:void 0,init:void 0}),t.sort();for(let i of t){const t=this.colorBy===i,n=i||"None";e.push(this.colorByCB({key:i,label:n},t))}e.push(this.colorByCB({key:void 0,label:"None"},void 0===this.colorBy)),e.push("
")}}this.getCallsetsLength()>0&&(e.push({object:ut('
')}),e.push({object:ut(Kt("Show Genotypes",this.showGenotypes)),click:()=>{this.showGenotypes=!this.showGenotypes,this.trackView.checkContentHeight(),this.trackView.repaintViews()}})),e.push({object:ut('
')});for(let t of["COLLAPSED","SQUISHED","EXPANDED"]){e.push({object:ut(Kt({COLLAPSED:"Collapse",SQUISHED:"Squish",EXPANDED:"Expand"}[t],t===this.displayMode)),click:()=>{this.displayMode=t,this.trackView.checkContentHeight(),this.trackView.repaintViews()}})}return this.browser.circularView&&(e.push("
"),e.push({label:"Add SVs to circular view",click:()=>{for(let e of this.trackView.viewports)this.sendChordsForViewport(e)}})),e}contextMenuItemList(e){if(this.browser.circularView){const t=e.viewport,i=[];return i.push({label:"Add SVs to Circular View",click:()=>{this.sendChordsForViewport(t)}}),i.push("
"),i}}sendChordsForViewport(e){const t=e.referenceFrame;let i;if("all"===t.chr){const e=this.featureSource.getAllFeatures(),t=Object.keys(e).map((t=>e[t]));i=[].concat(...t)}else i=this.featureSource.featureCache.queryFeatures(t.chr,t.start,t.end);const n=(e=>{const t=e.filter((e=>{const t=e._f||e;return t.info&&t.info.CHR2&&t.info.END&&(t.info.CHR2!==t.chr||Math.abs(Number.parseInt(t.info.END)-t.pos)>1e6)}));return t.map((e=>{const t=e._f||e,i=Number.parseInt(t.info.END),n=i-100,r=i+100;return{uniqueId:`${t.chr}:${t.start}-${t.end}_${t.info.CHR2}:${t.info.END}`,refName:kF(t.chr),start:t.start,end:t.end,mate:{refName:kF(t.info.CHR2),start:n,end:r}}}))})(i);IF(n,this,t,.5)}colorByCB(e,t){return{name:void 0,object:ut(Kt(e.label,t)),click:()=>{e.key===this.colorBy?(this.colorBy=void 0,delete this.config.colorBy,this.trackView.repaintViews()):(this.colorBy=e.key,this.config.colorBy=e.key,this.trackView.repaintViews())},init:void 0}}getState(){const e=super.getState();return this._color&&"function"!=typeof this._color&&(e.color=this._color),e}getVariantColorTable(e){if(this.colorTables||(this.colorTables=new Map),!this.colorTables.has(e)){let t;if("SVTYPE"===e)t=Uv;else t=new bo("Set1");this.colorTables.set(e,t)}return this.colorTables.get(e)}}const Uv=new vo({DEL:"#ff2101",INS:"#001888",DUP:"#028401",INV:"#008688",CNV:"#8931ff",BND:"#891100","*":"#002eff"});class Qv extends ag{constructor(e,t){super(e,t)}init(e){super.init(e),this.name=e.name,this.pValueField=e.pValueField||"pValue",this.geneField=e.geneField||"geneSymbol",this.snpField=e.snpField||"snp";const t=e.minLogP||e.min,i=e.maxLogP||e.max;this.dataRange={min:t||3.5,max:i||25},this.autoscale=!i||e.autoscale,this.autoscalePercentile=void 0===e.autoscalePercentile?98:e.autoscalePercentile,this.background=e.background,this.divider=e.divider||"rgb(225,225,225)",this.dotSize=e.dotSize||2,this.height=e.height||100,this.autoHeight=!1,this.disableButtons=e.disableButtons,this.visibilityWindow=void 0===e.visibilityWindow?2e6:e.visibilityWindow>=0?Math.min(2e6,e.visibilityWindow):2e6,this.featureSource=Pw(e,this.browser.genome),SF.gtexLoaded=!0}paintAxis(e,t,i){const n=(this.dataRange.max-this.dataRange.min)/i,r={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};Eo.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"});const s=Math.ceil(10*(this.dataRange.max-this.dataRange.min)/i);for(let o=4;o<=this.dataRange.max;o+=s){const s=.85*t,a=s-5,A=s,c=i-(o-this.dataRange.min)/n;Eo.strokeLine(e,a,c,A,c,r),c>8&&Eo.fillText(e,o,a-1,c+2,r)}r.textAlign="center",Eo.fillText(e,"-log10(pvalue)",t/4,i/2,r,{rotate:{angle:-90}})}async getFeatures(e,t,i){const n=this.pValueField,r=this.visibilityWindow,s=await this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r});return s.forEach((function(e){e.value=e[n]})),s}draw(e){const t=e.context,i=e.pixelWidth,n=e.pixelHeight;this.background&&Eo.fillRect(t,0,0,i,n,{fillStyle:this.background}),Eo.strokeLine(t,0,n-1,i,n-1,{strokeStyle:this.divider});const r=r=>{const s=r?2*this.dotSize:this.dotSize,o=e.bpStart,a=(this.dataRange.max-this.dataRange.min)/n,A=e.referenceFrame.selection;for(let l of e.features){const h=(l.start-o+.5)/e.bpPerPixel;if(h<0)continue;if(h>i)break;const d=l.snp.toUpperCase(),u=l[this.geneField].toUpperCase(),f=A&&(A.snp===d||A.gene===u);if(!r||f){A&&A.snp===d&&A.addGene(u);var c=-Math.log(l[this.pValueField])/Math.LN10;if(c>=this.dataRange.min){let e;c>this.dataRange.max?(c=this.dataRange.max,e=!0):e=!1;const i=Math.max(0+s,n-Math.round((c-this.dataRange.min)/a));let o;l.px=h,l.py=i,l.radius=s,r&&A?(o=A.colorForGene(u),Eo.setProperties(t,{fillStyle:o,strokeStyle:"black"})):(o=e?"rgb(150, 150, 150)":"rgb(180, 180, 180)",Eo.setProperties(t,{fillStyle:o,strokeStyle:o})),Eo.fillCircle(t,h,i,s),Eo.strokeCircle(t,h,i,s)}}}};r(!1),r(!0)}popupData(e,t){if(void 0===t&&(t=e.viewport.cachedFeatures),!t||0===t.length)return[];const i=this.name,n=[];for(let r of t)Math.abs(r.px-e.canvasX)0&&n.push("
"),n.push({name:"snp id",value:r.snp},{name:"gene id",value:r.geneId},{name:"gene name",value:r.geneName},{name:"p value",value:r.pValue},{name:"tissue",value:i}));return n}menuItemList(){return Gt.numericDataMenuItems(this.trackView)}doAutoscale(e){if(e.length>0){var t=e.map((function(e){return-Math.log(e.value)/Math.LN10}));this.dataRange.max=Ms.percentile(t,this.autoscalePercentile)}else{const e=this.config.maxLogP||this.config.max;this.dataRange.max=e||25}return this.dataRange}}const Sv={X:"rgb(204, 153, 0)",Y:"rgb(153, 204, 0)",Un:"darkGray)",1:"rgb(80, 80, 255)",2:"rgb(206, 61, 50)","2a":"rgb(210, 65, 55)","2b":"rgb(215, 70, 60)",3:"rgb(116, 155, 88)",4:"rgb(240, 230, 133)",5:"rgb(70, 105, 131)",6:"rgb(186, 99, 56)",7:"rgb(93, 177, 221)",8:"rgb(128, 34, 104)",9:"rgb(107, 215, 107)",10:"rgb(213, 149, 167)",11:"rgb(146, 72, 34)",12:"rgb(131, 123, 141)",13:"rgb(199, 81, 39)",14:"rgb(213, 143, 92)",15:"rgb(122, 101, 165)",16:"rgb(228, 175, 105)",17:"rgb(59, 27, 83)",18:"rgb(205, 222, 183)",19:"rgb(97, 42, 121)",20:"rgb(174, 31, 99)",21:"rgb(231, 199, 111)",22:"rgb(90, 101, 94)",23:"rgb(204, 153, 0)",24:"rgb(153, 204, 0)",25:"rgb(51, 204, 0)",26:"rgb(0, 204, 51)",27:"rgb(0, 204, 153)",28:"rgb(0, 153, 204)",29:"rgb(10, 71, 255)",30:"rgb(71, 117, 255)",31:"rgb(255, 194, 10)",32:"rgb(255, 209, 71)",33:"rgb(153, 0, 51)",34:"rgb(153, 26, 0)",35:"rgb(153, 102, 0)",36:"rgb(128, 153, 0)",37:"rgb(51, 153, 0)",38:"rgb(0, 153, 26)",39:"rgb(0, 153, 102)",40:"rgb(0, 128, 153)",41:"rgb(0, 51, 153)",42:"rgb(26, 0, 153)",43:"rgb(102, 0, 153)",44:"rgb(153, 0, 128)",45:"rgb(214, 0, 71)",46:"rgb(255, 20, 99)",47:"rgb(0, 214, 143)",48:"rgb(20, 255, 177)"};for(let Nx of Object.keys(Sv)){Sv["chr"+Nx]=Sv[Nx]}for(let Mx=1;Mx<=48;Mx++){if(10===Mx)continue;const Lx=Hv(Mx);Sv[Lx]=Sv[Mx.toString()]}function Hv(e){if(!+e)return!1;for(var t=String(+e).split(""),i=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"],n="",r=3;r--;)n=(i[+t.pop()+10*r]||"")+n;return Array(+t.join("")+1).join("M")+n}class Nv extends ag{constructor(e,t){super(e,t)}init(e){super.init(e),this.useChrColors=void 0===e.useChrColors||e.useChrColors,this.trait=e.trait,this.posteriorProbability=e.posteriorProbability,this.valueProperty="bed"===e.format?"score":"value",this.height=e.height||100,this.autoscale=e.autoscale,this.autoscalePercentile=void 0===e.autoscalePercentile?98:e.autoscalePercentile,this.background=e.background,this.divider=e.divider||"rgb(225,225,225)",this.dotSize=e.dotSize||3,this.popoverWindow=void 0===e.popoverWindow?1e8:e.popoverWindow,this.useChrColors?this.colorScale=new vo(e.colorTable||Sv):e.color?this.colorScale=new Vb(e.color):this.colorScale=new Ob(e.colorScale||{thresholds:[5e-8,5e-4,.5],colors:["rgb(255,50,50)","rgb(251,100,100)","rgb(251,170,170)","rgb(227,238,249)"]}),this.featureSource=Pw(e,this.browser.genome)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),this.autoscale||(this.posteriorProbability?this.dataRange={min:void 0===this.config.min?0:this.config.min,max:void 0===this.config.max?1:this.config.max}:this.dataRange={min:void 0===this.config.min?0:this.config.min,max:void 0===this.config.max?25:this.config.max}),this}get supportsWholeGenome(){return!0}async getFeatures(e,t,i){const n=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:n})}draw(e){const t=e.features,i=e.context,n=e.pixelWidth,r=e.pixelHeight;if(this.background&&Eo.fillRect(i,0,0,n,r,{fillStyle:this.background}),Eo.strokeLine(i,0,r-1,n,r-1,{strokeStyle:this.divider}),t){const s=e.bpPerPixel,o=e.bpStart,a=o+n*s+1;for(let e of t){const t=e.start;if(ta)break;let n;if(this.posteriorProbability)n=e[this.valueProperty];else{const t=e[this.valueProperty];if(!t)continue;n=-Math.log10(t)}const A=this.useChrColors?e._f?e._f.chr:e.chr:n,c=this.colorScale.getColor(A),l=(this.dataRange.max-this.dataRange.min)/r,h=Math.round((t-o)/s),d=Math.max(this.dotSize,r-Math.round((n-this.dataRange.min)/l));c&&Eo.setProperties(i,{fillStyle:c,strokeStyle:"black"}),Eo.fillCircle(i,h,d,this.dotSize),e.px=h,e.py=d}}}paintAxis(e,t,i){Eo.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"});var n={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};const r=(this.dataRange.max-this.dataRange.min)/i;if(this.posteriorProbability){const t=.1;for(let s=this.dataRange.min;s0&&i.push("
"),5==r){i.push("...");break}if("function"==typeof s.popupData)i=i.concat(s.popupData());else{const e=s.realChr||s.chr,t=(s.realStart||s.start)+1;i.push({name:"chromosome",value:e}),i.push({name:"position",value:t}),i.push({name:"name",value:s.name}),n.posteriorProbability?i.push({name:"posterior probability",value:a}):i.push({name:"pValue",value:a})}r++}}}return i}menuItemList(){return Gt.numericDataMenuItems(this.trackView)}doAutoscale(e){if(e.length>0){const t=this.valueProperty,i=this.posteriorProbability,n=e.map((function(e){const n=e[t];return{value:i?n:-Math.log(n)/Math.LN10}}));this.dataRange=nf(n)}else this.posteriorProbability?this.dataRange={min:this.config.min||0,max:this.config.max||1}:this.dataRange={min:this.config.max||25,max:this.config.min||0};return this.dataRange}}class Mv extends ag{constructor(e,t){super(e,t)}init(e){super.init(e),this.autoscale=e.autoscale||void 0===e.max,this.dataRange={min:e.min||0,max:e.max},this.windowFunction=e.windowFunction||"mean",this.paintAxis=Jm,this.graphType=e.graphType||"bar",e._featureSource?(this.featureSource=e._featureSource,delete e._featureSource):this.featureSource=Pw(this.config,this.browser.genome),this.visibilityWindow=-1,this.featureSource.visibilityWindow=this.visibilityWindow}async postInit(){if("function"==typeof this.featureSource.getHeader){if(this.header=await this.featureSource.getHeader(),this.disposed)return;if(this.sampleNames=this.header.columnNames.slice(3),this.setTrackProperties(this.header),this.header.hasOwnProperty("clickToHighlight")){let e=this.header.clickToHighlight;this.config.clickToHighlight=e,this.config.samplesClickedToHighlight={}}if(this.header.hasOwnProperty("highlight")){this.config.highlightSamples={};let e=this.header.highlight;Array.isArray(e)||(e=[e]);for(let t of e){const e=t.split(";");2===e.length&&(this.config.highlightSamples[e[0]]=e[1])}}}}menuItemList(){return Gt.numericDataMenuItems(this.trackView)}async getFeatures(e,t,i){const n=await this.featureSource.getFeatures({chr:e,start:0,end:Number.MAX_SAFE_INTEGER,visibilityWindow:this.visibilityWindow});let r,s;for(let e=1;et&&(r=e-1),void 0===s&&n[e].start>i){s=e+1;break}return void 0===r&&(r=0),void 0===s&&(s=n.length),n.slice(r,s)}draw(e){const{features:t,context:i,bpPerPixel:n,bpStart:r,pixelWidth:s,pixelHeight:o}=e,a=e=>(this.dataRange.max-e)/(this.dataRange.max-this.dataRange.min)*o,A=function(e){let t=Math.floor((e-r)/n);return isNaN(t)&&console.warn("isNaN(x). feature start "+Xt(e)+" bp start "+Xt(r)),t};if(t&&t.length>0&&(void 0===this.dataRange.min&&(this.dataRange.min=0),this.dataRange.max>this.dataRange.min)){const e=this.config.highlightSamples,n=this.config.onlyHandleClicksForHighlightedSamples,r=this.config.clickToHighlight;let s=-1,o={},c=[],l=[];this.clickDetectorCache={};for(let h of t){const t=A(h.start),d=A(h.end),u=s>=0?A(s):t;if(!isNaN(t)&&!isNaN(d)){this.clickDetectorCache[t]=[],this.clickDetectorCache[d]=[];for(let s=0;s=1){const s=o[A],l=a(s),h=e&&e[A];h?c.push([u,l,t,p,h]):r&&A in this.config.samplesClickedToHighlight?c.push([u,l,t,p,this.config.samplesClickedToHighlight[A]]):Eo.strokeLine(i,u,l,t,p,{strokeStyle:"#D9D9D9"}),n&&!(A in e)||this.clickDetectorCache[t].push([u,l,t,p,A,h||"gray"])}if(d-t>=1){const s=e&&e[A];s?l.push([t,p,d,p,s]):r&&A in this.config.samplesClickedToHighlight?l.push([t,p,d,p,this.config.samplesClickedToHighlight[A]]):Eo.strokeLine(i,t,p,d,p,{strokeStyle:"gray"}),n&&!(A in e)||this.clickDetectorCache[d].push([t,p,d,p,A,s||"gray"])}o[A]=f}s=h.end}}for(let e of c)Eo.strokeLine(i,e[0],e[1],e[2],e[3],{strokeStyle:e[4],lineWidth:1.3});for(let e of l)Eo.strokeLine(i,e[0],e[1],e[2],e[3],{strokeStyle:e[4],lineWidth:2})}(e=>{if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=a(t.y),n={strokeStyle:t.color,strokeWidth:2};t.dotted?Eo.dashedLine(e.context,0,i,e.pixelWidth,i,5,n):Eo.strokeLine(e.context,0,i,e.pixelWidth,i,n)}})(e)}doAutoscale(e){let t,i;return e.length>0?(t=Number.MAX_VALUE,i=-Number.MAX_VALUE,e.forEach((function(e){t=Math.min(t,...e.values),i=Math.max(i,...e.values)})),t-=.01,i+=.01):(t=0,i=100),{min:t,max:i}}clickedFeatures(e){const t=e.canvasX,i=e.canvasY;let n=null;for(n of Object.keys(this.clickDetectorCache))if(n=parseInt(n),n>=t)break;if(n){let e=Number.MAX_VALUE,o=[];const a=this.clickDetectorCache[n];for(let n of a){const r=n[0],s=n[2];if(ts)return[];const a=n[1],A=n[3];if(iMath.max(a,A)+10)continue;const c=Lv(t,i,r,a,s,A);c0?A/c:0}class Dv extends ag{constructor(e,t){super(e,t),e.height||(this.height=300),this.arcOrientation=!1,this.theta=Math.PI/2,"bp"===e.format?this.featureSource=new Rv(e,t.genome):this.featureSource=new pw(e,t.genome)}async getFeatures(e,t,i){const n=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:n})}draw(e){const t=e.context,i=Math.PI/2,n=e.pixelWidth,r=e.pixelHeight;e.viewportWidth;const s=e.bpPerPixel,o=e.bpStart,a=s,A=this.arcOrientation;Eo.fillRect(t,0,e.pixelTop,n,r,{fillStyle:"rgb(255, 255, 255)"});const c=e.features;if(c){Tv(c,1);for(let e of c)if(e.startLeft){let n=Math.round((e.startLeft-o)/a),r=Math.round((e.startRight-o)/a),s=Math.round((e.endLeft-o)/a),c=Math.round((e.endRight-o)/a);t.fillStyle=e.color,t.strokeStyle=e.color,t.beginPath();let l=(n+c)/2,h=(c-n)/2,d=this.height,u=Math.PI+(Math.PI/2-i),f=2*Math.PI-(Math.PI/2-i);A?(d=0,t.arc(l,d,h,f,u),t.lineTo(c,d)):(t.arc(l,d,h,u,f),t.lineTo(s,d));const p=(r+s)/2,g=(s-r)/2,w=d;A?(t.arc(p,w,g,u,f,!0),t.lineTo(s,w)):(t.arc(p,w,g,f,u,!0),t.lineTo(n,w)),t.stroke(),t.fill(),e.drawState={x1:l,y1:d,r1:h,x2:p,y2:w,r2:g,sa:u,ea:f}}else{let n=Math.round((e.start-o)/a),r=Math.round((e.end-o)/a);t.strokeStyle=e.color,t.beginPath();let s=(n+r)/2,c=(r-n)/2,l=this.height,h=Math.PI+(Math.PI/2-i),d=2*Math.PI-(Math.PI/2-i);A?(l=0,t.arc(s,l,c,d,h)):t.arc(s,l,c,h,d),t.stroke(),e.drawState={x1:s,y1:l,r1:c,sa:h,ea:d}}}}clickedFeatures(e){const t=super.clickedFeatures(e),i=[];Tv(t,-1);for(let n of t){const t=n.drawState,r=e.canvasX-t.x1,s=e.canvasY-t.y1,o=Math.sqrt(r*r+s*s),a=t.r1+3;let A,c;if(void 0===t.x2)A=o,c=t.r1-3;else{const i=e.canvasX-t.x2,n=e.canvasY-t.y2;A=Math.sqrt(i*i+n*n),c=t.r2-3}if(oc){i.push(n);break}}return i}popupData(e,t){if(void 0===t&&(t=this.clickedFeatures(e)),t&&t.length>0)return this.extractPopupData(t[0],this.getGenomeId())}menuItemList(){var e=this;return[{name:"Toggle arc direction",click:function(){e.arcOrientation=!e.arcOrientation,e.trackView.repaintViews()}}]}}function Tv(e,t){e.sort((function(e,i){const n=void 0===e.score?-Number.MAX_VALUE:e.score,r=void 0===i.score?-Number.MAX_VALUE:i.score;return(void 0===t?1:t)*(n-r)}))}class Rv{constructor(e,t){this.config=e,this.genome=t}async getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:r}){const s=this.genome;if(this.featureCache)return this.featureCache.queryFeatures(e,t,i);{const n=tf(this.config),r=await io.loadString(this.config.url,n);return this.featureCache=new uo(function(e){if(!e)return null;const t=zg(e);let i,n=!0;const r=[],s=[],o=[];for(;void 0!==(i=t.nextLine());){const e=i.split("\t");if(n&&i.startsWith("color:")){const t="rgb("+e[1]+","+e[2]+","+e[3]+")";r.push(t),e.length>4&&s.push(e[4])}else{n=!1;const t=e[0],i=Number.parseInt(e[1])-1,A=Number.parseInt(e[2])-1,c=Number.parseInt(e[3]),l=Number.parseInt(e[4]);var a=Number.parseInt(e[5]);const h=r[a];let d;d=i<=l?{chr:t,startLeft:Math.min(i,A),startRight:Math.max(i,A),endLeft:Math.min(c,l),endRight:Math.max(c,l),color:h,score:a}:{chr:t,startLeft:Math.min(c,l),startRight:Math.max(c,l),endLeft:Math.min(i,A),endRight:Math.max(i,A),color:h,score:a},d.start=d.startLeft,d.end=d.endRight,s.length>a&&(d.description=s[a]),o.push(d)}}return o}(r),s),this.featureCache.queryFeatures(e,t,i)}}}class zv{constructor(e){this.browser=e,this.type="ideogram",this.height=16,this.order=Number.MIN_SAFE_INTEGER,this.disableButtons=!0,this.ignoreTrackMenu=!0}async getFeatures(e,t,i){return[]}computePixelHeight(e){return this.height}draw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:n}){const r=t.chr,s=t.genome.getChromosome(r);if(void 0===s||i<=0||n<=0||"all"===r.toLowerCase())return;!function({ctx:e,chr:t,referenceFrame:i,genome:n,width:r,height:s,stainColors:o}){const a=1,A=.5*a,c=0;if(void 0===n)return;Eo.fillRect(e,0,0,r,s,{fillStyle:Ts.greyScale(255)});const l=n.getCytobands(t);if(l){const t=c+s/2,i=[],n=[];if(0===l.length)return;const h=r/l[l.length-1].end;e.beginPath(),Eo.roundRect(e,A,A+c,r-2*A,s-2*A,(s-2*A)/2,0,1),e.clip();for(let r=0;r0&&c[c.length-1].end&&(A=Math.max(A,c[c.length-1].end),s.bpLength=A),o{Pv.getColor(e)}));const Vv={};class Kv extends ag{constructor(e,t){super(e,t)}init(e){super.init(e),this.type=e.type||"junctions",e._featureSource?(this.featureSource=e._featureSource,delete e._featureSource):this.featureSource=e.featureSource?e.featureSource:Pw(e,this.browser.genome),this.margin=void 0===e.margin?10:e.margin,this.height||(this.height=100),void 0===e.colorByNumReadsThreshold&&(e.colorByNumReadsThreshold=5)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),void 0===this.visibilityWindow&&"function"==typeof this.featureSource.defaultVisibilityWindow&&(this.visibilityWindow=await this.featureSource.defaultVisibilityWindow()),this}get supportsWholeGenome(){return!1}async getFeatures(e,t,i,n){const r=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:r})}computePixelHeight(e){return this.height}draw(e){const t=e.features,i=e.context,n=e.bpPerPixel,r=e.bpStart,s=e.pixelWidth,o=e.pixelHeight,a=r+s*n+1;if(this.config.isMergedTrack||Eo.fillRect(i,0,e.pixelTop,s,o,{fillStyle:"rgb(255, 255, 255)"}),t){Vv.referenceFrame=e.viewport.referenceFrame,Vv.referenceFrameStart=Vv.referenceFrame.start,Vv.referenceFrameEnd=Vv.referenceFrameStart+Vv.referenceFrame.toBP(e.viewport.getWidth()),Vv.featureZoomOutTracker={};for(let e of t)if(!(e.enda)break;this.renderJunction(e,r,n,o,i)}}else console.log("No feature list")}renderJunction(e,t,i,n,r){e.isVisible=!1;const s=Math.round((e.start-t)/i),o=Math.round((e.end-t)/i),a=(s+o)/2;if(o-s<=3){if(a in Vv.featureZoomOutTracker)return;Vv.featureZoomOutTracker[a]=!0}if(this.config.hideAnnotatedJunctions&&"true"===e.attributes.annotated_junction)return;if(this.config.hideUnannotatedJunctions&&"false"===e.attributes.annotated_junction)return;if(this.config.hideMotifs&&this.config.hideMotifs.includes(e.attributes.motif))return;if(this.config.hideStrand===e.strand)return;if(this.config.minJunctionEndsVisible){let t=0;if(e.start>=Vv.referenceFrameStart&&e.start<=Vv.referenceFrameEnd&&(t+=1),e.end>=Vv.referenceFrameStart&&e.end<=Vv.referenceFrameEnd&&(t+=1),t0&&c/l>this.config.maxFractionMultiMappedReads)return;if(e.attributes.maximum_spliced_alignment_overhang&&parseInt(e.attributes.maximum_spliced_alignment_overhang)this.config.maxSamplesWithThisJunction)return;if(e.attributes.num_samples_total&&(e.attributes.percent_samples_with_this_junction=100*h/Number(e.attributes.num_samples_total),this.config.minPercentSamplesWithThisJunction&&(e.attributes.percent_samples_with_this_junctionthis.config.maxPercentSamplesWithThisJunction)))return}const d=this.margin,u=this.height,f=d+.5*u;let p=d;const g=d+u-10,w=(s+a)/2,m=(a+o)/2;let F,b,v=1;e.attributes.line_width?v=Number(e.attributes.line_width):(void 0===this.config.thicknessBasedOn||"numUniqueReads"===this.config.thicknessBasedOn?v=A:"numReads"===this.config.thicknessBasedOn?v=l:"numSamplesWithThisJunction"===this.config.thicknessBasedOn&&void 0!==h&&(v=h),v=1+Math.log(v+1)/Math.log(12)),void 0===this.config.bounceHeightBasedOn||"random"===this.config.bounceHeightBasedOn?F=(e.start+e.end)%7:"distance"===this.config.bounceHeightBasedOn?F=6*(e.end-e.start)/(Vv.referenceFrameEnd-Vv.referenceFrameStart):"thickness"===this.config.bounceHeightBasedOn&&(F=2*v),p+=u*Math.max(7-F,0)/10,b=e.attributes.color?e.attributes.color:void 0===this.config.colorBy||"numUniqueReads"===this.config.colorBy?A>this.config.colorByNumReadsThreshold?"blue":"#AAAAAA":"numReads"===this.config.colorBy?l>this.config.colorByNumReadsThreshold?"blue":"#AAAAAA":"isAnnotatedJunction"===this.config.colorBy?"true"===e.attributes.annotated_junction?"#b0b0ec":"orange":"strand"===this.config.colorBy?"+"===e.strand?"#b0b0ec":"#ecb0b0":"motif"===this.config.colorBy?Pv.getColor(e.attributes.motif):"#AAAAAA";let B="";e.attributes.label?B=e.attributes.label.replace(/_/g," "):void 0===this.config.labelWith||"uniqueReadCount"===this.config.labelWith?B=A:"totalReadCount"===this.config.labelWith?B=l:"numSamplesWithThisJunction"===this.config.labelWith?void 0!==h&&(B=h):"percentSamplesWithThisJunction"===this.config.labelWith?void 0!==e.attributes.percent_samples_with_this_junction&&(B=e.attributes.percent_samples_with_this_junction.toFixed(0)+"%"):"motif"===this.config.labelWith&&void 0!==e.attributes.motif&&(B+=e.attributes.motif),"uniqueReadCount"===this.config.labelWithInParen?B+=" ("+A+")":"totalReadCount"===this.config.labelWithInParen?B+=" ("+l+")":"multiMappedReadCount"===this.config.labelWithInParen?c>0&&(B+=" (+"+c+")"):"numSamplesWithThisJunction"===this.config.labelWithInParen?void 0!==h&&(B+=" ("+h+")"):"percentSamplesWithThisJunction"===this.config.labelWithInParen?void 0!==e.attributes.percent_samples_with_this_junction&&(B+=" ("+e.attributes.percent_samples_with_this_junction.toFixed(0)+"%)"):"motif"===this.config.labelWithInParen&&void 0!==e.attributes.motif&&(B+=` ${e.attributes.motif}`),e.attributes.effect&&(e.attributes.effect.includes("acceptor")?e.attributes.effect.includes("gain")?b="#90EE90":e.attributes.effect.includes("loss")&&(b="#FF7D6A"):e.attributes.effect.includes("donor")&&(e.attributes.effect.includes("gain")?b="#008600":e.attributes.effect.includes("loss")&&(b="#CE0000"))),e.isVisible=!0,r.beginPath(),r.moveTo(s,g),r.bezierCurveTo(w,p,m,p,o,g),r.lineWidth=v,r.strokeStyle=b,r.stroke();const y=(e,t,i,n)=>{e.beginPath(),e.moveTo(t,i),e.lineTo(t-n/2,i-n),e.lineTo(t+n/2,i-n),e.lineTo(t,i),e.closePath(),e.fill()};if(e.attributes.left_shape||e.attributes.right_shape){r.fillStyle=b;const t=r.lineWidth>2?10:7;e.attributes.left_shape&&y(r,s,g,t),e.attributes.right_shape&&y(r,o,g,t)}r.fillText(B,a-r.measureText(B).width/2,(7*p+f)/8)}clickedFeatures(e){return super.clickedFeatures(e).filter((function(e){return e.isVisible&&e.attributes}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,n=[];for(let e of t){const t="function"==typeof e.popupData?e.popupData(i):this.extractPopupData(e._f||e,this.getGenomeId());t&&(n.length>0&&n.push("

"),Array.prototype.push.apply(n,t))}return n}dispose(){this.trackView=void 0}}const Gv="#1fb839",qv="#FFCB1F",jv="#FF0000";class Wv extends ag{constructor(e,t){super(e,t),this.tool=e.tool||"spliceai",this.rawOrDelta=e.rawOrDelta||"delta",this.strand=e.strand||"+",this.paintAxis=this.paintAxisCustom,this.dataRange="delta"===this.rawOrDelta?{min:-1,max:1}:{min:0,max:1}}paintAxisCustom(e,t,i){if(Jm.call(this,e,t,i),e.fillStyle="black",e.font="bold 10pt sans-serif",e.textAlign="center","delta"==this.rawOrDelta){for(const[t,n]of["GAIN","LOSS"].entries())e.save(),e.translate(35,i*(0==t?.25:.75)),e.rotate(-Math.PI/2),e.fillText(n,0,0),e.restore();e.translate(15,.5*i),e.rotate(-Math.PI/2),e.font="12pt sans-serif",e.fillText(`${this.name}: Δ score`,0,0)}else e.translate(15,.5*i),e.rotate(-Math.PI/2),e.font="12pt sans-serif",e.fillText("raw score",0,0)}init(e){super.init(e),this.type=e.type||"spliceprediction",this.margin=void 0===e.margin?10:e.margin,this.height=e.height||100,this.features=e.features||[]}get supportsWholeGenome(){return!0}async getFeatures(e,t,i,n){return this.features.filter((n=>n.chr===e&&n.start<=i&&n.end>=t))}computePixelHeight(e){return this.height}drawLine(e,t,i,n,r,s,o,a){e.lineWidth=s,e.strokeStyle=o,e.beginPath(),e.moveTo(t,i),a?e.setLineDash([3,4]):e.setLineDash([]),e.lineTo(n,r),e.stroke()}drawText(e,t,i,n,r,s,o,a){if(e.fillStyle=r,e.textAlign="center",e.font=o?`bold ${s}pt sans-serif`:`${s}pt sans-serif`,a){e.save(),e.translate(i,n),e.rotate(a);const r=e.measureText(t),s=(r.fontBoundingBoxAscent-r.fontBoundingBoxDescent)/2;e.translate(0,s),e.fillText(t,0,0),e.restore()}else{const r=e.measureText(t),s=(r.fontBoundingBoxAscent-r.fontBoundingBoxDescent)/2;e.fillText(t,i,n+s)}}draw(e){const t=e.context,i=e.pixelWidth,n=e.pixelHeight,r=e.bpStart;this.config.isMergedTrack||Eo.fillRect(t,0,e.pixelTop,i,n,{fillStyle:"rgb(255, 255, 255)"}),"delta"==this.rawOrDelta?this.drawLine(t,0,n/2,i,n/2,.5,"#777777",!1):(this.drawLine(t,0,0,i,0,.5,"#777777",!1),this.drawLine(t,0,n,i,n,.5,"#777777",!1),this.drawLine(t,0,.2*n,i,.2*n,.5,jv,!0),this.drawLine(t,0,.5*n,i,.5*n,.5,qv,!0),this.drawLine(t,0,.8*n,i,.8*n,.5,Gv,!0));const s=.01;if(e.features)for(let t of e.features){const n=r+i*e.bpPerPixel+1;t.endn||("spliceai"==this.tool?(("delta"==this.rawOrDelta&&Math.abs(t.AA-t.RA)>=s||"delta"!=this.rawOrDelta&&(Math.abs(t.AA)>=s||Math.abs(t.RA)>=s))&&this.renderScore(t,e,t.RA,t.AA,"A"),("delta"==this.rawOrDelta&&Math.abs(t.AD-t.RD)>=s||"delta"!=this.rawOrDelta&&(Math.abs(t.AD)>=s||Math.abs(t.RD)>=s))&&this.renderScore(t,e,t.RD,t.AD,"D")):"pangolin"==this.tool&&"delta"==this.rawOrDelta&&(t.SL_ALT-t.SL_REF<=-.01?this.renderScore(t,e,t.SL_REF,t.SL_ALT,"P"):t.SG_ALT-t.SG_REF>=s&&this.renderScore(t,e,t.SG_REF,t.SG_ALT,"P")))}else console.log("No feature list")}renderScore(e,t,i,n,r){const s=n-i,o=t.context,a=t.bpPerPixel,A=t.bpStart,c=t.pixelHeight,l=s<0?-1:1;let h=0;h=l>0?"A"==r?0:-Math.PI/2:"A"==r?Math.PI:Math.PI/2;const d=(e.start-A-.5)/a,u=o.measureText("A"),f=(u.fontBoundingBoxAscent+u.fontBoundingBoxDescent)/2;if("delta"==this.rawOrDelta){let e;e=Math.abs(s)>=.8?jv:Math.abs(s)>=.5?qv:Math.abs(s)>=.2?Gv:"#AAAAAA";const t=c*(1-.65*s)/2,i=Math.max(.5,1/a);this.drawLine(o,d,c/2,d,t,i,e,!1),this.drawText(o,r,d,t-1.5*l*f,"black",10,i>1,h);const n=parseFloat("pangolin"==this.tool?s.toFixed(2):Math.abs(s).toFixed(2));this.drawText(o,n,d,t-2*l*f*2,"black",9,0)}else{const e=[];for(const[t,s]of[n,i].entries()){let n,a=c*(1-s);if(a>c-f&&(a=c-f),a.5?-1:1)*f*2;this.drawText(o,t,d,r,n,9,0),e.push(Math.abs(e[0]-a)=2&&Math.abs(e[0]-e[1])<10;if(1==t&&!A){const t=1;this.drawLine(o,d,Math.min(e[0],e[1])+1.3*f,d,Math.max(e[0],e[1])-1.3*f,t,n,!0)}this.drawText(o,r,d+(1==t&&A?2:0),a,n,10,!0,h)}}}clickedFeatures(e){return super.clickedFeatures(e).filter((function(e){return e.isVisible&&e.attributes}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,n=[];for(let e of t){const t="function"==typeof e.popupData?e.popupData(i):this.extractPopupData(e._f||e,this.getGenomeId());t&&(n.length>0&&n.push("

"),Array.prototype.push.apply(n,t))}return n}dispose(){this.trackView=void 0}}class $v{constructor(e){var t;this.config=e,this.url=(t=e.path||e.url).includes("//www.dropbox.com")?t.replace("//www.dropbox.com","//dl.dropboxusercontent.com"):t.startsWith("ftp://ftp.ncbi.nlm.nih.gov")?t.replace("ftp://","https://"):t}async read(e,t){const i=this.config.headers||{};if(void 0!==e&&t){const n="bytes="+e+"-"+(e+t-1);i.Range=n}let n=this.url.slice();if(this.config.oauthToken){const e=async function(e){return"function"==typeof e?await Promise.resolve(e()):e}(this.config.oauthToken);i.Authorization=`Bearer ${e}`}this.config.apiKey&&(n=function(e,t,i){const n=e.includes("?")?"&":"?";return e+n+t+"="+i}(n,"key",this.config.apiKey));const r=await fetch(n,{method:"GET",headers:i,redirect:"follow",mode:"cors"}),s=r.status;if(s>=400){const e=Error(r.statusText);throw e.code=s,e}return r.arrayBuffer()}}class Xv{constructor(e){this.file=e.file,this.fetchSize=e.fetchSize||16e3,this.maxSize=e.maxSize||1e6,this.buffers=[]}async read(e,t){let i=this.buffers.filter((i=>i.overlaps(e,e+t)));for(let n of i)if(n.contains(e,e+t))return n.slice(e,e+t);if(0===i.length){let i=Math.max(t,this.fetchSize);this.buffers.sort(((e,t)=>e.start-t.start));const n=function(e,t,i){let n=i-1,r=e.length;for(;1+n>1);t(e[i])?r=i:n=i}return r}(this.buffers,(t=>t.start>e),0);ne.start-t.start));const n=[];let r=e;for(let e of i){if(rr){const e=r,t=s-e,i=await this.file.read(e,t),o=new Zv(e,i);n.push(o)}const o=n[0].start,a=function(e){const t=e.reduce(((e,t)=>e+t.byteLength),0),i=new Uint8Array(t);let n=0;for(let t of e)i.set(new Uint8Array(t),n),n+=t.byteLength;return i.buffer}(n.map((e=>e.buffer))),A=new Zv(o,a),c=new Set(i);return this.buffers=this.buffers.filter((e=>!c.has(e))),this.addBuffer(A),A.slice(e,e+t)}}addBuffer(e){const t=this.buffers.reduce(((e,t)=>e+t.size),0)+e.size;if(t>this.maxSize){const e=t-this.maxSize;this.buffers.sort(((e,t)=>e.creationTime-t.creationTime));let i,n=0;for(i=0;ie));i++);this.buffers=ithis.buffer.byteLength)throw Error("buffer bounds error");return this.buffer.slice(e-this.start,t-this.start)}get end(){return this.start+this.buffer.byteLength}get size(){return this.buffer.byteLength}contains(e,t){return e>=this.start&&t<=this.end}overlaps(e,t){return e>this.start&&ethis.start&&t=!@]?(i|u|f)(\d*)/);i=parseInt(s||4,10),t="get"+rB[r]+(8*i).toFixed()}return[t,n,i]}var oB=new class{constructor(){this.big_endian=function(){const e=new Uint8Array(4);return!((new Uint32Array(e.buffer)[0]=1)&e[0])}(),this.getters={s:"getUint8",b:"getInt8",B:"getUint8",h:"getInt16",H:"getUint16",i:"getInt32",I:"getUint32",l:"getInt32",L:"getUint32",q:"getInt64",Q:"getUint64",f:"getFloat32",d:"getFloat64"},this.byte_lengths={s:1,b:1,B:1,h:2,H:2,i:4,I:4,l:4,L:4,q:8,Q:8,f:4,d:8};let e=Object.keys(this.byte_lengths).join("");this.fmt_size_regex="(\\d*)(["+e+"])"}calcsize(e){for(var t,i=0,n=new RegExp(this.fmt_size_regex,"g");null!==(t=n.exec(e));){let e=parseInt(t[1]||1,10),n=t[2];i+=e*this.byte_lengths[n]}return i}_is_big_endian(e){return!/^)/.test(e)||this.big_endian)}async unpack_from_async(e,t,i){i=Number(i||0);const n=this.calcsize(e),r=await t.slice(i,i+n);let s=0;for(var o,a=new aB(r),A=[],c=this._is_big_endian(e),l=new RegExp(this.fmt_size_regex,"g");null!==(o=l.exec(e));){let e=parseInt(o[1]||1,10),t=o[2],i=this.getters[t],n=this.byte_lengths[t];if("s"==t)A.push((new TextDecoder).decode(r.slice(s,s+e))),s+=e;else for(var h=0;he+(t<<8*i)),0);return o}var lB=class{constructor(e,t){this.buf=e,this.offset=t,this.dtype=this.determine_dtype()}async determine_dtype(){let e=await Yv(hB,this.buf,this.offset);this.offset+=dB;let t=15&e.get("class_and_version");if(t==uB)return this._determine_dtype_fixed_point(e);if(t==fB)return this._determine_dtype_floating_point(e);if(t==pB)throw"Time datatype class not supported.";if(t==gB)return this._determine_dtype_string(e);if(t==wB)throw"Bitfield datatype class not supported.";if(t==mB)return{datatype_class:mB,size:e.get("size")};if(t==FB)return this._determine_dtype_compound(e);if(t==bB)return["REFERENCE",e.get("size")];if(t==vB)return this.determine_dtype();if(t==yB)throw"Array datatype class not supported.";if(t==BB){let t=this._determine_dtype_vlen(e);if("VLEN_SEQUENCE"==t[0]){t=["VLEN_SEQUENCE",this.determine_dtype()]}return t}throw"Invalid datatype class "+t}_determine_dtype_fixed_point(e){let t=e.get("size");if(![1,2,4,8].includes(t))throw"Unsupported datatype size";var i;var n;return i=(8&e.get("class_bit_field_0"))>0?"i":"u",n=0==(1&e.get("class_bit_field_0"))?"<":">",this.offset+=4,n+i+t.toFixed()}_determine_dtype_floating_point(e){let t=e.get("size");if(![1,2,4,8].includes(t))throw"Unsupported datatype size";var i;return i=0==(1&e.get("class_bit_field_0"))?"<":">",this.offset+=12,i+"f"+t.toFixed()}_determine_dtype_string(e){return"S"+e.get("size").toFixed()}_determine_dtype_vlen(e){return 1!=(1&e.get("class_bit_field_0"))?["VLEN_SEQUENCE",0,0]:["VLEN_STRING",e.get("class_bit_field_0")>>4,1&e.get("class_bit_field_1")]}_determine_dtype_compound(e){throw"Compound type not yet implemented!"}},hB=new Map([["class_and_version","B"],["class_bit_field_0","B"],["class_bit_field_1","B"],["class_bit_field_2","B"],["size","I"]]),dB=iB(hB);iB(new Map([["offset","I"],["dimensionality","B"],["reserved_0","B"],["reserved_1","B"],["reserved_2","B"],["permutation","I"],["reserved_3","I"],["dim_size_1","I"],["dim_size_2","I"],["dim_size_3","I"],["dim_size_4","I"]]));var uB=0,fB=1,pB=2,gB=3,wB=4,mB=5,FB=6,bB=7,vB=8,BB=9,yB=10;function CB(e){let t=e.length;for(;--t>=0;)e[t]=0}CB(new Array(576)),CB(new Array(60)),CB(new Array(512)),CB(new Array(256)),CB(new Array(29)),CB(new Array(30));var _B=(e,t,i,n)=>{let r=65535&e|0,s=e>>>16&65535|0,o=0;for(;0!==i;){o=i>2e3?2e3:i,i-=o;do{r=r+t[n++]|0,s=s+r|0}while(--o);r%=65521,s%=65521}return r|s<<16|0},xB=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})()),kB=(e,t,i,n)=>{const r=xB,s=n+i;e^=-1;for(let i=n;i>>8^r[255&(e^t[i])];return-1^e},EB={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},IB={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},UB=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),QB={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)UB(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i=252?6:Tx>=248?5:Tx>=240?4:Tx>=224?3:Tx>=192?2:1;HB[254]=HB[254]=1;var NB={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,r,s,o=e.length,a=0;for(r=0;r>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let n,r;const s=new Array(2*i);for(r=0,n=0;n4)s[r++]=65533,n+=o-1;else{for(t&=2===o?31:3===o?15:7;o>1&&n1?s[r++]=65533:t<65536?s[r++]=t:(t-=65536,s[r++]=55296|t>>10&1023,s[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&SB)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+HB[e[i]]>t?i:t}};var MB=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},LB=function(e,t){let i,n,r,s,o,a,A,c,l,h,d,u,f,p,g,w,m,F,b,v,B,y,C,_;const x=e.state;i=e.next_in,C=e.input,n=i+(e.avail_in-5),r=e.next_out,_=e.output,s=r-(t-e.avail_out),o=r+(e.avail_out-257),a=x.dmax,A=x.wsize,c=x.whave,l=x.wnext,h=x.window,d=x.hold,u=x.bits,f=x.lencode,p=x.distcode,g=(1<>>24,d>>>=F,u-=F,F=m>>>16&255,0===F)_[r++]=65535&m;else{if(!(16&F)){if(0==(64&F)){m=f[(65535&m)+(d&(1<>>=F,u-=F),u<15&&(d+=C[i++]<>>24,d>>>=F,u-=F,F=m>>>16&255,!(16&F)){if(0==(64&F)){m=p[(65535&m)+(d&(1<a){e.msg="invalid distance too far back",x.mode=30;break e}if(d>>>=F,u-=F,F=r-s,v>F){if(F=v-F,F>c&&x.sane){e.msg="invalid distance too far back",x.mode=30;break e}if(B=0,y=h,0===l){if(B+=A-F,F2;)_[r++]=y[B++],_[r++]=y[B++],_[r++]=y[B++],b-=3;b&&(_[r++]=y[B++],b>1&&(_[r++]=y[B++]))}else{B=r-v;do{_[r++]=_[B++],_[r++]=_[B++],_[r++]=_[B++],b-=3}while(b>2);b&&(_[r++]=_[B++],b>1&&(_[r++]=_[B++]))}break}}break}}while(i>3,i-=b,u-=b<<3,d&=(1<{const A=a.bits;let c,l,h,d,u,f,p=0,g=0,w=0,m=0,F=0,b=0,v=0,B=0,y=0,C=0,_=null,x=0;const k=new Uint16Array(16),E=new Uint16Array(16);let I,U,Q,S=null,H=0;for(p=0;p<=DB;p++)k[p]=0;for(g=0;g=1&&0===k[m];m--);if(F>m&&(F=m),0===m)return r[s++]=20971520,r[s++]=20971520,a.bits=1,0;for(w=1;w0&&(0===e||1!==m))return-1;for(E[1]=0,p=1;p852||2===e&&y>592)return 1;for(;;){I=p-v,o[g]f?(U=S[H+o[g]],Q=_[x+o[g]]):(U=96,Q=0),c=1<>v)+l]=I<<24|U<<16|Q|0}while(0!==l);for(c=1<>=1;if(0!==c?(C&=c-1,C+=c):C=0,g++,0==--k[p]){if(p===m)break;p=t[i+o[g]]}if(p>F&&(C&d)!==h){for(0===v&&(v=F),u+=w,b=p-v,B=1<852||2===e&&y>592)return 1;h=C&d,r[h]=F<<24|b<<16|u-s|0}}return 0!==C&&(r[u+C]=p-v<<24|64<<16|0),a.bits=F,0},{Z_FINISH:VB,Z_BLOCK:KB,Z_TREES:GB,Z_OK:qB,Z_STREAM_END:jB,Z_NEED_DICT:WB,Z_STREAM_ERROR:$B,Z_DATA_ERROR:XB,Z_MEM_ERROR:ZB,Z_BUF_ERROR:JB,Z_DEFLATED:YB}=IB,ey=12,ty=30,iy=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function ny(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var ry,sy,oy=e=>{if(!e||!e.state)return $B;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,qB},ay=e=>{if(!e||!e.state)return $B;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,oy(e)},Ay=(e,t)=>{let i;if(!e||!e.state)return $B;const n=e.state;return t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?$B:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,ay(e))},cy=(e,t)=>{if(!e)return $B;const i=new ny;e.state=i,i.window=null;const n=Ay(e,t);return n!==qB&&(e.state=null),n},ly=!0,hy=e=>{if(ly){ry=new Int32Array(512),sy=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(PB(1,e.lens,0,288,ry,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;PB(2,e.lens,0,32,sy,0,e.work,{bits:5}),ly=!1}e.lencode=ry,e.lenbits=9,e.distcode=sy,e.distbits=5},dy=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave{let i,n,r,s,o,a,A,c,l,h,d,u,f,p,g,w,m,F,b,v,B,y,C=0;const _=new Uint8Array(4);let x,k;const E=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return $B;i=e.state,i.mode===ey&&(i.mode=13),o=e.next_out,r=e.output,A=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,c=i.hold,l=i.bits,h=a,d=A,y=qB;e:for(;;)switch(i.mode){case 1:if(0===i.wrap){i.mode=13;break}for(;l<16;){if(0===a)break e;a--,c+=n[s++]<>>8&255,i.check=kB(i.check,_,2,0),c=0,l=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&c)<<8)+(c>>8))%31){e.msg="incorrect header check",i.mode=ty;break}if((15&c)!==YB){e.msg="unknown compression method",i.mode=ty;break}if(c>>>=4,l-=4,B=8+(15&c),0===i.wbits)i.wbits=B;else if(B>i.wbits){e.msg="invalid window size",i.mode=ty;break}i.dmax=1<>8&1),512&i.flags&&(_[0]=255&c,_[1]=c>>>8&255,i.check=kB(i.check,_,2,0)),c=0,l=0,i.mode=3;case 3:for(;l<32;){if(0===a)break e;a--,c+=n[s++]<>>8&255,_[2]=c>>>16&255,_[3]=c>>>24&255,i.check=kB(i.check,_,4,0)),c=0,l=0,i.mode=4;case 4:for(;l<16;){if(0===a)break e;a--,c+=n[s++]<>8),512&i.flags&&(_[0]=255&c,_[1]=c>>>8&255,i.check=kB(i.check,_,2,0)),c=0,l=0,i.mode=5;case 5:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,c+=n[s++]<>>8&255,i.check=kB(i.check,_,2,0)),c=0,l=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(u=i.length,u>a&&(u=a),u&&(i.head&&(B=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(s,s+u),B)),512&i.flags&&(i.check=kB(i.check,n,u,s)),a-=u,s+=u,i.length-=u),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===a)break e;u=0;do{B=n[s+u++],i.head&&B&&i.length<65536&&(i.head.name+=String.fromCharCode(B))}while(B&&u>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=ey;break;case 10:for(;l<32;){if(0===a)break e;a--,c+=n[s++]<>>=7&l,l-=7&l,i.mode=27;break}for(;l<3;){if(0===a)break e;a--,c+=n[s++]<>>=1,l-=1,3&c){case 0:i.mode=14;break;case 1:if(hy(i),i.mode=20,t===GB){c>>>=2,l-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=ty}c>>>=2,l-=2;break;case 14:for(c>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,c+=n[s++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=ty;break}if(i.length=65535&c,c=0,l=0,i.mode=15,t===GB)break e;case 15:i.mode=16;case 16:if(u=i.length,u){if(u>a&&(u=a),u>A&&(u=A),0===u)break e;r.set(n.subarray(s,s+u),o),a-=u,s+=u,A-=u,o+=u,i.length-=u;break}i.mode=ey;break;case 17:for(;l<14;){if(0===a)break e;a--,c+=n[s++]<>>=5,l-=5,i.ndist=1+(31&c),c>>>=5,l-=5,i.ncode=4+(15&c),c>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=ty;break}i.have=0,i.mode=18;case 18:for(;i.have>>=3,l-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,x={bits:i.lenbits},y=PB(0,i.lens,0,19,i.lencode,0,i.work,x),i.lenbits=x.bits,y){e.msg="invalid code lengths set",i.mode=ty;break}i.have=0,i.mode=19;case 19:for(;i.have>>24,w=C>>>16&255,m=65535&C,!(g<=l);){if(0===a)break e;a--,c+=n[s++]<>>=g,l-=g,i.lens[i.have++]=m;else{if(16===m){for(k=g+2;l>>=g,l-=g,0===i.have){e.msg="invalid bit length repeat",i.mode=ty;break}B=i.lens[i.have-1],u=3+(3&c),c>>>=2,l-=2}else if(17===m){for(k=g+3;l>>=g,l-=g,B=0,u=3+(7&c),c>>>=3,l-=3}else{for(k=g+7;l>>=g,l-=g,B=0,u=11+(127&c),c>>>=7,l-=7}if(i.have+u>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=ty;break}for(;u--;)i.lens[i.have++]=B}}if(i.mode===ty)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=ty;break}if(i.lenbits=9,x={bits:i.lenbits},y=PB(1,i.lens,0,i.nlen,i.lencode,0,i.work,x),i.lenbits=x.bits,y){e.msg="invalid literal/lengths set",i.mode=ty;break}if(i.distbits=6,i.distcode=i.distdyn,x={bits:i.distbits},y=PB(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,x),i.distbits=x.bits,y){e.msg="invalid distances set",i.mode=ty;break}if(i.mode=20,t===GB)break e;case 20:i.mode=21;case 21:if(a>=6&&A>=258){e.next_out=o,e.avail_out=A,e.next_in=s,e.avail_in=a,i.hold=c,i.bits=l,LB(e,d),o=e.next_out,r=e.output,A=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,c=i.hold,l=i.bits,i.mode===ey&&(i.back=-1);break}for(i.back=0;C=i.lencode[c&(1<>>24,w=C>>>16&255,m=65535&C,!(g<=l);){if(0===a)break e;a--,c+=n[s++]<>F)],g=C>>>24,w=C>>>16&255,m=65535&C,!(F+g<=l);){if(0===a)break e;a--,c+=n[s++]<>>=F,l-=F,i.back+=F}if(c>>>=g,l-=g,i.back+=g,i.length=m,0===w){i.mode=26;break}if(32&w){i.back=-1,i.mode=ey;break}if(64&w){e.msg="invalid literal/length code",i.mode=ty;break}i.extra=15&w,i.mode=22;case 22:if(i.extra){for(k=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;C=i.distcode[c&(1<>>24,w=C>>>16&255,m=65535&C,!(g<=l);){if(0===a)break e;a--,c+=n[s++]<>F)],g=C>>>24,w=C>>>16&255,m=65535&C,!(F+g<=l);){if(0===a)break e;a--,c+=n[s++]<>>=F,l-=F,i.back+=F}if(c>>>=g,l-=g,i.back+=g,64&w){e.msg="invalid distance code",i.mode=ty;break}i.offset=m,i.extra=15&w,i.mode=24;case 24:if(i.extra){for(k=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=ty;break}i.mode=25;case 25:if(0===A)break e;if(u=d-A,i.offset>u){if(u=i.offset-u,u>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=ty;break}u>i.wnext?(u-=i.wnext,f=i.wsize-u):f=i.wnext-u,u>i.length&&(u=i.length),p=i.window}else p=r,f=o-i.offset,u=i.length;u>A&&(u=A),A-=u,i.length-=u;do{r[o++]=p[f++]}while(--u);0===i.length&&(i.mode=21);break;case 26:if(0===A)break e;r[o++]=i.length,A--,i.mode=21;break;case 27:if(i.wrap){for(;l<32;){if(0===a)break e;a--,c|=n[s++]<cy(e,15),inflateInit2:cy,inflate:uy,inflateEnd:e=>{if(!e||!e.state)return $B;let t=e.state;return t.window&&(t.window=null),e.state=null,qB},inflateGetHeader:(e,t)=>{if(!e||!e.state)return $B;const i=e.state;return 0==(2&i.wrap)?$B:(i.head=t,t.done=!1,qB)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return e&&e.state?(n=e.state,0!==n.wrap&&11!==n.mode?$B:11===n.mode&&(r=1,r=_B(r,t,i,0),r!==n.check)?XB:(s=dy(e,t,i,i),s?(n.mode=31,ZB):(n.havedict=1,qB))):$B},inflateInfo:"pako inflate (from Nodeca project)"};var py=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1},gy=Object.prototype.toString,{Z_NO_FLUSH:wy,Z_FINISH:my,Z_OK:Fy,Z_STREAM_END:by,Z_NEED_DICT:vy,Z_STREAM_ERROR:By,Z_DATA_ERROR:yy,Z_MEM_ERROR:Cy}=IB;function _y(e){this.options=QB.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new MB,this.strm.avail_out=0;let i=fy.inflateInit2(this.strm,t.windowBits);if(i!==Fy)throw new Error(EB[i]);if(this.header=new py,fy.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=NB.string2buf(t.dictionary):"[object ArrayBuffer]"===gy.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=fy.inflateSetDictionary(this.strm,t.dictionary),i!==Fy)))throw new Error(EB[i])}function xy(e,t){const i=new _y(t);if(i.push(e),i.err)throw i.msg||EB[i.err];return i.result}_y.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,o,a;if(this.ended)return!1;for(o=t===~~t?t:!0===t?my:wy,"[object ArrayBuffer]"===gy.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),s=fy.inflate(i,o),s===vy&&r&&(s=fy.inflateSetDictionary(i,r),s===Fy?s=fy.inflate(i,o):s===yy&&(s=vy));i.avail_in>0&&s===by&&i.state.wrap>0&&0!==e[i.next_in];)fy.inflateReset(i),s=fy.inflate(i,o);switch(s){case By:case yy:case vy:case Cy:return this.onEnd(s),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||s===by))if("string"===this.options.to){let e=NB.utf8border(i.output,i.next_out),t=i.next_out-e,r=NB.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==Fy||0!==a){if(s===by)return s=fy.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},_y.prototype.onData=function(e){this.chunks.push(e)},_y.prototype.onEnd=function(e){e===Fy&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=QB.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ky=function(e,t){return(t=t||{}).raw=!0,xy(e,t)},Ey={Inflate:_y,inflate:xy,inflateRaw:ky,ungzip:xy,constants:IB},{Inflate:Iy,inflate:Uy,inflateRaw:Qy,ungzip:Sy}=Ey,Hy=Uy,Ny=Sy;var My=new Map([[1,function(e,t){let i=new Uint8Array(e);return Hy(i).buffer}],[2,function(e,t){let i=e.byteLength,n=new Uint8Array(i),r=Math.floor(i/t),s=new DataView(e);for(var o=0;oHH",e,i);if(A%=65535,r!=(a%=65535)||s!=A)throw'ValueError("fletcher32 checksum invalid")'}(e),e.slice(0,-4)}]]),Ly=class{constructor(e,t){this.fh=e,this.offset=t,this.depth=null}async init(){this.all_nodes=new Map,await this._read_root_node(),await this._read_children()}async _read_children(){let e=this.depth;for(;e>0;){for(var t of this.all_nodes.get(e))for(var i of t.get("addresses"))this._add_node(await this._read_node(i,e-1));e--}}async _read_root_node(){let e=await this._read_node(this.offset,null);this._add_node(e),this.depth=e.get("node_level")}_add_node(e){let t=e.get("node_level");this.all_nodes.has(t)?this.all_nodes.get(t).push(e):this.all_nodes.set(t,[e])}async _read_node(e,t){let i=await this._read_node_header(e,t);return i.set("keys",[]),i.set("addresses",[]),i}async _read_node_header(e){throw"NotImplementedError: must define _read_node_header in implementation class"}},Dy=class extends Ly{B_LINK_NODE=new Map([["signature","4s"],["node_type","B"],["node_level","B"],["entries_used","H"],["left_sibling","Q"],["right_sibling","Q"]]);async _read_node_header(e,t){let i=await Yv(this.B_LINK_NODE,this.fh,e);if(null!=t&&i.get("node_level")!=t)throw"node level does not match";return i}},Ty=class extends Dy{NODE_TYPE=0;constructor(e,t){super(e,t),this.ready=this.init()}async _read_node(e,t){let i=await this._read_node_header(e,t);e+=iB(this.B_LINK_NODE);let n=[],r=[],s=i.get("entries_used");for(var o=0;o=0&&F[B]>=e[B];B--)F[B]=0,m[B]=w[B],B>0&&(F[B-1]+=1,m[B-1]+=1);if(m.slice(0,-1).every((function(e,i){return e=0;o--){if(t&1<0?r*=n:r=n}}return s}_nrecords_max(e,t,i){return Math.floor((e-10-i)/(t+i))}_required_bytes(e){return Math.ceil(AB(e)/8)}_int_format(e){return["0&&(l=(await oB.unpack_from_async(a,this.fh,i))[0],i+=r),A.push([n,c,l])}}return s.set("keys",a),s.set("addresses",A),s}async _read_node_header(e,t){let i=await Yv(this.B_LINK_NODE,this.fh,e);return i.set("node_level",t),i}*iter_records(){for(let e of this.all_nodes.values())for(let t of e)for(let e of t.get("keys"))yield e}_parse_record(e){throw"NotImplementedError"}},Oy=class extends zy{NODE_TYPE=5;async _parse_record(e,t,i){let n=(await oB.unpack_from_async("this._chunks))}get shape(){let e=this.find_msg_type(HC)[0].get("offset_to_message");return async function(e,t){let i=(await oB.unpack_from_async("255&&(s=(await oB.unpack_from_async("0;e.set("optional",a);let A,c=(await oB.unpack_from_async("0&&(A=(await oB.unpack_from_async(`${s}s`,i,t))[0],t+=s),e.set("name",A);let l=await oB.unpack_from_async(`<${c}i`,i,t);t+=4*c,e.set("client_data_values",l),r.push(e)}}return this._filter_pipeline=r,this._filter_pipeline}find_msg_type(e){return this.msgs.filter((function(t){return t.get("type")==e}))}async get_attributes(){let e={},t=this.find_msg_type(zC);for(let i of t){let t=i.get("offset_to_message"),[n,r]=await this.unpack_attribute(t);e[n]=r}return e}async get_fillvalue(){var e,t=this.find_msg_type(LC)[0].get("offset_to_message");let i=(await oB.unpack_from_async("=r&&([s,r]=a[++A],c=0);let t=await Yv(bC,e,s+c),i=s+c+vC;if(t.set("offset_to_message",i),t.get("type")==OC){var[d,u]=await oB.unpack_from_async("=o-yC){let e=A[++c];if(null==e)break;[r,o]=e,l=0}let t=await Yv(BC,e,r+l),i=r+l+yC+n;if(t.set("offset_to_message",i),t.get("type")==OC){var[h,d]=await oB.unpack_from_async("0,A=(4&n)>0;(8&n)>0?(r=(await oB.unpack_from_async("0)throw"Filter info size not supported on FractalHeap";if(t.get("btree_address_huge_objects")!=qy)throw"Huge objects not implemented in FractalHeap";t.set("btree_address_huge_objects",null),t.get("root_block_address")==qy&&t.set("root_block_address",null);let i=t.get("log2_maximum_heap_size"),n=this._min_size_nbits(i),r=new Map([["signature","4s"],["version","B"],["heap_header_adddress","Q"],["block_offset",`${n}B`]]);this.indirect_block_header=new Map(r),this.indirect_block_header_size=iB(r),2==(2&t.get("flags"))&&r.set("checksum","I"),this.direct_block_header=r,this.direct_block_header_size=iB(r);let s=t.get("maximum_direct_block_size");this._managed_object_offset_size=this._min_size_nbits(i);let o=Math.min(s,t.get("max_managed_object_size"));this._managed_object_length_size=this._min_size_integer(o);let a=t.get("starting_block_size"),A=t.get("table_width");if(!(a>0))throw"Starting block size == 0 not implemented";let c=Number(Math.floor(Math.log2(s)));tB(1n<0)for await(let e of this._iter_indirect_block(this.fh,u,f))d.push(e);else{let e=await this._read_direct_block(this.fh,u,a);d.push(e)}let p=d.reduce(((e,t)=>e+t.byteLength),0),g=new Uint8Array(p),w=0;d.forEach((e=>{g.set(new Uint8Array(e),w),w+=e.byteLength})),this.managed=g.buffer}async _read_direct_block(e,t,i){let n=await e.slice(t,t+i);return tB("FHDB"==eB(this.direct_block_header,n).get("signature")),n}get_data(e){let t=oB.unpack_from(">4&3,n=1;if(0==i){tB(0==t>>6);let i=this._managed_object_offset_size,r=cB(i,e,n);n+=i,i=this._managed_object_length_size;let s=cB(i,e,n);return this.managed.slice(r,r+s)}throw 1==i?"tiny objectID not supported in FractalHeap":2==i?"huge objectID not supported in FractalHeap":"unknown objectID type in FractalHeap"}_min_size_integer(e){return this._min_size_nbits(AB(e))}_min_size_nbits(e){return Math.ceil(e/8)}async*_iter_indirect_block(e,t,i){let n=await Yv(this.indirect_block_header,e,t);t+=this.indirect_block_header_size,tB("FHIB"==n.get("signature"));let r=n.get("block_offset").reduce(((e,t,i)=>e+(t<<8*i)),0);n.set("block_offset",r);let[s,o]=this._indirect_info(i),a=[];for(let i=0;i0&&(t+=8);let r=(2&n)>0?xC:_C,s=await Yv(r,e,t),o=new Map;for(let[e,t]of s.entries())o.set(e,t==AC?null:t);return o}get is_dataset(){return this.find_msg_type(HC).length>0}async get_data(){let e=this.find_msg_type(TC)[0].get("offset_to_message");var[t,i,n,r]=await this._get_data_message_properties(e);if(0==n)throw"Compact storage of DataObject not implemented";return 1==n?this._get_contiguous_data(r):2==n?this._get_chunked_data(e):void 0}async _get_data_message_properties(e){let t,i,n,[r,s,o]=await oB.unpack_from_async("=1&&r<=4),[r,t,i,n]}async _get_contiguous_data(e){let[t]=await oB.unpack_from_async("=!@\|]?(i|u|f|S)(\d*)/.test(n)){let[e,i,s]=sB(n),a=new Array(r);const A=await this.fh.slice(t,t+s*r);let c=new aB(A);for(var o=0;o=1&&t<=3);var a="<"+(i-1).toFixed()+"I",A=await oB.unpack_from_async(a,this.fh,s);this._chunks=A,this._chunk_dims=i,this._chunk_address=o}}}};var AC=oB.unpack_from("this.get(e)))}length(){return this.keys.length}_dereference(e){if(!e)throw"cannot deference null reference";let t=this.file._get_object_by_address(e);if(null==t)throw"reference not found in file";return t}async get(e){if("number"==typeof e)return this._dereference(e);var t=qC(e);if("/"==t)return this.file;if("."==t)return this;if(/^\//.test(t))return this.file.get(t.slice(1));if(""!=function(e){let t="/",i=e.lastIndexOf(t)+1,n=e.slice(0,i),r=new RegExp("^"+t+"+$"),s=new RegExp(t+"$");n&&!r.test(n)&&(n=n.replace(s,""));return n}(t))var[i,n]=t.split(/\/(.*)/);else var i=t,n=".";if(!(i in this._links))throw i+" not found in group";var r=qC(this.name+"/"+i);let s=this._links[i];if("string"==typeof s)try{return this.get(s)}catch(e){return null}var o=new aC(this.file._fh,s);if(await o.ready,o.is_dataset){if("."!=n)throw r+" is a dataset, not a group";return new GC(r,o,this)}var a=new VC(r,this);return await a.init(o),a.get(n)}visit(e){return this.visititems(((t,i)=>e(t)))}visititems(e){var t=this.name.length;/\/$/.test(this.name)||(t+=1);for(var i=this.values.slice();i;){let n=i.shift();1==i.length&&console.log(n);let r=e(n.name.slice(t),n);if(null!=r)return r;n instanceof VC&&(i=i.concat(n.values))}return null}get attrs(){return null==this._attrs&&(this._attrs=this._dataobjects.get_attributes()),this._attrs}},KC=class extends VC{constructor(e,t,i){super("/",null),this.ready=this.init(e,t,i)}async init(e,t,i){var n=new class{constructor(e,t){this.ready=this.init(e,t)}async init(e,t){let i=await oB.unpack_from_async("{e._dataobjects.offset}))}},GC=class extends Array{constructor(e,t,i){super(),this.parent=i,this.file=i.file,this.name=e,this._dataobjects=t,this._attrs=null,this._astype=null}get value(){var e=this._dataobjects.get_data();return null==this._astype?this.getValue(e):e.astype(this._astype)}get shape(){return this._dataobjects.shape}get attrs(){return this._dataobjects.get_attributes()}get dtype(){return this._dataobjects.dtype}get fillvalue(){return this._dataobjects.get_fillvalue()}async to_array(){return function(e,t){const i=e.length,n=t.reduce(((e,t)=>e*t),1);i!==n&&console.warn(`shape product: ${n} does not match length of flattened array: ${i}`);let r=e;const s=t.slice(1).reverse();for(let e of s){const t=[],{length:i}=r;let n=0;for(;n1&&void 0!==arguments[1]?arguments[1]:1;return(t>0?e.toFixed(t).replace(/0+$/,"").replace(/\.$/,""):e.toString())||"0"}var sF=function(){function e(t,i,n,r){eF(this,e);var s=this;if(void 0===t);else if(Array.isArray(t))this.rgba=t;else if(void 0===n){var o=t&&""+t;o&&function(t){if(t.startsWith("hsl")){var i=t.match(/([\-\d\.e]+)/g).map(Number),n=iF(i,4),r=n[0],o=n[1],a=n[2],A=n[3];void 0===A&&(A=1),r/=360,o/=100,a/=100,s.hsla=[r,o,a,A]}else if(t.startsWith("rgb")){var c=t.match(/([\-\d\.e]+)/g).map(Number),l=iF(c,4),h=l[0],d=l[1],u=l[2],f=l[3];void 0===f&&(f=1),s.rgba=[h,d,u,f]}else t.startsWith("#")?s.rgba=e.hexToRgb(t):s.rgba=e.nameToRgb(t)||e.hexToRgb(t)}(o.toLowerCase())}else this.rgba=[t,i,n,void 0===r?1:r]}return tF(e,[{key:"printRGB",value:function(e){var t=(e?this.rgba:this.rgba.slice(0,3)).map((function(e,t){return rF(e,3===t?3:0)}));return e?"rgba("+t+")":"rgb("+t+")"}},{key:"printHSL",value:function(e){var t=[360,100,100,1],i=["","%","%",""],n=(e?this.hsla:this.hsla.slice(0,3)).map((function(e,n){return rF(e*t[n],3===n?3:1)+i[n]}));return e?"hsla("+n+")":"hsl("+n+")"}},{key:"printHex",value:function(e){var t=this.hex;return e?t:t.substring(0,7)}},{key:"rgba",get:function(){if(this._rgba)return this._rgba;if(!this._hsla)throw new Error("No color is set");return this._rgba=e.hslToRgb(this._hsla)},set:function(e){3===e.length&&(e[3]=1),this._rgba=e,this._hsla=null}},{key:"rgbString",get:function(){return this.printRGB()}},{key:"rgbaString",get:function(){return this.printRGB(!0)}},{key:"hsla",get:function(){if(this._hsla)return this._hsla;if(!this._rgba)throw new Error("No color is set");return this._hsla=e.rgbToHsl(this._rgba)},set:function(e){3===e.length&&(e[3]=1),this._hsla=e,this._rgba=null}},{key:"hslString",get:function(){return this.printHSL()}},{key:"hslaString",get:function(){return this.printHSL(!0)}},{key:"hex",get:function(){var e=this.rgba.map((function(e,t){return t<3?e.toString(16):Math.round(255*e).toString(16)}));return"#"+e.map((function(e){return e.padStart(2,"0")})).join("")},set:function(t){this.rgba=e.hexToRgb(t)}}],[{key:"hexToRgb",value:function(e){var t=(e.startsWith("#")?e.slice(1):e).replace(/^(\w{3})$/,"$1F").replace(/^(\w)(\w)(\w)(\w)$/,"$1$1$2$2$3$3$4$4").replace(/^(\w{6})$/,"$1FF");if(!t.match(/^([0-9a-fA-F]{8})$/))throw new Error("Unknown hex color; "+e);var i=t.match(/^(\w\w)(\w\w)(\w\w)(\w\w)$/).slice(1).map((function(e){return parseInt(e,16)}));return i[3]=i[3]/255,i}},{key:"nameToRgb",value:function(t){var i=t.toLowerCase().replace("at","T").replace(/[aeiouyldf]/g,"").replace("ght","L").replace("rk","D").slice(-5,4),n=nF[i];return void 0===n?n:e.hexToRgb(n.replace(/\-/g,"00").padStart(6,"f"))}},{key:"rgbToHsl",value:function(e){var t=iF(e,4),i=t[0],n=t[1],r=t[2],s=t[3];i/=255,n/=255,r/=255;var o=Math.max(i,n,r),a=Math.min(i,n,r),A=void 0,c=void 0,l=(o+a)/2;if(o===a)A=c=0;else{var h=o-a;switch(c=l>.5?h/(2-o-a):h/(o+a),o){case i:A=(n-r)/h+(n1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e},l=r<.5?r*(1+n):r+n-r*n,h=2*r-l;o=c(h,l,i+1/3),a=c(h,l,i),A=c(h,l,i-1/3)}var d=[255*o,255*a,255*A].map(Math.round);return d[3]=s,d}}]),e}(),oF=function(){function e(){eF(this,e),this._events=[]}return tF(e,[{key:"add",value:function(e,t,i){e.addEventListener(t,i,!1),this._events.push({target:e,type:t,handler:i})}},{key:"remove",value:function(t,i,n){this._events=this._events.filter((function(r){var s=!0;return t&&t!==r.target&&(s=!1),i&&i!==r.type&&(s=!1),n&&n!==r.handler&&(s=!1),s&&e._doRemove(r.target,r.type,r.handler),!s}))}},{key:"destroy",value:function(){this._events.forEach((function(t){return e._doRemove(t.target,t.type,t.handler)})),this._events=[]}}],[{key:"_doRemove",value:function(e,t,i){e.removeEventListener(t,i,!1)}}]),e}();function aF(e,t,i){var n=!1;function r(e,t,i){return Math.max(t,Math.min(e,i))}function s(e,s,o){if(o&&(n=!0),n){e.preventDefault();var a=t.getBoundingClientRect(),A=a.width,c=a.height,l=s.clientX,h=s.clientY,d=r(l-a.left,0,A),u=r(h-a.top,0,c);i(d/A,u/c)}}function o(e,t){1===(void 0===e.buttons?e.which:e.buttons)?s(e,e,t):n=!1}function a(e,t){1===e.touches.length?s(e,e.touches[0],t):n=!1}e.add(t,"mousedown",(function(e){o(e,!0)})),e.add(t,"touchstart",(function(e){a(e,!0)})),e.add(window,"mousemove",o),e.add(t,"touchmove",a),e.add(window,"mouseup",(function(e){n=!1})),e.add(t,"touchend",(function(e){n=!1})),e.add(t,"touchcancel",(function(e){n=!1}))}var AF="keydown",cF="mousedown",lF="focusin";function hF(e,t){return(t||document).querySelector(e)}function dF(e){e.preventDefault(),e.stopPropagation()}function uF(e,t,i,n,r){e.add(t,AF,(function(e){i.indexOf(e.key)>=0&&(r&&dF(e),n(e))}))}var fF=function(){function e(t){eF(this,e),this.settings={popup:"right",layout:"default",alpha:!0,editor:!0,editorFormat:"hex",cancelButton:!1,defaultColor:"#0cf"},this._events=new oF,this.onChange=null,this.onDone=null,this.onOpen=null,this.onClose=null,this.setOptions(t)}return tF(e,[{key:"setOptions",value:function(e){var t=this;if(e){var i=this.settings;if(e instanceof HTMLElement)i.parent=e;else{i.parent&&e.parent&&i.parent!==e.parent&&(this._events.remove(i.parent),this._popupInited=!1),function(e,t,i){for(var n in e)i&&i.indexOf(n)>=0||(t[n]=e[n])}(e,i),e.onChange&&(this.onChange=e.onChange),e.onDone&&(this.onDone=e.onDone),e.onOpen&&(this.onOpen=e.onOpen),e.onClose&&(this.onClose=e.onClose);var n=e.color||e.colour;n&&this._setColor(n)}var r=i.parent;if(r&&i.popup&&!this._popupInited){var s=function(e){return t.openHandler(e)};this._events.add(r,"click",s),uF(this._events,r,[" ","Spacebar","Enter"],s),this._popupInited=!0}else e.parent&&!i.popup&&this.show()}}},{key:"openHandler",value:function(e){if(this.show()){e&&e.preventDefault(),this.settings.parent.style.pointerEvents="none";var t=e&&e.type===AF?this._domEdit:this.domElement;setTimeout((function(){return t.focus()}),100),this.onOpen&&this.onOpen(this.colour)}}},{key:"closeHandler",value:function(e){var t=e&&e.type,i=!1;if(e)if(t===cF||t===lF){var n=(this.__containedEvent||0)+100;e.timeStamp>n&&(i=!0)}else dF(e),i=!0;else i=!0;i&&this.hide()&&(this.settings.parent.style.pointerEvents="",t!==cF&&this.settings.parent.focus(),this.onClose&&this.onClose(this.colour))}},{key:"movePopup",value:function(e,t){this.closeHandler(),this.setOptions(e),t&&this.openHandler()}},{key:"setColor",value:function(e,t){this._setColor(e,{silent:t})}},{key:"_setColor",value:function(e,t){if("string"==typeof e&&(e=e.trim()),e){t=t||{};var i=void 0;try{i=new sF(e)}catch(e){if(t.failSilently)return;throw e}if(!this.settings.alpha){var n=i.hsla;n[3]=1,i.hsla=n}this.colour=this.color=i,this._setHSLA(null,null,null,null,t)}}},{key:"setColour",value:function(e,t){this.setColor(e,t)}},{key:"show",value:function(){if(!this.settings.parent)return!1;if(this.domElement){var e=this._toggleDOM(!0);return this._setPosition(),e}var t=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstElementChild}(this.settings.template||'
');return this.domElement=t,this._domH=hF(".picker_hue",t),this._domSL=hF(".picker_sl",t),this._domA=hF(".picker_alpha",t),this._domEdit=hF(".picker_editor input",t),this._domSample=hF(".picker_sample",t),this._domOkay=hF(".picker_done button",t),this._domCancel=hF(".picker_cancel button",t),t.classList.add("layout_"+this.settings.layout),this.settings.alpha||t.classList.add("no_alpha"),this.settings.editor||t.classList.add("no_editor"),this.settings.cancelButton||t.classList.add("no_cancel"),this._ifPopup((function(){return t.classList.add("popup")})),this._setPosition(),this.colour?this._updateUI():this._setColor(this.settings.defaultColor),this._bindEvents(),!0}},{key:"hide",value:function(){return this._toggleDOM(!1)}},{key:"destroy",value:function(){this._events.destroy(),this.domElement&&this.settings.parent.removeChild(this.domElement)}},{key:"_bindEvents",value:function(){var e=this,t=this,i=this.domElement,n=this._events;function r(e,t,i){n.add(e,t,i)}r(i,"click",(function(e){return e.preventDefault()})),aF(n,this._domH,(function(e,i){return t._setHSLA(e)})),aF(n,this._domSL,(function(e,i){return t._setHSLA(null,e,1-i)})),this.settings.alpha&&aF(n,this._domA,(function(e,i){return t._setHSLA(null,null,null,1-i)}));var s=this._domEdit;r(s,"input",(function(e){t._setColor(this.value,{fromEditor:!0,failSilently:!0})})),r(s,"focus",(function(e){var t=this;t.selectionStart===t.selectionEnd&&t.select()})),this._ifPopup((function(){var t=function(t){return e.closeHandler(t)};r(window,cF,t),r(window,lF,t),uF(n,i,["Esc","Escape"],t);var s=function(t){e.__containedEvent=t.timeStamp};r(i,cF,s),r(i,lF,s),r(e._domCancel,"click",t)}));var o=function(t){e._ifPopup((function(){return e.closeHandler(t)})),e.onDone&&e.onDone(e.colour)};r(this._domOkay,"click",o),uF(n,i,["Enter"],o)}},{key:"_setPosition",value:function(){var e=this.settings.parent,t=this.domElement;e!==t.parentNode&&e.appendChild(t),this._ifPopup((function(i){"static"===getComputedStyle(e).position&&(e.style.position="relative");var n=!0===i?"popup_right":"popup_"+i;["popup_top","popup_bottom","popup_left","popup_right"].forEach((function(e){e===n?t.classList.add(e):t.classList.remove(e)})),t.classList.add(n)}))}},{key:"_setHSLA",value:function(e,t,i,n,r){r=r||{};var s=this.colour,o=s.hsla;[e,t,i,n].forEach((function(e,t){(e||0===e)&&(o[t]=e)})),s.hsla=o,this._updateUI(r),this.onChange&&!r.silent&&this.onChange(s)}},{key:"_updateUI",value:function(e){if(this.domElement){e=e||{};var t=this.colour,i=t.hsla,n="hsl("+360*i[0]+", 100%, 50%)",r=t.hslString,s=t.hslaString,o=this._domH,a=this._domSL,A=this._domA,c=hF(".picker_selector",o),l=hF(".picker_selector",a),h=hF(".picker_selector",A);m(0,c,i[0]),this._domSL.style.backgroundColor=this._domH.style.color=n,m(0,l,i[1]),F(0,l,1-i[2]),a.style.color=r,F(0,h,1-i[3]);var d=r,u=d.replace("hsl","hsla").replace(")",", 0)"),f="linear-gradient("+[d,u]+")";if(this._domA.style.background=f+", linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0 / 2em 2em,\n linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em / 2em 2em",!e.fromEditor){var p=this.settings.editorFormat,g=this.settings.alpha,w=void 0;switch(p){case"rgb":w=t.printRGB(g);break;case"hsl":w=t.printHSL(g);break;default:w=t.printHex(g)}this._domEdit.value=w}this._domSample.style.color=s}function m(e,t,i){t.style.left=100*i+"%"}function F(e,t,i){t.style.top=100*i+"%"}}},{key:"_ifPopup",value:function(e,t){this.settings.parent&&this.settings.popup?e&&e(this.settings.popup):t&&t()}},{key:"_toggleDOM",value:function(e){var t=this.domElement;if(!t)return!1;var i=e?"":"none",n=t.style.display!==i;return n&&(t.style.display=i),n}}]),e}(),pF=document.createElement("style");function gF(e){if(wF[e])return wF[e];if(wF["chr"+e]){const t=wF["chr"+e];return wF[e]=t,t}{const r=(t=Math.round(255*Math.random()).toString(10),i=Math.round(255*Math.random()).toString(10),n=Math.round(255*Math.random()).toString(10),"rgb("+t+","+i+","+n+")");return wF[e]=r,r}var t,i,n}pF.textContent='.picker_wrapper.no_alpha .picker_alpha{display:none}.picker_wrapper.no_editor .picker_editor{position:absolute;z-index:-1;opacity:0}.picker_wrapper.no_cancel .picker_cancel{display:none}.layout_default.picker_wrapper{display:flex;flex-flow:row wrap;justify-content:space-between;align-items:stretch;font-size:10px;width:25em;padding:.5em}.layout_default.picker_wrapper input,.layout_default.picker_wrapper button{font-size:1rem}.layout_default.picker_wrapper>*{margin:.5em}.layout_default.picker_wrapper::before{content:"";display:block;width:100%;height:0;order:1}.layout_default .picker_slider,.layout_default .picker_selector{padding:1em}.layout_default .picker_hue{width:100%}.layout_default .picker_sl{flex:1 1 auto}.layout_default .picker_sl::before{content:"";display:block;padding-bottom:100%}.layout_default .picker_editor{order:1;width:6.5rem}.layout_default .picker_editor input{width:100%;height:100%}.layout_default .picker_sample{order:1;flex:1 1 auto}.layout_default .picker_done,.layout_default .picker_cancel{order:1}.picker_wrapper{box-sizing:border-box;background:#f2f2f2;box-shadow:0 0 0 1px silver;cursor:default;font-family:sans-serif;color:#444;pointer-events:auto}.picker_wrapper:focus{outline:none}.picker_wrapper button,.picker_wrapper input{box-sizing:border-box;border:none;box-shadow:0 0 0 1px silver;outline:none}.picker_wrapper button:focus,.picker_wrapper button:active,.picker_wrapper input:focus,.picker_wrapper input:active{box-shadow:0 0 2px 1px #1e90ff}.picker_wrapper button{padding:.4em .6em;cursor:pointer;background-color:#f5f5f5;background-image:linear-gradient(0deg, gainsboro, transparent)}.picker_wrapper button:active{background-image:linear-gradient(0deg, transparent, gainsboro)}.picker_wrapper button:hover{background-color:#fff}.picker_selector{position:absolute;z-index:1;display:block;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);border:2px solid #fff;border-radius:100%;box-shadow:0 0 3px 1px #67b9ff;background:currentColor;cursor:pointer}.picker_slider .picker_selector{border-radius:2px}.picker_hue{position:relative;background-image:linear-gradient(90deg, red, yellow, lime, cyan, blue, magenta, red);box-shadow:0 0 0 1px silver}.picker_sl{position:relative;box-shadow:0 0 0 1px silver;background-image:linear-gradient(180deg, white, rgba(255, 255, 255, 0) 50%),linear-gradient(0deg, black, rgba(0, 0, 0, 0) 50%),linear-gradient(90deg, #808080, rgba(128, 128, 128, 0))}.picker_alpha,.picker_sample{position:relative;background:linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0/2em 2em,linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em/2em 2em;box-shadow:0 0 0 1px silver}.picker_alpha .picker_selector,.picker_sample .picker_selector{background:none}.picker_editor input{font-family:monospace;padding:.2em .4em}.picker_sample::before{content:"";position:absolute;display:block;width:100%;height:100%;background:currentColor}.picker_arrow{position:absolute;z-index:-1}.picker_wrapper.popup{position:absolute;z-index:2;margin:1.5em}.picker_wrapper.popup,.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{background:#f2f2f2;box-shadow:0 0 10px 1px rgba(0,0,0,.4)}.picker_wrapper.popup .picker_arrow{width:3em;height:3em;margin:0}.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{content:"";display:block;position:absolute;top:0;left:0;z-index:-99}.picker_wrapper.popup .picker_arrow::before{width:100%;height:100%;-webkit-transform:skew(45deg);transform:skew(45deg);-webkit-transform-origin:0 100%;transform-origin:0 100%}.picker_wrapper.popup .picker_arrow::after{width:150%;height:150%;box-shadow:none}.popup.popup_top{bottom:100%;left:0}.popup.popup_top .picker_arrow{bottom:0;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.popup.popup_bottom{top:100%;left:0}.popup.popup_bottom .picker_arrow{top:0;left:0;-webkit-transform:rotate(90deg) scale(1, -1);transform:rotate(90deg) scale(1, -1)}.popup.popup_left{top:0;right:100%}.popup.popup_left .picker_arrow{top:0;right:0;-webkit-transform:scale(-1, 1);transform:scale(-1, 1)}.popup.popup_right{top:0;left:100%}.popup.popup_right .picker_arrow{top:0;left:0}',document.documentElement.firstElementChild.appendChild(pF),fF.StyleElement=pF;const wF={chrX:"rgb(204, 153, 0)",chrY:"rgb(153, 204, 0",chrUn:"rgb(50, 50, 50)",chr1:"rgb(80, 80, 255)",chrI:"rgb(139, 155, 187)",chr2:"rgb(206, 61, 50)",chrII:"rgb(206, 61, 50)",chr2a:"rgb(216, 71, 60)",chr2b:"rgb(226, 81, 70)",chr3:"rgb(116, 155, 88)",chrIII:"rgb(116, 155, 88)",chr4:"rgb(240, 230, 133)",chrIV:"rgb(240, 230, 133)",chr5:"rgb(70, 105, 131)",chr6:"rgb(186, 99, 56)",chr7:"rgb(93, 177, 221)",chr8:"rgb(128, 34, 104)",chr9:"rgb(107, 215, 107)",chr10:"rgb(213, 149, 167)",chr11:"rgb(146, 72, 34)",chr12:"rgb(131, 123, 141)",chr13:"rgb(199, 81, 39)",chr14:"rgb(213, 143, 92)",chr15:"rgb(122, 101, 165)",chr16:"rgb(228, 175, 105)",chr17:"rgb(59, 27, 83)",chr18:"rgb(205, 222, 183)",chr19:"rgb(97, 42, 121)",chr20:"rgb(174, 31, 99)",chr21:"rgb(231, 199, 111)",chr22:"rgb(90, 101, 94)",chr23:"rgb(204, 153, 0)",chr24:"rgb(153, 204, 0)",chr25:"rgb(51, 204, 0)",chr26:"rgb(0, 204, 51)",chr27:"rgb(0, 204, 153)",chr28:"rgb(0, 153, 204)",chr29:"rgb(10, 71, 255)",chr30:"rgb(71, 117, 255)",chr31:"rgb(255, 194, 10)",chr32:"rgb(255, 209, 71)",chr33:"rgb(153, 0, 51)",chr34:"rgb(153, 26, 0)",chr35:"rgb(153, 102, 0)",chr36:"rgb(128, 153, 0)",chr37:"rgb(51, 153, 0)",chr38:"rgb(0, 153, 26)",chr39:"rgb(0, 153, 102)",chr40:"rgb(0, 128, 153)",chr41:"rgb(0, 51, 153)",chr42:"rgb(26, 0, 153)",chr43:"rgb(102, 0, 153)",chr44:"rgb(153, 0, 128)",chr45:"rgb(214, 0, 71)",chr46:"rgb(255, 20, 99)",chr47:"rgb(0, 214, 143)",chr48:"rgb(20, 255, 177)"};class mF{constructor(e){this.tracks=[],this.chordSets=[]}addChordSet(e){this.chordSets=this.chordSets.filter((t=>t.name!==e.name)),this.chordSets.push(e);let t=this.tracks.find((t=>e.trackName===t.name));t&&(t.chordSets=t.chordSets.filter((t=>t.name!==e.name)),t.chordSets.push(e)),t||(t=new FF(e),this.tracks.push(t))}clearChords(){this.tracks=[],this.chordSets=[]}getTrack(e){return this.tracks.find((t=>e===t.name))}getChordSet(e){return this.chordSets.find((t=>e===t.name))}}class FF{constructor(e){this.name=e.trackName,this.color=e.trackColor,this.visible=!0,this.chordSets=[e],this.id=("0000"+(Math.random()*Math.pow(36,4)<<0).toString(36)).slice(-4)}get chords(){if(1===this.chordSets.length)return this.chordSets[0].chords;const e=[];for(let t of this.chordSets)for(let i of t.chords)e.push(i);return e}}const bF=Math.exp(5);class vF{static isInstalled(){return void 0!==window.JBrowseReactCircularGenomeView&&void 0!==window.React&&void 0!==window.ReactDOM}constructor(e,t){if(t=t||{},this.config=t,vF.isInstalled()){this.parent=e,this.groupByTrack=!0===t.groupByTrack,this.chordManager=new mF(t);const i=document.createElement("div");i.className="igv-circview-container",e.appendChild(i),this.createControls(i),this.resetControlPanel();const n=document.createElement("div");n.className="igv-circview-circular-genome-view",i.appendChild(n),this.container=n,t.assembly&&this.setAssembly(t.assembly),this.width=t.width||500,this.height=t.height||500,this.setSize(this.width,this.height)}else console.error("JBrowse circular view is not installed")}createControls(e){const t=document.createElement("div");t.className="igv-circview-toolbar",e.appendChild(t),this.toolbar=t;const i=document.createElement("div");i.className="igv-circview-track-panel",e.appendChild(i),this.controlPanel=i,this.controlPanel.style.display="none";const n=document.createElement("div");n.className="igv-circview-toolbar-button-container",this.toolbar.appendChild(n),this.showControlsButton=document.createElement("div"),this.showControlsButton.className="igv-circview-button",n.appendChild(this.showControlsButton),this.showControlsButton.innerText="none"===this.controlPanel.style.display?"Show Controls":"Hide Controls",this.showControlsButton.addEventListener("click",(e=>{this.controlPanel.querySelectorAll("div").length>0&&("none"===this.controlPanel.style.display?(this.controlPanel.style.display="flex",e.target.innerText="Hide Controls"):(this.controlPanel.style.display="none",e.target.innerText="Show Controls"))}));let r=document.createElement("div");r.className="igv-circview-button",n.appendChild(r),r.innerText="Clear All",r.addEventListener("click",(()=>{this.clearChords()})),!1!==this.config.showCloseButton&&(r=document.createElement("div"),r.className="igv-circview-button",n.appendChild(r),r.innerText="Close",r.addEventListener("click",(()=>{this.visible=!1})))}resetControlPanel(){this.controlPanel.innerHTML="",this.controlPanel.appendChild(this.createGroupByCB());const e=this.groupByTrack?this.chordManager.tracks:this.chordManager.chordSets;for(let t of e)this.addToControlPanel(t)}createGroupByCB(){const e=document.createElement("input");e.type="checkbox",e.id="groupByCB",e.style.width="1.4em",e.style.height="1.4em",e.checked=this.groupByTrack,e.onclick=e=>{this.groupByTrack=e.target.checked,this.resetControlPanel(),this.render()};const t=document.createElement("label");t.for="groupByCB",t.innerText="Group by track",t.style.color="black",t.style.paddingLeft="10px";const i=document.createElement("div");return i.style.width="100%",i.style.paddingTop="5px",i.style.paddingBottom="5px",i.style.background="rgb(216, 230, 234)",i.appendChild(e),i.appendChild(t),i}addToControlPanel(e){const t=document.createElement("div");this.controlPanel.appendChild(t);const i=document.createElement("div");i.className="igv-circview-button",t.appendChild(i),i.innerText=!0===e.visible?"Hide":"Show",i.addEventListener("click",(t=>{!0===e.visible?(this.hideChordSet(e.name),t.target.innerText="Show"):(this.showChordSet(e.name),t.target.innerText="Hide")}));const n=document.createElement("input"),r=e=>200*Math.log(e*bF),s=document.createElement("div");s.className="igv-circview-button",s.innerHTML="    ",t.appendChild(s),s.style.backgroundColor=BF(e.color,1);const o={parent:s,popup:"right",editorFormat:"rgb",color:e.color,onChange:({rgbaString:t})=>{s.style.backgroundColor=BF(t,1),this.setColor(e.name,t),n.value=r(yF(e.color))}},a=new fF(o);n.setAttribute("title","Adjust transparency of arcs"),n.type="range",n.style.width="100px",n.style.marginRight="10px",n.setAttribute("class","range"),n.setAttribute("min","0"),n.setAttribute("max","1000"),n.value=r(yF(e.color)),n.oninput=()=>{const t=(i=n.value,Math.exp(i/200)/bF);var i;this.setColor(e.name,BF(e.color,t)),a.setColor(e.color)},t.appendChild(n);const A=document.createElement("div");A.style.color="black",t.appendChild(A),A.innerText=A.title=e.name}setAssembly(e){const t=this.genomeId||xF();if(this.genomeId===t)return;this.chordManager.clearChords(),this.genomeId=t,this.chrNames=new Set(e.chromosomes.map((e=>CF(e.name))));const i=[],n=[];for(let t of e.chromosomes){const e=CF(t.name);n.push(t.color||gF(e)),i.push({refName:e,uniqueId:e,start:0,end:t.bpLength})}this.assembly={name:e.name,sequence:{trackId:t,type:"ReferenceSequenceTrack",adapter:{type:"FromConfigSequenceAdapter",features:i}},refNameColors:n},this.render()}addChords(e,t={}){const i=t.name||t.track||"*",n=i.split(" ")[0].replaceAll("%20"," "),r={name:i.replaceAll("%20"," "),trackName:n,chords:e,color:t.color||"black",trackColor:t.trackColor||t.color||"black",visible:!0,id:t.id||xF()};this.chordManager.addChordSet(r),this.resetControlPanel(),this.render()}setSize(e,t){if(t=t||e,this.width=e,this.height=t,this.viewState){const i=this.viewState.session.view;i.setWidth(e),i.setHeight(t),i.setBpPerPx(i.minBpPerPx)}}getSize(){return Math.min(this.width,this.height)}clearChords(){this.chordManager.clearChords(),this.resetControlPanel(),this.render()}clearSelection(){this.viewState.pluginManager.rootModel.session.clearSelection()}show(){this.parent.style.display="block"}hide(){this.parent.style.display="none"}get visible(){return"none"!==this.parent.style.display}set visible(e){this.parent.style.display=e?"block":"none"}hideChordSet(e){let t=this.getChordSet(e);t?(t.visible=!1,this.render()):console.warn(`No track with name: ${name}`)}showChordSet(e){let t=this.getChordSet(e);t?(t.visible=!0,this.render()):console.warn(`No track with name: ${e}`)}deleteTrack(e){let t=this.tracks.findIndex((t=>e===t.name));t>=0&&this.tracks.splice(t,1),this.render()}getChordSet(e){return this.groupByTrack?this.chordManager.getTrack(e):this.chordManager.getChordSet(e)}setColor(e,t){const i=this.getChordSet(e);if(i){i.color=t;const e=i.id;for(let i of this.viewState.config.tracks)if(e===i.trackId){i.displays[0].renderer.strokeColor.set(t);break}}}render(){const{createViewState:e,JBrowseCircularGenomeView:t}=JBrowseReactCircularGenomeView;ReactDOM.unmountComponentAtNode(this.container);const i=(this.groupByTrack?this.chordManager.tracks:this.chordManager.chordSets).filter((e=>e.visible)),n=[],r=[];for(let e of i)n.push({trackId:e.id,name:e.name,assemblyNames:["forIGV"],type:"VariantTrack",adapter:{type:"FromConfigAdapter",features:e.chords}}),r.push(e.color);this.viewState=e({assembly:this.assembly,tracks:n});for(let e=0;e div {\n margin: 4px;\n}\n\n.igv-circview-track-panel {\n z-index: 1024;\n position: absolute;\n top: 33px;\n left: 0;\n width: 100%;\n height: fit-content;\n border-bottom-style: solid;\n border-bottom-color: dimgray;\n border-bottom-width: thin;\n background-color: white;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n}\n.igv-circview-track-panel > div {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-circview-track-panel > div > div {\n margin: 4px;\n}\n\n.igv-circview-swatch-button {\n cursor: pointer;\n padding: 5px;\n width: 8px;\n height: 8px;\n border: 1px solid #8d8b8b;\n border-radius: 16px;\n}\n\n.igv-circview-button {\n cursor: pointer;\n padding: 5px;\n color: #444;\n vertical-align: middle;\n text-align: center;\n font-family: "Open Sans", sans-serif;\n font-size: 12px;\n border: 1px solid #8d8b8b;\n border-radius: 4px;\n background: #efefef;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.2);\n}\n\n.igv-circview-button:hover {\n background: #efefef;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.6);\n}\n\n.igv-circview-button:active {\n color: #007bff;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.6);\n}\n\n/*# sourceMappingURL=circular-view.css.map */\n',document.head.insertBefore(e,document.head.childNodes[document.head.childNodes.length-1])}()}const kF=e=>e.startsWith("chr")?e.substring(3):e;function EF(e){const t=[],i=[];for(let n of e.wgChromosomeNames){const r=e.getChromosome(n);i.push(lb(r.name)),t.push({name:r.name,bpLength:r.bpLength})}return t}function IF(e,t,i,n){const r=t.color||"rgb(0,0,255)",s=Ts.addAlpha("all"===i.chr?r:lb(i.chr),n),o=Ts.addAlpha(r,n),a=t.name.replaceAll(" ","%20"),A="all"===i.chr?a:`${a} ${i.chr}:${i.start}-${i.end}`;t.browser.circularView.addChords(e,{track:A,color:s,trackColor:o}),t.browser.circularViewVisible||(t.browser.circularViewVisible=!0)}class UF{constructor(e,{minTLENPercentile:t,maxTLENPercentile:i}){this.totalCount=0,this.frCount=0,this.rfCount=0,this.ffCount=0,this.sumF=0,this.sumF2=0,this.lp=void 0===t?.1:t,this.up=void 0===i?99.5:i,this.isizes=[],this.compute(e)}compute(e){for(let n of e)if(n.isProperPair()){var t=Math.abs(n.fragmentLength);this.sumF+=t,this.sumF2+=t*t,this.isizes.push(t);var i=n.pairOrientation;if("string"==typeof i&&4===i.length)switch(""+i.charAt(0)+i.charAt(2)){case"FF":case"RR":this.ffCount++;break;case"FR":this.frCount++;break;case"RF":this.rfCount++}this.totalCount++}this.ffCount/this.totalCount>.9?this.orienation="ff":this.frCount/this.totalCount>.9?this.orienation="fr":this.rfCount/this.totalCount>.9&&(this.orienation="rf"),this.minTLEN=0===this.lp?0:QF(this.isizes,this.lp),this.maxTLEN=QF(this.isizes,this.up)}}function QF(e,t){if(0!==e.length){var i=Math.floor(e.length*(t/100));return e.sort((function(e,t){return e-t})),e[i]}}const SF={getTissueInfo:function(e,t){let i=(t=t||"https://gtexportal.org/rest/v1")+"/dataset/tissueInfo?datasetId="+(e=e||"gtex_v8");return io.loadJson(i,{})},trackConfiguration:function(e,t){return{type:"eqtl",sourceType:"gtex-ws",url:(t=t||"https://gtexportal.org/rest/v1")+"/association/singleTissueEqtlByLocation",tissueSiteDetailId:e.tissueSiteDetailId,name:e.tissueSiteDetailId.split("_").join(" "),visibilityWindow:25e4}}};function HF(e,t,i){let n=(e.start-t)/i,r=(e.end-t)/i,s=r-n;return s<3&&(s=3,n-=1.5),{px:n,px1:r,pw:s}}function NF(e,t,i,n,r,s){try{r.save(),r.fillStyle=this.color,r.strokeStyle=this.color;const n=this.getColorForFeature(e);let o,a;r.fillStyle=n,r.strokeStyle=n,"SQUISHED"===this.displayMode&&void 0!==e.row?(o=this.featureHeight/2,a=this.margin+this.squishedRowHeight*e.row):"EXPANDED"===this.displayMode&&void 0!==e.row?(o=this.featureHeight,a=this.margin+this.expandedRowHeight*e.row):(o=this.featureHeight,a=this.margin);const A=s.pixelWidth,c=a+o/2,l=o/2,h=c-l/2,d=e.exons?e.exons.length:0,u=HF(e,t,i),f=this.arrowSpacing,p="+"===e.strand?1:"-"===e.strand?-1:0;if(0===d){const e=Math.max(0,u.px),t=Math.min(A,u.px1),i=t-e;if(r.fillRect(e,a,i,o),0!==p){r.fillStyle="white",r.strokeStyle="white";for(let i=e+f/2;iA)break;if(d.utr)r.fillRect(g,h,m,l);else if(d.cdStart&&(u=Math.round((d.cdStart-t)/i),r.fillRect(g,h,u-g,l),m-=u-g,g=u),d.cdEnd&&(u=Math.round((d.cdEnd-t)/i),r.fillRect(u,h,w-u,l),m-=w-u,w=u),m=Math.max(m,1),r.fillRect(g,a,m,o),m>f+5&&0!==p){r.fillStyle="white",r.strokeStyle="white";for(let e=g+f/2;eb||p)&&(o.rowLastLabelX[t.row]=F,"y"===o.axis?(e.save(),Eo.labelTransformWithContext(e,h),Eo.fillText(e,a,h,d,g,l),e.restore()):Eo.fillText(e,a,h,d,g,l))}finally{e.restore()}}const LF=new Set(["nonsense","missense","stop-loss","frameshift","cds-indel"]),DF=new Set(["coding-synon"]),TF=new Set(["splice-3","splice-5"]),RF=new Set(["untranslated-5","untranslated-3"]);function zF(e,t,i,n,r){var s,o,a,A,c=HF(e,t,i),l=this.margin,h=this.snpColors.length;switch(s="squished"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight,this.colorBy){case"function":A=e.func,o=A.split(",").map((function(e){return LF.has(e)||TF.has(e)?h-1:DF.has(e)?h-2:RF.has(e)?h-3:0})).reduce((function(e,t){return Math.max(e,t)}));break;case"class":o="deletion"===(a=e.class)?h-1:"mnp"===a?h-2:"microsatellite"===a||"named"===a?h-3:0}r.fillStyle=this.snpColors[o],r.fillRect(c.px,l,c.pw,s)}function OF(e,t,i,n,r){const s="EXPANDED"===this.displayMode?this.expandedRowHeight:this.squishedRowHeight;let o=this.margin;"COLLAPSED"!==this.displayMode&&void 0!==e.row&&(o+=e.row*s);const a=o+.5*s,A=a-.5*s,c=a+.5*s,l=Math.round((e.junction_left-t)/i),h=Math.round((e.junction_right-t)/i);r.beginPath(),r.moveTo(l,a),r.bezierCurveTo(l,A,h,A,h,a),r.lineWidth=1+Math.log(e.num_junction_reads)/Math.log(2),r.strokeStyle="blue",r.stroke();const d=e.spanning_frag_coords;for(let e=0;et&&(t=i.row);return this.margin+(t+1)*("SQUISHED"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight)}}draw(e){const t=e.features,i=e.context,n=e.bpPerPixel,r=e.bpStart,s=e.pixelWidth,o=e.pixelHeight,a=r+s*n+1;if(this.config.isMergedTrack||Eo.fillRect(i,0,e.pixelTop,s,o,{fillStyle:"rgb(255, 255, 255)"}),t){const A=[];e.rowLastX=[],e.rowLastLabelX=[];for(let i of t)if(i.start>r&&i.enda)break;const t="COLLAPSED"===this.displayMode?0:s.row;e.drawLabel=e.labelAllFeatures||c>10;const A=Math.ceil((s.end-r)/n),h=l[t];if(!h||A>h){this.render.call(this,s,r,n,o,i,e);const a=Math.floor((s.start-r)/n);h&&a-h<=0&&(i.globalAlpha=.5,Eo.strokeLine(i,a,0,a,o,{strokeStyle:"rgb(255, 255, 255)"}),i.globalAlpha=1),l[t]=A}}}else console.log("No feature list")}clickedFeatures(e){const t=e.y-this.margin,i=super.clickedFeatures(e);let n;switch(this.displayMode){case"SQUISHED":n=Math.floor(t/this.squishedRowHeight);break;case"EXPANDED":n=Math.floor(t/this.expandedRowHeight);break;default:n=void 0}return i.filter((function(e){return void 0===n||void 0===e.row||n===e.row}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,n=[];for(let e of t){const t=e._f||e,r="function"==typeof t.popupData?t.popupData(i):this.extractPopupData(t);if(r){n.length>0&&n.push("

");const s=this.infoURL||this.config.infoURL;for(let t of r)if(n.push(t),s&&t.name&&"name"===t.name.toLowerCase()&&t.value&&$t(t.value)&&!t.value.startsWith("<")){const i=s.replace("$$",e.name);t.value=`${t.value}`}const o="gff"===this.config.format||"gff3"===this.config.format||"gtf"===this.config.format;if(t.exons)for(let e=0;e=r.start&&i<=r.end){const i=o?r.number:"-"===t.strand?t.exons.length-e:e+1;i&&(n.push("
"),n.push({name:"Exon Number",value:i}));break}}}}return n}menuItemList(){const e=[];if(this.render===zF){e.push("
");for(let t of["function","class"])e.push({object:ut(Kt("Color by "+t,t===this.colorBy)),click:()=>{this.colorBy=t,this.trackView.repaintViews()}})}e.push("
");for(let t of["COLLAPSED","SQUISHED","EXPANDED"]){const i={COLLAPSED:"Collapse",SQUISHED:"Squish",EXPANDED:"Expand"};e.push({object:ut(Kt(i[t],t===this.displayMode)),click:()=>{this.displayMode=t,this.config.displayMode=t,this.trackView.checkContentHeight(),this.trackView.repaintViews()}})}return e}contextMenuItemList(e){const t=this.clickedFeatures(e);if(void 0===t||0===t.length)return;t.length>1&&t.sort(((e,t)=>t.end-t.start-(e.end-e.start)));const i=t[0];if(i.end-i.start<=1e6){const e=[{label:"View feature sequence",click:async()=>{let e=await this.browser.genome.getSequence(i.chr,i.start,i.end);e?"-"===i.strand&&(e=kf(e)):e="Unknown sequence",this.browser.alert.present(e)}}];return hf()&&void 0!==navigator.clipboard&&e.push({label:"Copy feature sequence",click:async()=>{let e=await this.browser.genome.getSequence(i.chr,i.start,i.end);e?"-"===i.strand&&(e=kf(e)):e="Unknown sequence";try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),e.push("
"),e}}description(){if(zF===this.render){let e=""+this.name+"
";return e+="Color By Function:
",e+='Red: Coding-Non-Synonymous, Splice Site
',e+='Green: Coding-Synonymous
',e+='Blue: Untranslated
',e+='Black: Intron, Locus, Unknown

',e+="Color By Class:
",e+='Red: Deletion
',e+='Green: MNP
',e+='Blue: Microsatellite, Named
',e+='Black: Indel, Insertion, SNP',e+="",e}return super.description()}getColorForFeature(e){const t=e._f||e;let i;if(this.altColor&&"-"===t.strand)i="function"==typeof this.altColor?this.altColor(t):this.altColor;else if(this.color)i="function"==typeof this.color?this.color(t):this.color;else if(this.colorBy){const e=t.getAttributeValue?t.getAttributeValue(this.colorBy):t[this.colorBy];i=this.colorTable.getColor(e)}else t.color&&(i=t.color);if(i||(i="rgb(0, 0, 150)"),t.alpha&&1!==t.alpha)i=Ts.addAlpha(i,t.alpha);else if(this.useScore&&t.score&&!Number.isNaN(t.score)){const e=function(e,t,i){const n=(t-e)/9,r=Math.floor((i-e)/n);return Math.min(1,.2+.8*r/9)}(this.config.min?this.config.min:this.viewLimitMin?this.viewLimitMin:0,this.config.max?this.config.max:this.viewLimitMax?this.viewLimitMax:1e3,t.score);t.alpha=e,i=Ts.addAlpha(i,e)}return i}dispose(){this.trackView=void 0}}class VF{constructor(e){this.config=e,this.browser=e.browser,this.columnFormat=e.columnFormat,this.tableRowSelectionList=[],this.tableDOM=vt.div({class:"igv-roi-table"}),e.parent.appendChild(this.tableDOM),this.headerDOM=e,this.tableColumnTitles=this.tableDOM,this.tableRowContainer=this.tableDOM,this.footerDOM=e.gotoButtonHandler}set headerDOM({browser:e,parent:t,headerTitle:i,dismissHandler:n}){const r=vt.div();this.tableDOM.appendChild(r);const s=vt.div();r.appendChild(s),s.innerHTML=i;const o=vt.div();r.appendChild(o),o.appendChild(xt.createIcon("times")),this.boundDismissHandler=function(e){e.stopPropagation(),n()}.bind(this),o.addEventListener("click",this.boundDismissHandler);const{y:a}=e.root.getBoundingClientRect(),{y:A}=t.getBoundingClientRect(),c=-(A-a);Ut(this.tableDOM,r,{minX:0,minY:c}),this.tableDOM.style.display="none",this._headerDOM=r}set tableColumnTitles(e){const t=vt.div({class:"igv-roi-table-column-titles"});e.appendChild(t);for(const{label:e,width:i}of this.columnFormat){const n=vt.div();t.appendChild(n),n.style.width=i,n.innerText=e}this._tableColumnTitlesDOM=t}get tableColumnTitles(){return this._tableColumnTitlesDOM}set tableRowContainer(e){const t=vt.div({class:"igv-roi-table-row-container"});e.appendChild(t),this._tableRowContainerDOM=t}get tableRowContainer(){return this._tableRowContainerDOM}set footerDOM(e){const t=vt.div();this.tableDOM.appendChild(t);const i=vt.div({class:"igv-roi-table-button"});t.appendChild(i),i.id="igv-roi-table-view-button",i.textContent="Go To",i.style.pointerEvents="none",this._footerDOM=t,this.gotoButton=i,this.boundGotoButtonHandler=e.bind(this),this.gotoButton.addEventListener("click",this.boundGotoButtonHandler)}tableRowDOMHelper(e){e.addEventListener("mousedown",(t=>{t.stopPropagation(),e.classList.toggle("igv-roi-table-row-selected"),e.classList.contains("igv-roi-table-row-selected")?e.classList.remove("igv-roi-table-row-hover"):e.classList.add("igv-roi-table-row-hover"),this.setTableRowSelectionState(e.classList.contains("igv-roi-table-row-selected"))})),e.addEventListener("mouseover",(t=>{e.classList.contains("igv-roi-table-row-selected")?e.classList.remove("igv-roi-table-row-hover"):e.classList.add("igv-roi-table-row-hover")})),e.addEventListener("mouseout",(t=>{e.classList.remove("igv-roi-table-row-hover")}))}clearTable(){const e=this.tableRowContainer.querySelectorAll(".igv-roi-table-row");for(let t of e)t.remove()}setTableRowSelectionState(e){e?this.tableRowSelectionList.push(1):this.tableRowSelectionList.pop(),this.gotoButton.style.pointerEvents=this.tableRowSelectionList.length>0?"auto":"none"}present(){this.tableDOM.style.left="0px";const{y:e}=this.browser.root.getBoundingClientRect(),{y:t}=this.config.parent.getBoundingClientRect();this.tableDOM.style.top=e-t+"px",this.tableDOM.style.display="flex"}dismiss(){this.tableDOM.style.display="none"}dispose(){this.tableDOM.innerHTML="",this.tableDOM.remove();for(const e of Object.keys(this))this[e]=void 0;document.removeEventListener("click",this.boundDismissHandler)}}class KF extends VF{constructor(e){super(Object.assign({width:"1024px"},e)),this.descriptionDOM=e}set descriptionDOM(e){if(e.description){let t;t=vt.div({class:"igv-roi-table-description"}),this.tableDOM.insertBefore(t,this.tableColumnTitles),t.style.height="auto",t.innerHTML="BLAT result for query sequence:",t=vt.div({class:"igv-roi-table-description"}),this.tableDOM.insertBefore(t,this.tableColumnTitles),t.style.height="auto",t.style.maxHeight="128px",t.innerHTML=e.description,t=vt.div({class:"igv-roi-table-goto-explainer"}),this.tableDOM.insertBefore(t,this.tableColumnTitles),t.innerHTML="Select one or more rows and click Go To to view the regions"}}tableRowDOM(e){const t=vt.div({class:"igv-roi-table-row"}),i=e.map((e=>isFinite(e)?Xt(e):e));for(let e=0;ee.remove())),e.length>0)for(let t of e){const e=this.tableRowDOM(t);this.tableRowContainer.appendChild(e)}}static getColumnFormatConfiguration(){return[{label:"chr",width:"7%"},{label:"start",width:"12%"},{label:"end",width:"12%"},{label:"strand",width:"5%"},{label:"score",width:"5%"},{label:"match",width:"5%"},{label:"mis-match",width:"7%"},{label:"rep. match",width:"7%"},{label:"N's",width:"3%"},{label:"Q gap count",width:"9%"},{label:"Q gap bases",width:"9%"},{label:"T gap count",width:"9%"},{label:"T gap bases",width:"9%"}]}static gotoButtonHandler(e){e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected"),i=[];for(const e of t){const t=[];e.querySelectorAll("div").forEach((e=>t.push(e.innerText)));const[n,r,s]=t;i.push(`${n}:${r}-${s}`)}for(const e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");this.setTableRowSelectionState(!1),this.browser.search(i.join(" "))}}const GF="https://igv.org/services/blatUCSC.php";async function qF({url:e,userSeq:t,db:i}){e=e||GF;const n=await async function(e="",t,i){const n=new URLSearchParams;n.append("userSeq",t),n.append("db",i);const r=await fetch(e,{method:"post",body:n});return r.json()}(e,t,i);n.fields;return n.blat.map(Vp)}const jF=25e3;class WF extends PF{constructor(e,t){super(e,t),this.name||(this.name="Blat Results"),this.sequence=e.sequence,this.table=void 0}openTableView(){if(void 0===this.table){const e=this.config.features.map((e=>[e.chr,e.start+1,e.end,e.strand,e.score,e.matches,e.misMatches,e.repMatches,e.nCount,e.qNumInsert,e.qBaseInsert,e.tNumInsert,e.tBaseInsert])),t={browser:this.browser,parent:this.browser.parent,headerTitle:this.config.title,description:this.sequence,dismissHandler:()=>{this.table.dismiss(),this.table.dispose(),this.table=void 0},columnFormat:KF.getColumnFormatConfiguration(),gotoButtonHandler:KF.gotoButtonHandler};this.table=new KF(t),this.table.renderTable(e)}this.table.present()}menuItemList(){const e=super.menuItemList();return e.push("
"),e.push({label:"Open table view",click:()=>this.openTableView()}),e}dispose(){super.dispose(),this.table&&this.table.popover.parentElement.removeChild(this.table.popover)}}async function $F({sequence:e,browser:t,name:i,title:n}){if(e.length>jF)return void t.alert.present(`Sequence size exceeds maximum allowed length (${e.length} > ${jF})`);const r=t.genome.id,s=t.config.blatServerURL;try{const o={type:"blat",name:i||"blat results",title:n||"blat results",sequence:e,altColor:"rgb(176, 176, 236)",color:"rgb(236, 176, 176)",features:await qF({url:s,userSeq:e,db:r})};(await t.loadTrack(o)).openTableView()}catch(e){t.alert.present(`Error performing blat search: ${e}`)}}const XF="rgb(255,0,255)",ZF="rgb(0,0,255)",JF="rgb(132, 178, 158)",YF=new Map;YF.set("m","rgb(255,0,0)"),YF.set("h",XF),YF.set("o","rgb(111, 78, 129)"),YF.set("f","rgb(246, 200, 95)"),YF.set("c","rgb(157, 216, 102)"),YF.set("g","rgb(255, 160, 86)"),YF.set("e","rgb(141, 221, 208)"),YF.set("b","rgb(202, 71, 47)"),YF.set("h",XF),YF.set("a","rgb(51,0,111)"),YF.set("NONE_A",ZF),YF.set("NONE_C",ZF),YF.set("NONE_T",ZF),YF.set("NONE_G",ZF),YF.set("NONE_N",ZF);const eb=new Map;function tb(e,t,i){let n=function(e,t){return YF.has(e)?YF.get(e):JF}(e),r=rm(t);if(r>255)return n;const s=e+r+i;if(r<0&&(r=0),!eb.has(s)){const e="basemod2"===i?Math.max(20,Math.min(255,r*r/50-4*r+200+20)):Math.max(20,Math.min(255,.006127*r*r)),[t,o,a]=Ts.rgbComponents(n);eb.set(s,`rgba(${t},${o},${a},${e/255})`)}return eb.get(s)}function ib(e,t,i,n,r,s,o,a,A){const c=o.baseModCounts,l=o.coverageMap;if(c){const o=Array.from(c.allModifications);o.sort(sm.compare);const h=l.getTotalCount(s);for(let d of o){if(d.modification.startsWith("NONE_")&&"basemod2"!==a)continue;const o=d.base,u=xf(o),f=l.getCount(s,o)+l.getCount(s,u),p=c.simplexModifications.has(d.modification)?l.getPosCount(s,o)+l.getNegCount(s,u):f;if(0==p)continue;const g=c.getCount(s,d,A,"basemod2"===a);if(0==g)continue;const w=f/h*(g/p),m=Math.round(w*r),F=c.getLikelihoodSum(s,d,A,"basemod2")/g,b=i-m,v=tb(d.modification,F,a);e.fillStyle=v,e.fillRect(t,b,n,m),i=b}}}class nb{constructor(e){this.alignmentTrack=e}updateContext(e){this.context=e}drawModifications(e,t,i,n,r){const{ctx:s,pixelEnd:o,bpStart:a,bpPerPixel:A}=n,c=e.getBaseModificationSets();if(c)for(let n of e.blocks){if("S"===n.type)continue;const e=t,l=i;let h=Math.max(1,1/A);for(let t=n.seqOffset;to)break;if(i+h<0)continue;let d,u=-1,f=255,p=0;for(let e of c)if(e.containsPosition(t)){const i=rm(e.likelihoods.get(t));f-=i,(!d||i>u)&&(d=e.modification,p=e.canonicalBase,u=i)}if(d){const t=127.5;let n;f>u&&"basemod2"===r&&f>=t?n=tb("NONE_"+p,f,r):u>=t&&(n=tb(d,u,r)),s.fillStyle=n,h<3&&(h=3,i--),s.fillRect(i,e,h,Math.max(1,l-2))}}}}}const rb="rgb(185, 185, 185)";class sb extends ag{static defaults={alleleFreqThreshold:.2,visibilityWindow:3e4,showCoverage:!0,showAlignments:!0,viewAsPairs:!1,pairsSupported:!0,showSoftClips:!1,showAllBases:!1,showInsertions:!0,showMismatches:!0,height:300,coverageTrackHeight:50,colorBy:void 0};constructor(e,t){super(e,t)}init(e){this.type="alignment",this.featureSource=new Zm(e,this.browser),this.coverageTrack=new ob(e,this),this.alignmentTrack=new ab(e,this),super.init(e),this.alignmentTrack.setTop(this.coverageTrack,this.showCoverage),this.showAlignments||(this._height=this.coverageTrackHeight),e.sort&&(Array.isArray(e.sort)?this.assignSort(e.sort[0]):this.assignSort(e.sort))}setHighlightedReads(e){this.alignmentTrack.setHighlightedReads(e),this.updateViews()}set height(e){this._height=e,this.showAlignments&&(this.alignmentTrack.height=this.showCoverage?e-this.coverageTrackHeight:e)}get height(){return this._height}get minTemplateLength(){const e=void 0!==this.config.minTLEN?this.config.minTLEN:this.config.minFragmentLength;return void 0!==e?e:this._pairedEndStats?this._pairedEndStats.minTLEN:0}get maxTemplateLength(){const e=void 0!==this.config.maxTLEN?this.config.maxTLEN:this.config.maxFragmentLength;return void 0!==e?e:this._pairedEndStats?this._pairedEndStats.maxTLEN:1e3}sort(e){e=this.assignSort(e);for(let t of this.trackView.viewports)if(t.containsPosition(e.chr,e.position)){const i=t.cachedFeatures;i&&(i.sortRows(e),t.repaint())}}assignSort(e){if(e.locus){const t=function(e){const t=e.split(":"),i=t[1].split("-"),n={chr:t[0],start:Number.parseInt(i[0].replace(/,/g,""))-1};return i.length>1?n.end=Number.parseInt(i[1].replace(/,/g,"")):n.end=n.start+1,n}(e.locus);e.chr=t.chr,e.position=t.start}else e.position--;return e.direction="ASC"===e.direction||!0===e.direction,e.chr=this.browser.genome.getChromosomeName(e.chr),this.sortObject=e,this.sortObject}async getFeatures(e,t,i,n,r){const s=await this.featureSource.getAlignments(e,t,i);if(s.paired&&!this._pairedEndStats&&!this.config.maxFragmentLength){const e=new UF(s.alignments,this.config);e.totalCount>99&&(this._pairedEndStats=e)}s.alignments=void 0;const o=this.sortObject;return o&&o.chr===e&&o.position>=t&&o.position<=i&&s.sortRows(o),s}computePixelHeight(e){return(this.showCoverage?this.coverageTrackHeight:0)+(this.showAlignments?this.alignmentTrack.computePixelHeight(e):0)}draw(e){Eo.fillRect(e.context,0,e.pixelTop,e.pixelWidth,e.pixelHeight,{fillStyle:"rgb(255, 255, 255)"}),!0===this.showCoverage&&this.coverageTrackHeight>0?(this.trackView.axisCanvas.style.display="block",this.coverageTrack.draw(e)):this.trackView.axisCanvas.style.display="none",!0===this.showAlignments&&(this.alignmentTrack.setTop(this.coverageTrack,this.showCoverage),this.alignmentTrack.draw(e))}paintAxis(e,t,i){this.coverageTrack.paintAxis(e,t,this.coverageTrackHeight)}contextMenuItemList(e){return this.alignmentTrack.contextMenuItemList(e)}popupData(e){return!0===this.showCoverage&&e.y>=this.coverageTrack.top&&e.y=this.coverageTrack.top&&e.y=this.coverageTrack.top&&e.y");const t=ut('
');t.text("Color by:"),e.push({name:void 0,object:t,click:void 0,init:void 0});const i=[{key:"strand",label:"read strand"}];this.alignmentTrack.hasPairs&&(i.push({key:"firstOfPairStrand",label:"first-of-pair strand"}),i.push({key:"pairOrientation",label:"pair orientation"}),i.push({key:"tlen",label:"insert size (TLEN)"}),i.push({key:"unexpectedPair",label:"pair orientation & insert size (TLEN)"}));const n="tag"+(this.alignmentTrack.colorByTag?" ("+this.alignmentTrack.colorByTag+")":"");i.push({key:"tag",label:n});for(let t of i){const i=this.alignmentTrack.colorBy===t.key;e.push(this.colorByCB(t,i))}const r=()=>{if(!this.autoHeight){const e=(this.showCoverage?this.coverageTrackHeight:0)+(this.showAlignments?this.alignmentTrack.height:0);this.trackView.setTrackHeight(e)}};e.push("
"),e.push({object:ut(Kt("Show Coverage",this.showCoverage)),click:()=>{this.showCoverage=!this.showCoverage,r(),this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e.push({object:ut(Kt("Show Alignments",this.showAlignments)),click:()=>{this.showAlignments=!this.showAlignments,r(),this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e.push("
"),e.push({object:ut(Kt("Show all bases",this.showAllBases)),click:()=>{this.showAllBases=!this.showAllBases,this.config.showAllBases=this.showAllBases,this.trackView.repaintViews()}}),e.push("
"),e.push({object:ut(Kt("Show mismatches",this.showMismatches)),click:()=>{this.showMismatches=!this.showMismatches,this.config.showMismatches=this.showMismatches,this.trackView.repaintViews()}}),e.push({object:ut(Kt("Show insertions",this.showInsertions)),click:()=>{this.showInsertions=!this.showInsertions,this.config.showInsertions=this.showInsertions,this.getCachedAlignmentContainers(),this.trackView.repaintViews()}}),e.push({object:ut(Kt("Show soft clips",this.showSoftClips)),click:()=>{this.showSoftClips=!this.showSoftClips,this.config.showSoftClips=this.showSoftClips,this.featureSource.setShowSoftClips(this.showSoftClips);const e=this.getCachedAlignmentContainers();for(let t of e)t.setShowSoftClips(this.showSoftClips);this.trackView.repaintViews()}}),this.pairsSupported&&this.alignmentTrack.hasPairs&&(e.push("
"),e.push({object:ut(Kt("View as pairs",this.viewAsPairs)),click:()=>{this.viewAsPairs=!this.viewAsPairs,this.config.viewAsPairs=this.viewAsPairs,this.featureSource.setViewAsPairs(this.viewAsPairs);const e=this.getCachedAlignmentContainers();for(let t of e)t.setViewAsPairs(this.viewAsPairs);this.trackView.repaintViews()}})),this.browser.circularView&&(this.alignmentTrack.hasPairs||this.alignmentTrack.hasSupplemental)&&(e.push("
"),this.alignmentTrack.hasPairs&&e.push({label:"Add discordant pairs to circular view",click:()=>{for(let e of this.trackView.viewports)this.addPairedChordsForViewport(e)}}),this.alignmentTrack.hasSupplemental&&e.push({label:"Add split reads to circular view",click:()=>{for(let e of this.trackView.viewports)this.addSplitChordsForViewport(e)}})),e.push("
");const s=ut('
');return s.text("Display mode:"),e.push({name:void 0,object:s,click:void 0,init:void 0}),e.push({object:ut(Kt("expand","EXPANDED"===this.alignmentTrack.displayMode)),click:()=>{this.alignmentTrack.displayMode="EXPANDED",this.config.displayMode="EXPANDED",this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e.push({object:ut(Kt("squish","SQUISHED"===this.alignmentTrack.displayMode)),click:()=>{this.alignmentTrack.displayMode="SQUISHED",this.config.displayMode="SQUISHED",this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e}colorByCB(e,t){return{name:void 0,object:ut(Kt(e.label,t)),click:t=>{"tag"!==e.key?e.key===this.alignmentTrack.colorBy?(this.alignmentTrack.colorBy="none",this.config.colorBy="none",this.trackView.repaintViews()):(this.alignmentTrack.colorBy=e.key,this.config.colorBy=e.key,this.trackView.repaintViews()):this.browser.inputDialog.present({label:"Tag Name",value:this.alignmentTrack.colorByTag?this.alignmentTrack.colorByTag:"",callback:e=>{e?(this.alignmentTrack.colorBy="tag",this.alignmentTrack.colorByTag=e,this.alignmentTrack.tagColors||(this.alignmentTrack.tagColors=new bo("Set1"))):(this.alignmentTrack.colorBy="none",this.alignmentTrack.colorByTag=""),this.trackView.repaintViews()}},t)},init:void 0}}getState(){const e=super.getState();return this.sortObject&&(e.sort={chr:this.sortObject.chr,position:this.sortObject.position+1,option:this.sortObject.option,direction:this.sortObject.direction?"ASC":"DESC"}),this.alignmentTrack.highlightedReads&&(e.highlightedReads=Array.from(this.alignmentTrack.highlightedReads)),e}getCachedAlignmentContainers(){return this.trackView.viewports.map((e=>e.cachedFeatures))}get dataRange(){return this.coverageTrack.dataRange}set dataRange(e){this.coverageTrack.dataRange=e}get logScale(){return this.coverageTrack.logScale}set logScale(e){this.coverageTrack.logScale=e}get autoscale(){return this.coverageTrack.autoscale}set autoscale(e){this.coverageTrack.autoscale=e}addPairedChordsForViewport(e){const t=this.maxTemplateLength,i=[],n=e.referenceFrame;for(let r of e.cachedFeatures.allAlignments())r.end>=n.start&&r.start<=n.end&&(r.paired?r.end-r.start>t&&i.push(r):r.mate&&r.mate.chr&&(r.mate.chr!==r.chr||Math.max(r.fragmentLength)>t)&&i.push(r));const r=(e=>{const t=[];for(let i of e)if(i.paired)i.firstAlignment&&i.secondAlignment&&t.push({uniqueId:i.readName,refName:kF(i.firstAlignment.chr),start:i.firstAlignment.start,end:i.firstAlignment.end,mate:{refName:kF(i.secondAlignment.chr),start:i.secondAlignment.start,end:i.secondAlignment.end}});else{const e=i.mate;e&&e.chr&&e.position&&t.push({uniqueId:i.readName,refName:kF(i.chr),start:i.start,end:i.end,mate:{refName:kF(e.chr),start:e.position-1,end:e.position}})}return t})(i);IF(r,this,n,.02)}addSplitChordsForViewport(e){const t=[],i=e.referenceFrame;for(let n of e.cachedFeatures.allAlignments()){const e=n.hasTag("SA");n.end>=i.start&&n.start<=i.end&&e&&t.push(n)}const n=(e=>{const t=e=>{const t=fm(e.tags().SA);let n=0;for(let r of t)r.start!==e.start&&i.push({uniqueId:`${e.readName}_${n++}`,refName:kF(e.chr),start:e.start,end:e.end,mate:{refName:kF(r.chr),start:r.start,end:r.start+r.lenOnRef}})},i=[];for(let i of e)i.paired?(t(i.firstAlignment),i.secondAlignment&&t(i.secondAlignment)):t(i);return i})(t);IF(n,this,i,.02)}}class ob{constructor(e,t){this.parent=t,this.featureSource=t.featureSource,this.paintAxis=Jm,this.top=0,this.autoscale=e.autoscale||void 0===e.max,this.autoscale||(this.dataRange={min:e.min||0,max:e.max})}get height(){return this.parent.coverageTrackHeight}draw(e){const t=e.pixelTop;e.pixelHeight;const i=this.parent.browser.nucleotideColors;if(t>this.height)return;const n=e.context,r=e.features,s=r.coverageMap;let o;s.refSeq&&(o=s.refSeq.toUpperCase());const a=e.bpPerPixel,A=e.bpStart,c=A+e.pixelWidth*a+1;let l;l=this.parent.coverageColor?this.parent.coverageColor:this.parent.color&&"function"!=typeof this.parent.color?Ts.darkenLighten(this.parent.color,-35):"rgb(150, 150, 150)",Eo.setProperties(n,{fillStyle:l,strokeStyle:l});const h=Math.max(1,Math.ceil(1/a));for(let e=0,t=s.coverage.length;ec)break;const i=s.coverage[e];if(!i)continue;const r=Math.round(i.total/this.dataRange.max*this.height),o=this.height-r,l=Math.floor((t-A)/a);Eo.fillRect(n,l,o,h,r)}if(o)for(let e=0,t=s.coverage.length;ec)break;const l=s.coverage[e];if(!l)continue;const d=l.total/this.dataRange.max*this.height;let u=this.height-d;const f=Math.floor((t-A)/a),p=o[e];if("basemod2"===this.parent.colorBy||"basemod"===this.parent.colorBy){const e=.5;ib(n,f,this.height,h,d,t,r,this.parent.colorBy,e)}else if(l.isMismatch(p)){Eo.setProperties(n,{fillStyle:i[p]}),Eo.fillRect(n,f,u,h,d);let e=0;for(let t of["A","C","T","G"]){const r=(l["pos"+t]+l["neg"+t])/this.dataRange.max*this.height;u=this.height-r-e,e+=r,Eo.setProperties(n,{fillStyle:i[t]}),Eo.fillRect(n,f,u,h,r)}}}}getClickedObject(e){let t=e.viewport.cachedFeatures;if(!t||0===t.length)return;const i=Math.floor(e.genomicLocation),n=t.coverageMap,r=Math.floor(i-n.bpStart);return n.coverage[r]}popupData(e){const t=[],i=this.getClickedObject(e);if(i){const n=Math.floor(e.genomicLocation),r=e.viewport.referenceFrame;t.push(r.chr+":"+Xt(1+n)),t.push({name:"Total Count",value:i.total});let s=i.posA+i.negA;s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posA+"+, "+i.negA+"- )"),t.push({name:"A",value:s}),s=i.posC+i.negC,s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posC+"+, "+i.negC+"- )"),t.push({name:"C",value:s}),s=i.posG+i.negG,s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posG+"+, "+i.negG+"- )"),t.push({name:"G",value:s}),s=i.posT+i.negT,s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posT+"+, "+i.negT+"- )"),t.push({name:"T",value:s}),s=i.posN+i.negN,s>0&&(s=s.toString()+" ("+Math.round(s/i.total*100)+"%, "+i.posN+"+, "+i.negN+"- )"),t.push({name:"N",value:s}),t.push("
"),t.push({name:"DEL",value:i.del.toString()}),t.push({name:"INS",value:i.ins.toString()})}return t}}class ab{constructor(e,t){this.parent=t,this.browser=t.browser,this.featureSource=t.featureSource,this.top=0===e.coverageTrackHeight?0:e.coverageTrackHeight+5,this.displayMode=e.displayMode||"EXPANDED",this.alignmentRowHeight=e.alignmentRowHeight||14,this.squishedRowHeight=e.squishedRowHeight||3,this.negStrandColor=e.negStrandColor||"rgba(150, 150, 230, 0.75)",this.posStrandColor=e.posStrandColor||"rgba(230, 150, 150, 0.75)",this.insertionColor=e.insertionColor||"rgb(138, 94, 161)",this.insertionTextColor=e.insertionTextColor||"white",this.showInsertionText=void 0!==e.showInsertionText&&!!e.showInsertionText,this.deletionColor=e.deletionColor||"black",this.deletionTextColor=e.deletionTextColor||"black",this.showDeletionText=void 0!==e.showDeletionText&&!!e.showDeletionText,this.skippedColor=e.skippedColor||"rgb(150, 170, 170)",this.pairConnectorColor=e.pairConnectorColor,this.smallTLENColor=e.smallTLENColor||e.smallFragmentLengthColor||"rgb(0, 0, 150)",this.largeTLENColor=e.largeTLENColor||e.largeFragmentLengthColor||"rgb(200, 0, 0)",this.pairOrientation=e.pairOrienation||"fr",this.pairColors={},this.pairColors.RL=e.rlColor||"rgb(0, 150, 0)",this.pairColors.RR=e.rrColor||"rgb(20, 50, 200)",this.pairColors.LL=e.llColor||"rgb(0, 150, 150)",this.colorBy=e.colorBy||"unexpectedPair",this.colorByTag=e.colorByTag?e.colorByTag.toUpperCase():void 0,this.bamColorTag=void 0===e.bamColorTag?"YC":e.bamColorTag,this.hideSmallIndels=e.hideSmallIndels,this.indelSizeThreshold=e.indelSizeThreshold||1,e.highlightedReads&&this.setHighlightedReads(e.highlightedReads),e.highlightColor&&(this.highlightColor=e.highlightColor),this.hasPairs=!1,this.hasSupplemental=!1}get baseModRenderer(){return this._baseModRenderer||(this._baseModRenderer=new nb(this)),this._baseModRenderer}setTop(e,t){this.top=0===e.height||!1===t?0:5+e.height}setHighlightedReads(e){if(!Array.isArray(e)||!e.every((e=>"string"==typeof e)))throw new Error("AlignmentTrack.setHighlightedReads() only accept array of strings");this.highlightedReads=new Set(e)}computePixelHeight(e){if(e.packedAlignmentRows){return(e.hasDownsampledIntervals()?10:0)+("SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight)*e.packedAlignmentRows.length+5}return 0}draw(e){const t=e.features,i=e.context,n=e.bpPerPixel,r=e.bpStart,s=e.pixelWidth,o=r+s*n+1,a=this.parent.showSoftClips,A=this.parent.showAllBases,c=this.browser.nucleotideColors,l=t.packedAlignmentRows;i.save();let h=t.sequence;h&&(h=h.toUpperCase());let d=0,u=e.pixelTop;this.top&&i.translate(0,this.top);const f=u+e.pixelHeight;t.hasDownsampledIntervals()?(d=10,t.downsampledIntervals.forEach((function(e){var t=(e.start-r)/n,s=(e.end-r)/n;s-t>5&&(t+=1,s-=1),Eo.fillRect(i,t,2,s-t,3,{fillStyle:"black"})}))):d=0,this.alignmentsYOffset=d;const p="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight;if(l){const e=l.length;for(let t=0;tf)break;if(!(i+no)break;!0!==t.hidden&&(t instanceof $w?(g.call(this,t,i,n),w.call(this,t.firstAlignment,i,n),t.secondAlignment&&w.call(this,t.secondAlignment,i,n)):w.call(this,t,i,n))}}}function g(e,t,s){var a=this.getConnectorColor(e.firstAlignment),A=(e.connectingStart-r)/n,c=(e.connectingEnd-r)/n,l=t+s/2;e.connectingEndo||(e.mq<=0&&(a=Ts.addAlpha(a,.15)),Eo.setProperties(i,{fillStyle:a,strokeStyle:a}),Eo.strokeLine(i,A,l,c,l))}function w(e,l,d){if(e.start+e.lengthOnRefo)return;const u=a?e.blocks:e.blocks.filter((e=>"S"!==e.type));let f=this.getAlignmentColor(e);const g=f;e.mq<=0&&(f=Ts.addAlpha(f,.15)),Eo.setProperties(i,{fillStyle:f,strokeStyle:g});const w=[];for(let e=0;eo))break}if(e.gaps){const t=l+d/2;for(let s of e.gaps){const e=(s.start-r)/n,o=(s.start+s.len-r)/n,a=o-e,A=s.len.toString(),c=6*A.length,h=e+a/2,d="D"===s.type?this.deletionColor:this.skippedColor;if(Eo.strokeLine(i,e,t,o,t,{strokeStyle:d,lineWidth:2}),this.showDeletionText&&s.len>1&&a>=c+8){const e=h-c/2;Eo.fillRect(i,e-1,l-1,c+2,12,{fillStyle:"white"}),Eo.fillText(i,A,e,l+10,{font:"normal 10px monospace",fillStyle:this.deletionTextColor})}}}if(e.insertions&&this.parent.showInsertions){let t=-1;for(let s of e.insertions){if(this.hideSmallIndels&&s.len<=this.indelSizeThreshold)continue;if(s.starto)break;const e=s.start-r,a=s.len.toString(),A=2+6*a.length,c=this.showInsertionText&&1!==s.len?Math.round(s.len/n):2,h=Math.max(Math.min(A,c),2),u=e/n-h/2;if(u-t>2){const e={fillStyle:this.insertionColor};Eo.fillRect(i,u-2,l,h+4,2,e),Eo.fillRect(i,u,l+2,h,d-4,e),Eo.fillRect(i,u-2,l+d-2,h+4,2,e),this.showInsertionText&&s.len>1&&c>A&&Eo.fillText(i,a,u+1,l+10,{font:"normal 10px monospace",fillStyle:this.insertionTextColor}),t=u}}}for(let{bbox:e,baseColor:t,readChar:r}of w){if(n<=.1&&e.height>=8){const n=Math.min(10,e.height);i.font=n+"px sans-serif";const s=e.x+e.width/2;Eo.strokeText(i,r,s-i.measureText(r).width/2,n-1+e.y,{strokeStyle:t})}else Eo.fillRect(i,e.x,e.y,e.width,e.height,{fillStyle:t})}if("basemod2"===this.colorBy||"basemod"===this.parent.colorBy){const t={ctx:i,bpPerPixel:n,bpStart:r,bpEnd:o,pixelEnd:s};this.baseModRenderer.drawModifications(e,l,d,t,this.parent.colorBy)}function m(o,a){const w=[],m=o.start-t.start,F=(o.start-r)/n,b=(o.start+o.len-r)/n,v=Math.max(1,b-F),B=100/n,y=Math.min(p/2,B/6),C="S"===o.type,_=e.mq<=0||this.selectedReadName===e.readName||C||this.highlightedReads&&this.highlightedReads.has(e.readName);let x=g;this.selectedReadName===e.readName?x="red":C?x="rgb(50,50,50)":this.highlightedReads&&this.highlightedReads.has(e.readName)&&(x=this.highlightColor||"#00ff00");const k=!0===e.strand&&a===u.length-1,E=!1===e.strand&&0===a;if(k|E){let e,t;k?(e=[F,b,b+y,b,F,F],t=[l,l,l+d/2,l+d,l+d,l]):E&&(e=[b,F,F-y,F,b,b],t=[l,l,l+d/2,l+d,l+d,l]),Eo.fillPolygon(i,e,t,{fillStyle:f}),_&&Eo.strokePolygon(i,e,t,{strokeStyle:x})}else Eo.fillRect(i,F,l,v,d,{fillStyle:f}),_&&(i.save(),i.strokeStyle=x,i.strokeRect(F,l,v,d),i.restore());if(C||A||this.parent.showMismatches&&h&&e.seq&&"*"!==e.seq){const t=e.seq?e.seq.toUpperCase():void 0,i=e.qual,a=o.seqOffset,u=Math.max(1,1/n);for(let e=0,f=o.len;es)break;let p=t?t.charAt(a+e):"";const g=m+e>=0?h.charAt(m+e):"";if("="===p&&(p=g),"X"===p||g!==p||C||A){let t;if(!C&&void 0!==i&&i.length>a+e){t=Ab(i[a+e],c[p])}else t=c[p];t&&w.push({bbox:{x:f,y:l,width:u,height:d},baseColor:t,readChar:p})}}}return w}}i.restore()}popupData(e){const t=this.getClickedObject(e);return t?t.popupData(e.genomicLocation):void 0}contextMenuItemList(e){const t=e.viewport,i=[],n=i=>{const n=this.parent.sortObject,r=!n||n.position!==Math.floor(e.genomicLocation)||!n.direction,s={chr:t.referenceFrame.chr,position:Math.floor(e.genomicLocation),option:i,direction:r,sortAsPairs:t.trackView.track.viewAsPairs};this.parent.sortObject=s,t.cachedFeatures.sortRows(s),t.repaint()};i.push("Sort by..."),i.push({label:"  base",click:()=>n("BASE")}),i.push({label:"  read strand",click:()=>n("STRAND")}),i.push({label:"  start location",click:()=>n("START")}),i.push({label:"  insert size",click:()=>n("INSERT_SIZE")}),i.push({label:"  gap size",click:()=>n("GAP_SIZE")}),i.push({label:"  chromosome of mate",click:()=>n("MATE_CHR")}),i.push({label:"  mapping quality",click:()=>n("MQ")}),i.push({label:"  read name",click:()=>n("READ_NAME")}),i.push({label:"  aligned read length",click:()=>n("ALIGNED_READ_LENGTH")}),i.push({label:"  tag",click:()=>{const i=this.parent.sortObject,n=!i||i.position!==Math.floor(e.genomicLocation)||!i.direction,r={label:"Tag Name",value:this.sortByTag?this.sortByTag:"",callback:i=>{if(i){const r={chr:t.referenceFrame.chr,position:Math.floor(e.genomicLocation),option:"TAG",tag:i,direction:n};this.sortByTag=i,this.parent.sortObject=r,t.cachedFeatures.sortRows(r),t.repaint()}}};this.browser.inputDialog.present(r,e.event)}}),i.push("
");const r=this.getClickedObject(e);if(r){const t=this.parent.showSoftClips,n="function"==typeof r.alignmentContaining?r.alignmentContaining(e.genomicLocation,t):r;if(n){n.isPaired()&&n.isMateMapped()&&i.push({label:"View mate in split screen",click:()=>{if(n.mate){const t=e.viewport.referenceFrame,i=this.browser.genome.getChromosome(n.mate.chr);if(i){this.selectedReadName=n.readName;const e=t.end-t.start,r=n.mate.position-e/2,s=n.mate.position+e/2;this.browser.addMultiLocusPanel(i.name,r,s,t)}else this.browser.alert.present(`Reference does not contain chromosome: ${n.mate.chr}`)}},init:void 0}),i.push({label:"View read sequence",click:()=>{const e=n.seq;e&&"*"!==e?this.browser.alert.present(e):this.browser.alert.present("Read sequence: *")}}),hf()&&i.push({label:"Copy read sequence",click:async()=>{const e=n.seq;try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}});const t=n.seq;if(t&&"*"!=t){t.length{const e=n.isNegativeStrand()?kf(t):t,i=`${n.readName} - blat`,r=`${this.parent.name} - ${i}`;$F({sequence:e,browser:this.browser,name:i,title:r})}});const e=n.softClippedBlocks();e.left&&e.left.len>20&&e.left.len{const i=t.substr(e.left.seqOffset,e.left.len),r=n.isNegativeStrand()?kf(i):i,s=`${n.readName} - blat left clip`,o=`${this.parent.name} - ${s}`;$F({sequence:r,browser:this.browser,name:s,title:o})}}),e.right&&e.right.len>20&&e.right.len{const i=t.substr(e.right.seqOffset,e.right.len),r=n.isNegativeStrand()?kf(i):i,s=`${n.readName} - blat right clip`,o=`${this.parent.name} - ${s}`;$F({sequence:r,browser:this.browser,name:s,title:o})}})}i.push("
")}}return this.browser.circularView&&(this.hasPairs||this.hasSupplemental)&&(this.hasPairs&&i.push({label:"Add discordant pairs to circular view",click:()=>{this.parent.addPairedChordsForViewport(t)}}),this.hasSupplemental&&i.push({label:"Add split reads to circular view",click:()=>{this.parent.addSplitChordsForViewport(t)}}),i.push("
")),i}getClickedObject(e){const t=e.viewport,i=e.y,n=e.genomicLocation,r=this.parent.showSoftClips;let s=t.cachedFeatures;if(!s||0===s.length)return;let o=s.packedAlignmentRows,a=s.downsampledIntervals;const A="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight;let c=Math.floor((i-this.top-this.alignmentsYOffset)/A);if(c<0){for(let e=0;e=n)return a[e]}else if(ce.containsLocation(n,r)));if(e.length>0)return e[0]}}getConnectorColor(e){if(this.pairConnectorColor)return this.pairConnectorColor;switch(this.colorBy){case"strand":case"firstOfPairStrand":case"pairOrientation":case"tag":return this.parent.color?"function"==typeof this.parent.color?this.parent.color(e):this.parent.color:"rgb(200, 200, 200)";default:return this.getAlignmentColor(e)}}getAlignmentColor(e){let t=rb;t=this.parent.color?"function"==typeof this.parent.color?this.parent.color(e):this.parent.color:rb;const i=this.colorBy;switch(i){case"strand":t=e.strand?this.posStrandColor:this.negStrandColor;break;case"firstOfPairStrand":e instanceof $w?t=e.firstOfPairStrand()?this.posStrandColor:this.negStrandColor:e.isPaired()&&(e.isFirstOfPair()?t=e.strand?this.posStrandColor:this.negStrandColor:e.isSecondOfPair()?t=e.strand?this.negStrandColor:this.posStrandColor:console.error("ERROR. Paired alignments are either first or second."));break;case"unexpectedPair":case"pairOrientation":if(this.pairOrientation&&e.pairOrientation){const i=cb[this.pairOrientation];if(i){const n=this.pairColors[i[e.pairOrientation]];if(n){t=n;break}}}if("pairOrientation"===i)break;case"tlen":case"fragmentLength":e.mate&&e.isMateMapped()&&(e.mate.chr!==e.chr?t=lb(e.mate.chr):this.parent.minTemplateLength&&Math.abs(e.fragmentLength)this.parent.maxTemplateLength&&(t=this.largeTLENColor));break;case"tag":const n=e.tags()[this.colorByTag];void 0!==n&&(this.bamColorTag===this.colorByTag?t="rgb("+n+")":(this.tagColors||(this.tagColors=new bo("Set1")),t=this.tagColors.getColor(n)))}return t}get color(){return this.parent.color}get showSortClips(){return this.parent.showSoftClips}get showAllBases(){return this.parent.showAllBases}get nucleotideColors(){return this.browser.nucleotideColors}get minTemplateLength(){return this.parent.minTemplateLength}get maxTemplateLength(){return this.parent.maxTemplateLength}get colorBy(){return this.parent.colorBy}set colorBy(e){this.parent.colorBy=e}}function Ab(e,t){let i;return i=e<5?.1:Math.max(.1,Math.min(1,.1+.9*(e-5)/15)),i=Math.round(10*i)/10,i<1&&(t=Ts.addAlpha(t,i)),t}const cb={fr:{F1R2:"LR",F2R1:"LR",F1F2:"LL",F2F1:"LL",R1R2:"RR",R2R1:"RR",R1F2:"RL",R2F1:"RL"},rf:{R1F2:"LR",R2F1:"LR",R1R2:"LL",R2R1:"LL",F1F2:"RR",F2F1:"RR",F1R2:"RL",F2R1:"RL"},ff:{F2F1:"LR",R1R2:"LR",F2R1:"LL",R1F2:"LL",R2F1:"RR",F1R2:"RR",R2R1:"RL",F1F2:"RL"}};function lb(e){if(hb[e])return hb[e];if(hb["chr"+e]){const t=hb["chr"+e];return hb[e]=t,t}{const t=Ts.randomRGB(0,255);return hb[e]=t,t}}const hb={chrX:"rgb(204, 153, 0)",chrY:"rgb(153, 204, 0)",chrUn:"rgb(50, 50, 50)",chr1:"rgb(80, 80, 255)",chrI:"rgb(139, 155, 187)",chr2:"rgb(206, 61, 50)",chrII:"rgb(206, 61, 50)",chr2a:"rgb(216, 71, 60)",chr2b:"rgb(226, 81, 70)",chr3:"rgb(116, 155, 88)",chrIII:"rgb(116, 155, 88)",chr4:"rgb(240, 230, 133)",chrIV:"rgb(240, 230, 133)",chr5:"rgb(70, 105, 131)",chr6:"rgb(186, 99, 56)",chr7:"rgb(93, 177, 221)",chr8:"rgb(128, 34, 104)",chr9:"rgb(107, 215, 107)",chr10:"rgb(213, 149, 167)",chr11:"rgb(146, 72, 34)",chr12:"rgb(131, 123, 141)",chr13:"rgb(199, 81, 39)",chr14:"rgb(213, 143, 92)",chr15:"rgb(122, 101, 165)",chr16:"rgb(228, 175, 105)",chr17:"rgb(59, 27, 83)",chr18:"rgb(205, 222, 183)",chr19:"rgb(97, 42, 121)",chr20:"rgb(174, 31, 99)",chr21:"rgb(231, 199, 111)",chr22:"rgb(90, 101, 94)",chr23:"rgb(204, 153, 0)",chr24:"rgb(153, 204, 0)",chr25:"rgb(51, 204, 0)",chr26:"rgb(0, 204, 51)",chr27:"rgb(0, 204, 153)",chr28:"rgb(0, 153, 204)",chr29:"rgb(10, 71, 255)",chr30:"rgb(71, 117, 255)",chr31:"rgb(255, 194, 10)",chr32:"rgb(255, 209, 71)",chr33:"rgb(153, 0, 51)",chr34:"rgb(153, 26, 0)",chr35:"rgb(153, 102, 0)",chr36:"rgb(128, 153, 0)",chr37:"rgb(51, 153, 0)",chr38:"rgb(0, 153, 26)",chr39:"rgb(0, 153, 102)",chr40:"rgb(0, 128, 153)",chr41:"rgb(0, 51, 153)",chr42:"rgb(26, 0, 153)",chr43:"rgb(102, 0, 153)",chr44:"rgb(153, 0, 128)",chr45:"rgb(214, 0, 71)",chr46:"rgb(255, 20, 99)",chr47:"rgb(0, 214, 143)",chr48:"rgb(20, 255, 177)"};let db,ub;class fb extends up{constructor(e,t,i,n){super(e,t,i,n)}get contentDiv(){return this.$viewport.get(0)}initializationHelper(){let e;this.$multiLocusCloseButton=ut("
",{class:"igv-multi-locus-close-button"}),this.$viewport.append(this.$multiLocusCloseButton),this.$multiLocusCloseButton.get(0).appendChild(xt.createIcon("times-circle")),this.$multiLocusCloseButton.click((()=>{this.browser.removeMultiLocusPanel(this.referenceFrame)})),this.$rulerLabel=ut("
",{class:"igv-multi-locus-ruler-label"}),this.$viewport.append(this.$rulerLabel),e=document.createElement("div"),this.$rulerLabel.append(ut(e)),this.$rulerLabel.get(0).addEventListener("click",(async e=>{e.stopPropagation(),await this.browser.gotoMultilocusPanel(this.referenceFrame)})),this.$tooltip=ut("
",{class:"igv-ruler-tooltip"}),this.$tooltip.height(this.$viewport.height()),this.$viewport.append(this.$tooltip),this.$tooltipContent=ut("
"),this.$tooltip.append(this.$tooltipContent),this.rulerSweeper=new Ww(this,this.$viewport.get(0).parentElement,this.browser,this.referenceFrame),this.attachMouseHandlers(Ap.isWholeGenomeView(this.referenceFrame.chr)),this.$tooltip.hide(),this.dismissLocusLabel()}presentLocusLabel(e){this.$multiLocusCloseButton.show(),this.$rulerLabel.show(),this.$rulerLabel.get(0).style.backgroundColor=lb(this.referenceFrame.chr);const t=this.$rulerLabel.get(0).querySelector("div"),{width:i}=this.$rulerLabel.get(0).getBoundingClientRect();t.innerHTML=`${this.referenceFrame.getMultiLocusLabel(e)}`;const{width:n}=t.getBoundingClientRect();n/i>.5&&(t.innerHTML=`${this.referenceFrame.getMultiLocusLabelBPLengthOnly(e)}`)}dismissLocusLabel(){this.$rulerLabel.hide(),this.$multiLocusCloseButton.hide()}attachMouseHandlers(e){if(this.namespace=`.ruler_track_viewport_${this.browser.referenceFrameList.indexOf(this.referenceFrame)}`,this.$viewport.off(this.namespace),!0===e){const e=this.browser.referenceFrameList.indexOf(this.referenceFrame),t=`click${this.namespace}`;this.$viewport.on(t,(t=>{const{x:i}=vt.translateMouseCoordinates(t,this.$viewport.get(0)),n=Math.round(this.referenceFrame.start+this.referenceFrame.toBP(i));let r;const{chr:s}=this.browser.genome.getChromosomeCoordinate(n);if(1===this.browser.referenceFrameList.length)r=s;else{let t=this.browser.referenceFrameList.map((({locusSearchString:e})=>e));t[e]=s,r=t.join(" ")}this.browser.search(r)})),this.$viewport.get(0).style.cursor="pointer"}else this.$viewport.get(0).style.cursor="default"}mouseMove(e){if(!0===this.browser.cursorGuideVisible){void 0===ub?(ub=this,this.$tooltip.show()):ub.guid!==this.guid?(ub.$tooltip&&ub.$tooltip.hide(),this.$tooltip.show(),ub=this):this.$tooltip.show();if(this.browser.isMultiLocusWholeGenomeView()||Ap.isWholeGenomeView(this.referenceFrame.chr))return void this.$tooltip.hide();const{x:t}=vt.translateMouseCoordinates(e,this.$viewport.get(0)),{start:i,bpPerPixel:n}=this.referenceFrame,r=Math.round(.5+i+Math.max(0,t)*n);this.$tooltipContent.text(Xt(r));const{width:s}=this.$tooltipContent.get(0).getBoundingClientRect(),{width:o}=this.$viewport.get(0).getBoundingClientRect();this.$tooltip.css({left:`${Ms.clamp(t,0,o-s)}px`}),clearTimeout(db),db=setTimeout((()=>{this.$tooltip&&this.$tooltip.hide()}),1e4)}}startSpinner(){}stopSpinner(){}dispose(){this.rulerSweeper.dispose(),super.dispose()}}class pb extends up{constructor(e,t,i,n){super(e,t,i,n)}initializationHelper(){this.canvas=document.createElement("canvas"),this.canvas.className="igv-ideogram-canvas",this.$viewport.append(ut(this.canvas)),this.ideogram_ctx=this.canvas.getContext("2d"),this.addMouseHandlers()}addMouseHandlers(){this.addViewportClickHandler(this.$viewport.get(0))}addViewportClickHandler(e){this.boundClickHandler=function(e){const{xNormalized:t,width:i}=vt.translateMouseCoordinates(e,this.ideogram_ctx.canvas),{bpLength:n}=this.browser.genome.getChromosome(this.referenceFrame.chr),r=this.referenceFrame.bpPerPixel*i/n;let s=t;s-r/2<0&&(s=r/2);s+r/2>1&&(s=1-r/2);const o=Math.round((s-r/2)*n),a=Math.round((s+r/2)*n);this.referenceFrame.start=o,this.referenceFrame.end=a,this.referenceFrame.bpPerPixel=(a-o)/i,this.browser.updateViews(this.referenceFrame,this.browser.trackViews,!0)}.bind(this),e.addEventListener("click",this.boundClickHandler)}setWidth(e){this.$viewport.width(e)}drawSVGWithContext(e,t,i,n,r,s,o){e.saveWithTranslationAndClipRect(n,r,s,t,i,o),this.trackView.track.draw({context:e,referenceFrame:this.referenceFrame,pixelWidth:t,pixelHeight:i}),e.restore()}repaint(){this.draw({referenceFrame:this.referenceFrame})}draw({referenceFrame:e}){Eo.configureHighDPICanvas(this.ideogram_ctx,this.$viewport.width(),this.$viewport.height()),this.trackView.track.draw({context:this.ideogram_ctx,referenceFrame:e,pixelWidth:this.$viewport.width(),pixelHeight:this.$viewport.height()})}startSpinner(){}stopSpinner(){}}function gb(e,t,i,n){if("ruler"===e.track.type)return new fb(e,t,i,n);if("ideogram"===e.track.id)return new pb(e,t,i,n);return new up(e,t,i,n)}const wb=["rgb(255, 0, 0)","rgb(0, 255, 0)","rgb(0, 0, 255)","rgb(255, 0, 255)","rgb(0, 255, 255)","rgb(128, 0, 128)","rgb(255, 165, 0)","rgb(255, 105, 180)","rgb(255, 127, 80)","rgb(220, 20, 60)","rgb(255, 99, 71)","rgb(173, 216, 230)","rgb(144, 238, 144)","rgb(224, 255, 255)","rgb(250, 250, 210)","rgb(152, 251, 152)","rgb(70, 130, 180)","rgb(102, 205, 170)"].map((e=>{const[t,i,n]=e.split(","),[r,s]=t.split("("),[o,a]=n.split(")");return[s,i,o]}));let mb,Fb,bb,vb,Bb,yb={};const Cb="|",_b=mo("magnesium");class xb{constructor(e){this.sampleInfoFiles=[];e.findTracks((e=>"function"==typeof e.getSamples)).length>0&&e.sampleInfoControl.setButtonVisibility(!0),e.on("trackorderchanged",(t=>{if(this.isInitialized()){e.findTracks((e=>"function"==typeof e.getSamples)).length>0&&e.layoutChange()}}))}initialize(){vb=void 0}isInitialized(){return void 0!==vb}getAttributeNames(){return mb}getAttributes(e){const t=void 0===Bb?e:Bb[e]||e;return vb[t]}async loadSampleInfoFile(e,t){let i;try{i=await io.loadString(t),this.processSampleInfoFileAsString(e,i)}catch(e){console.error(e.message)}!1===ti(t)&&this.sampleInfoFiles.push(t),await Ib.update(e);e.findTracks((e=>"function"==typeof e.getSamples)).length>0&&e.sampleInfoControl.setButtonVisibility(!0)}processSampleInfoFileAsString(e,t){const i=t.split("#").filter((e=>e.length>0));!function(e){const t=e.split(/[\r\n]/);t.shift();const i=t.shift().split("\t");i.shift(),mb=i.map((e=>e.split(" ").join(Cb))),Fb=new Map(mb.map(((e,t)=>[e,t])));const n=t.filter((e=>e.length>0));for(const e of n){const t=e.split("\t"),i=t.shift();void 0===vb&&(vb={}),vb[i]={};for(let e=0;e"number"==typeof e,n=e=>"string"==typeof e;for(const e of Object.keys(t)){const r=t[e],s=new Set(r),o=Array.from(s);if(!0===o.some(n)&&!0===o.some(i)?t[e]=o.filter((e=>!n(e))):t[e]=o,!t[e].some(n)){const i=t[e].slice();t[e]=[Math.min(...i),Math.max(...i)]}}return t}(vb),i.length>1&&(function(e,t){let i;if("copynumber"===t&&(i=e.filter((e=>e.startsWith(t))),i.length>0)){let e=i[0];e=e.split(/[\r\n]/).filter((e=>e.length>0)),e.shift();for(const t of e){const[e,i]=t.split("\t");void 0===Bb&&(Bb={}),Bb[e]=i}}}(i,"copynumber"),function(e){const t=e.filter((e=>e.startsWith("colors")));if(t.length>0){let e=t[0];e=e.split(/[\r\n]/).filter((e=>e.length>0)),e.shift();const i=(e,t,i)=>{let n;switch(t){case 0:n=e.split(" ").join(Cb);break;case 1:n=e.includes(":")?e.split(":").map((e=>parseFloat(e))):e;break;case 2:case 3:n=`rgb(${e})`}return n},n=e.map((e=>e.split("\t").map(i))),r=n.filter((e=>3===e.length&&!e.includes("*"))).filter((([e,t,i])=>!Array.isArray(t))),s={};for(const e of r){const[t,i,n]=e;void 0===s[t]&&(s[t]={}),s[t][i.toUpperCase()]=n}for(const[e,t]of Object.entries(s)){const i=Object.assign({},t);yb[e]=e=>{const t=e.toUpperCase();return i[t]||mo("snow")}}const o=n.filter((e=>Array.isArray(e[1])));for(const e of o){const[t,i]=e[1],n=e[0];if(3===e.length){const[r,s,o]=_o(e[2]);yb[n]=e=>{e=Ms.clamp(e,t,i);return yo(r,s,o,(e-t)/(i-t))}}else if(4===e.length){const[t,i]=e[1],[n,r,s,o]=e;yb[n]=e=>{e=Ms.clamp(e,t,i);return ko(s,o,(e-t)/(i-t))}}}const a=n.filter((e=>3===e.length&&e.includes("*")));for(const e of a)if("*"===e[1]){const[t,i,n]=e;yb[t]=e=>{if("NA"===e)return _b;{const[i,r]=bb[t],s=(e-i)/(r-i),[o,a,A]=_o(n);return yo(o,a,A,s)}}}else if("*"===e[0]){const[t,i,n]=e;yb[i]=()=>n}}}(i))}getAttributeColor(e,t){let i;if("-"===t)i=mo("snow");else if("string"==typeof t&&yb[t])i=yb[t]();else if(yb[e])i=yb[e](t);else if("string"==typeof t)i="NA"===t?_b:function(e){let t=0;for(let i=0;i>8*e&255;i.push(n)}return`rgb(${i.join(", ")})`}(t);else{const[n,r]=bb[e],s=.2,o=Math.max((t-n)/(r-n),s),[a,A,c]=wb[Object.keys(bb).indexOf(e)];i=`rgba(${a},${A},${c},${o})`}return i}getSortedSampleKeysByAttribute(e,t,i){const n=e.filter((e=>"number"==typeof this.getAttributes(e)[t])),r=e.filter((e=>"string"==typeof this.getAttributes(e)[t])),s=(e,n)=>{const r=this.getAttributes(e)[t],s=this.getAttributes(n)[t];return"string"==typeof r&&"string"==typeof s?i*r.localeCompare(s):"number"==typeof r&&"number"==typeof s?i*(r-s):void 0};return n.sort(s),r.sort(s),-1===i?[...n,...r]:[...r,...n]}toJSON(e){for(const t of this.sampleInfoFiles)e.push({type:"sampleinfo",url:t})}}function kb(e){const t=Object.assign({},e);for(const[e,i]of Object.entries(t))"string"!=typeof i||isNaN(i)||(t[e]=Number(i));return t}class Eb{constructor(e,t,i){this.guid=vt.guid(),this.trackView=e,this.browser=e.browser,this.viewport=vt.div({class:"igv-viewport"}),t.appendChild(this.viewport),this.viewport.style.height=`${e.track.height}px`,this.canvas=document.createElement("canvas"),this.viewport.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.contentTop=0,this.hitList=void 0,this.sortDirection=1,this.setWidth(i),this.addMouseHandlers()}static getSampleInfoColumnWidth(e){return e.findTracks((e=>"function"==typeof e.getSamples)).length>0&&e.sampleInfo.isInitialized()&&!0===e.sampleInfoControl.showSampleInfo?8+16*e.sampleInfo.getAttributeNames().length:0}checkCanvas(){const e=window.devicePixelRatio,t=this.viewport.clientHeight,i=this.browser.getSampleInfoViewportWidth();if(this.canvas.width!==i*e||this.canvas.height!==t*e){const n=this.canvas;n.width=i*e,n.height=t*e,n.style.width=`${i}px`,n.style.height=`${t}px`,this.ctx=this.canvas.getContext("2d"),this.ctx.scale(e,e)}}setTop(e){if("function"==typeof this.trackView.track.getSamples){this.contentTop=e;const t=this.trackView.track.getSamples();this.repaint(t)}}setWidth(e){this.viewport.innerWidth=e,this.checkCanvas()}static async update(e){for(const{sampleNameViewport:t}of e.trackViews)t.setWidth(Eb.getSampleInfoColumnWidth(e));await e.layoutChange()}async repaint(e){this.checkCanvas(),this.draw({context:this.ctx,samples:e})}draw({context:e,samples:t}){if(e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillStyle=mo("snow"),e.fillRect(0,0,e.canvas.width,e.canvas.height),vb&&t&&t.names.length>0){this.browser.sampleInfo.getAttributeNames();const i=this.viewport.getBoundingClientRect().height;let n=1;const r=t.height;n=r-2*n<=1?0:1;let s=this.contentTop;this.hitList={};for(const o of t.names){if(s>i)break;if(s+r>0){const t=this.browser.sampleInfo.getAttributes(o);if(t){const i=Object.entries(t);for(const t of i){const[i,o]=t;e.fillStyle=this.browser.sampleInfo.getAttributeColor(i,o);const a=8+16*Fb.get(i),A=s+n,c=r-2*n;e.fillRect(a,A,16,c);const l=`${Math.floor(a)}#${Math.floor(A)}#16#${Math.ceil(c)}`;this.hitList[l]=`${i}#${o}`}}}s+=r}}}renderSVGContext(e,{deltaX:t,deltaY:i}){if("function"==typeof this.trackView.track.getSamples){const n=this.trackView.track.getSamples(),r=0,{width:s,height:o}=this.viewport.getBoundingClientRect(),a=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_sample_names_guid_${vt.guid()}`;e.saveWithTranslationAndClipRect(a,t,i+r,s,o,-r),this.draw({context:e,samples:n}),e.restore()}}addMouseHandlers(){this.addMouseMoveHandler()}addMouseMoveHandler(){this.boundMouseMoveHandler=function(e){if(e.stopPropagation(),this.hitList){const t=Object.entries(this.hitList),{x:i,y:n}=vt.translateMouseCoordinates(e,this.viewport);this.viewport.setAttribute("title","");for(const[e,r]of t){const[t,s,o,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+o||ns+a)){const[e,t]=r.split("#");this.viewport.setAttribute("title",`${e.split(Cb).join(" ")}: ${"-"===t?"":t}`);break}}}}.bind(this),this.viewport.addEventListener("mousemove",this.boundMouseMoveHandler)}removeMouseHandlers(){this.viewport.removeEventListener("mousemove",this.boundMouseMoveHandler)}show(){this.viewport.style.display="block"}hide(){this.viewport.style.display="none"}dispose(){this.removeMouseHandlers(),this.viewport.remove()}}var Ib=Eb;const Ub={textAlign:"start",textBaseline:"bottom",strokeStyle:"black",fillStyle:"black"};class Qb{constructor(e,t,i,n){this.guid=vt.guid(),this.trackView=e,this.browser=e.browser,this.viewport=vt.div({class:"igv-viewport"}),t.appendChild(this.viewport),e.track.height&&(this.viewport.style.height=`${e.track.height}px`),this.canvas=document.createElement("canvas"),this.viewport.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.trackScrollDelta=0,this.contentTop=0,this.hitList=void 0,this.sortDirection=1,this.setWidth(n),!1===this.browser.showSampleNames&&this.hide(),this.addMouseHandlers()}checkCanvas(){const e=this.browser.sampleNameViewportWidth||0;this.ctx.canvas.width=e*window.devicePixelRatio,this.ctx.canvas.style.width=`${e}px`,this.ctx.canvas.height=this.viewport.clientHeight*window.devicePixelRatio,this.ctx.canvas.style.height=`${this.viewport.clientHeight}px`,this.ctx.scale(window.devicePixelRatio,window.devicePixelRatio)}setTop(e){if("function"==typeof this.trackView.track.getSamples){this.contentTop=e;const t=this.trackView.track.getSamples();this.repaint(t)}}setWidth(e){this.viewport.innerWidth=e,this.checkCanvas()}show(){this.viewport.style.display="block"}hide(){this.viewport.style.display="none"}async repaint(e){if(e.names.length>0&&!0===this.browser.showSampleNames&&(this.checkCanvas(),this.draw({context:this.ctx,samples:e}),void 0===this.browser.sampleNameViewportWidth)){const t=e.names.map((e=>this.ctx.measureText(e).width));this.browser.sampleNameViewportWidth=Math.min(200,4+Math.ceil(Math.max(...t))),this.browser.layoutChange()}}draw({context:e,samples:t}){if(!t||0===t.names.length)return;!function(e,{textAlign:t,textBaseline:i,strokeStyle:n,fillStyle:r},s){const o=Math.min(s,10);e.font=`${o}px sans-serif`,e.textAlign=t,e.textBaseline=i,e.fillStyle=r}(e,Ub,t.height);e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillStyle=mo("lead");const i=this.viewport.getBoundingClientRect().height;let n=(t.yOffset||0)+this.contentTop;this.hitList={};for(let r of t.names){if(n>i)break;if(n+t.height>0){const i=r,s=Sb(e,i,n,t.height);e.fillText(i,4,s);const o=`${Math.floor(4)}#${Math.floor(n)}#${e.canvas.width}#${Math.ceil(t.height)}`;this.hitList[o]=`${r}`}n+=t.height}}renderSVGContext(e,{deltaX:t,deltaY:i}){if("function"==typeof this.trackView.track.getSamples){const n=this.trackView.track.getSamples(),r=0,{width:s,height:o}=this.viewport.getBoundingClientRect(),a=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_sample_names_guid_${vt.guid()}`;e.saveWithTranslationAndClipRect(a,t,i+r,s,o,-r),this.draw({context:e,samples:n}),e.restore()}}addMouseHandlers(){this.boundClickHandler=function(e){e.preventDefault(),e.stopPropagation();const t={label:"Name Panel Width",value:this.browser.sampleNameViewportWidth,callback:e=>{this.browser.sampleNameViewportWidth=parseInt(e),this.browser.layoutChange()}};this.browser.inputDialog.present(t,e)}.bind(this),this.viewport.addEventListener("contextmenu",this.boundClickHandler),this.boundMouseMoveHandler=function(e){if(e.stopPropagation(),this.hitList){const t=Object.entries(this.hitList),{x:i,y:n}=vt.translateMouseCoordinates(e,this.viewport);this.viewport.setAttribute("title","");for(const[e,r]of t){const[t,s,o,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+o||ns+a)){this.viewport.setAttribute("title",`${r}`);break}}}}.bind(this),this.viewport.addEventListener("mousemove",this.boundMouseMoveHandler)}removeMouseHandlers(){this.viewport.removeEventListener("contextmenu",this.boundClickHandler),this.viewport.removeEventListener("mousemove",this.boundMouseMoveHandler)}dispose(){this.removeMouseHandlers(),this.viewport.remove()}}function Sb(e,t,i,n){return Hb(e,t,n),i+n-Hb(e,t,n)}function Hb(e,t,i){const{actualBoundingBoxAscent:n,actualBoundingBoxDescent:r}=e.measureText(t);return(i-(n+r))/2}const Nb=function(e){this.popover=vt.div({class:"igv-menu-popup"}),e.appendChild(this.popover);const t=vt.div({class:"igv-menu-popup-header"});this.popover.appendChild(t),Et.attachDialogCloseHandlerWithParent(t,(()=>this.hide())),this.popoverContent=vt.div(),this.popover.appendChild(this.popoverContent),Ut(this.popover,t),t.addEventListener("click",(e=>{e.stopPropagation(),e.preventDefault()})),this.hide()};Nb.prototype.hide=function(){this.popover.style.display="none"},Nb.prototype.presentMenuList=function(e){if(Mb(),e.length>0){this.popoverContent.innerHTML="",e=Gt.trackMenuItemListHelper(e,this);for(let t of e){t.init&&t.init();let i=t.object;0===e.indexOf(t)&&i.removeClass("igv-track-menu-border-top"),i.hasClass("igv-track-menu-border-top")||i.hasClass("igv-menu-popup-check-container")||i.is("div")&&i.addClass("igv-menu-popup-shim"),this.popoverContent.appendChild(i.get(0))}this.popover.style.display="flex";const{width:t}=this.popover.getBoundingClientRect();this.popover.style.left=-t+"px",this.popover.style.top="0px"}},Nb.prototype.presentTrackContextMenu=function(e,t){this.popoverContent.innerHTML="";const i=(n=t,r=this.popover,n.map((e=>{let t;if("string"==typeof e&&"
"===e)t=document.createElement("hr");else if("string"==typeof e)t=vt.div({class:"context-menu"}),t.innerHTML=e;else if("Node"==typeof e)t=e;else{if("function"==typeof e.init&&e.init(),"checkbox"===e.type)t=Kt("Show all bases",e.value);else if("color"===e.type){const i=new Vt({parent:r.parentElement,width:364});i.configure(void 0,{color:t=>e.click(t)}),t=vt.div({class:"context-menu"}),"string"==typeof e.label&&(t.innerHTML=e.label);const n=e=>{i.show(),vt.hide(r),e.preventDefault(),e.stopPropagation()};t.addEventListener("click",n),t.addEventListener("touchend",n),t.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}else t=vt.div({class:"context-menu"}),"string"==typeof e.label&&(t.innerHTML=e.label);if(e.click&&"color"!==e.type){function s(t){e.click(),vt.hide(r),t.preventDefault(),t.stopPropagation()}t.addEventListener("click",s),t.addEventListener("touchend",s),t.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}}return{el:t,init:e.init}})));var n,r;for(let{el:e}of i)this.popoverContent.appendChild(e);!function(e,t){t.style.display="flex";const{x:i,y:n}=vt.translateMouseCoordinates(e,t.parentNode),{width:r}=t.getBoundingClientRect(),s=i+r,{width:o}=t.parentNode.getBoundingClientRect();t.style.left=`${s>o?i-(s-o):i}px`,t.style.top=`${n}px`}(e,this.popover)},Nb.prototype.dispose=function(){this.popoverContent.innerHTML="",this.popover.innerHTML="",Object.keys(this).forEach((function(e){this[e]=void 0}))};const Mb=()=>{const e=document.querySelectorAll(".igv-menu-popup");for(let t=0;t0&&this.viewports[0].startSpinner()}stopSpinner(){this.viewports&&this.viewports.length>0&&this.viewports[0].stopSpinner()}addDOMToColumnContainer(e,t,i){this.axis=this.createAxis(e,this.track),this.viewports=[];const n=e.calculateViewportWidth(i.length),r=t.querySelectorAll(".igv-column");for(let e=0;e{e.dataRangeDialog.configure(this),e.dataRangeDialog.present(ut(e.columnContainer))}));const{width:n,height:r}=i.getBoundingClientRect();this.axisCanvas=document.createElement("canvas"),this.axisCanvas.style.width=`${n}px`,this.axisCanvas.style.height=`${r}px`,i.appendChild(this.axisCanvas)}return i}resizeAxisCanvas(e,t){this.axis.style.width=`${e}px`,this.axis.style.height=`${t}px`,"function"==typeof this.track.paintAxis&&(this.axisCanvas.style.width=`${e}px`,this.axisCanvas.style.height=`${t}px`)}renderSVGContext(e,{deltaX:t,deltaY:i}){!function(e,t,i,n,r){if("function"==typeof t.paintAxis){const{y:s,width:o,height:a}=i.getBoundingClientRect(),A=`${(t.name||t.id).replace(/\W/g,"")}_axis_guid_${vt.guid()}`;e.saveWithTranslationAndClipRect(A,n,s+r,o,a,0),t.paintAxis(e,o,a),e.restore()}}(e,this.track,this.axisCanvas,t,i);const{width:n}=this.axis.getBoundingClientRect(),{y:r}=this.viewports[0].$viewport.get(0).getBoundingClientRect();let s={deltaX:n+t,deltaY:r+i};for(let t of this.viewports){t.renderSVGContext(e,s);const{width:i}=t.$viewport.get(0).getBoundingClientRect();s.deltaX+=i}if(!0===this.browser.sampleInfo.isInitialized()&&!0===this.browser.sampleInfoControl.showSampleInfo){this.sampleInfoViewport.renderSVGContext(e,s);const{width:t}=this.sampleInfoViewport.viewport.getBoundingClientRect();s.deltaX+=t}!0===this.browser.showSampleNames&&this.sampleNameViewport.renderSVGContext(e,s)}dataRange(){return this.track.dataRange?this.track.dataRange:void 0}setDataRange(e,t){void 0!==e&&(this.track.dataRange.min=e),void 0!==t&&(this.track.dataRange.max=t),this.track.autoscale=!1,this.repaintViews()}presentColorPicker(e){if(!1===Db.has(this.track.type)){const t=[],i=this.track.color||this.track.defaultColor;$t(i)&&t.push(i),this.track.altColor&&$t(this.track.altColor)&&t.push(this.track.altColor);const n=t.map((e=>e.startsWith("#")?e:e.startsWith("rgb(")?Ts.rgbToHex(e):Ts.colorNameToHex(e))),r={color:e=>{this.track.color=e,this.repaintViews()},altColor:e=>{this.track.altColor=e,this.repaintViews()}};this.browser.genericColorPicker.configure(n,r),this.browser.genericColorPicker.setActiveColorHandler(e),this.browser.genericColorPicker.show()}}setTrackHeight(e,t){t||(this.track.minHeight&&(e=Math.max(this.track.minHeight,e)),this.track.maxHeight&&(e=Math.min(this.track.maxHeight,e))),this.track.height=e,this.resizeAxisCanvas(this.axis.clientWidth,this.track.height),"function"==typeof this.track.paintAxis&&this.paintAxis();for(let{$viewport:t}of this.viewports)t.height(e);if(this.sampleInfoViewport.viewport.style.height=`${e}px`,this.sampleNameViewport.viewport.style.height=`${e}px`,"function"!=typeof this.track.computePixelHeight)for(let t of this.viewports)t.setContentHeight(e);this.repaintViews(),!1===Lb.has(this.track.type)&&this.updateScrollbar(),this.dragHandle.style.height=`${e}px`,this.gearContainer.style.height=`${e}px`}updateScrollbar(){const e=this.viewports[0].$viewport.height();this.outerScroll.style.height=`${e}px`;const t=this.maxViewportContentHeight(),i=Math.round(e/t*e);t>e?(this.innerScroll.style.display="block",this.innerScroll.style.height=`${i}px`):this.innerScroll.style.display="none"}moveScroller(e){const t=ut(this.innerScroll).position().top+e,i=Math.min(Math.max(0,t),this.outerScroll.clientHeight-this.innerScroll.clientHeight);ut(this.innerScroll).css("top",`${i}px`);const n=this.maxViewportContentHeight(),r=-Math.round(i*(n/this.viewports[0].$viewport.height()));for(let e of this.viewports)e.setTop(r);this.sampleInfoViewport.setTop(r),this.sampleNameViewport.trackScrollDelta=e,this.sampleNameViewport.setTop(r)}isLoading(){for(let e of this.viewports)if(e.isLoading())return!0}repaintViews(){for(let e of this.viewports)e.isVisible()&&e.repaint();"function"==typeof this.track.paintAxis&&this.paintAxis(),this.repaintSampleInfo(),this.repaintSamples()}repaintSampleInfo(){if("function"==typeof this.track.getSamples){const e=this.track.getSamples();this.sampleInfoViewport.repaint(e)}}repaintSamples(){if("function"==typeof this.track.getSamples){const e=this.track.getSamples();this.sampleNameViewport.repaint(e)}}setTrackLabelName(e){this.viewports.forEach((t=>t.setTrackLabel(e)))}resize(e){for(let t of this.viewports)t.setWidth(e)}async updateViews(){if(!this.browser||!this.browser.referenceFrameList)return;const e=this.viewports.filter((e=>e.isVisible()));if(e.forEach((e=>e.shift())),this.browser.dragObject)return;const t=e.filter((e=>e.needsRepaint())).filter((e=>e.checkZoomIn())),i=t.filter((e=>e.needsReload()));for(let e of i)await e.loadFeatures();if(this.disposed)return;if(this.track&&"function"==typeof this.track.variantRowCount&&i.length>0){let e=0;for(let t of this.viewports)t.featureCache&&t.featureCache.features&&(e=Math.max(e,t.featureCache.features.reduce(((e,t)=>Math.max(e,t.row||0)),0)));if(this.track.nVariantRows!==e+1){this.track.variantRowCount(e+1);for(let e of this.viewports)e.checkContentHeight()}}if(this.track.autoscale){let t=[];for(let i of e){const e=i.referenceFrame,n=e.start,r=n+e.toBP(i.getWidth());if(i.featureCache&&i.featureCache.features)if("function"==typeof i.featureCache.features.getMax){const e=i.featureCache.features.getMax(n,r);t.push({value:e})}else{const e=go(i.featureCache.features,n,r);for(let i of e)t.push(i)}}"function"==typeof this.track.doAutoscale?this.track.dataRange=this.track.doAutoscale(t):this.track.dataRange=nf(t)}const n=this.track.autoscale||this.track.autoscaleGroup||"ruler"===this.track.type;for(let i of e)t.includes(i)?i.repaint():n&&i.refresh();this.adjustTrackHeight(),this.repaintSampleInfo(),this.repaintSamples(),this.updateRulerViewportLabels()}clearCachedFeatures(){for(let e of this.viewports)e.clearCache()}updateRulerViewportLabels(){const e=this.browser.calculateViewportWidth(this.viewports.length);for(let t of this.viewports)"ruler"===this.track.type&&(this.viewports.length>1?t.presentLocusLabel(e):t.dismissLocusLabel())}async getInViewFeatures(){if(!this.browser||!this.browser.referenceFrameList)return[];let e=[];const t=this.viewports.filter((e=>e.isVisible()));for(let i of t){const t=i.referenceFrame,{chr:n,start:r,bpPerPixel:s}=i.referenceFrame,o=r+t.toBP(i.getWidth());if((!i.featureCache||!i.featureCache.containsRange(n,r,o,s))&&await i.loadFeatures(),i.featureCache&&i.featureCache.features)if("function"==typeof i.featureCache.features.getMax){const t=i.featureCache.features.getMax(r,o);e.push({value:t})}else{const t="function"==typeof i.featureCache.queryFeatures?i.featureCache.queryFeatures(n,r,o):go(i.featureCache.features,r,o);e=e.concat(t)}}return e}checkContentHeight(){for(let e of this.viewports)e.checkContentHeight();this.adjustTrackHeight()}adjustTrackHeight(){var e=this.maxViewportContentHeight();if(this.track.autoHeight?this.setTrackHeight(e,!1):this.track.paintAxis&&this.paintAxis(),!1===Lb.has(this.track.type)){const t=this.viewports[0].getContentTop(),i=this.viewports[0].$viewport.height(),n=Math.min(0,i-e);if(t{e.preventDefault(),void 0===t&&e.target.classList.remove("igv-track-drag-handle-hover")})),this.boundTrackDragMouseOutHandler=s.bind(this),this.dragHandle.addEventListener("mouseout",this.boundTrackDragMouseOutHandler)}}removeTrackDragMouseHandlers(){"ideogram"===this.track.id||"ruler"===this.track.id||(this.dragHandle.removeEventListener("mousedown",this.boundTrackDragMouseDownHandler),document.removeEventListener("mouseup",this.boundDocumentTrackDragMouseUpHandler),this.dragHandle.removeEventListener("mouseup",this.boundTrackDragMouseEnterHandler),this.dragHandle.removeEventListener("mouseout",this.boundTrackDragMouseOutHandler))}addTrackGearMouseHandlers(){if(!0===this.track.ignoreTrackMenu);else{function e(e){e.preventDefault(),e.stopPropagation(),this.trackGearPopup.presentMenuList(Gt.trackMenuItemList(this))}this.boundTrackGearClickHandler=e.bind(this),this.gear.addEventListener("click",this.boundTrackGearClickHandler)}}removeTrackGearMouseHandlers(){!0===this.track.ignoreTrackMenu||this.gear.removeEventListener("click",this.boundTrackGearClickHandler)}removeDOMFromColumnContainer(){this.boundAxisClickHander&&this.removeAxisEventListener(this.axis),this.axis.remove();for(let e of this.viewports)e.$viewport.remove();this.sampleInfoViewport.dispose(),this.sampleNameViewport.dispose(),this.removeTrackScrollMouseHandlers(),this.outerScroll.remove(),this.removeTrackDragMouseHandlers(),this.dragHandle.remove(),this.removeTrackGearMouseHandlers(),this.gearContainer.remove()}dispose(){this.removeAxisEventListener(this.axis),this.axis.remove();for(let e of this.viewports)e.dispose();this.sampleInfoViewport.dispose(),this.sampleNameViewport.dispose(),this.removeTrackScrollMouseHandlers(),this.outerScroll.remove(),this.removeTrackDragMouseHandlers(),this.dragHandle.remove(),this.removeTrackGearMouseHandlers(),this.gearContainer.remove(),"function"==typeof this.track.dispose&&this.track.dispose();for(let e of Object.keys(this))this[e]=void 0;this.alert&&this.alert.container.remove(),this.disposed=!0}paintAxis(){if("function"==typeof this.track.paintAxis){const{width:e,height:t}=this.axisCanvas.getBoundingClientRect(),i=window.devicePixelRatio||1;this.axisCanvas.height=i*t,this.axisCanvas.width=i*e;const n=this.axisCanvas.getContext("2d");n.scale(i,i),this.track.paintAxis(n,e,t)}}maxViewportContentHeight(){return Math.max(this.viewports.map((e=>e.getContentHeight())))}}const Rb="rgb(150, 150, 150)";class zb extends ag{static defaults={height:50,flipAxis:!1,logScale:!1,windowFunction:"mean",graphType:"bar",autoscale:!0,normalize:void 0,scaleFactor:void 0};constructor(e,t){super(e,t)}init(e){super.init(e),this.type="wig",this.featureType="numeric",this.paintAxis=Jm;const t=e.format?e.format.toLowerCase():e.format;e.featureSource?(this.featureSource=e.featureSource,delete e.featureSource):"bigwig"===t?(this.featureSource=new Uw(e,this.browser.genome),this.resolutionAware=!0):"tdf"===t?(this.featureSource=new Mw(e,this.browser.genome),this.resolutionAware=!0):(this.featureSource=Pw(e,this.browser.genome),this.resolutionAware=!1),void 0===e.max||!0===e.autoscale?this.autoscale=!0:this.dataRange={min:e.min||0,max:e.max}}async postInit(){const e=await this.getHeader();this.disposed||e&&this.setTrackProperties(e)}async getFeatures(e,t,i,n){const r=await this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:this.visibilityWindow,windowFunction:this.windowFunction});if(this.normalize&&this.featureSource.normalizationFactor){const e=this.featureSource.normalizationFactor;for(let t of r)t.value*=e}if(this.scaleFactor){const e=this.scaleFactor;for(let t of r)t.value*=e}return r}menuItemList(){let e=[];return void 0!==this.flipAxis&&(e.push("
"),e.push({label:"Flip y-axis",click:()=>{this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}})),e=e.concat(Gt.numericDataMenuItems(this.trackView)),e}async getHeader(){return"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader()),this.header}getScaleFactor(e,t,i,n){return n?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}computeYPixelValue(e,t){return(this.flipAxis?e-this.dataRange.min:this.dataRange.max-e)*t}computeYPixelValueInLogScale(e,t){let i=this.dataRange.max,n=this.dataRange.min;return i<=0?0:(n<=-1&&(n=0),n=n<=0?0:Math.log10(n+1),i=Math.log10(i+1),e=Math.log10(e+1),(this.flipAxis?e-n:i-e)*t)}draw(e){const t=e.features,i=e.context,n=e.bpPerPixel,r=e.bpStart,s=e.pixelWidth;e.pixelHeight;const o=r+s*n+1,a=this.color||Rb;let A;"string"==typeof a&&a.startsWith("rgb(")&&(A=Ts.addAlpha(a,.1));const c=this.getScaleFactor(this.dataRange.min,this.dataRange.max,e.pixelHeight,this.logScale),l=e=>this.logScale?this.computeYPixelValueInLogScale(e,c):this.computeYPixelValue(e,c);if(t&&t.length>0&&(void 0===this.dataRange.min&&(this.dataRange.min=0),this.dataRange.max>this.dataRange.min)){let s,a=-1;const c=l(0);for(let e of t){if(e.endo)break;const t=Math.floor((e.start-r)/n);if(isNaN(t))continue;let A=l(e.value);const h=Math.ceil((e.end-r)/n),d=Math.max(1,h-t),u=this.getColorForFeature(e);if("points"===this.graphType){const e=this.config.pointSize||3,n=t+d/2;Eo.fillCircle(i,n,A,e/2,{fillStyle:u,strokeStyle:u})}else if("line"===this.graphType)null!=s&&Eo.strokeLine(i,a,s,t,A,{fillStyle:u,strokeStyle:u}),Eo.strokeLine(i,t,A,t+d,A,{fillStyle:u,strokeStyle:u});else{const e=A-c;Eo.fillRect(i,t,c,d,e,{fillStyle:u})}a=t+d,s=A}if(this.dataRange.min<0){const t=this.dataRange.max/(this.dataRange.max-this.dataRange.min)*e.pixelHeight;Eo.strokeLine(i,0,t,e.pixelWidth,t,{strokeStyle:A})}}if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=l(t.y),n={strokeStyle:t.color,strokeWidth:2};t.dotted?Eo.dashedLine(e.context,0,i,e.pixelWidth,i,5,n):Eo.strokeLine(e.context,0,i,e.pixelWidth,i,n)}}popupData(e,t){if(void 0===t&&(t=this.clickedFeatures(e)),t&&t.length>0){const i=e.genomicLocation,n=[];t.sort((function(e,t){return Math.abs((e.start+e.end)/2-i)-Math.abs((t.start+t.end)/2-i)}));const r=t.length>10?t.slice(0,10):t;r.sort((function(e,t){return e.start-t.start}));for(let e of r)if(e){n.length>0&&n.push("
");let t=e.end-e.start==1?Xt(e.start+1):Xt(e.start+1)+"-"+Xt(e.end);n.push({name:"Position:",value:t}),n.push({name:"Value:     ",value:Xt(e.value)})}return r.length..."),n}return[]}get supportsWholeGenome(){return!this.config.indexURL&&!1!==this.config.supportsWholeGenome}getColorForFeature(e){let t=e.value<0&&this.altColor?this.altColor:this.color||Rb;return"function"==typeof t?t(e.value):t}dispose(){this.trackView=void 0}}function Ob(e){this.thresholds=e.thresholds,this.colors=e.colors}function Pb(e){this.scale=e,this.lowColor="rgb("+e.lowR+","+e.lowG+","+e.lowB+")",this.highColor="rgb("+e.highR+","+e.highG+","+e.highB+")",this.diff=e.high-e.low}Ob.prototype.getColor=function(e){for(let t of this.thresholds)if(e=i.high?this.highColor:(t=(e-i.low)/this.diff,"rgb("+Math.floor(i.lowR+t*(i.highR-i.lowR))+","+Math.floor(i.lowG+t*(i.highG-i.lowG))+","+Math.floor(i.lowB+t*(i.highB-i.lowB))+")")};class Vb{constructor(e){this.color=e}getColor(){return this.color}}const Kb={threshold:2e3,r:0,g:0,b:255};class Gb{constructor(e){e=e||Kb,this.threshold=e.threshold,this.r=e.r,this.g=e.g,this.b=e.b,this.cache=[],this.nbins=2e3,this.binsize=this.threshold/this.nbins}setThreshold(e){this.threshold=e,this.cache=[],this.binsize=this.threshold/this.nbins}getThreshold(){return this.threshold}setColorComponents(e){this.r=e.r,this.g=e.g,this.b=e.b,this.cache=[]}getColorComponents(){return{r:this.r,g:this.g,b:this.b}}equals(e){return JSON.stringify(this)===JSON.stringify(e)}getColor(e){const t=Math.floor(Math.min(this.threshold,e)/this.binsize);if(void 0===this.cache[t]){const i=(Ms.clamp(e,0,this.threshold)-0)/(this.threshold-0);this.cache[t]=`rgba(${this.r},${this.g},${this.b}, ${i})`}return this.cache[t]}stringify(){return this.threshold+","+this.r+","+this.g+","+this.b}static parse(e){var t,i;return e.startsWith("R:")?(t=e.substring(2).split(":"),(i=new RatioColorScale(Number.parseFloat(t[0]))).positiveScale=n(t[1]),i.negativeScale=n(t[2]),i):n(e);function n(e){var t,i;return t={threshold:(i=e.split(","))[0],r:i[1],g:i[2],b:i[3]},new Gb(t)}}}class qb{constructor(e){this.config=e,this.url=e.path||e.url}async read(e,t){const i={start:e,size:t};return io.loadArrayBuffer(this.url,{range:i})}}class jb{constructor(e){this.file=e}async read(e,t){const i=this.file;return void 0!==e?i.slice(e,e+t).arrayBuffer():i.arrayBuffer()}}class Wb{constructor(e,t){this.file=e,this.rateLimiter=t}async read(e,t){const i=this.file,n=this.rateLimiter;return new Promise((function(r,s){n.limiter((async function(i){try{const n=await i.read(e,t);r(n)}catch(e){s(e)}}))(i)}))}}var $b=function(e,t){var i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer};const Xb=function(e,t){this.littleEndian=void 0===t||t,this.position=0,this.view=e,this.length=e.byteLength};function Zb(e,t){this.block=e,this.offset=t}Xb.prototype.available=function(){return this.length-this.position},Xb.prototype.remLength=function(){return this.length-this.position},Xb.prototype.hasNext=function(){return this.position=0;i--)t=256*t+e[i];else for(i=0;i0&&(n+=String.fromCharCode(i));return n},Xb.prototype.getFixedLengthTrimmedString=function(e){var t,i,n="";for(t=0;t32&&(n+=String.fromCharCode(i));return n},Xb.prototype.getFloat=function(){var e=this.view.getFloat32(this.position,this.littleEndian);return this.position+=4,e},Xb.prototype.getDouble=function(){var e=this.view.getFloat64(this.position,this.littleEndian);return this.position+=8,e},Xb.prototype.skip=function(e){return this.position+=e,this.position},Xb.prototype.getVPointer=function(){var e=this.position,t=this.view.getUint8(e+1)<<8|this.view.getUint8(e),i=4294967296*(255&this.view.getUint8(e+6))+16777216*(255&this.view.getUint8(e+5))+65536*(255&this.view.getUint8(e+4))+256*(255&this.view.getUint8(e+3))+(255&this.view.getUint8(e+2));return this.position+=8,new Zb(i,t)},Zb.prototype.isLessThan=function(e){return this.blocke.block||this.block===e.block&&this.offset>e.offset},Zb.prototype.print=function(){return this.block+":"+this.offset};class Jb{constructor(e,t){this.chr1=e,this.chr2=t}getKey(){return this.chr1.name+"_"+this.chr2.name+"_"+this.zoom.unit+"_"+this.zoom.binSize}getBlockNumbers(e,t,i){if(e.chr==this.chr2&&t.chr===this.chr1){const i=e;e=t,t=i}const n=this.chr1===this.chr2,r=this.zoom.binSize,s=this.blockBinCount,o=this.blockColumnCount;return i<9||!n?function(){const i=e.start/r,a=e.end/r,A=t.start/r,c=t.end/r,l=Math.floor(i/s),h=Math.floor((a-1)/s),d=Math.floor(A/s),u=Math.floor((c-1)/s),f=[];for(let e=d;e<=u;e++)for(let t=l;t<=h;t++){let i;i=n&&e0;){const e=t.getInt(),i=t.getLong(),n=t.getInt();this.blockIndex[e]={filePosition:i,size:n}}}getBlockIndexEntry(e){return this.blockIndex[e]}}class ev{constructor(e,t,i){this.chr1=e,this.chr2=t,this.bpZoomData=[],this.fragZoomData=[];for(let e of i)"BP"===e.zoom.unit?this.bpZoomData.push(e):this.fragZoomData.push(e)}findZoomForResolution(e,t){const i="FRAG"===t?this.fragZoomData:this.bpZoomData;for(let t=1;tt){const i=e;e=t,t=i}return`${e}_${t}`}static parseMatrix(e,t){const i=new Xb(new DataView(e)),n=i.getInt(),r=i.getInt(),s=t[n],o=t[r];let a=i.getInt();const A=[];for(;a-- >0;){const e=Jb.parseMatrixZoomData(s,o,i);A.push(e)}return new ev(n,r,A)}}class tv{constructor(e,t,i){this.bin1=e,this.bin2=t,this.counts=i}getKey(){return this.bin1+"_"+this.bin2}}class iv{constructor(e=10){this.max=e,this.map=new Map}get(e){let t=this.map.get(e);return t&&(this.map.delete(e),this.map.set(e,t)),t}set(e,t){this.map.has(e)?this.map.delete(e):this.map.size===this.max&&this.map.delete(this.first()),this.map.set(e,t)}has(e){return this.map.has(e)}clear(){this.map.clear()}first(){return this.map.keys().next().value}}class nv{constructor(e,t,i,n){this.file=e,this.filePosition=t,this.nValues=i,this.dataType=n,this.cache=void 0}async getValues(e,t){if(!this.cache||ethis.cache.end){const i=Math.max(0,e-1e3),n=Math.min(this.nValues,t+1e3),r=this.filePosition+i*this.dataType,s=n-i,o=s*this.dataType,a=await this.file.read(r,o);if(!a)return;const A=new Xb(new DataView(a)),c=[];for(let e=0;e=0||t.indexOf("www.googleapis.com/drive")>0?this.file=new Wb(i,ov):this.file=i}}var t}async init(){this.initialized||(await this.readHeaderAndFooter(),this.initialized=!0)}async getVersion(){if(void 0===this.version){const e=await this.file.read(0,128);if(!e)return;const t=new Xb(new DataView(e));return this.magic=t.getString(),this.version=t.getInt(),this.version}return this.version}async getMetaData(){return await this.init(),this.meta}async readHeaderAndFooter(){let e=await this.file.read(0,16);if(!e||0===e.byteLength)throw Error("File content is empty");let t=new Xb(new DataView(e));if(this.magic=t.getString(),this.version=t.getInt(),this.version<5)throw Error("Unsupported hic version: "+this.version);this.footerPosition=t.getLong(),await this.readFooter();const i=Object.values(this.masterIndex).reduce(((e,t)=>Math.min(e,t.start)),Number.MAX_VALUE)-16;e=await this.file.read(16,i),t=new Xb(new DataView(e)),this.genomeId=t.getString(),this.version>=9&&(this.normVectorIndexPosition=t.getLong(),this.normVectorIndexSize=t.getLong()),this.attributes={};let n=t.getInt();for(;n-- >0;)this.attributes[t.getString()]=t.getString();this.chromosomes=[],this.chromosomeIndexMap={};let r=t.getInt(),s=0;for(;r-- >0;){const e={index:s,name:t.getString(),size:this.version<9?t.getInt():t.getLong()};"all"===e.name.toLowerCase()&&(this.wholeGenomeChromosome=e,this.wholeGenomeResolution=Math.round(2*e.size)),this.chromosomes.push(e),this.chromosomeIndexMap[e.name]=e.index,s++}this.bpResolutions=[];let o=t.getInt();for(;o-- >0;)this.bpResolutions.push(t.getInt());if(this.loadFragData){this.fragResolutions=[];let e=t.getInt();if(e>0)for(;e-- >0;)this.fragResolutions.push(t.getInt())}this.chrAliasTable={};for(let e of Object.keys(this.chromosomeIndexMap))e.startsWith("chr")?this.chrAliasTable[e.substr(3)]=e:"MT"===e?this.chrAliasTable.chrM=e:this.chrAliasTable["chr"+e]=e;this.meta={version:this.version,genome:this.genomeId,chromosomes:this.chromosomes,resolutions:this.bpResolutions}}async readFooter(){const e=this.version<9?8:12;let t=await this.file.read(this.footerPosition,e);if(!t)return null;let i=new Xb(new DataView(t));const n=this.version<9?i.getInt():i.getLong();let r=i.getInt();const s=196*r;for(t=await this.file.read(this.footerPosition+e,Math.min(s,n)),i=new Xb(new DataView(t)),this.masterIndex={};r-- >0;){const e=i.getString(),t=i.getLong(),n=i.getInt();this.masterIndex[e]={start:t,size:n}}if(this.expectedValueVectors={},this.version>5){const e=this.version<9?4:8;this.normExpectedValueVectorsPosition=this.footerPosition+e+n}return this}async printIndexStats(){let e,t=0,i=0;await await this.init();for(let n of Object.keys(this.masterIndex)){const r=this.masterIndex[n];t+=r.size,r.size>i&&(i=r.size,e=n)}console.log(`${i} ${e} ${this.config.url}`)}async getMatrix(e,t){const i=ev.getKey(e,t);if(this.matrixCache.has(i))return this.matrixCache.get(i);{const n=await this.readMatrix(e,t);return this.matrixCache.set(i,n),n}}async readMatrix(e,t){if(await this.init(),e>t){const i=e;e=t,t=i}const i=ev.getKey(e,t),n=this.masterIndex[i];if(!n)return;const r=await this.file.read(n.start,n.size);return r?ev.parseMatrix(r,this.chromosomes):void 0}async getContactRecords(e,t,i,n,r,s=!1){await this.init();const o=this.chromosomeIndexMap[this.getFileChrName(t.chr)],a=this.chromosomeIndexMap[this.getFileChrName(i.chr)];if(o>a||o===a&&t.start>=i.end){const e=t;t=i,i=e}const A=await this.getBlocks(t,i,n,r);if(!A||0===A.length)return[];const c=[],l=t.start/r,h=t.end/r,d=i.start/r,u=i.end/r,f=Math.floor(l),p=Math.ceil(h),g=Math.floor(d),w=Math.ceil(u);for(let o of A)if(o){let a,A,m=e&&"NONE"!==e;const F=this.getFileChrName(t.chr),b=this.getFileChrName(i.chr);if(m){const t=await this.getNormalizationVector(e,F,n,r),i=F===b?t:await this.getNormalizationVector(e,b,n,r);t&&i?(a=await t.getValues(f,p),A=await i.getValues(g,w)):m=!1}for(let e of o.records)if(s||e.bin1>=l&&e.bin1=d&&e.bin210&&(this.percentile95=hv(o.records,95))}return c}async getBlocks(e,t,i,n){const r=(e,t)=>`${t.getKey()}_${e}`;await this.init();const s=this.getFileChrName(e.chr),o=this.getFileChrName(t.chr),a=this.chromosomeIndexMap[s],A=this.chromosomeIndexMap[o];if(void 0===a)return console.log("No chromosome named: "+e.chr),[];if(void 0===A)return console.log("No chromosome named: "+t.chr),[];const c=await this.getMatrix(a,A);if(!c)return console.log("No matrix for "+e.chr+"-"+t.chr),[];const l=c.getZoomData(n,i);if(!l){let i=`No data avalailble for resolution: ${n} for map ${e.chr}-${t.chr}`;throw new Error(i)}const h=l.getBlockNumbers(e,t,this.version),d=[],u=[];for(let e of h){const t=r(e,l);this.blockCache.has(n,t)?d.push(this.blockCache.get(n,t)):u.push(e)}const f=u.map((e=>this.readBlock(e,l))),p=await Promise.all(f);for(let e of p)e&&this.blockCache.set(n,r(e.blockNumber,l),e);return d.concat(p)}async readBlock(e,t){const i=await t.blockIndex.getBlockIndexEntry(e);if(i){let n=await this.file.read(i.filePosition,i.size);if(!n)return;n=new _s(new Uint8Array(n)).buffer;const r=new Xb(new DataView(n)),s=r.getInt(),o=[];if(this.version<7)for(let e=0;e0;)this.parseNormVectorEntry(i);return this.normVectorIndex}async readNormExpectedValuesAndNormVectorIndex(){if(await this.init(),void 0===this.normExpectedValueVectorsPosition)return;const e=await this.skipExpectedValues(this.normExpectedValueVectorsPosition);let t=4,i=await this.file.read(e,4);if(0===i.byteLength)return;const n=new Xb(new DataView(i)).getInt(),r={start:e+t,size:30*n};i=await this.file.read(r.start,r.size),this.normalizedExpectedValueVectors={},this.normVectorIndex={},await async function i(n,r){const s=new Xb(new DataView(r));for(;n-- >0;){if(s.available()<100){n++,t+=s.position;const r=Math.max(1e3,30*n),o={start:e+t,size:r},a=await this.file.read(o.start,o.size);return i.call(this,n,a)}this.parseNormVectorEntry(s)}t+=s.position}.call(this,n,i),this.config.nvi=e.toString()+","+t}async skipExpectedValues(e){const t=this.version,i=new class{constructor(e){this.file=e.file,this.size=e.size||64e3,this.position=0,this.bufferStart=0,this.bufferLength=0,this.buffer=void 0}async read(e,t){const i=e,n=e+t,r=this.bufferStart,s=this.bufferStart+this.bufferLength;if(t>this.size)return this.buffer=void 0,this.bufferStart=0,this.bufferLength=0,this.file.read(e,t);if(i>=r&&n<=s){const e=i-r,n=e+t;return this.buffer.slice(e,n)}if(ir){const n=r-i,s=await this.file.read(e,n),o=t-n;if(o>0){const e=this.buffer.slice(0,o);return $b(s,e)}return s}if(!(is))return this.buffer=await this.file.read(e,this.size),this.bufferStart=e,this.bufferLength=this.buffer.byteLength,this.buffer.slice(0,t);{const e=s-i,n=this.bufferLength-e,r=this.buffer.slice(n,this.bufferLength),o=t-e;if(!(o>0))return r;try{this.buffer=await this.file.read(s,this.size),this.bufferStart=s,this.bufferLength=this.buffer.byteLength;const e=this.buffer.slice(0,o);return $b(r,e)}catch(e){if(e.code&&416===e.code)return r;throw e}}}}({file:this.file,size:256e3}),n={start:e,size:4},r=await i.read(n.start,n.size),s=new Xb(new DataView(r)).getInt();return 0===s?e+4:async function e(n,r){let s={start:n,size:500},o=0,a=n,A=await i.read(s.start,s.size),c=new Xb(new DataView(A));c.getString(),c.getString(),c.getInt();const l=t<9?c.getInt():c.getLong();o+=c.position+l*(t<9?8:4),s={start:n+o,size:4},A=await i.read(s.start,s.size),c=new Xb(new DataView(A));const h=c.getInt();return o+=4+h*(4+(t<9?8:4)),r--,0===r?a+o:e(a+o,r)}(e+4,s)}getZoomIndexForBinSize(e,t){let i;if("BP"===(t=t||"BP"))i=this.bpResolutions;else{if("FRAG"!==t)throw new Error("Invalid unit: "+t);i=this.fragResolutions}for(let t=0;te.counts));i.sort((function(e,t){return e-t}));return i[Math.floor(t/100*e.length)]}class dv{constructor(e,t){this.config=e,this.genome=t,this.hicFile=e._hicFile?e._hicFile:new av(e),e._hicFile=void 0}async getHeader(){return await this.hicFile.init(),this.hicFile}async getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:r}){this.hicFile.initialized||await this.hicFile.init();const s=this.hicFile.bpResolutions,o=s[s.length-1];return(await this.hicFile.getContactRecords(void 0,{chr:e,start:t,end:i},{chr:"celltype",start:0,end:1e8},"BP",o)).map((t=>{const i=t.bin1*o;return{chr:e,start:i,end:i+o,value:t.counts,sample:t.bin2.toString()}}))}supportsWholeGenome(){return!1}}class uv extends ag{constructor(e,t){super(e,t)}init(e){if(super.init(e),this.type=e.type||"seg","maf"===this.type&&(this.type="mut"),this.isLog=e.isLog,this.displayMode=e.displayMode||"EXPANDED",this.height=e.height||300,this.maxHeight=e.maxHeight||500,this.squishedRowHeight=e.sampleSquishHeight||e.squishedRowHeight||2,this.expandedRowHeight=e.sampleExpandHeight||e.expandedRowHeight||13,this.sampleHeight=this.squishedRowHeight,this.sampleKeys=[],this.sampleNames=new Map,e.samples){for(let t of e.samples)this.sampleKeys.push(t),this.sampleNames.set(t,t);this.explicitSamples=!0}if(e.color)this.color=e.color;else if(e.colorTable)this.colorTable=new vo(e.colorTable);else switch(this.type){case"mut":this.colorTable=new vo(wv);break;case"shoebox":e.colorScale&&(this.sbColorScale=Gb.parse(e.colorScale));break;default:this.posColorScale=new Pb(e.posColorScale||pv),this.negColorScale=new Pb(e.negColorScale||gv)}const t=Object.assign({},this.config);t.maxWGCount=t.maxWGCount||Number.MAX_SAFE_INTEGER,"shoebox"===this.type?(this.featureSource=new dv(t,this.browser.genome),this.height=e.height||500,this.maxHeight=e.maxHeight||800,this.isLog=!1,this.squishedRowHeight=e.squishedRowHeight||1,this.displayMode=e.displayMode||"SQUISHED",this.visibilityWindow=void 0===e.visibilityWindow?1e6:e.visibilityWindow):this.featureSource=Pw(t,this.browser.genome),this.initialSort=e.sort}async postInit(){"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader(),this.disposed)||this.header&&this.setTrackProperties(this.header)}menuItemList(){const e=[];if(e.push("
"),e.push(function(e){const t=ut("
");t.text("Sort by sample names");const i=()=>{e.track.sampleKeys.sort(((t,i)=>e.sampleNameViewport.sortDirection*t.localeCompare(i))),e.repaintViews(),e.sampleNameViewport.sortDirection*=-1};return{object:t,click:i}}(this.trackView)),vb){e.push("
"),e.push("Sort by attribute:");for(const t of this.browser.sampleInfo.getAttributeNames())e.push(fv(this.trackView,t))}const t={SQUISHED:"Squish",EXPANDED:"Expand",FILL:"Fill"};"shoebox"===this.type&&this.sbColorScale&&(e.push("
"),e.push({object:ut("
Set color scale threshold
"),click:e=>{this.browser.inputDialog.present({label:"Color Scale Threshold",value:this.sbColorScale.threshold,callback:()=>{const e=Number(this.browser.inputDialog.input.value,10);e&&(this.sbColorScale.setThreshold(e),this.trackView.repaintViews())}},e)}})),e.push("
"),e.push("DisplayMode:");const i="seg"===this.type||"shoebox"===this.type?["SQUISHED","EXPANDED","FILL"]:["SQUISHED","EXPANDED"];for(let n of i){const i=Kt(t[n],n===this.displayMode);e.push({object:ut(i),click:()=>{this.displayMode=n,this.config.displayMode=n,this.trackView.checkContentHeight(),this.trackView.repaintViews(),this.trackView.moveScroller(this.trackView.sampleNameViewport.trackScrollDelta)}})}return e}hasSamples(){return!0}getSamples(){return{names:this.sampleKeys.map((e=>this.sampleNames.get(e))),height:this.sampleHeight,yOffset:0}}async getFeatures(e,t,i){const n=await this.featureSource.getFeatures({chr:e,start:t,end:i});if(this.initialSort){const e=this.initialSort;this.sortSamples(e.chr,e.start,e.end,e.direction,n),this.initialSort=void 0}return n}draw({context:e,renderSVG:t,pixelTop:i,pixelWidth:n,pixelHeight:r,features:s,bpPerPixel:o,bpStart:a}){if(Eo.fillRect(e,0,i,n,r,{fillStyle:"rgb(255, 255, 255)"}),s&&s.length>0){if(this.checkForLog(s),"shoebox"===this.type&&!this.sbColorScale){const e=this.featureSource.hicFile.percentile95||2e3;this.sbColorScale=new Gb({threshold:e,r:0,g:0,b:255})}this.updateSampleKeys(s);const t={};let A;switch(this.sampleKeys.forEach((function(e,i){t[e]=i})),this.displayMode){case"FILL":this.sampleHeight=r/this.sampleKeys.length,A=0;break;case"SQUISHED":this.sampleHeight=this.squishedRowHeight,A=0;break;default:this.sampleHeight=this.expandedRowHeight,A=1}const c=this.sampleHeight;for(let e of s)e.pixelRect=void 0;const l=i+r,h=a+n*o+1,d=o;this.sampleYStart=void 0;for(let n of s){if(n.endh)continue;const r=n.sampleKey||n.sample;n.row=t[r];const s=n.row*c+A;void 0===this.sampleYStart&&(this.sampleYStart=s);if(s+cl)continue;const o=Math.max(n.start,a);let u=Math.round((o-a)/d);const f=Math.min(n.end,h),p=Math.round((f-a)/d);let g,w,m=Math.max(1,p-u);if(this.color?g="function"==typeof this.color?this.color(n):this.color:this.colorTable&&(g=this.colorTable.getColor(n.value.toLowerCase())),"mut"===this.type)w=c-2*A,m<3&&(m=3,u-=1);else if("shoebox"===this.type){g=this.sbColorScale.getColor(n.value);let e=c;if(c<.25){const t=.1+2*Math.abs(t.value);e=Math.min(1,t*c)}w=e-2*A}else{let e=n.value;this.isLog||(e=Ms.log2(e/2)),g=e<-.1?this.negColorScale.getColor(e):e>.1?this.posColorScale.getColor(e):"white";let t=c;if(c<.25){const i=.1+2*Math.abs(e);t=Math.min(1,i*c)}w=t-2*A}n.pixelRect={x:u,y:s,w:m,h:w},e.fillStyle=g,e.fillRect(u,s,m,w)}}}checkForLog(e){if(void 0===this.isLog){this.isLog=!1;for(let t of e)if(t.value<0)return void(this.isLog=!0)}}computePixelHeight(e){if(!e)return 0;const t="SQUISHED"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight;return this.updateSampleKeys(e),this.sampleKeys.length*t}async sortSamples(e,t,i,n,r){if(r||(r=await this.featureSource.getFeatures({chr:e,start:t,end:i})),!r)return;this.updateSampleKeys(r);const s={},o="ASC"===n?1:-1,a=()=>{const e=i-t+1;for(let n of r){if(n.endi)break;const r=Math.max(t,n.start),o=(Math.min(i,n.end)-r)/e,a=n.sampleKey||n.sample,A=s[a]||0;s[a]=A+o*n.value}this.sampleKeys.sort((function(e,t){let i=s[e],n=s[t];return i||(i=o*Number.MAX_VALUE),n||(n=o*Number.MAX_VALUE),i===n?0:i>n?o:-1*o}))},A=()=>{for(let e of r){if(e.endi)break;const n=e.sampleKey||e.sample;(!s.hasOwnProperty(n)||e.value.localeCompare(s[n])>0)&&(s[n]=e.value)}this.sampleKeys.sort((function(e,t){let i=s[e]||"",n=s[t]||"";return o*i.localeCompare(n)}))};"mut"===this.type?A():a(),this.trackView.repaintViews()}clickedFeatures(e){const t=super.clickedFeatures(e),i=e.y;return t.filter((function(e){const t=e.pixelRect;return t&&i>=t.y&&i<=t.y+t.h}))}hoverText(e){const t=this.clickedFeatures(e);if(t&&t.length>0)return`${t[0].sample}: ${t[0].value}`}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){i.length>0&&(i.push("
"),i.push("
"));const t=e._f||e,n="function"==typeof t.popupData?t.popupData(this.type,this.browser.genome.id):this.extractPopupData(t);Array.prototype.push.apply(i,n)}return i}contextMenuItemList(e){const t=e.viewport.referenceFrame,i=e.genomicLocation,n=this.config.sort?"ASC"===this.config.sort.direction?"DESC":"ASC":"DESC",r=t.toBP(2.5),s=t=>{const i=e.viewport.cachedFeatures;this.sortSamples(t.chr,t.start,t.end,t.direction,i)};return[{label:"seg"===this.type||"shoebox"===this.type?"Sort by value":"Sort by type",click:t=>{const o={direction:n,chr:e.viewport.referenceFrame.chr,start:i-r,end:i+r};s(o),this.config.sort=o}}]}get supportsWholeGenome(){return(!1===this.config.indexed||!this.config.indexURL)&&!1!==this.config.supportsWholeGenome}updateSampleKeys(e){if(!this.explicitSamples)for(let t of e){const e=t.sampleKey||t.sample;this.sampleNames.has(e)||(this.sampleNames.set(e,t.sample),this.sampleKeys.push(e))}}}function fv(e,t){const i=ut("
");i.html(`  ${t.split(Cb).join(" ")}`);return{object:i,click:()=>{e.track.sampleKeys=e.browser.sampleInfo.getSortedSampleKeysByAttribute(e.track.sampleKeys,t,e.sampleInfoViewport.sortDirection),e.repaintViews(),e.sampleInfoViewport.sortDirection*=-1}}}const pv={low:.1,lowR:255,lowG:255,lowB:255,high:1.5,highR:255,highG:0,highB:0},gv={low:-1.5,lowR:0,lowG:0,lowB:255,high:-.1,highR:255,highG:255,highB:255},wv={indel:"rgb(0,200,0)","targeted region":"rgb(236,155,43)",truncating:"rgb(\t150,0,0)","non-coding transcript":"rgb(0,0,150)",synonymous:"rgb(109,165,95)",silent:"rgb(109,135,80)",missense_mutation:"rgb(72,130,187)",missense:"rgb(72,130,187)","splice site":"rgb(143,83,155)",splice_region:"rgb(143,83,155)",nonsense:"rgb(216, 57,81)",nonsense_mutation:"rgb(216, 57,81)",frame_shift_del:"rgb(226,135,65)",frame_shift_ins:"rgb(226,135,65)",in_frame_del:"rgb(247,235,94)",in_frame_ins:"rgb(247,235,94)","*other*":"rgb(159,91,50)"};class mv extends ag{constructor(e,t){super(e,t),this.type="merged",this.featureType="numeric",this.paintAxis=Jm,this.graphType=e.graphType}init(e){if(!e.tracks)throw Error("Error: no tracks defined for merged track"+e);super.init(e)}async postInit(){this.tracks=[];const e=[];for(let t of this.config.tracks){t.isMergedTrack=!0;const i=await this.browser.createTrack(t);i?(i.autoscale=!1,this.tracks.push(i)):console.warn("Could not create track "+t),"function"==typeof i.postInit&&e.push(i.postInit())}this.flipAxis=!!this.config.flipAxis&&this.config.flipAxis,this.logScale=!!this.config.logScale&&this.config.logScale,this.autoscale=this.config.autoscale||void 0===this.config.max,this.autoscale||(this.dataRange={min:this.config.min||0,max:this.config.max});for(let e of this.tracks)e.autoscale=!1,e.dataRange=this.dataRange;return this.height=this.config.height||50,this.resolutionAware=this.tracks.some((e=>e.resolutionAware)),Promise.all(e)}get height(){return this._height}set height(e){if(this._height=e,this.tracks)for(let t of this.tracks)t.height=e,t.config.height=e}menuItemList(){let e=[];return void 0!==this.flipAxis&&e.push({label:"Flip y-axis",click:()=>{this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}}),e=e.concat(Gt.numericDataMenuItems(this.trackView)),e}async getFeatures(e,t,i,n){const r=this.tracks.map((r=>r.getFeatures(e,t,i,n))),s=await Promise.all(r);return new Fv(s)}draw(e){const t=e.features;for(let i=0,n=this.tracks.length;i0&&i.push("
"),i.push(`
${this.tracks[n].name}
`);const r=this.tracks[n].popupData(e,t[n]);i.push(...r)}return i}}}clickedFeatures(e){const t=e.viewport.cachedFeatures;if(!t)return[];const i=e.genomicLocation,n=[];for(let r of t.featureArrays){const t=e.referenceFrame.bpPerPixel>.2?3*e.referenceFrame.bpPerPixel:.2,s=go(r,i-t,i+t);for(let e of s)n.push(e)}return n}get supportsWholeGenome(){return this.tracks.every((e=>e.supportsWholeGenome))}}class Fv{constructor(e){this.featureArrays=e}getMax(e,t){let i=-Number.MAX_VALUE;for(let n of this.featureArrays)for(let r of n)if(void 0!==r.value&&!Number.isNaN(r.value)){if(r.endt)break;i=Math.max(i,r.value)}return i}}class bv extends ag{static defaults={height:250,theta:Math.PI/4,arcOrientation:!0,showBlocks:!0,blockHeight:3,thickness:1,alpha:.02,logScale:!0};constructor(e,t){super(e,t)}init(e){super.init(e),this.sinTheta=Math.sin(this.theta),this.cosTheta=Math.cos(this.theta),this.arcType=function(e){if(!e.arcType)return"nested";switch(e.arcType){case"chiapet":return"inView";case"chiapetoutbound":return"partialInView";default:return e.arcType}}(e),this.alpha=e.alpha||.02,this.painter={flipAxis:!this.arcOrientation,dataRange:this.dataRange,paintAxis:Jm},e.valueColumn?(this.valueColumn=e.valueColumn,this.hasValue=!0):e.useScore&&(this.hasValue=!0,this.valueColumn="score"),e.max?(this.dataRange={min:e.min||0,max:e.max},this.autoscale=!1):this.autoscale=!0,e.featureSource?(this.featureSource=e.featureSource,delete e._featureSource):(this.featureSource=Pw(e,this.browser.genome),this.featureSource.getWGFeatures=_v)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),void 0===this.visibilityWindow&&"function"==typeof this.featureSource.defaultVisibilityWindow&&(this.visibilityWindow=await this.featureSource.defaultVisibilityWindow(),this.featureSource.visibilityWindow=this.visibilityWindow),this}get supportsWholeGenome(){return!0}async getFeatures(e,t,i){const n=this.visibilityWindow,r=await this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:n});return void 0===this.hasValue&&r&&r.length>0&&(this.hasValue=void 0!==r[0].score),r}draw(e){"proportional"===this.arcType||"inView"===this.arcType||"partialInView"===this.arcType?this.drawProportional(e):this.drawNested(e)}drawNested(e){const t=e.context,i=e.pixelWidth,n=e.pixelHeight,r=e.viewportWidth,s=e.bpPerPixel,o=e.bpStart,a=s;Eo.fillRect(t,0,e.pixelTop,i,n,{fillStyle:"rgb(255, 255, 255)"});const A=e.features;if(A){(function(){let e=0;for(let t of A){let n=(t.start-o)/a,r=(t.end-o)/a;n>=0&&r<=i&&(e=Math.max(e,r-n))}let t=Math.min(r,e)/2;if(e>0){let e=(n-10)/t;this.theta=function(e){let t,i=[.01570925532366355,.15838444032453644,.3249196962329063,.5095254494944288,.7265425280053609,.9999999999999999],n=[.031415926535897934,.3141592653589793,.6283185307179586,.9424777960769379,1.2566370614359172,1.5707963267948966];for(t=0;te);t++);let r=0===t?0:i[t-1],s=ti)continue;let u=d-h;u<3&&(u=3,h--);const f=u/2,p=f/this.sinTheta,g=this.cosTheta*p,w=h+f;let m,F,b;if(l?(m=this.height+g,F=Math.PI+Math.PI/2-this.theta,b=Math.PI+Math.PI/2+this.theta):(m=-g,F=Math.PI/2-this.theta,b=Math.PI/2+this.theta),this.showBlocks&&"all"!==e.chr){const i=(e.start1-o)/a,n=(e.end1-o)/a,r=(e.start2-o)/a,A=(e.end2-o)/a,c=this.arcOrientation?-this.blockHeight:this.blockHeight;t.fillRect(i,s,n-i,c),t.fillRect(r,s,A-r,c)}n&&!this.config.useScore&&u>r&&(n=Cv(n,this.alpha)),t.strokeStyle=n,t.fillStyle=n,t.beginPath(),t.arc(w,m,p,F,b,!1),t.stroke(),e.drawState={xc:w,yc:m,r:p}}else{let r=Math.round((e.start-o)/a),s=Math.round((e.end-o)/a);if(s<0||r>i)continue;let A=s-r;A<3&&(A=3,r--);const c=e.chr===e.chr1?e.chr2:e.chr1;t.strokeStyle=n,t.fillStyle=Cv(lb(c),.5),l?(t.fillRect(r,this.height/2,A,this.height/2),t.fillText(c,r+A/2,this.height/2-5),e.drawState={x:r,y:this.height/2,w:A,h:this.height/2}):(t.fillRect(r,0,A,this.height/2),t.fillText(c,r+A/2,this.height/2+13),e.drawState={x:r,y:0,w:A,h:this.height/2})}}}var c}getScaleFactor(e,t,i,n){return n?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}drawProportional(e){const t=e.context,i=e.pixelWidth,n=e.pixelHeight,r=e.bpPerPixel,s=e.bpStart,o=r,a=e.referenceFrame.start,A=e.referenceFrame.end;Eo.fillRect(t,0,e.pixelTop,i,n,{fillStyle:"rgb(255, 255, 255)"});const c=e.features;if(c&&c.length>0){new Map;const n=0,r=this.getScaleFactor(n,this.dataRange.max,e.pixelHeight-1,this.logScale),l=this.arcOrientation?e.pixelHeight:0;for(let e of c){e.drawState=void 0;const n=this.valueColumn?e[this.valueColumn]:e.score;if(void 0===n||Number.isNaN(n))continue;const c=Math.round((this.logScale?Math.log10(n+1):n)*r);if(e.chr1===e.chr2||"all"===e.chr){const{m1:i,m2:r}=vv(e,this.browser.genome);let h=Math.round((i-s)/o),d=Math.round((r-s)/o)-h;if(d<3&&(d=3,h--),nthis.dataRange.max)continue;if("proportional"!==this.arcType){const e="partialInView"===this.arcType,t=i>=a&&r<=A;let n=!1,s=!1;if(!t&&e&&(n=a<=i&&i<=A,n||(s=a<=r&&r<=A)),!(t||n||s))continue}const u=d/2,f=h+d/2;e.drawState={xc:f,yc:l,radiusX:u,radiusY:c};const p=!!this.arcOrientation,g=e.color||this.color;if(t.strokeStyle=g,t.lineWidth=e.thickness||this.thickness||1,!0===t.isSVG?t.strokeEllipse(f,l,u,c,0,0,Math.PI,p):(t.beginPath(),t.ellipse(f,l,u,c,0,0,Math.PI,p),t.stroke()),this.alpha&&(t.fillStyle=Cv(g,this.alpha),!0===t.isSVG?t.fillEllipse(f,l,u,c,0,0,Math.PI,p):t.fill()),this.showBlocks&&"all"!==e.chr){t.fillStyle=g;const i=(e.start1-s)/o,n=(e.end1-s)/o,r=(e.start2-s)/o,a=(e.end2-s)/o,A=this.arcOrientation?-this.blockHeight:this.blockHeight;t.fillRect(i,l,n-i,A),t.fillRect(r,l,a-r,A)}}else{let r=Math.round((e.start-s)/o),a=Math.round((e.end-s)/o);if(a<0||r>i||nthis.dataRange.max)continue;const A=Math.min(c,this.height-13);let l=a-r;l<3&&(l=3,r--);const h=e.chr===e.chr1?e.chr2:e.chr1;if(t.font="8px sans-serif",t.textAlign="center",t.fillStyle=Cv(lb(h),.5),this.arcOrientation){const i=this.height-A;t.fillRect(r,i,l,A),t.fillText(h,r+l/2,i-5),e.drawState={x:r,y:i,w:l,h:A}}else t.fillRect(r,0,l,A),t.fillText(h,r+l/2,A+13),e.drawState={x:r,y:0,w:l,h:A}}}}}clearAxis(e,t,i){Eo.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"})}paintAxis(e,t,i){const n={min:0,max:this.dataRange.max};"proportional"===this.arcType||"inView"===this.arcType||"partialInView"===this.arcType?(this.painter.flipAxis=!this.arcOrientation,this.painter.dataRange=n,this.painter.paintAxis(e,t,i)):this.clearAxis(e,t,i)}menuItemList(){let e=[];if(this.hasValue){e.push("
");const t={nested:"Nested",proportional:"Proportional - All",inView:"Proportional - Both Ends in View",partialInView:"Proportional - One End in View"};e.push("Arc Type");for(let i of["nested","proportional","inView","partialInView"])e.push({object:ut(Kt(t[i],i===this.arcType)),click:()=>{this.arcType=i,this.trackView.repaintViews()}})}return e.push("
"),e.push({name:"Toggle arc direction",click:()=>{this.arcOrientation=!this.arcOrientation,this.trackView.repaintViews()}}),e.push({name:this.showBlocks?"Hide Blocks":"Show Blocks",click:()=>{this.showBlocks=!this.showBlocks,this.trackView.repaintViews()}}),"proportional"!==this.arcType&&"inView"!==this.arcType&&"partialInView"!==this.arcType||(e=e.concat(Gt.numericDataMenuItems(this.trackView))),this.browser.circularView&&(e.push("
"),e.push({label:"Add interactions to circular view",click:()=>{for(let e of this.trackView.viewports)this.addChordsForViewport(e.referenceFrame)}})),e}contextMenuItemList(e){if(this.browser.circularView){const t=e.viewport,i=[];return i.push({label:"Add interactions to circular view",click:()=>{const e=t.referenceFrame;this.addChordsForViewport(e)}}),i.push("
"),i}}addChordsForViewport(e){const t=("all"===e.chr?this.featureSource.getAllFeatures():this.featureSource.featureCache.queryFeatures(e.chr,e.start,e.end)).filter((e=>e.drawState));if(0===t.length)return;const i=t.map((e=>{const t=e._f||e;return{uniqueId:`${t.chr1}:${t.start1}-${t.end1}_${t.chr2}:${t.start2}-${t.end2}`,refName:kF(t.chr1),start:t.start1,end:t.end1,mate:{refName:kF(t.chr2),start:t.start2,end:t.end2}}}));IF(i,this,e,.5)}doAutoscale(e){let t=0;if(e)for(let i of e){const e=this.valueColumn?i[this.valueColumn]:i.score;Number.isNaN(e)||(t=Math.max(t,e))}return{min:0,max:t}}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){const t=e._||e;if(i.push({name:"Region 1",value:Bv(t.chr1,t.start1,t.end1,t.strand1)}),i.push({name:"Region 2",value:Bv(t.chr2,t.start2,t.end2,t.strand2)}),t.name&&i.push({name:"Name",value:t.name}),void 0!==t.value&&i.push({name:"Value",value:t.value}),void 0!==t.score&&i.push({name:"Score",value:t.score}),t.extras&&this.header&&this.header.columnNames){const e=this.header.columnNames,n=this.header.hiccups?6:10;for(let r=n;r=t-a&&e.canvasX<=t+s+a&&e.canvasY>=n&&e.canvasY<=n+o){const n=-Math.abs(e.canvasX-(t+s/2));i.push({score:n,feature:r});break}}}return i.length>1&&i.sort(((e,t)=>e.score-t.score)),i.map((e=>e.feature))}}function vv(e,t){let i=(e.start1+e.end1)/2,n=(e.start2+e.end2)/2;if("all"===e.chr&&(i=t.getGenomeCoordinate(e.chr1,i),n=t.getGenomeCoordinate(e.chr2,n)),i>n){const e=i;i=n,n=e}return{m1:i,m2:n}}function Bv(e,t,i,n){return n&&"."!==n?`${e}:${Xt(t+1)}-${Xt(i)} (${n})`:`${e}:${Xt(t+1)}-${Xt(i)}`}const yv=new Map;function Cv(e,t){const i=`${e}_${t}`;let n=yv.get(i);return n||(n=Ts.addAlpha(e,t),yv.set(i,n)),n}function _v(e){const t=e=>{const t=Object.assign({},e);return t.chr="all",t.start=i.getGenomeCoordinate(e.chr1,e.start1),t.end=i.getGenomeCoordinate(e.chr2,e.end2),t},i=this.genome;let n,r=0;for(let t of i.wgChromosomeNames){let i=e[t];if(i)for(let e of i)e.dup||(r++,e.score&&(!n||e.score>n.score)&&(n=e))}const s=this.maxWGCount,o=n&&n.score>0&&r>s?5:1,a=Math.floor(s/o),A=n&&n.score>0?Math.log(n.score)/o:Number.MAX_SAFE_INTEGER;let c,l=[],h=[];for(let e=0;ee.name)):[]}return this.header}getCallsetsLength(){return this.callSets?this.callSets.length:0}async getFeatures(e,t,i,n){return void 0===this.header&&(this.header=await this.getHeader()),this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:this.visibilityWindow})}hasSamples(){return this.getCallsetsLength()>0}getSamples(){return{yOffset:this.sampleYOffset,names:this.sampleNames,height:this.sampleHeight}}computePixelHeight(e){if(!e||0==e.length)return 10;const t="COLLAPSED"===this.displayMode?1:this.nVariantRows,i="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,n="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,r="SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight;return 10+t*(n+i)+i+((!1===this.showGenotypes?0:this.getCallsetsLength()*t)+1)*(r+i)}variantRowCount(e){this.nVariantRows=e}draw({context:e,pixelWidth:t,pixelHeight:i,bpPerPixel:n,bpStart:r,pixelTop:s,features:o}){Eo.fillRect(e,0,s,t,i,{fillStyle:"rgb(255, 255, 255)"});const a="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,A="COLLAPSED"===this.displayMode?1:this.nVariantRows,c="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight;this.variantBandHeight=10+A*(c+a);let l=this.callSets;!l&&this._f&&(l=this._f.callSets);const h=this.getCallsetsLength();if(l&&h>0&&!1!==this.showGenotypes&&Eo.strokeLine(e,0,this.variantBandHeight,t,this.variantBandHeight,{strokeStyle:"rgb(224,224,224) "}),o){const i="SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight,s="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,a=r+t*n+1;for(let t of o){if(t.enda)break;const o="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,A=10+("COLLAPSED"===this.displayMode?0:t.row*(o+s)),c=o;let d=Math.round((t.start-r)/n),u=Math.round((t.end-r)/n),f=Math.max(1,u-d);f<3?(f=3,d-=1):f>5&&(d+=1,f-=2),e.fillStyle=this.getColorForFeature(t),e.fillRect(d,A,f,c);let p=this.getVariantStrokecolor(t);if(p&&(e.strokeStyle=p,e.strokeRect(d,A,f,c)),this.callContextHook(t,e,d,A,f,c),t.pixelRect={x:d,y:A,w:f,h:c},h>0&&!1!==this.showGenotypes){const n="COLLAPSED"===this.displayMode?1:this.nVariantRows;this.sampleYOffset=this.variantBandHeight+s,this.sampleHeight=n*(i+s);let r=0;if(l&&t.calls)for(let n of l){const o=t.calls[n.id];if(o){const a="COLLAPSED"===this.displayMode?0:t.row,A=this.sampleYOffset+r*this.sampleHeight+a*(i+s);let c=!0,l=!0,h=!1;if(o.genotype)for(let e of o.genotype){if("."===e){h=!0;break}0!==e&&(l=!1),0===e&&(c=!1)}o.genotype?e.fillStyle=h?this.noCallColor:l?this.homrefColor:c?this.homvarColor:this.hetvarColor:e.fillStyle=this.noGenotypeColor,e.fillRect(d,A,f,i),n.pixelRect={x:d,y:A,w:f,h:i}}r++}}}}else console.log("No feature list")}getColorForFeature(e){const t=e._f||e;let i;if(this.colorBy){const e=this.colorBy;let n;if(t.info.hasOwnProperty(e))n=t.info[e];else if(Ev.has(e)){n=t[Ev.get(e)]}i=this.getVariantColorTable(e).getColor(n),i||(i="gray")}else i=this._color?"function"==typeof this._color?this._color(e):this._color:"NONVARIANT"===t.type?this.nonRefColor:"MIXED"===t.type?this.mixedColor:this.color;return i}getVariantStrokecolor(e){const t=e._f||e;let i;return i=this._strokecolor?"function"==typeof this._strokecolor?this._strokecolor(t):this._strokecolor:void 0,i}callContextHook(e,t,i,n,r,s){if(this._context_hook&&"function"==typeof this._context_hook){const o=e._f||e;t.save(),this._context_hook(o,t,i,n,r,s),t.restore()}}clickedFeatures(e){let t=super.clickedFeatures(e);const i="EXPANDED"===this.displayMode?this.expandedVGap:this.squishedVGap,n=i+("SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight),r=e.y;if(r<=this.variantBandHeight){const e="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,n=Math.floor((r-10)/(e+i));"COLLAPSED"!==this.displayMode&&(t=t.filter((e=>e.row===n)))}else if(this.callSets){const e=this.callSets,i=r-this.variantBandHeight,s=Math.floor(i/this.sampleHeight);if(s>=0&&se.row===r)),a=e[s];t=o.map((e=>{const t=e.calls[a.id];return function(e,t){if(e.genotype){let i="";if("."===t.alternateBases)i="No Call";else{const n=t.alternateBases.split(",");for(let r of e.genotype)if(i.length>0&&(i+="|"),"."===r)i+=".";else if(0===r)i+=t.referenceBases;else{i+=n[r-1].replace("<","<")}}e.genotypeName=i}}(t,e),t}))}}return t}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,n=this.browser.genome.id,r=this.browser.sampleInformation;let s=[];for(let e of t){const t=e._f||e;if(s.length>0&&s.push({html:'
'}),"function"==typeof t.popupData){const e=t.popupData(i,n);Array.prototype.push.apply(s,e)}else{const e=t;if(void 0!==e.callSetName&&s.push({name:"Name",value:e.callSetName}),e.genotypeName&&s.push({name:"Genotype",value:e.genotypeName}),void 0!==e.phaseset&&s.push({name:"Phase set",value:e.phaseset}),void 0!==e.genotypeLikelihood&&s.push({name:"genotypeLikelihood",value:e.genotypeLikelihood.toString()}),r){var o=r.getAttributes(e.callSetName);o&&Object.keys(o).forEach((function(e){var t=e.replace(/([A-Z])/g," $1");t=t.charAt(0).toUpperCase()+t.slice(1),s.push({name:t,value:o[e]})}))}var a=Object.keys(e.info);a.length&&s.push("
"),a.forEach((function(t){s.push({name:t,value:decodeURIComponent(e.info[t])})}))}}return s}menuItemList(){const e=[];if(this.header.INFO&&this.header.INFO){const t=this.header.INFO.SVTYPE?["SVTYPE"]:[];if(this._initColorBy&&"SVTYPE"!==this._initColorBy&&t.push(this._initColorBy),t.length>0){e.push("
");const i=ut('
');i.text("Color by:"),e.push({name:void 0,object:i,click:void 0,init:void 0}),t.sort();for(let i of t){const t=this.colorBy===i,n=i||"None";e.push(this.colorByCB({key:i,label:n},t))}e.push(this.colorByCB({key:void 0,label:"None"},void 0===this.colorBy)),e.push("
")}}this.getCallsetsLength()>0&&(e.push({object:ut('
')}),e.push({object:ut(Kt("Show Genotypes",this.showGenotypes)),click:()=>{this.showGenotypes=!this.showGenotypes,this.trackView.checkContentHeight(),this.trackView.repaintViews()}})),e.push({object:ut('
')});for(let t of["COLLAPSED","SQUISHED","EXPANDED"]){e.push({object:ut(Kt({COLLAPSED:"Collapse",SQUISHED:"Squish",EXPANDED:"Expand"}[t],t===this.displayMode)),click:()=>{this.displayMode=t,this.trackView.checkContentHeight(),this.trackView.repaintViews()}})}return this.browser.circularView&&(e.push("
"),e.push({label:"Add SVs to circular view",click:()=>{for(let e of this.trackView.viewports)this.sendChordsForViewport(e)}})),e}contextMenuItemList(e){if(this.browser.circularView){const t=e.viewport,i=[];return i.push({label:"Add SVs to Circular View",click:()=>{this.sendChordsForViewport(t)}}),i.push("
"),i}}sendChordsForViewport(e){const t=e.referenceFrame;let i;if("all"===t.chr){const e=this.featureSource.getAllFeatures(),t=Object.keys(e).map((t=>e[t]));i=[].concat(...t)}else i=this.featureSource.featureCache.queryFeatures(t.chr,t.start,t.end);const n=(e=>{const t=e.filter((e=>{const t=e._f||e;return t.info&&t.info.CHR2&&t.info.END&&(t.info.CHR2!==t.chr||Math.abs(Number.parseInt(t.info.END)-t.pos)>1e6)}));return t.map((e=>{const t=e._f||e,i=Number.parseInt(t.info.END),n=i-100,r=i+100;return{uniqueId:`${t.chr}:${t.start}-${t.end}_${t.info.CHR2}:${t.info.END}`,refName:kF(t.chr),start:t.start,end:t.end,mate:{refName:kF(t.info.CHR2),start:n,end:r}}}))})(i);IF(n,this,t,.5)}colorByCB(e,t){return{name:void 0,object:ut(Kt(e.label,t)),click:()=>{e.key===this.colorBy?(this.colorBy=void 0,delete this.config.colorBy,this.trackView.repaintViews()):(this.colorBy=e.key,this.config.colorBy=e.key,this.trackView.repaintViews())},init:void 0}}getState(){const e=super.getState();return this._color&&"function"!=typeof this._color&&(e.color=this._color),e}getVariantColorTable(e){if(this.colorTables||(this.colorTables=new Map),!this.colorTables.has(e)){let t;if("SVTYPE"===e)t=Uv;else t=new bo("Set1");this.colorTables.set(e,t)}return this.colorTables.get(e)}}const Uv=new vo({DEL:"#ff2101",INS:"#001888",DUP:"#028401",INV:"#008688",CNV:"#8931ff",BND:"#891100","*":"#002eff"});class Qv extends ag{constructor(e,t){super(e,t)}init(e){super.init(e),this.name=e.name,this.pValueField=e.pValueField||"pValue",this.geneField=e.geneField||"geneSymbol",this.snpField=e.snpField||"snp";const t=e.minLogP||e.min,i=e.maxLogP||e.max;this.dataRange={min:t||3.5,max:i||25},this.autoscale=!i||e.autoscale,this.autoscalePercentile=void 0===e.autoscalePercentile?98:e.autoscalePercentile,this.background=e.background,this.divider=e.divider||"rgb(225,225,225)",this.dotSize=e.dotSize||2,this.height=e.height||100,this.autoHeight=!1,this.disableButtons=e.disableButtons,this.visibilityWindow=void 0===e.visibilityWindow?2e6:e.visibilityWindow>=0?Math.min(2e6,e.visibilityWindow):2e6,this.featureSource=Pw(e,this.browser.genome),SF.gtexLoaded=!0}paintAxis(e,t,i){const n=(this.dataRange.max-this.dataRange.min)/i,r={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};Eo.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"});const s=Math.ceil(10*(this.dataRange.max-this.dataRange.min)/i);for(let o=4;o<=this.dataRange.max;o+=s){const s=.85*t,a=s-5,A=s,c=i-(o-this.dataRange.min)/n;Eo.strokeLine(e,a,c,A,c,r),c>8&&Eo.fillText(e,o,a-1,c+2,r)}r.textAlign="center",Eo.fillText(e,"-log10(pvalue)",t/4,i/2,r,{rotate:{angle:-90}})}async getFeatures(e,t,i){const n=this.pValueField,r=this.visibilityWindow,s=await this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r});return s.forEach((function(e){e.value=e[n]})),s}draw(e){const t=e.context,i=e.pixelWidth,n=e.pixelHeight;this.background&&Eo.fillRect(t,0,0,i,n,{fillStyle:this.background}),Eo.strokeLine(t,0,n-1,i,n-1,{strokeStyle:this.divider});const r=r=>{const s=r?2*this.dotSize:this.dotSize,o=e.bpStart,a=(this.dataRange.max-this.dataRange.min)/n,A=e.referenceFrame.selection;for(let l of e.features){const h=(l.start-o+.5)/e.bpPerPixel;if(h<0)continue;if(h>i)break;const d=l.snp.toUpperCase(),u=l[this.geneField].toUpperCase(),f=A&&(A.snp===d||A.gene===u);if(!r||f){A&&A.snp===d&&A.addGene(u);var c=-Math.log(l[this.pValueField])/Math.LN10;if(c>=this.dataRange.min){let e;c>this.dataRange.max?(c=this.dataRange.max,e=!0):e=!1;const i=Math.max(0+s,n-Math.round((c-this.dataRange.min)/a));let o;l.px=h,l.py=i,l.radius=s,r&&A?(o=A.colorForGene(u),Eo.setProperties(t,{fillStyle:o,strokeStyle:"black"})):(o=e?"rgb(150, 150, 150)":"rgb(180, 180, 180)",Eo.setProperties(t,{fillStyle:o,strokeStyle:o})),Eo.fillCircle(t,h,i,s),Eo.strokeCircle(t,h,i,s)}}}};r(!1),r(!0)}popupData(e,t){if(void 0===t&&(t=e.viewport.cachedFeatures),!t||0===t.length)return[];const i=this.name,n=[];for(let r of t)Math.abs(r.px-e.canvasX)0&&n.push("
"),n.push({name:"snp id",value:r.snp},{name:"gene id",value:r.geneId},{name:"gene name",value:r.geneName},{name:"p value",value:r.pValue},{name:"tissue",value:i}));return n}menuItemList(){return Gt.numericDataMenuItems(this.trackView)}doAutoscale(e){if(e.length>0){var t=e.map((function(e){return-Math.log(e.value)/Math.LN10}));this.dataRange.max=Ms.percentile(t,this.autoscalePercentile)}else{const e=this.config.maxLogP||this.config.max;this.dataRange.max=e||25}return this.dataRange}}const Sv={X:"rgb(204, 153, 0)",Y:"rgb(153, 204, 0)",Un:"darkGray)",1:"rgb(80, 80, 255)",2:"rgb(206, 61, 50)","2a":"rgb(210, 65, 55)","2b":"rgb(215, 70, 60)",3:"rgb(116, 155, 88)",4:"rgb(240, 230, 133)",5:"rgb(70, 105, 131)",6:"rgb(186, 99, 56)",7:"rgb(93, 177, 221)",8:"rgb(128, 34, 104)",9:"rgb(107, 215, 107)",10:"rgb(213, 149, 167)",11:"rgb(146, 72, 34)",12:"rgb(131, 123, 141)",13:"rgb(199, 81, 39)",14:"rgb(213, 143, 92)",15:"rgb(122, 101, 165)",16:"rgb(228, 175, 105)",17:"rgb(59, 27, 83)",18:"rgb(205, 222, 183)",19:"rgb(97, 42, 121)",20:"rgb(174, 31, 99)",21:"rgb(231, 199, 111)",22:"rgb(90, 101, 94)",23:"rgb(204, 153, 0)",24:"rgb(153, 204, 0)",25:"rgb(51, 204, 0)",26:"rgb(0, 204, 51)",27:"rgb(0, 204, 153)",28:"rgb(0, 153, 204)",29:"rgb(10, 71, 255)",30:"rgb(71, 117, 255)",31:"rgb(255, 194, 10)",32:"rgb(255, 209, 71)",33:"rgb(153, 0, 51)",34:"rgb(153, 26, 0)",35:"rgb(153, 102, 0)",36:"rgb(128, 153, 0)",37:"rgb(51, 153, 0)",38:"rgb(0, 153, 26)",39:"rgb(0, 153, 102)",40:"rgb(0, 128, 153)",41:"rgb(0, 51, 153)",42:"rgb(26, 0, 153)",43:"rgb(102, 0, 153)",44:"rgb(153, 0, 128)",45:"rgb(214, 0, 71)",46:"rgb(255, 20, 99)",47:"rgb(0, 214, 143)",48:"rgb(20, 255, 177)"};for(let Nx of Object.keys(Sv)){Sv["chr"+Nx]=Sv[Nx]}for(let Mx=1;Mx<=48;Mx++){if(10===Mx)continue;const Lx=Hv(Mx);Sv[Lx]=Sv[Mx.toString()]}function Hv(e){if(!+e)return!1;for(var t=String(+e).split(""),i=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"],n="",r=3;r--;)n=(i[+t.pop()+10*r]||"")+n;return Array(+t.join("")+1).join("M")+n}class Nv extends ag{constructor(e,t){super(e,t)}init(e){super.init(e),this.useChrColors=void 0===e.useChrColors||e.useChrColors,this.trait=e.trait,this.posteriorProbability=e.posteriorProbability,this.valueProperty="bed"===e.format?"score":"value",this.height=e.height||100,this.autoscale=e.autoscale,this.autoscalePercentile=void 0===e.autoscalePercentile?98:e.autoscalePercentile,this.background=e.background,this.divider=e.divider||"rgb(225,225,225)",this.dotSize=e.dotSize||3,this.popoverWindow=void 0===e.popoverWindow?1e8:e.popoverWindow,this.useChrColors?this.colorScale=new vo(e.colorTable||Sv):e.color?this.colorScale=new Vb(e.color):this.colorScale=new Ob(e.colorScale||{thresholds:[5e-8,5e-4,.5],colors:["rgb(255,50,50)","rgb(251,100,100)","rgb(251,170,170)","rgb(227,238,249)"]}),this.featureSource=Pw(e,this.browser.genome)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),this.autoscale||(this.posteriorProbability?this.dataRange={min:void 0===this.config.min?0:this.config.min,max:void 0===this.config.max?1:this.config.max}:this.dataRange={min:void 0===this.config.min?0:this.config.min,max:void 0===this.config.max?25:this.config.max}),this}get supportsWholeGenome(){return!0}async getFeatures(e,t,i){const n=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:n})}draw(e){const t=e.features,i=e.context,n=e.pixelWidth,r=e.pixelHeight;if(this.background&&Eo.fillRect(i,0,0,n,r,{fillStyle:this.background}),Eo.strokeLine(i,0,r-1,n,r-1,{strokeStyle:this.divider}),t){const s=e.bpPerPixel,o=e.bpStart,a=o+n*s+1;for(let e of t){const t=e.start;if(ta)break;let n;if(this.posteriorProbability)n=e[this.valueProperty];else{const t=e[this.valueProperty];if(!t)continue;n=-Math.log10(t)}const A=this.useChrColors?e._f?e._f.chr:e.chr:n,c=this.colorScale.getColor(A),l=(this.dataRange.max-this.dataRange.min)/r,h=Math.round((t-o)/s),d=Math.max(this.dotSize,r-Math.round((n-this.dataRange.min)/l));c&&Eo.setProperties(i,{fillStyle:c,strokeStyle:"black"}),Eo.fillCircle(i,h,d,this.dotSize),e.px=h,e.py=d}}}paintAxis(e,t,i){Eo.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"});var n={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};const r=(this.dataRange.max-this.dataRange.min)/i;if(this.posteriorProbability){const t=.1;for(let s=this.dataRange.min;s0&&i.push("
"),5==r){i.push("...");break}if("function"==typeof s.popupData)i=i.concat(s.popupData());else{const e=s.realChr||s.chr,t=(s.realStart||s.start)+1;i.push({name:"chromosome",value:e}),i.push({name:"position",value:t}),i.push({name:"name",value:s.name}),n.posteriorProbability?i.push({name:"posterior probability",value:a}):i.push({name:"pValue",value:a})}r++}}}return i}menuItemList(){return Gt.numericDataMenuItems(this.trackView)}doAutoscale(e){if(e.length>0){const t=this.valueProperty,i=this.posteriorProbability,n=e.map((function(e){const n=e[t];return{value:i?n:-Math.log(n)/Math.LN10}}));this.dataRange=nf(n)}else this.posteriorProbability?this.dataRange={min:this.config.min||0,max:this.config.max||1}:this.dataRange={min:this.config.max||25,max:this.config.min||0};return this.dataRange}}class Mv extends ag{constructor(e,t){super(e,t)}init(e){super.init(e),this.autoscale=e.autoscale||void 0===e.max,this.dataRange={min:e.min||0,max:e.max},this.windowFunction=e.windowFunction||"mean",this.paintAxis=Jm,this.graphType=e.graphType||"bar",e._featureSource?(this.featureSource=e._featureSource,delete e._featureSource):this.featureSource=Pw(this.config,this.browser.genome),this.visibilityWindow=-1,this.featureSource.visibilityWindow=this.visibilityWindow}async postInit(){if("function"==typeof this.featureSource.getHeader){if(this.header=await this.featureSource.getHeader(),this.disposed)return;if(this.sampleNames=this.header.columnNames.slice(3),this.setTrackProperties(this.header),this.header.hasOwnProperty("clickToHighlight")){let e=this.header.clickToHighlight;this.config.clickToHighlight=e,this.config.samplesClickedToHighlight={}}if(this.header.hasOwnProperty("highlight")){this.config.highlightSamples={};let e=this.header.highlight;Array.isArray(e)||(e=[e]);for(let t of e){const e=t.split(";");2===e.length&&(this.config.highlightSamples[e[0]]=e[1])}}}}menuItemList(){return Gt.numericDataMenuItems(this.trackView)}async getFeatures(e,t,i){const n=await this.featureSource.getFeatures({chr:e,start:0,end:Number.MAX_SAFE_INTEGER,visibilityWindow:this.visibilityWindow});let r,s;for(let e=1;et&&(r=e-1),void 0===s&&n[e].start>i){s=e+1;break}return void 0===r&&(r=0),void 0===s&&(s=n.length),n.slice(r,s)}draw(e){const{features:t,context:i,bpPerPixel:n,bpStart:r,pixelWidth:s,pixelHeight:o}=e,a=e=>(this.dataRange.max-e)/(this.dataRange.max-this.dataRange.min)*o,A=function(e){let t=Math.floor((e-r)/n);return isNaN(t)&&console.warn("isNaN(x). feature start "+Xt(e)+" bp start "+Xt(r)),t};if(t&&t.length>0&&(void 0===this.dataRange.min&&(this.dataRange.min=0),this.dataRange.max>this.dataRange.min)){const e=this.config.highlightSamples,n=this.config.onlyHandleClicksForHighlightedSamples,r=this.config.clickToHighlight;let s=-1,o={},c=[],l=[];this.clickDetectorCache={};for(let h of t){const t=A(h.start),d=A(h.end),u=s>=0?A(s):t;if(!isNaN(t)&&!isNaN(d)){this.clickDetectorCache[t]=[],this.clickDetectorCache[d]=[];for(let s=0;s=1){const s=o[A],l=a(s),h=e&&e[A];h?c.push([u,l,t,p,h]):r&&A in this.config.samplesClickedToHighlight?c.push([u,l,t,p,this.config.samplesClickedToHighlight[A]]):Eo.strokeLine(i,u,l,t,p,{strokeStyle:"#D9D9D9"}),n&&!(A in e)||this.clickDetectorCache[t].push([u,l,t,p,A,h||"gray"])}if(d-t>=1){const s=e&&e[A];s?l.push([t,p,d,p,s]):r&&A in this.config.samplesClickedToHighlight?l.push([t,p,d,p,this.config.samplesClickedToHighlight[A]]):Eo.strokeLine(i,t,p,d,p,{strokeStyle:"gray"}),n&&!(A in e)||this.clickDetectorCache[d].push([t,p,d,p,A,s||"gray"])}o[A]=f}s=h.end}}for(let e of c)Eo.strokeLine(i,e[0],e[1],e[2],e[3],{strokeStyle:e[4],lineWidth:1.3});for(let e of l)Eo.strokeLine(i,e[0],e[1],e[2],e[3],{strokeStyle:e[4],lineWidth:2})}(e=>{if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=a(t.y),n={strokeStyle:t.color,strokeWidth:2};t.dotted?Eo.dashedLine(e.context,0,i,e.pixelWidth,i,5,n):Eo.strokeLine(e.context,0,i,e.pixelWidth,i,n)}})(e)}doAutoscale(e){let t,i;return e.length>0?(t=Number.MAX_VALUE,i=-Number.MAX_VALUE,e.forEach((function(e){t=Math.min(t,...e.values),i=Math.max(i,...e.values)})),t-=.01,i+=.01):(t=0,i=100),{min:t,max:i}}clickedFeatures(e){const t=e.canvasX,i=e.canvasY;let n=null;for(n of Object.keys(this.clickDetectorCache))if(n=parseInt(n),n>=t)break;if(n){let e=Number.MAX_VALUE,o=[];const a=this.clickDetectorCache[n];for(let n of a){const r=n[0],s=n[2];if(ts)return[];const a=n[1],A=n[3];if(iMath.max(a,A)+10)continue;const c=Lv(t,i,r,a,s,A);c0?A/c:0}class Dv extends ag{constructor(e,t){super(e,t),e.height||(this.height=300),this.arcOrientation=!1,this.theta=Math.PI/2,"bp"===e.format?this.featureSource=new Rv(e,t.genome):this.featureSource=new pw(e,t.genome)}async getFeatures(e,t,i){const n=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:n})}draw(e){const t=e.context,i=Math.PI/2,n=e.pixelWidth,r=e.pixelHeight;e.viewportWidth;const s=e.bpPerPixel,o=e.bpStart,a=s,A=this.arcOrientation;Eo.fillRect(t,0,e.pixelTop,n,r,{fillStyle:"rgb(255, 255, 255)"});const c=e.features;if(c){Tv(c,1);for(let e of c)if(e.startLeft){let n=Math.round((e.startLeft-o)/a),r=Math.round((e.startRight-o)/a),s=Math.round((e.endLeft-o)/a),c=Math.round((e.endRight-o)/a);t.fillStyle=e.color,t.strokeStyle=e.color,t.beginPath();let l=(n+c)/2,h=(c-n)/2,d=this.height,u=Math.PI+(Math.PI/2-i),f=2*Math.PI-(Math.PI/2-i);A?(d=0,t.arc(l,d,h,f,u),t.lineTo(c,d)):(t.arc(l,d,h,u,f),t.lineTo(s,d));const p=(r+s)/2,g=(s-r)/2,w=d;A?(t.arc(p,w,g,u,f,!0),t.lineTo(s,w)):(t.arc(p,w,g,f,u,!0),t.lineTo(n,w)),t.stroke(),t.fill(),e.drawState={x1:l,y1:d,r1:h,x2:p,y2:w,r2:g,sa:u,ea:f}}else{let n=Math.round((e.start-o)/a),r=Math.round((e.end-o)/a);t.strokeStyle=e.color,t.beginPath();let s=(n+r)/2,c=(r-n)/2,l=this.height,h=Math.PI+(Math.PI/2-i),d=2*Math.PI-(Math.PI/2-i);A?(l=0,t.arc(s,l,c,d,h)):t.arc(s,l,c,h,d),t.stroke(),e.drawState={x1:s,y1:l,r1:c,sa:h,ea:d}}}}clickedFeatures(e){const t=super.clickedFeatures(e),i=[];Tv(t,-1);for(let n of t){const t=n.drawState,r=e.canvasX-t.x1,s=e.canvasY-t.y1,o=Math.sqrt(r*r+s*s),a=t.r1+3;let A,c;if(void 0===t.x2)A=o,c=t.r1-3;else{const i=e.canvasX-t.x2,n=e.canvasY-t.y2;A=Math.sqrt(i*i+n*n),c=t.r2-3}if(oc){i.push(n);break}}return i}popupData(e,t){if(void 0===t&&(t=this.clickedFeatures(e)),t&&t.length>0)return this.extractPopupData(t[0],this.getGenomeId())}menuItemList(){var e=this;return[{name:"Toggle arc direction",click:function(){e.arcOrientation=!e.arcOrientation,e.trackView.repaintViews()}}]}}function Tv(e,t){e.sort((function(e,i){const n=void 0===e.score?-Number.MAX_VALUE:e.score,r=void 0===i.score?-Number.MAX_VALUE:i.score;return(void 0===t?1:t)*(n-r)}))}class Rv{constructor(e,t){this.config=e,this.genome=t}async getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:r}){const s=this.genome;if(this.featureCache)return this.featureCache.queryFeatures(e,t,i);{const n=tf(this.config),r=await io.loadString(this.config.url,n);return this.featureCache=new uo(function(e){if(!e)return null;const t=zg(e);let i,n=!0;const r=[],s=[],o=[];for(;void 0!==(i=t.nextLine());){const e=i.split("\t");if(n&&i.startsWith("color:")){const t="rgb("+e[1]+","+e[2]+","+e[3]+")";r.push(t),e.length>4&&s.push(e[4])}else{n=!1;const t=e[0],i=Number.parseInt(e[1])-1,A=Number.parseInt(e[2])-1,c=Number.parseInt(e[3]),l=Number.parseInt(e[4]);var a=Number.parseInt(e[5]);const h=r[a];let d;d=i<=l?{chr:t,startLeft:Math.min(i,A),startRight:Math.max(i,A),endLeft:Math.min(c,l),endRight:Math.max(c,l),color:h,score:a}:{chr:t,startLeft:Math.min(c,l),startRight:Math.max(c,l),endLeft:Math.min(i,A),endRight:Math.max(i,A),color:h,score:a},d.start=d.startLeft,d.end=d.endRight,s.length>a&&(d.description=s[a]),o.push(d)}}return o}(r),s),this.featureCache.queryFeatures(e,t,i)}}}class zv{constructor(e){this.browser=e,this.type="ideogram",this.height=16,this.order=Number.MIN_SAFE_INTEGER,this.disableButtons=!0,this.ignoreTrackMenu=!0}async getFeatures(e,t,i){return[]}computePixelHeight(e){return this.height}draw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:n}){const r=t.chr,s=t.genome.getChromosome(r);if(void 0===s||i<=0||n<=0||"all"===r.toLowerCase())return;!function({ctx:e,chr:t,referenceFrame:i,genome:n,width:r,height:s,stainColors:o}){const a=1,A=.5*a,c=0;if(void 0===n)return;Eo.fillRect(e,0,0,r,s,{fillStyle:Ts.greyScale(255)});const l=n.getCytobands(t);if(l){const t=c+s/2,i=[],n=[];if(0===l.length)return;const h=r/l[l.length-1].end;e.beginPath(),Eo.roundRect(e,A,A+c,r-2*A,s-2*A,(s-2*A)/2,0,1),e.clip();for(let r=0;r0&&c[c.length-1].end&&(A=Math.max(A,c[c.length-1].end),s.bpLength=A),o{Pv.getColor(e)}));const Vv={};class Kv extends ag{constructor(e,t){super(e,t)}init(e){super.init(e),this.type=e.type||"junctions",e._featureSource?(this.featureSource=e._featureSource,delete e._featureSource):this.featureSource=e.featureSource?e.featureSource:Pw(e,this.browser.genome),this.margin=void 0===e.margin?10:e.margin,this.height||(this.height=100),void 0===e.colorByNumReadsThreshold&&(e.colorByNumReadsThreshold=5)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),void 0===this.visibilityWindow&&"function"==typeof this.featureSource.defaultVisibilityWindow&&(this.visibilityWindow=await this.featureSource.defaultVisibilityWindow()),this}get supportsWholeGenome(){return!1}async getFeatures(e,t,i,n){const r=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:n,visibilityWindow:r})}computePixelHeight(e){return this.height}draw(e){const t=e.features,i=e.context,n=e.bpPerPixel,r=e.bpStart,s=e.pixelWidth,o=e.pixelHeight,a=r+s*n+1;if(this.config.isMergedTrack||Eo.fillRect(i,0,e.pixelTop,s,o,{fillStyle:"rgb(255, 255, 255)"}),t){Vv.referenceFrame=e.viewport.referenceFrame,Vv.referenceFrameStart=Vv.referenceFrame.start,Vv.referenceFrameEnd=Vv.referenceFrameStart+Vv.referenceFrame.toBP(e.viewport.getWidth()),Vv.featureZoomOutTracker={};for(let e of t)if(!(e.enda)break;this.renderJunction(e,r,n,o,i)}}else console.log("No feature list")}renderJunction(e,t,i,n,r){e.isVisible=!1;const s=Math.round((e.start-t)/i),o=Math.round((e.end-t)/i),a=(s+o)/2;if(o-s<=3){if(a in Vv.featureZoomOutTracker)return;Vv.featureZoomOutTracker[a]=!0}if(this.config.hideAnnotatedJunctions&&"true"===e.attributes.annotated_junction)return;if(this.config.hideUnannotatedJunctions&&"false"===e.attributes.annotated_junction)return;if(this.config.hideMotifs&&this.config.hideMotifs.includes(e.attributes.motif))return;if(this.config.hideStrand===e.strand)return;if(this.config.minJunctionEndsVisible){let t=0;if(e.start>=Vv.referenceFrameStart&&e.start<=Vv.referenceFrameEnd&&(t+=1),e.end>=Vv.referenceFrameStart&&e.end<=Vv.referenceFrameEnd&&(t+=1),t0&&c/l>this.config.maxFractionMultiMappedReads)return;if(e.attributes.maximum_spliced_alignment_overhang&&parseInt(e.attributes.maximum_spliced_alignment_overhang)this.config.maxSamplesWithThisJunction)return;if(e.attributes.num_samples_total&&(e.attributes.percent_samples_with_this_junction=100*h/Number(e.attributes.num_samples_total),this.config.minPercentSamplesWithThisJunction&&(e.attributes.percent_samples_with_this_junctionthis.config.maxPercentSamplesWithThisJunction)))return}const d=this.margin,u=this.height,f=d+.5*u;let p=d;const g=d+u-10,w=(s+a)/2,m=(a+o)/2;let F,b,v=1;e.attributes.line_width?v=Number(e.attributes.line_width):(void 0===this.config.thicknessBasedOn||"numUniqueReads"===this.config.thicknessBasedOn?v=A:"numReads"===this.config.thicknessBasedOn?v=l:"numSamplesWithThisJunction"===this.config.thicknessBasedOn&&void 0!==h&&(v=h),v=1+Math.log(v+1)/Math.log(12)),void 0===this.config.bounceHeightBasedOn||"random"===this.config.bounceHeightBasedOn?F=(e.start+e.end)%7:"distance"===this.config.bounceHeightBasedOn?F=6*(e.end-e.start)/(Vv.referenceFrameEnd-Vv.referenceFrameStart):"thickness"===this.config.bounceHeightBasedOn&&(F=2*v),p+=u*Math.max(7-F,0)/10,b=e.attributes.color?e.attributes.color:void 0===this.config.colorBy||"numUniqueReads"===this.config.colorBy?A>this.config.colorByNumReadsThreshold?"blue":"#AAAAAA":"numReads"===this.config.colorBy?l>this.config.colorByNumReadsThreshold?"blue":"#AAAAAA":"isAnnotatedJunction"===this.config.colorBy?"true"===e.attributes.annotated_junction?"#b0b0ec":"orange":"strand"===this.config.colorBy?"+"===e.strand?"#b0b0ec":"#ecb0b0":"motif"===this.config.colorBy?Pv.getColor(e.attributes.motif):"#AAAAAA";let B="";e.attributes.label?B=e.attributes.label.replace(/_/g," "):void 0===this.config.labelWith||"uniqueReadCount"===this.config.labelWith?B=A:"totalReadCount"===this.config.labelWith?B=l:"numSamplesWithThisJunction"===this.config.labelWith?void 0!==h&&(B=h):"percentSamplesWithThisJunction"===this.config.labelWith?void 0!==e.attributes.percent_samples_with_this_junction&&(B=e.attributes.percent_samples_with_this_junction.toFixed(0)+"%"):"motif"===this.config.labelWith&&void 0!==e.attributes.motif&&(B+=e.attributes.motif),"uniqueReadCount"===this.config.labelWithInParen?B+=" ("+A+")":"totalReadCount"===this.config.labelWithInParen?B+=" ("+l+")":"multiMappedReadCount"===this.config.labelWithInParen?c>0&&(B+=" (+"+c+")"):"numSamplesWithThisJunction"===this.config.labelWithInParen?void 0!==h&&(B+=" ("+h+")"):"percentSamplesWithThisJunction"===this.config.labelWithInParen?void 0!==e.attributes.percent_samples_with_this_junction&&(B+=" ("+e.attributes.percent_samples_with_this_junction.toFixed(0)+"%)"):"motif"===this.config.labelWithInParen&&void 0!==e.attributes.motif&&(B+=` ${e.attributes.motif}`),e.attributes.effect&&(e.attributes.effect.includes("acceptor")?e.attributes.effect.includes("gain")?b="#90EE90":e.attributes.effect.includes("loss")&&(b="#FF7D6A"):e.attributes.effect.includes("donor")&&(e.attributes.effect.includes("gain")?b="#008600":e.attributes.effect.includes("loss")&&(b="#CE0000"))),e.isVisible=!0,r.beginPath(),r.moveTo(s,g),r.bezierCurveTo(w,p,m,p,o,g),r.lineWidth=v,r.strokeStyle=b,r.stroke();const y=(e,t,i,n)=>{e.beginPath(),e.moveTo(t,i),e.lineTo(t-n/2,i-n),e.lineTo(t+n/2,i-n),e.lineTo(t,i),e.closePath(),e.fill()};if(e.attributes.left_shape||e.attributes.right_shape){r.fillStyle=b;const t=r.lineWidth>2?10:7;e.attributes.left_shape&&y(r,s,g,t),e.attributes.right_shape&&y(r,o,g,t)}r.fillText(B,a-r.measureText(B).width/2,(7*p+f)/8)}clickedFeatures(e){return super.clickedFeatures(e).filter((function(e){return e.isVisible&&e.attributes}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,n=[];for(let e of t){const t="function"==typeof e.popupData?e.popupData(i):this.extractPopupData(e._f||e,this.getGenomeId());t&&(n.length>0&&n.push("

"),Array.prototype.push.apply(n,t))}return n}dispose(){this.trackView=void 0}}const Gv="#1fb839",qv="#FFCB1F",jv="#FF0000";class Wv extends ag{constructor(e,t){super(e,t),this.tool=e.tool||"SpliceAI",this.rawOrDelta=e.rawOrDelta||"delta",this.strand=e.strand||"+",this.paintAxis=this.paintAxisCustom,this.dataRange="delta"===this.rawOrDelta?{min:-1,max:1}:{min:0,max:1}}paintAxisCustom(e,t,i){if(Jm.call(this,e,t,i),e.fillStyle="black",e.font="bold 10pt sans-serif",e.textAlign="center","delta"==this.rawOrDelta){for(const[t,n]of["GAIN","LOSS"].entries())e.save(),e.translate(35,i*(0==t?.25:.75)),e.rotate(-Math.PI/2),e.fillText(n,0,0),e.restore();e.translate(15,.5*i),e.rotate(-Math.PI/2),e.font="12pt sans-serif",e.fillText(`${this.tool}: Δ score`,0,0)}else e.translate(15,.5*i),e.rotate(-Math.PI/2),e.font="12pt sans-serif",e.fillText("raw score",0,0)}init(e){super.init(e),this.type=e.type||"spliceprediction",this.margin=void 0===e.margin?10:e.margin,this.height=e.height||100,this.features=e.features||[]}get supportsWholeGenome(){return!0}async getFeatures(e,t,i,n){return this.features.filter((n=>n.chr===e&&n.start<=i&&n.end>=t))}computePixelHeight(e){return this.height}drawLine(e,t,i,n,r,s,o,a){e.lineWidth=s,e.strokeStyle=o,e.beginPath(),e.moveTo(t,i),a?e.setLineDash([3,4]):e.setLineDash([]),e.lineTo(n,r),e.stroke()}drawText(e,t,i,n,r,s,o,a){if(e.fillStyle=r,e.textAlign="center",e.font=o?`bold ${s}pt sans-serif`:`${s}pt sans-serif`,a){e.save(),e.translate(i,n),e.rotate(a);const r=e.measureText(t),s=(r.fontBoundingBoxAscent-r.fontBoundingBoxDescent)/2;e.translate(0,s),e.fillText(t,0,0),e.restore()}else{const r=e.measureText(t),s=(r.fontBoundingBoxAscent-r.fontBoundingBoxDescent)/2;e.fillText(t,i,n+s)}}draw(e){const t=e.context,i=e.pixelWidth,n=e.pixelHeight,r=e.bpStart;this.config.isMergedTrack||Eo.fillRect(t,0,e.pixelTop,i,n,{fillStyle:"rgb(255, 255, 255)"}),"delta"==this.rawOrDelta?this.drawLine(t,0,n/2,i,n/2,.5,"#777777",!1):(this.drawLine(t,0,0,i,0,.5,"#777777",!1),this.drawLine(t,0,n,i,n,.5,"#777777",!1),this.drawLine(t,0,.2*n,i,.2*n,.5,jv,!0),this.drawLine(t,0,.5*n,i,.5*n,.5,qv,!0),this.drawLine(t,0,.8*n,i,.8*n,.5,Gv,!0));const s=.01;if(e.features)for(let t of e.features){const n=r+i*e.bpPerPixel+1;t.endn||("spliceai"==this.tool.toLowerCase()?(("delta"==this.rawOrDelta&&Math.abs(t.AA-t.RA)>=s||"delta"!=this.rawOrDelta&&(Math.abs(t.AA)>=s||Math.abs(t.RA)>=s))&&this.renderScore(t,e,t.RA,t.AA,"A"),("delta"==this.rawOrDelta&&Math.abs(t.AD-t.RD)>=s||"delta"!=this.rawOrDelta&&(Math.abs(t.AD)>=s||Math.abs(t.RD)>=s))&&this.renderScore(t,e,t.RD,t.AD,"D")):"pangolin"==this.tool.toLowerCase()&&"delta"==this.rawOrDelta&&(t.SL_ALT-t.SL_REF<=-.01?this.renderScore(t,e,t.SL_REF,t.SL_ALT,"P"):t.SG_ALT-t.SG_REF>=s&&this.renderScore(t,e,t.SG_REF,t.SG_ALT,"P")))}else console.log("No feature list")}renderScore(e,t,i,n,r){const s=n-i,o=t.context,a=t.bpPerPixel,A=t.bpStart,c=t.pixelHeight,l=s<0?-1:1;let h=0;h=l>0?"A"==r?0:-Math.PI/2:"A"==r?Math.PI:Math.PI/2;const d=(e.start-A-.5)/a,u=o.measureText("A"),f=(u.fontBoundingBoxAscent+u.fontBoundingBoxDescent)/2;if("delta"==this.rawOrDelta){let e;e=Math.abs(s)>=.8?jv:Math.abs(s)>=.5?qv:Math.abs(s)>=.2?Gv:"#AAAAAA";const t=c*(1-.65*s)/2,i=Math.max(.5,1/a);this.drawLine(o,d,c/2,d,t,i,e,!1),this.drawText(o,r,d,t-1.5*l*f,"black",10,i>1,h);const n=parseFloat("pangolin"==this.tool.toLowerCase()?s.toFixed(2):Math.abs(s).toFixed(2));this.drawText(o,n,d,t-2*l*f*2,"black",9,0)}else{const e=[];for(const[t,s]of[n,i].entries()){let n,a=c*(1-s);if(a>c-f&&(a=c-f),a.5?-1:1)*f*2;this.drawText(o,t,d,r,n,9,0),e.push(Math.abs(e[0]-a)=2&&Math.abs(e[0]-e[1])<10;if(1==t&&!A){const t=1;this.drawLine(o,d,Math.min(e[0],e[1])+1.3*f,d,Math.max(e[0],e[1])-1.3*f,t,n,!0)}this.drawText(o,r,d+(1==t&&A?2:0),a,n,10,!0,h)}}}clickedFeatures(e){return super.clickedFeatures(e).filter((function(e){return e.isVisible&&e.attributes}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,n=[];for(let e of t){const t="function"==typeof e.popupData?e.popupData(i):this.extractPopupData(e._f||e,this.getGenomeId());t&&(n.length>0&&n.push("

"),Array.prototype.push.apply(n,t))}return n}dispose(){this.trackView=void 0}}class $v{constructor(e){var t;this.config=e,this.url=(t=e.path||e.url).includes("//www.dropbox.com")?t.replace("//www.dropbox.com","//dl.dropboxusercontent.com"):t.startsWith("ftp://ftp.ncbi.nlm.nih.gov")?t.replace("ftp://","https://"):t}async read(e,t){const i=this.config.headers||{};if(void 0!==e&&t){const n="bytes="+e+"-"+(e+t-1);i.Range=n}let n=this.url.slice();if(this.config.oauthToken){const e=async function(e){return"function"==typeof e?await Promise.resolve(e()):e}(this.config.oauthToken);i.Authorization=`Bearer ${e}`}this.config.apiKey&&(n=function(e,t,i){const n=e.includes("?")?"&":"?";return e+n+t+"="+i}(n,"key",this.config.apiKey));const r=await fetch(n,{method:"GET",headers:i,redirect:"follow",mode:"cors"}),s=r.status;if(s>=400){const e=Error(r.statusText);throw e.code=s,e}return r.arrayBuffer()}}class Xv{constructor(e){this.file=e.file,this.fetchSize=e.fetchSize||16e3,this.maxSize=e.maxSize||1e6,this.buffers=[]}async read(e,t){let i=this.buffers.filter((i=>i.overlaps(e,e+t)));for(let n of i)if(n.contains(e,e+t))return n.slice(e,e+t);if(0===i.length){let i=Math.max(t,this.fetchSize);this.buffers.sort(((e,t)=>e.start-t.start));const n=function(e,t,i){let n=i-1,r=e.length;for(;1+n>1);t(e[i])?r=i:n=i}return r}(this.buffers,(t=>t.start>e),0);ne.start-t.start));const n=[];let r=e;for(let e of i){if(rr){const e=r,t=s-e,i=await this.file.read(e,t),o=new Zv(e,i);n.push(o)}const o=n[0].start,a=function(e){const t=e.reduce(((e,t)=>e+t.byteLength),0),i=new Uint8Array(t);let n=0;for(let t of e)i.set(new Uint8Array(t),n),n+=t.byteLength;return i.buffer}(n.map((e=>e.buffer))),A=new Zv(o,a),c=new Set(i);return this.buffers=this.buffers.filter((e=>!c.has(e))),this.addBuffer(A),A.slice(e,e+t)}}addBuffer(e){const t=this.buffers.reduce(((e,t)=>e+t.size),0)+e.size;if(t>this.maxSize){const e=t-this.maxSize;this.buffers.sort(((e,t)=>e.creationTime-t.creationTime));let i,n=0;for(i=0;ie));i++);this.buffers=ithis.buffer.byteLength)throw Error("buffer bounds error");return this.buffer.slice(e-this.start,t-this.start)}get end(){return this.start+this.buffer.byteLength}get size(){return this.buffer.byteLength}contains(e,t){return e>=this.start&&t<=this.end}overlaps(e,t){return e>this.start&&ethis.start&&t=!@]?(i|u|f)(\d*)/);i=parseInt(s||4,10),t="get"+rB[r]+(8*i).toFixed()}return[t,n,i]}var oB=new class{constructor(){this.big_endian=function(){const e=new Uint8Array(4);return!((new Uint32Array(e.buffer)[0]=1)&e[0])}(),this.getters={s:"getUint8",b:"getInt8",B:"getUint8",h:"getInt16",H:"getUint16",i:"getInt32",I:"getUint32",l:"getInt32",L:"getUint32",q:"getInt64",Q:"getUint64",f:"getFloat32",d:"getFloat64"},this.byte_lengths={s:1,b:1,B:1,h:2,H:2,i:4,I:4,l:4,L:4,q:8,Q:8,f:4,d:8};let e=Object.keys(this.byte_lengths).join("");this.fmt_size_regex="(\\d*)(["+e+"])"}calcsize(e){for(var t,i=0,n=new RegExp(this.fmt_size_regex,"g");null!==(t=n.exec(e));){let e=parseInt(t[1]||1,10),n=t[2];i+=e*this.byte_lengths[n]}return i}_is_big_endian(e){return!/^)/.test(e)||this.big_endian)}async unpack_from_async(e,t,i){i=Number(i||0);const n=this.calcsize(e),r=await t.slice(i,i+n);let s=0;for(var o,a=new aB(r),A=[],c=this._is_big_endian(e),l=new RegExp(this.fmt_size_regex,"g");null!==(o=l.exec(e));){let e=parseInt(o[1]||1,10),t=o[2],i=this.getters[t],n=this.byte_lengths[t];if("s"==t)A.push((new TextDecoder).decode(r.slice(s,s+e))),s+=e;else for(var h=0;he+(t<<8*i)),0);return o}var lB=class{constructor(e,t){this.buf=e,this.offset=t,this.dtype=this.determine_dtype()}async determine_dtype(){let e=await Yv(hB,this.buf,this.offset);this.offset+=dB;let t=15&e.get("class_and_version");if(t==uB)return this._determine_dtype_fixed_point(e);if(t==fB)return this._determine_dtype_floating_point(e);if(t==pB)throw"Time datatype class not supported.";if(t==gB)return this._determine_dtype_string(e);if(t==wB)throw"Bitfield datatype class not supported.";if(t==mB)return{datatype_class:mB,size:e.get("size")};if(t==FB)return this._determine_dtype_compound(e);if(t==bB)return["REFERENCE",e.get("size")];if(t==vB)return this.determine_dtype();if(t==yB)throw"Array datatype class not supported.";if(t==BB){let t=this._determine_dtype_vlen(e);if("VLEN_SEQUENCE"==t[0]){t=["VLEN_SEQUENCE",this.determine_dtype()]}return t}throw"Invalid datatype class "+t}_determine_dtype_fixed_point(e){let t=e.get("size");if(![1,2,4,8].includes(t))throw"Unsupported datatype size";var i;var n;return i=(8&e.get("class_bit_field_0"))>0?"i":"u",n=0==(1&e.get("class_bit_field_0"))?"<":">",this.offset+=4,n+i+t.toFixed()}_determine_dtype_floating_point(e){let t=e.get("size");if(![1,2,4,8].includes(t))throw"Unsupported datatype size";var i;return i=0==(1&e.get("class_bit_field_0"))?"<":">",this.offset+=12,i+"f"+t.toFixed()}_determine_dtype_string(e){return"S"+e.get("size").toFixed()}_determine_dtype_vlen(e){return 1!=(1&e.get("class_bit_field_0"))?["VLEN_SEQUENCE",0,0]:["VLEN_STRING",e.get("class_bit_field_0")>>4,1&e.get("class_bit_field_1")]}_determine_dtype_compound(e){throw"Compound type not yet implemented!"}},hB=new Map([["class_and_version","B"],["class_bit_field_0","B"],["class_bit_field_1","B"],["class_bit_field_2","B"],["size","I"]]),dB=iB(hB);iB(new Map([["offset","I"],["dimensionality","B"],["reserved_0","B"],["reserved_1","B"],["reserved_2","B"],["permutation","I"],["reserved_3","I"],["dim_size_1","I"],["dim_size_2","I"],["dim_size_3","I"],["dim_size_4","I"]]));var uB=0,fB=1,pB=2,gB=3,wB=4,mB=5,FB=6,bB=7,vB=8,BB=9,yB=10;function CB(e){let t=e.length;for(;--t>=0;)e[t]=0}CB(new Array(576)),CB(new Array(60)),CB(new Array(512)),CB(new Array(256)),CB(new Array(29)),CB(new Array(30));var _B=(e,t,i,n)=>{let r=65535&e|0,s=e>>>16&65535|0,o=0;for(;0!==i;){o=i>2e3?2e3:i,i-=o;do{r=r+t[n++]|0,s=s+r|0}while(--o);r%=65521,s%=65521}return r|s<<16|0},xB=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})()),kB=(e,t,i,n)=>{const r=xB,s=n+i;e^=-1;for(let i=n;i>>8^r[255&(e^t[i])];return-1^e},EB={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},IB={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},UB=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),QB={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)UB(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i=252?6:Tx>=248?5:Tx>=240?4:Tx>=224?3:Tx>=192?2:1;HB[254]=HB[254]=1;var NB={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,r,s,o=e.length,a=0;for(r=0;r>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let n,r;const s=new Array(2*i);for(r=0,n=0;n4)s[r++]=65533,n+=o-1;else{for(t&=2===o?31:3===o?15:7;o>1&&n1?s[r++]=65533:t<65536?s[r++]=t:(t-=65536,s[r++]=55296|t>>10&1023,s[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&SB)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+HB[e[i]]>t?i:t}};var MB=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},LB=function(e,t){let i,n,r,s,o,a,A,c,l,h,d,u,f,p,g,w,m,F,b,v,B,y,C,_;const x=e.state;i=e.next_in,C=e.input,n=i+(e.avail_in-5),r=e.next_out,_=e.output,s=r-(t-e.avail_out),o=r+(e.avail_out-257),a=x.dmax,A=x.wsize,c=x.whave,l=x.wnext,h=x.window,d=x.hold,u=x.bits,f=x.lencode,p=x.distcode,g=(1<>>24,d>>>=F,u-=F,F=m>>>16&255,0===F)_[r++]=65535&m;else{if(!(16&F)){if(0==(64&F)){m=f[(65535&m)+(d&(1<>>=F,u-=F),u<15&&(d+=C[i++]<>>24,d>>>=F,u-=F,F=m>>>16&255,!(16&F)){if(0==(64&F)){m=p[(65535&m)+(d&(1<a){e.msg="invalid distance too far back",x.mode=30;break e}if(d>>>=F,u-=F,F=r-s,v>F){if(F=v-F,F>c&&x.sane){e.msg="invalid distance too far back",x.mode=30;break e}if(B=0,y=h,0===l){if(B+=A-F,F2;)_[r++]=y[B++],_[r++]=y[B++],_[r++]=y[B++],b-=3;b&&(_[r++]=y[B++],b>1&&(_[r++]=y[B++]))}else{B=r-v;do{_[r++]=_[B++],_[r++]=_[B++],_[r++]=_[B++],b-=3}while(b>2);b&&(_[r++]=_[B++],b>1&&(_[r++]=_[B++]))}break}}break}}while(i>3,i-=b,u-=b<<3,d&=(1<{const A=a.bits;let c,l,h,d,u,f,p=0,g=0,w=0,m=0,F=0,b=0,v=0,B=0,y=0,C=0,_=null,x=0;const k=new Uint16Array(16),E=new Uint16Array(16);let I,U,Q,S=null,H=0;for(p=0;p<=DB;p++)k[p]=0;for(g=0;g=1&&0===k[m];m--);if(F>m&&(F=m),0===m)return r[s++]=20971520,r[s++]=20971520,a.bits=1,0;for(w=1;w0&&(0===e||1!==m))return-1;for(E[1]=0,p=1;p852||2===e&&y>592)return 1;for(;;){I=p-v,o[g]f?(U=S[H+o[g]],Q=_[x+o[g]]):(U=96,Q=0),c=1<>v)+l]=I<<24|U<<16|Q|0}while(0!==l);for(c=1<>=1;if(0!==c?(C&=c-1,C+=c):C=0,g++,0==--k[p]){if(p===m)break;p=t[i+o[g]]}if(p>F&&(C&d)!==h){for(0===v&&(v=F),u+=w,b=p-v,B=1<852||2===e&&y>592)return 1;h=C&d,r[h]=F<<24|b<<16|u-s|0}}return 0!==C&&(r[u+C]=p-v<<24|64<<16|0),a.bits=F,0},{Z_FINISH:VB,Z_BLOCK:KB,Z_TREES:GB,Z_OK:qB,Z_STREAM_END:jB,Z_NEED_DICT:WB,Z_STREAM_ERROR:$B,Z_DATA_ERROR:XB,Z_MEM_ERROR:ZB,Z_BUF_ERROR:JB,Z_DEFLATED:YB}=IB,ey=12,ty=30,iy=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function ny(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var ry,sy,oy=e=>{if(!e||!e.state)return $B;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,qB},ay=e=>{if(!e||!e.state)return $B;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,oy(e)},Ay=(e,t)=>{let i;if(!e||!e.state)return $B;const n=e.state;return t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?$B:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,ay(e))},cy=(e,t)=>{if(!e)return $B;const i=new ny;e.state=i,i.window=null;const n=Ay(e,t);return n!==qB&&(e.state=null),n},ly=!0,hy=e=>{if(ly){ry=new Int32Array(512),sy=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(PB(1,e.lens,0,288,ry,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;PB(2,e.lens,0,32,sy,0,e.work,{bits:5}),ly=!1}e.lencode=ry,e.lenbits=9,e.distcode=sy,e.distbits=5},dy=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave{let i,n,r,s,o,a,A,c,l,h,d,u,f,p,g,w,m,F,b,v,B,y,C=0;const _=new Uint8Array(4);let x,k;const E=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return $B;i=e.state,i.mode===ey&&(i.mode=13),o=e.next_out,r=e.output,A=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,c=i.hold,l=i.bits,h=a,d=A,y=qB;e:for(;;)switch(i.mode){case 1:if(0===i.wrap){i.mode=13;break}for(;l<16;){if(0===a)break e;a--,c+=n[s++]<>>8&255,i.check=kB(i.check,_,2,0),c=0,l=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&c)<<8)+(c>>8))%31){e.msg="incorrect header check",i.mode=ty;break}if((15&c)!==YB){e.msg="unknown compression method",i.mode=ty;break}if(c>>>=4,l-=4,B=8+(15&c),0===i.wbits)i.wbits=B;else if(B>i.wbits){e.msg="invalid window size",i.mode=ty;break}i.dmax=1<>8&1),512&i.flags&&(_[0]=255&c,_[1]=c>>>8&255,i.check=kB(i.check,_,2,0)),c=0,l=0,i.mode=3;case 3:for(;l<32;){if(0===a)break e;a--,c+=n[s++]<>>8&255,_[2]=c>>>16&255,_[3]=c>>>24&255,i.check=kB(i.check,_,4,0)),c=0,l=0,i.mode=4;case 4:for(;l<16;){if(0===a)break e;a--,c+=n[s++]<>8),512&i.flags&&(_[0]=255&c,_[1]=c>>>8&255,i.check=kB(i.check,_,2,0)),c=0,l=0,i.mode=5;case 5:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,c+=n[s++]<>>8&255,i.check=kB(i.check,_,2,0)),c=0,l=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(u=i.length,u>a&&(u=a),u&&(i.head&&(B=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(s,s+u),B)),512&i.flags&&(i.check=kB(i.check,n,u,s)),a-=u,s+=u,i.length-=u),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===a)break e;u=0;do{B=n[s+u++],i.head&&B&&i.length<65536&&(i.head.name+=String.fromCharCode(B))}while(B&&u>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=ey;break;case 10:for(;l<32;){if(0===a)break e;a--,c+=n[s++]<>>=7&l,l-=7&l,i.mode=27;break}for(;l<3;){if(0===a)break e;a--,c+=n[s++]<>>=1,l-=1,3&c){case 0:i.mode=14;break;case 1:if(hy(i),i.mode=20,t===GB){c>>>=2,l-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=ty}c>>>=2,l-=2;break;case 14:for(c>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,c+=n[s++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=ty;break}if(i.length=65535&c,c=0,l=0,i.mode=15,t===GB)break e;case 15:i.mode=16;case 16:if(u=i.length,u){if(u>a&&(u=a),u>A&&(u=A),0===u)break e;r.set(n.subarray(s,s+u),o),a-=u,s+=u,A-=u,o+=u,i.length-=u;break}i.mode=ey;break;case 17:for(;l<14;){if(0===a)break e;a--,c+=n[s++]<>>=5,l-=5,i.ndist=1+(31&c),c>>>=5,l-=5,i.ncode=4+(15&c),c>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=ty;break}i.have=0,i.mode=18;case 18:for(;i.have>>=3,l-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,x={bits:i.lenbits},y=PB(0,i.lens,0,19,i.lencode,0,i.work,x),i.lenbits=x.bits,y){e.msg="invalid code lengths set",i.mode=ty;break}i.have=0,i.mode=19;case 19:for(;i.have>>24,w=C>>>16&255,m=65535&C,!(g<=l);){if(0===a)break e;a--,c+=n[s++]<>>=g,l-=g,i.lens[i.have++]=m;else{if(16===m){for(k=g+2;l>>=g,l-=g,0===i.have){e.msg="invalid bit length repeat",i.mode=ty;break}B=i.lens[i.have-1],u=3+(3&c),c>>>=2,l-=2}else if(17===m){for(k=g+3;l>>=g,l-=g,B=0,u=3+(7&c),c>>>=3,l-=3}else{for(k=g+7;l>>=g,l-=g,B=0,u=11+(127&c),c>>>=7,l-=7}if(i.have+u>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=ty;break}for(;u--;)i.lens[i.have++]=B}}if(i.mode===ty)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=ty;break}if(i.lenbits=9,x={bits:i.lenbits},y=PB(1,i.lens,0,i.nlen,i.lencode,0,i.work,x),i.lenbits=x.bits,y){e.msg="invalid literal/lengths set",i.mode=ty;break}if(i.distbits=6,i.distcode=i.distdyn,x={bits:i.distbits},y=PB(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,x),i.distbits=x.bits,y){e.msg="invalid distances set",i.mode=ty;break}if(i.mode=20,t===GB)break e;case 20:i.mode=21;case 21:if(a>=6&&A>=258){e.next_out=o,e.avail_out=A,e.next_in=s,e.avail_in=a,i.hold=c,i.bits=l,LB(e,d),o=e.next_out,r=e.output,A=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,c=i.hold,l=i.bits,i.mode===ey&&(i.back=-1);break}for(i.back=0;C=i.lencode[c&(1<>>24,w=C>>>16&255,m=65535&C,!(g<=l);){if(0===a)break e;a--,c+=n[s++]<>F)],g=C>>>24,w=C>>>16&255,m=65535&C,!(F+g<=l);){if(0===a)break e;a--,c+=n[s++]<>>=F,l-=F,i.back+=F}if(c>>>=g,l-=g,i.back+=g,i.length=m,0===w){i.mode=26;break}if(32&w){i.back=-1,i.mode=ey;break}if(64&w){e.msg="invalid literal/length code",i.mode=ty;break}i.extra=15&w,i.mode=22;case 22:if(i.extra){for(k=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;C=i.distcode[c&(1<>>24,w=C>>>16&255,m=65535&C,!(g<=l);){if(0===a)break e;a--,c+=n[s++]<>F)],g=C>>>24,w=C>>>16&255,m=65535&C,!(F+g<=l);){if(0===a)break e;a--,c+=n[s++]<>>=F,l-=F,i.back+=F}if(c>>>=g,l-=g,i.back+=g,64&w){e.msg="invalid distance code",i.mode=ty;break}i.offset=m,i.extra=15&w,i.mode=24;case 24:if(i.extra){for(k=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=ty;break}i.mode=25;case 25:if(0===A)break e;if(u=d-A,i.offset>u){if(u=i.offset-u,u>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=ty;break}u>i.wnext?(u-=i.wnext,f=i.wsize-u):f=i.wnext-u,u>i.length&&(u=i.length),p=i.window}else p=r,f=o-i.offset,u=i.length;u>A&&(u=A),A-=u,i.length-=u;do{r[o++]=p[f++]}while(--u);0===i.length&&(i.mode=21);break;case 26:if(0===A)break e;r[o++]=i.length,A--,i.mode=21;break;case 27:if(i.wrap){for(;l<32;){if(0===a)break e;a--,c|=n[s++]<cy(e,15),inflateInit2:cy,inflate:uy,inflateEnd:e=>{if(!e||!e.state)return $B;let t=e.state;return t.window&&(t.window=null),e.state=null,qB},inflateGetHeader:(e,t)=>{if(!e||!e.state)return $B;const i=e.state;return 0==(2&i.wrap)?$B:(i.head=t,t.done=!1,qB)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return e&&e.state?(n=e.state,0!==n.wrap&&11!==n.mode?$B:11===n.mode&&(r=1,r=_B(r,t,i,0),r!==n.check)?XB:(s=dy(e,t,i,i),s?(n.mode=31,ZB):(n.havedict=1,qB))):$B},inflateInfo:"pako inflate (from Nodeca project)"};var py=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1},gy=Object.prototype.toString,{Z_NO_FLUSH:wy,Z_FINISH:my,Z_OK:Fy,Z_STREAM_END:by,Z_NEED_DICT:vy,Z_STREAM_ERROR:By,Z_DATA_ERROR:yy,Z_MEM_ERROR:Cy}=IB;function _y(e){this.options=QB.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new MB,this.strm.avail_out=0;let i=fy.inflateInit2(this.strm,t.windowBits);if(i!==Fy)throw new Error(EB[i]);if(this.header=new py,fy.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=NB.string2buf(t.dictionary):"[object ArrayBuffer]"===gy.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=fy.inflateSetDictionary(this.strm,t.dictionary),i!==Fy)))throw new Error(EB[i])}function xy(e,t){const i=new _y(t);if(i.push(e),i.err)throw i.msg||EB[i.err];return i.result}_y.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,o,a;if(this.ended)return!1;for(o=t===~~t?t:!0===t?my:wy,"[object ArrayBuffer]"===gy.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),s=fy.inflate(i,o),s===vy&&r&&(s=fy.inflateSetDictionary(i,r),s===Fy?s=fy.inflate(i,o):s===yy&&(s=vy));i.avail_in>0&&s===by&&i.state.wrap>0&&0!==e[i.next_in];)fy.inflateReset(i),s=fy.inflate(i,o);switch(s){case By:case yy:case vy:case Cy:return this.onEnd(s),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||s===by))if("string"===this.options.to){let e=NB.utf8border(i.output,i.next_out),t=i.next_out-e,r=NB.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==Fy||0!==a){if(s===by)return s=fy.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},_y.prototype.onData=function(e){this.chunks.push(e)},_y.prototype.onEnd=function(e){e===Fy&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=QB.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ky=function(e,t){return(t=t||{}).raw=!0,xy(e,t)},Ey={Inflate:_y,inflate:xy,inflateRaw:ky,ungzip:xy,constants:IB},{Inflate:Iy,inflate:Uy,inflateRaw:Qy,ungzip:Sy}=Ey,Hy=Uy,Ny=Sy;var My=new Map([[1,function(e,t){let i=new Uint8Array(e);return Hy(i).buffer}],[2,function(e,t){let i=e.byteLength,n=new Uint8Array(i),r=Math.floor(i/t),s=new DataView(e);for(var o=0;oHH",e,i);if(A%=65535,r!=(a%=65535)||s!=A)throw'ValueError("fletcher32 checksum invalid")'}(e),e.slice(0,-4)}]]),Ly=class{constructor(e,t){this.fh=e,this.offset=t,this.depth=null}async init(){this.all_nodes=new Map,await this._read_root_node(),await this._read_children()}async _read_children(){let e=this.depth;for(;e>0;){for(var t of this.all_nodes.get(e))for(var i of t.get("addresses"))this._add_node(await this._read_node(i,e-1));e--}}async _read_root_node(){let e=await this._read_node(this.offset,null);this._add_node(e),this.depth=e.get("node_level")}_add_node(e){let t=e.get("node_level");this.all_nodes.has(t)?this.all_nodes.get(t).push(e):this.all_nodes.set(t,[e])}async _read_node(e,t){let i=await this._read_node_header(e,t);return i.set("keys",[]),i.set("addresses",[]),i}async _read_node_header(e){throw"NotImplementedError: must define _read_node_header in implementation class"}},Dy=class extends Ly{B_LINK_NODE=new Map([["signature","4s"],["node_type","B"],["node_level","B"],["entries_used","H"],["left_sibling","Q"],["right_sibling","Q"]]);async _read_node_header(e,t){let i=await Yv(this.B_LINK_NODE,this.fh,e);if(null!=t&&i.get("node_level")!=t)throw"node level does not match";return i}},Ty=class extends Dy{NODE_TYPE=0;constructor(e,t){super(e,t),this.ready=this.init()}async _read_node(e,t){let i=await this._read_node_header(e,t);e+=iB(this.B_LINK_NODE);let n=[],r=[],s=i.get("entries_used");for(var o=0;o=0&&F[B]>=e[B];B--)F[B]=0,m[B]=w[B],B>0&&(F[B-1]+=1,m[B-1]+=1);if(m.slice(0,-1).every((function(e,i){return e=0;o--){if(t&1<0?r*=n:r=n}}return s}_nrecords_max(e,t,i){return Math.floor((e-10-i)/(t+i))}_required_bytes(e){return Math.ceil(AB(e)/8)}_int_format(e){return["0&&(l=(await oB.unpack_from_async(a,this.fh,i))[0],i+=r),A.push([n,c,l])}}return s.set("keys",a),s.set("addresses",A),s}async _read_node_header(e,t){let i=await Yv(this.B_LINK_NODE,this.fh,e);return i.set("node_level",t),i}*iter_records(){for(let e of this.all_nodes.values())for(let t of e)for(let e of t.get("keys"))yield e}_parse_record(e){throw"NotImplementedError"}},Oy=class extends zy{NODE_TYPE=5;async _parse_record(e,t,i){let n=(await oB.unpack_from_async("this._chunks))}get shape(){let e=this.find_msg_type(HC)[0].get("offset_to_message");return async function(e,t){let i=(await oB.unpack_from_async("255&&(s=(await oB.unpack_from_async("0;e.set("optional",a);let A,c=(await oB.unpack_from_async("0&&(A=(await oB.unpack_from_async(`${s}s`,i,t))[0],t+=s),e.set("name",A);let l=await oB.unpack_from_async(`<${c}i`,i,t);t+=4*c,e.set("client_data_values",l),r.push(e)}}return this._filter_pipeline=r,this._filter_pipeline}find_msg_type(e){return this.msgs.filter((function(t){return t.get("type")==e}))}async get_attributes(){let e={},t=this.find_msg_type(zC);for(let i of t){let t=i.get("offset_to_message"),[n,r]=await this.unpack_attribute(t);e[n]=r}return e}async get_fillvalue(){var e,t=this.find_msg_type(LC)[0].get("offset_to_message");let i=(await oB.unpack_from_async("=r&&([s,r]=a[++A],c=0);let t=await Yv(bC,e,s+c),i=s+c+vC;if(t.set("offset_to_message",i),t.get("type")==OC){var[d,u]=await oB.unpack_from_async("=o-yC){let e=A[++c];if(null==e)break;[r,o]=e,l=0}let t=await Yv(BC,e,r+l),i=r+l+yC+n;if(t.set("offset_to_message",i),t.get("type")==OC){var[h,d]=await oB.unpack_from_async("0,A=(4&n)>0;(8&n)>0?(r=(await oB.unpack_from_async("0)throw"Filter info size not supported on FractalHeap";if(t.get("btree_address_huge_objects")!=qy)throw"Huge objects not implemented in FractalHeap";t.set("btree_address_huge_objects",null),t.get("root_block_address")==qy&&t.set("root_block_address",null);let i=t.get("log2_maximum_heap_size"),n=this._min_size_nbits(i),r=new Map([["signature","4s"],["version","B"],["heap_header_adddress","Q"],["block_offset",`${n}B`]]);this.indirect_block_header=new Map(r),this.indirect_block_header_size=iB(r),2==(2&t.get("flags"))&&r.set("checksum","I"),this.direct_block_header=r,this.direct_block_header_size=iB(r);let s=t.get("maximum_direct_block_size");this._managed_object_offset_size=this._min_size_nbits(i);let o=Math.min(s,t.get("max_managed_object_size"));this._managed_object_length_size=this._min_size_integer(o);let a=t.get("starting_block_size"),A=t.get("table_width");if(!(a>0))throw"Starting block size == 0 not implemented";let c=Number(Math.floor(Math.log2(s)));tB(1n<0)for await(let e of this._iter_indirect_block(this.fh,u,f))d.push(e);else{let e=await this._read_direct_block(this.fh,u,a);d.push(e)}let p=d.reduce(((e,t)=>e+t.byteLength),0),g=new Uint8Array(p),w=0;d.forEach((e=>{g.set(new Uint8Array(e),w),w+=e.byteLength})),this.managed=g.buffer}async _read_direct_block(e,t,i){let n=await e.slice(t,t+i);return tB("FHDB"==eB(this.direct_block_header,n).get("signature")),n}get_data(e){let t=oB.unpack_from(">4&3,n=1;if(0==i){tB(0==t>>6);let i=this._managed_object_offset_size,r=cB(i,e,n);n+=i,i=this._managed_object_length_size;let s=cB(i,e,n);return this.managed.slice(r,r+s)}throw 1==i?"tiny objectID not supported in FractalHeap":2==i?"huge objectID not supported in FractalHeap":"unknown objectID type in FractalHeap"}_min_size_integer(e){return this._min_size_nbits(AB(e))}_min_size_nbits(e){return Math.ceil(e/8)}async*_iter_indirect_block(e,t,i){let n=await Yv(this.indirect_block_header,e,t);t+=this.indirect_block_header_size,tB("FHIB"==n.get("signature"));let r=n.get("block_offset").reduce(((e,t,i)=>e+(t<<8*i)),0);n.set("block_offset",r);let[s,o]=this._indirect_info(i),a=[];for(let i=0;i0&&(t+=8);let r=(2&n)>0?xC:_C,s=await Yv(r,e,t),o=new Map;for(let[e,t]of s.entries())o.set(e,t==AC?null:t);return o}get is_dataset(){return this.find_msg_type(HC).length>0}async get_data(){let e=this.find_msg_type(TC)[0].get("offset_to_message");var[t,i,n,r]=await this._get_data_message_properties(e);if(0==n)throw"Compact storage of DataObject not implemented";return 1==n?this._get_contiguous_data(r):2==n?this._get_chunked_data(e):void 0}async _get_data_message_properties(e){let t,i,n,[r,s,o]=await oB.unpack_from_async("=1&&r<=4),[r,t,i,n]}async _get_contiguous_data(e){let[t]=await oB.unpack_from_async("=!@\|]?(i|u|f|S)(\d*)/.test(n)){let[e,i,s]=sB(n),a=new Array(r);const A=await this.fh.slice(t,t+s*r);let c=new aB(A);for(var o=0;o=1&&t<=3);var a="<"+(i-1).toFixed()+"I",A=await oB.unpack_from_async(a,this.fh,s);this._chunks=A,this._chunk_dims=i,this._chunk_address=o}}}};var AC=oB.unpack_from("this.get(e)))}length(){return this.keys.length}_dereference(e){if(!e)throw"cannot deference null reference";let t=this.file._get_object_by_address(e);if(null==t)throw"reference not found in file";return t}async get(e){if("number"==typeof e)return this._dereference(e);var t=qC(e);if("/"==t)return this.file;if("."==t)return this;if(/^\//.test(t))return this.file.get(t.slice(1));if(""!=function(e){let t="/",i=e.lastIndexOf(t)+1,n=e.slice(0,i),r=new RegExp("^"+t+"+$"),s=new RegExp(t+"$");n&&!r.test(n)&&(n=n.replace(s,""));return n}(t))var[i,n]=t.split(/\/(.*)/);else var i=t,n=".";if(!(i in this._links))throw i+" not found in group";var r=qC(this.name+"/"+i);let s=this._links[i];if("string"==typeof s)try{return this.get(s)}catch(e){return null}var o=new aC(this.file._fh,s);if(await o.ready,o.is_dataset){if("."!=n)throw r+" is a dataset, not a group";return new GC(r,o,this)}var a=new VC(r,this);return await a.init(o),a.get(n)}visit(e){return this.visititems(((t,i)=>e(t)))}visititems(e){var t=this.name.length;/\/$/.test(this.name)||(t+=1);for(var i=this.values.slice();i;){let n=i.shift();1==i.length&&console.log(n);let r=e(n.name.slice(t),n);if(null!=r)return r;n instanceof VC&&(i=i.concat(n.values))}return null}get attrs(){return null==this._attrs&&(this._attrs=this._dataobjects.get_attributes()),this._attrs}},KC=class extends VC{constructor(e,t,i){super("/",null),this.ready=this.init(e,t,i)}async init(e,t,i){var n=new class{constructor(e,t){this.ready=this.init(e,t)}async init(e,t){let i=await oB.unpack_from_async("{e._dataobjects.offset}))}},GC=class extends Array{constructor(e,t,i){super(),this.parent=i,this.file=i.file,this.name=e,this._dataobjects=t,this._attrs=null,this._astype=null}get value(){var e=this._dataobjects.get_data();return null==this._astype?this.getValue(e):e.astype(this._astype)}get shape(){return this._dataobjects.shape}get attrs(){return this._dataobjects.get_attributes()}get dtype(){return this._dataobjects.dtype}get fillvalue(){return this._dataobjects.get_fillvalue()}async to_array(){return function(e,t){const i=e.length,n=t.reduce(((e,t)=>e*t),1);i!==n&&console.warn(`shape product: ${n} does not match length of flattened array: ${i}`);let r=e;const s=t.slice(1).reverse();for(let e of s){const t=[],{length:i}=r;let n=0;for(;ne.substr(0,e.indexOf("\0")))):e}};function qC(e){return e.replace(/\/(\/)+/g,"/")}async function jC(e){var t;e.url&&("function"==typeof(t=e.url).slice&&"function"==typeof t.arrayBuffer)&&(e.file=e.url,e.url=void 0);const i=void 0!==e.url;let n=e.reader?e.reader:function(e){if(e.url)return new $v(e);if(e.path)return new NodeLocalFile(e);if(e.file)return new Jv(e.file);throw Error("One of 'url', 'path (node only)', or 'file (browser only)' must be specified")}(e);const r=e.fetchSize||2e3,s=e.maxSize||2e5;i&&(n=new Xv({file:n,fetchSize:r,maxSize:s}));const o=new WC(n),a=await async function(e){let t;if(e.indexReader)t=e.indexReader;else{if(e.index)return e.index;e.indexURL?t=new $v({url:e.indexURL}):e.indexPath?t=new NodeLocalFile({path:e.indexPath}):e.indexFile&&(t=new Jv({file:e.indexFile}))}if(t){const e=await t.read(),i=(new TextDecoder).decode(e);return JSON.parse(i)}return}(e),A=e.indexOffset,c=function(e){if(e.url)return $C(e.url);if(e.path)return $C(e.path);if(e.file)return e.file.name}(e),l=new KC(o,c,{index:a,indexOffset:A});return await l.ready,l}class WC{constructor(e){this.fileReader=e}async slice(e,t){return this.fileReader.read(e,t-e)}}function $C(e){const t=e.lastIndexOf("/");return t>0?e.substring(t+1):e}class XC{constructor(e,t=1e5){this.h5_file=e,this.bin_size=t,this.h5_obj=void 0}async fetch(){return this.h5_obj||(this.h5_obj=await jC({url:this.h5_file,fetchSize:1e6,maxSize:2e8})),this.h5_obj}async get_keys(){return(await this.fetch()).keys}async get_rd_signal(e=this.bin_size){let t=await this.fetch(),i=t.keys,n=new ZC(i),r=n.get_rd_bins(),s=n.get_snp_bins();this.available_bins=[...new Set(r,s)],this.available_bins.includes(e)||(e=this.available_bins.at(-1));const o=await t.get("rd_chromosomes");await o.dtype;let a=await o.value,A=await this.rd_stat(t,i,e);var c=[],l=[],h=[],d=[],u=[],f=[];for(let n of a){var p=`his_rd_p_${n}_${e}`;let r=await this.get_chr_signal(t,i,n,e,p,A);c=c.concat(r);var g=`his_rd_p_${n}_${e}_GC`;let s=await this.get_chr_signal(t,i,n,e,g,A);l=l.concat(s);let o=`his_rd_p_${n}_${e}_partition_GC_merge`,a=await this.get_chr_signal(t,i,n,e,o,A);h=h.concat(a);let w=await this.rd_call_combined(t,i,n,e,A);d=d.concat(w);let m=`snp_likelihood_${n}_${e}_mask`,F=await this.get_baf_signals(t,i,n,e,m);u=u.concat(F[0]),f=f.concat(F[1])}this.callers=[],0!=d.length&&this.callers.push("ReadDepth"),0!=d.length&&this.callers.push("2D");var w={},m={RD_Raw:c,RD_Raw_gc_coor:l,ReadDepth:h,"2D":d,BAF1:u,BAF2:f};return w[e]=m,w}decode_segments(e){let t=[],i=[];for(let n of e)4294967295==n?(t.push(i),i=[]):i.push(n);return t}async rd_call_combined(e,t,i,n,r){let s,o=[],a=`his_rd_p_${i}_${n}_partition_GC_mosaic_segments_2d`;if(t.includes(a)){const t=await e.get(a);let i=await t.value;s=this.decode_segments(i)}let A=`his_rd_p_${i}_${n}_partition_GC_mosaic_call_2d`;if(t.includes(A)){const t=await e.get(A);let a=await t.to_array();s.forEach(((e,t)=>{e.forEach(((e,s)=>{o.push({chr:i,start:e*n,end:(e+1)*n,value:a[0][t]/r[4]*2})}))}))}return o}async rd_stat(e,t,i){let n,r=`rd_stat_${i}_auto`;if(t.includes(r)){const t=await e.get(r);n=await t.value}return n}async get_chr_signal(e,t,i,n,r,s){let o=[];if(t.includes(r)){const t=await e.get(r);(await t.value).forEach(((e,t)=>{o.push({chr:i,start:t*n,end:(t+1)*n,value:e/s[4]*2})}))}return o}async get_baf_signals(e,t,i,n,r){let s=[],o=[];if(t.includes(r)){let t=await e.get(r);(await t.to_array()).forEach(((e,t)=>{let r=Math.max(...e);const a=e.indexOf(r);let A=Math.max(a/200,1-a/200);s.push({chr:i,start:t*n,end:(t+1)*n,value:-2*A}),.5!=A&&o.push({chr:i,start:t*n,end:(t+1)*n,value:-2*(1-A)})}))}return[s,o]}async get_baf_signals_v2(e,t,i,n,r){let s=[],o=[];if(t.includes(r)){let t=await e.get(r);(await t.to_array()).forEach(((e,t)=>{isNaN(e)||(s.push({chr:i,start:t*n,end:(t+1)*n,value:-2*(.5-e)}),.5!=e&&o.push({chr:i,start:t*n,end:(t+1)*n,value:-2*(.5+e)}))}))}return console.log(i,s,o),[s,o]}}class ZC{constructor(e){this.signals=e}get_rd_bins(){let e=[];this.signals.forEach((t=>{let i=t.match(/^his_rd_p_(.*)_(\d+)$/);i&&e.push({chr:i[1],bin_size:i[2]})}));return[...new Set(e.map((e=>Number(e.bin_size))))]}get_snp_bins(){let e=[];this.signals.forEach((t=>{let i=t.match(/^snp_likelihood_(.*)_(\d+)_mask$/);i&&e.push({chr:i[1],bin_size:i[2]})}));return[...new Set(e.map((e=>Number(e.bin_size))))]}}function JC(e){let t=function(e){if(e.length<4)return e;let t,i,n,r,s,o;return t=e.slice().sort(((e,t)=>e-t)),t.length/4%1==0?(i=.5*(t[t.length/4]+t[t.length/4+1]),n=.5*(t[t.length*(3/4)]+t[t.length*(3/4)+1])):(i=t[Math.floor(t.length/4+1)],n=t[Math.ceil(t.length*(3/4)+1)]),r=n-i,s=n+1.5*r,o=i-1.5*r,t.filter((e=>e>=o&&e<=s))}(e);const i=t.length,n=t.reduce(((e,t)=>e+t))/i,r=Math.sqrt(t.map((e=>Math.pow(e-n,2))).reduce(((e,t)=>e+t))/i);return[n,r]}var YC={range_function:function(e,t,i){return Array(Math.ceil((t-e)/i)).fill(e).map(((e,t)=>e+t*i))},getDistParams:JC,linspace:function(e,t,i){if(void 0===i&&(i=Math.max(Math.round(t-e)+1,1)),i<2)return 1===i?[e]:[];var n=Array(i);for(let r=--i;r>=0;r--)n[r]=(r*t+(i-r)*e)/i;return n},GetFit:class{constructor(e){this.allBins=e}getValues(){const e=Object.values(this.allBins).reduce(((e,t)=>e.concat(t.filter((e=>e.binScore>0)).map((e=>e.binScore)))),[]);return e}getMean(e){return e.reduce((function(e,t){return e+t}))/e.length}fit_data(){return JC(this.getValues())}histogram(e,t){const i=t[1]-t[0],n=[];e.forEach(((e,r)=>{t.forEach(((t,r)=>{if(n[t]||(n[t]={count:0}),t<=e&&e{r.push(e.count)})),r}}};function e_(e,t){return isNaN(e)||isNaN(t)||t<=0?NaN:0===e?.5:.5+.5*(t_(.5*t,.5,1)-t_(.5*t,.5,t/(t+e*e)))*Math.sign(e)}function t_(e,t,i){if(0==i)return 0;if(1==i)return 1;{let n=s_(e+t)-s_(e)-s_(t)+e*Math.log(i)+t*Math.log(1-i);return i<(e+1)/(e+t+2)?Math.exp(n)*i_(e,t,i)/e:1-Math.exp(n)*i_(t,e,1-i)/t}}function i_(e,t,i,n=1e3){let r=1,s=1,o=1,a=e+t,A=e+1,c=e-1,l=1-a*i/A;for(let h=0;h<=n;h++){let n=parseFloat(h+1),d=n+n,u=n*(t-n)*i/((c+d)*(e+d)),f=r+u*s,p=l+u*o;u=-(e+n)*(a+n)*i/((A+d)*(e+d));let g=p+u*l,w=r;if(s=f/g,o=p/g,r=(f+u*r)/g,l=1,Math.abs(r-w)<3e-7*Math.abs(r))return r}}function n_(e){if(0==e||1==e)return 1;return e*n_(e-1)}function r_(e){let t;var i=[75122.633153,80916.6278952,36308.2951477,8687.24529705,1168.92649479,83.8676043424,2.50662827511],n=0,r=1;if(0==e)t=1e99;else if(e%1==0)t=n_(e-1);else{for(let t=0;tt?e:t}))}function A_(e,t,i,n){return t*Math.exp(-1*(e-i)**2/(2*n**2))/Math.sqrt(2*Math.PI)/n}function c_(e,t,i,n){return Math.exp(-1*(e-i)**2/(t**2+n**2))}function l_(e,t){let i;try{i=e.reduce(((e,i,n)=>e+Math.min(i,t[n])))}catch{return console.log("Failed to find likelihood overlap: ",e,t),0}return i}function h_(e,t,i,n){return 0==t&&0==n?{nl:.5*(e+i),ne:0}:{nl:(e*n*n+i*t*t)/(t*t+n*n),ne:Math.sqrt(t*t*n*n/(t*t+n*n))}}function d_(e,t){let i=parseInt(t*(e.length-1)),n=t*(e.length-1)-i;return iMath.floor(t/2)&&(n=t-1-n);const r=(t/2-n)/(t+1),s=Math.floor((t/2+n)/2),o=t-1-s;let a=e.slice(s,o+1).reduce(((e,t)=>e+t),0)/e.reduce(((e,t)=>e+t),0);return n===Math.floor(t/2)&&(a=1),{mean:r,p:a}}var f_=class{constructor(e,t){this.wigFeatures=e,this.binSize=t}get_fit(){var e=new YC.GetFit(this.wigFeatures),[t,i]=e.fit_data();return{globalMean:t,globalStd:i}}async call_2d(e=null,t=null,i="both",n=.1,r=0,s=10,o=0){let a=this.get_fit();this.globalMean=a.globalMean,this.globalStd=a.globalStd;let A=null==e?.05*this.binSize/3e9:e,c=null==t?parseInt(this.binSize/1e4):t,l=[],h=[],d=[],u=[],f=[],p=[];for(const[e,t]of Object.entries(this.wigFeatures)){let e=[],i=[],s=[];t.forEach(((t,n)=>{t.hets_count>4&&t.dp_count>c&&(e.push([n]),i.push(t.binScore),s.push(t.likelihood_score),delete t.likelihood_score)}));let o=[];for(let e=1;eMath.sqrt(Math.sqrt(e)**2+this.globalStd**2+Math.pow(a[t]/2,2)))),g=[];for(let t=0;t0;){g=g.filter((e=>"number"==typeof e));let t=a_(g);if(isNaN(t)&&console.log("NaN value",g),te*s[o+1][t])),r=n.reduce(((e,t)=>e+t))}catch{console.log(s),console.log("max_overlap:",t,o,g.length),console.log("likelihood: ",o,s[o],s[o+1]),console.log("nlh: ",r)}if(i[o]=a.nl,p[o]=a.ne,s[o]=n.map((function(e){return e/r})),e[o].push(...e[o+1]),i.splice(o+1,1),p.splice(o+1,1),e.splice(o+1,1),s.splice(o+1,1),g.splice(o,1),o0){let e=c_(i[o-1],p[o-1],i[o],p[o])*l_(s[o-1],s[o]);g[o-1]=e}}let w=-1;for(;;){g=[];for(let t=0;te*s[r+1][t])),a=n.reduce(((e,t)=>e+t));s[r]=n.map((function(e){return e/a})),e[r].push(...e[r+1]),e[r]=e[r].sort(((e,t)=>e-t)),i.splice(o,1),p.splice(o,1),e.splice(o,1),s.splice(o,1),o>=e.length&&(r+=1,o=r+1)}else o+=1,o>=e.length&&(r+=1,o=r+1)}if(w==e.length)break;w=e.length}e.forEach(((e,n)=>{let o=u_(s[n]);e.length>1&&(e.forEach(((e,s)=>{h.push(t[e]),o.mean<=r&&l.push(t[e]),t[e].segment_score=i[n]})),d.push(i[n]),u.push(p[n]),f.push(s[n]))}))}let g=parseInt(1e3*(1-o));0==g&&(g=1);let w=YC.linspace(o,1,g),m={},F={};for(let e=10;e>-1;e--)for(let t=0;t1-t+t*e/2)),a=e/2;e>0?(n=.5-t/(t+s),r=w.map(((e,i)=>.5-(1-e+e*t)/(2-2*e+(t+s)*e)))):(n=0,r=w.map(((e,t)=>0*e)));for(let i=0;i{if(!isNaN(r[t])){let n=A_(e*this.globalMean,1,d[i],u[i])*d_(f[i],.5+r[t]);c+=n,n>l&&(l=n,h=w[t])}})),i in m?m[i].push([e,t,s,c/w.length,h]):m[i]=[e,t,s,c/w.length,h]}for(let e=0;ee[3]-t[3]));else if(m[e].sort(((e,t)=>e[3]-t[3])),"both"==i&&(F[e].sort(((e,t)=>e[3]-t[3])),F[e][0][3]>m[e][0][3])){let t=m[e].filter((t=>t[0]!=F[e][0][0]&&t[1]<=F[e][0][1]));m[e]=[F[e][0]].push(...t)}for(let e=0;e{var r={...e};1!=i&&(r.value=e[t]/i*2),n.push(r)}));return n}formatDataStructure_BAF(e,t=2){const i=[],n=[];for(const[t,r]of Object.entries(this.wigFeatures))r.forEach((t=>{var r={...t},s={...t};let o=t[e];.5!=o&&(s.value=-2*(1-o),n.push(s)),r.value=-2*o,i.push(r)}));return[i,n]}};const p_=2871e6;function g_(e){for(var t=1,i=1,n=1*e,r=1;r<50;r++)t*=r,n+=(i*=-1)*Math.pow(e,2*r+1)/(t*(2*r+1));return 2*n/Math.sqrt(3.14159265358979)}function w_(e,t,i,n,r){var s=new b_(i.slice(n,r));return 0==s.std&&(s.std=t>0?t*s.mean/e:1),v_(e,s.mean,s.std,r-n)/(r-n)}function m_(e,t,i,n,r){var s=new b_(i.slice(n,r));if(s.means&!c&A0&&(l=w_(e,t,i,n-1,r)),r-n>2)var h=w_(e,t,i,n+1,r),d=w_(e,t,i,n,r-1);if(re+t))/e.length,this.std=Math.sqrt(e.reduce(((e,t)=>(t-this.mean)**2))/e.length)}}function v_(e,t,i,n){0==i&&(i=1);var r=(e-t)/i*Math.sqrt(n);return 1-o_.TdistributionCDF(Math.abs(r),n-1)}function B_(e,t,i,n,r,s){0==t&&(t=1),0==r&&(r=1);var o=(e-n)/Math.sqrt(t**2/i+r**2/s),a=(t**2/i+r**2/s)**2*(i-1)*(s-1)/(t**4*(s-1)/i**2+r**4*(i-1)/s**2);return 1-o_.TdistributionCDF(Math.abs(o),parseInt(a+.5))}var y_=class{constructor(e,t,i){this.rd=e,this.mean=t,this.std=i,this.bin_bands=[2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128]}get_rd_signal_bandwidth(e){var t=[];return e.forEach(((e,i)=>{var n=0;n=e>this.mean/4?this.mean/(this.std**2*e):4/this.std**2,t.push(n)})),t}meanShiftCaller(e,t=3){var i={};return Object.entries(this.rd).forEach((([e,n])=>{var r=new Array(n.length).fill(!1),s=new Array(n.length);for(let e=0;e{var o=r.map(((e,t)=>!e)),a=[];Object.entries(n).forEach((([e,t])=>{a.push(t.binScore)}));var A=[0],c=0;for(let e=0;e0&&(A.push(A[A.length-1]+c-1),c=0):c+=1;A.shift();for(let i=0;i=a.length||Math.abs(t-i)>=a.length)){var d=(i-t)*Math.exp(-.5*(i-t)**2/e**2)*Math.exp(-.5*(a[t]-a[i])**2*l[t]);h[t]+=d}for(var u=new Array,f=0;f=0&&u.push(f);u.push(h.length-1),u=u.concat(A).sort(((e,t)=>e-t)),u=Array.from(new Set(u));var p=0;for(f=0;fe+t))/g.length;a.fill(w,p,u[f]+1),p=u[f]+1}}f=0;for(var m=0;f.01&&u.push(f+1)}u.unshift(0),u.push(s.length),r=new Array(this.rd.length).fill(!1);for(f=1;f1))continue;b[0]=u[f-2];var v=[u[f],u[f]];if(!(f.01/p_*bin_size*(B+y))continue;if(B_(_.mean,_.std,_.data.length,U.mean,U.std,U.data.length)>.01/p_*bin_size*(B+C))continue}if(v_(this.mean,_.mean,_.std,_.data.length)>.05)continue;let e=a.slice(F[0],F[1]);var Q=new b_(e);r.fill(!0,F[0],F[1]),s.fill(Q.mean,F[0],F[1])}})),i[e]=s})),i}call_mean_shift(e=3){for(var t=new Array(this.rd.length).fill(!1),i=new Array(this.rd.length),n=0;n{var s=t.map(((e,t)=>!e)),o=[];s.forEach(((e,t)=>{e&&o.push(this.rd[t])}));for(var a=[0],A=0,c=0;c0&&(a.push(a[a.length-1]+A-1),A=0):A+=1;a.shift();for(var l=0;l=o.length||Math.abs(c-u)>=o.length)){var f=(u-c)*Math.exp(-.5*(u-c)**2/n**2)*Math.exp(-.5*(o[c]-o[u])**2*h[c]);d[c]+=f}var p=new Array;for(c=0;c=0&&p.push(c);p.push(d.length-1),p=p.concat(a).sort(((e,t)=>e-t)),p=Array.from(new Set(p));var g=0;for(c=0;ce+t))/w.length;o.fill(m,g,p[c]+1),g=p[c]+1}}for(c=0,u=0;c.01&&p.push(c+1)}p.unshift(0),p.push(i.length),t=new Array(this.rd.length).fill(!1);for(c=1;c1){b[0]=p[c-2];var v=[p[c],p[c]];if(c3.483106931382794e-9*(B+y))continue;if(B_(_.mean,_.std,_.data.length,U.mean,U.std,U.data.length)>3.483106931382794e-9*(B+C))continue}if(!(v_(this.mean,_.mean,_.std,_.data.length)>.05)){var Q=new b_(this.rd.slice(F[0],F[1]));t.fill(!0,F[0],F[1]),i.fill(Q.mean,F[0],F[1])}}}}}})),i}cnv_calling(e=1e5){var t=.25*this.mean,i=this.mean-t,n=this.mean+t,r=2971e6,s=this.meanShiftCaller(e),o={},a=[];return Object.entries(s).forEach((([A,c])=>{for(var l=!1;!l;){l=!0;var h=new Array(1).fill(0);for(let e=0;e.01&&h.push(e+1)}h.push(c.length);for(let e=0;e0&&(u=Math.abs(c[h[e]]-c[h[e-1]])),e{g.push(t.binScore)}));for(var w,m=new Array(c.length).fill(""),F=0,b=.05*e/r;FB+1){var y=F_(this.mean,this.std,g,B,C,b);if(y){var C=y;m.fill("D",B,C)}}for(B=F;Fn;)F+=1;(C=F)>B+1&&(y=F_(this.mean,this.std,g,B,C,b))&&(C=y,m.fill("A",B,C)),F==v&&(F+=1)}for(F=0;FB+1&&(m_(this.mean,this.std,g,B,C)<1682935038707506e-26&&m.fill(["d"]*(C-B),B,C),F-=1),F+=1}(F=0)=m.length););if(F>B){var x=new b_(_.slice(B,F));_.fill(x.mean,B,F)}Fa&&(s>0&&t.push({chr:i,start:o,end:a,value:r,bin:A,count:s}),r=0,o=n.start-n.start%this.binSize,a=o+this.binSize);const c=n.calls[9].info.DP;c&&(r+=Number.parseInt(c),s++)}s>0&&t.push({chr:i,start:o,end:a,value:r,bin:A,count:s})}return t}async computeReadDepth(){const e=Object.keys(this.allVariants);var t={};for(let n of e){const e=this.allVariants[n];var i;if(0!==e.length)for(let r of e){i=Math.max(Math.floor(r.start/this.rowBinSize),0),t[n]||(t[n]=[]),t[n][i]||(t[n][i]={chr:n,start:i*this.rowBinSize,end:(i+1)*this.rowBinSize,value:0,sum_score:0,count:0});const e=r.calls[9].info.DP;e&&(t[n][i].sum_score+=Number.parseInt(e),t[n][i].count++)}}var n={};for(let i of e){n[i]||(n[i]=[]);for(let e=0;e{t.forEach(((t,i)=>{t.partition_level=parseInt(s[e][i]),t.partition_call=parseInt(o[0][e][i])}))})),[this.formatDataStructure(e,"binScore",i),this.formatDataStructure(e,"partition_level",i),this.formatDataStructure(e,"partition_call",i),o[1]]}formatDataStructure(e,t,i=1){const n=[];for(const[s,o]of Object.entries(e))for(let e of o){var r={...e};1!=i&&(r.value=e[t]/i*2),n.push(r)}return n}async computeBAF_v2(){const e=Object.keys(this.allVariants),t={},i=[],n=[];for(let o of e){const e=this.allVariants[o];if(0===e.length)continue;var r;for(let a of e){if(r=Math.max(Math.floor(a.start/this.binSize),0),t[o]||(t[o]=[]),!t[o][r]){if(r>0){let e=r-1;if(t[o][e]){const r=this.get_max_min_score(t[o][e]);if(.5!=r.value){let e=Object.assign({},r);e.value=-2*(1-r.value),n.push(e)}r.value=-2*r.value,t[o][e]=r,i.push(t[o][e])}}t[o][r]={chr:o,start:r*this.binSize,end:(r+1)*this.binSize,value:0,count:0,likelihood_score:[],min_score:0}}const e=a.calls[9];let A=e.genotype,c=e.info.AD.split(","),l=c[0],h=c[1];if(0==A[0]&&1==A[1]||1==A[0]&&0==A[1]){if(0==t[o][r].likelihood_score.length)t[o][r].likelihood_score=YC.linspace(0,1,100).map(((e,t)=>__(l,h,e)));else{var s=0;t[o][r].likelihood_score=YC.linspace(0,1,100).map(((e,i)=>{var n=t[o][r].likelihood_score[i]*__(l,h,e);return s+=n,n})),t[o][r].likelihood_score=YC.linspace(0,1,100).map(((e,i)=>t[o][r].likelihood_score[i]/s))}t[o][r].count++}}const a=this.get_max_min_score(t[o][r]);if(.5!=a.value){let e=Object.assign({},a);e.value=-2*(1-a.value),n.push(e)}a.value=-2*a.value,t[o][r]=a,i.push(t[o][r])}return[i,n]}format_BAF_likelihood(e){const t=[];for(const[n,r]of Object.entries(e))for(let e of r){var i={...e};.5!=e.value&&(i.value=1-e.value,t.push(i))}return t}get_max_min_score(e){if(e.likelihood_score.length>0){const t=Math.max(...e.likelihood_score),i=e.likelihood_score.indexOf(t);e.value=Math.max(i/100,1-i/100),e.min_score=Math.min(i/100,1-i/100)}else e.score=0;return e}async getAllbins(){const e=await this.computeDepthFeatures();return new YC.GetFit(e).fit_data(),e}async read_rd_baf(e="ReadDepth"){const t=Object.keys(this.allVariants);var i={};for(let e of t){const t=this.allVariants[e];var n;if(0!==t.length)for(let r of t){n=Math.max(Math.floor(r.start/this.rowBinSize),0),i[e]||(i[e]=[]),i[e][n]||(i[e][n]={chr:e,start:n*this.rowBinSize,end:(n+1)*this.rowBinSize,dp_sum_score:0,dp_count:0,hets_count:0,hets:[]});const t=r.calls[9],s=t.info.DP;s&&(i[e][n].dp_sum_score+=Number.parseInt(s),i[e][n].dp_count++);let o=t.info.AD.split(","),a=t.genotype;if(0==a[0]&&1==a[1]||1==a[0]&&0==a[1]){i[e][n].hets_count++;let t=parseInt(o[0]),r=parseInt(o[1]);i[e][n].hets.push({ref:t,alt:r})}}}var r,s=this.adjust_bin_size(i);if("ReadDepth"==e){r=this.readDepthMeanshift(s);var o=this.formatDataStructure_BAF(s,"max_likelihood")}else if("2D"==e){let e=new f_(s,this.binSize),t=await e.call_2d();r=[t.binScore,[],t.segment_score];o=e.formatDataStructure_BAF("max_likelihood")}return[r,o]}formatDataStructure_BAF(e,t,i=2){const n=[],r=[];for(const[i,a]of Object.entries(e))for(let e of a){var s={...e},o={...e};let i=e[t];.5!=i&&(o.value=-2*(1-i),r.push(o)),s.value=-2*i,n.push(s)}return[n,r]}adjust_bin_size(e){const t=Object.keys(this.allVariants);var i={};for(let o of t){i[o]||(i[o]=[]);for(let t=0;t__(r.ref,r.alt,e)));else{var s=0;i[o][t].likelihood_score=YC.linspace(0,1,100).map(((e,n)=>{var a=i[o][t].likelihood_score[n]*__(r.ref,r.alt,e);return s+=a,a})),i[o][t].likelihood_score=YC.linspace(0,1,100).map(((e,n)=>i[o][t].likelihood_score[n]/s))}}const A=this.get_max_min_score(i[o][t]);i[o][t].max_likelihood=A.value}}return i}}function __(e,t,i,n=!0){return Math.pow(i,e)*Math.pow(1-i,t)+Math.pow(i,t)*Math.pow(1-i,e)}class x_ extends ag{constructor(e,t){super(e,t),this.featureType="numeric",this.paintAxis=Jm,e.max||(this.defaultScale=!0,this.autoscale=!1),this.height=void 0!==e.height?e.height:250}async init(e){this.type="cnvpytor",this.graphType=e.graphType||"points",this.bin_size=e.bin_size||1e5,this.signal_name=e.signal_name||"rd_snp",this.cnv_caller=e.cnv_caller||"2D",this.colors=e.colors||["gray","black","green","blue"],super.init(e)}get supportsWholeGenome(){return!0}get_signals(){let e=[];return"rd_snp"==this.signal_name?e=["RD_Raw","RD_Raw_gc_coor",this.cnv_caller,"BAF1","BAF2"]:"rd"==this.signal_name?e=["RD_Raw","RD_Raw_gc_coor",this.cnv_caller]:"snp"==this.signal_name?e=["BAF1","BAF2"]:"cnh"==this.signal_name&&(e=[this.cnv_caller]),e}get_signal_colors(){return[{singal_name:"RD_Raw",color:this.colors[0]},{singal_name:"RD_Raw_gc_coor",color:this.colors[1]},{singal_name:"ReadDepth",color:this.colors[2]},{singal_name:"2D",color:this.colors[2]},{singal_name:"BAF1",color:this.colors[3]},{singal_name:"BAF2",color:this.colors[3]}]}async postInit(){if("vcf"==this.config.format){this.featureSource=Pw(this.config,this.browser.genome),this.header=await this.getHeader();var e=this.featureSource.reader.features.reduce((function(e,t){return e[t.chr]=e[t.chr]||[],e[t.chr].push(t),e}),Object.create(null));const t=new C_(e,this.bin_size);let i,n,r;this.wigFeatures_obj={},this.wigFeatures_obj[this.bin_size]={},"2D"==this.config.cnv_caller?(r=await t.read_rd_baf("2D"),i=r[0],n=r[1],this.wigFeatures_obj[this.bin_size]["2D"]=i[2],this.available_callers=["2D"]):(r=await t.read_rd_baf(),i=r[0],n=r[1],this.wigFeatures_obj[this.bin_size].ReadDepth=i[2],this.available_callers=["ReadDepth"]),this.wigFeatures_obj[this.bin_size].RD_Raw=i[0],this.wigFeatures_obj[this.bin_size].RD_Raw_gc_coor=i[1],this.wigFeatures_obj[this.bin_size].BAF1=n[0],this.wigFeatures_obj[this.bin_size].BAF2=n[1],this.available_bins=[this.bin_size],this.set_available_callers()}else this.cnvpytor_obj=new XC(this.config.url,this.bin_size),this.wigFeatures_obj=await this.cnvpytor_obj.get_rd_signal(this.bin_size),this.available_bins=this.cnvpytor_obj.available_bins,this.available_callers=this.cnvpytor_obj.callers,this.set_available_callers();this.tracks=[];const t=[];this.signals=this.get_signals(),this.signal_colors=this.get_signal_colors();for(let e in this.wigFeatures_obj)for(const[i,n]of Object.entries(this.wigFeatures_obj[e]))if(this.signals.includes(i)){let e={type:"wig",isMergedTrack:!0};e.features=n,e.name=i,e.color=this.signal_colors.filter((e=>e.singal_name===i)).map((e=>e.color));const r=await this.browser.createTrack(e);r?(r.autoscale=!1,this.tracks.push(r)):console.warn("Could not create track "+e),"function"==typeof r.postInit&&t.push(r.postInit())}this.flipAxis=!!this.config.flipAxis&&this.config.flipAxis,this.logScale=!!this.config.logScale&&this.config.logScale,this.autoscale=this.config.autoscale,this.autoscale||(this.dataRange={min:this.config.min||0,max:this.config.max});for(let e of this.tracks)e.autoscale=!1,e.dataRange=this.dataRange;return Promise.all(t)}set_available_callers(){this.available_callers.includes(this.cnv_caller)||(this.available_callers.length>0?this.cnv_caller=this.available_callers[0]:this.cnv_caller=null)}async getHeader(){if(!this.header){if("function"==typeof this.featureSource.getHeader){const e=await this.featureSource.getHeader();e&&(this.callSets=e.callSets||[]),this.header=e}this.sampleNames=this.callSets?this.callSets.map((e=>e.name)):[]}return this.header}get height(){return this._height}set height(e){if(this._height=e,this.tracks)for(let t of this.tracks)t.height=e,t.config.height=e}menuItemList(){let e=[];void 0!==this.flipAxis&&e.push({label:"Flip y-axis",click:()=>{this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}}),e=e.concat(Gt.numericDataMenuItems(this.trackView)),e.push("
"),e.push("Bin Sizes");for(let t of this.available_bins){const i=Kt(t,t===this.bin_size);e.push({object:ut(i),click:async()=>{this.bin_size=t,await this.recreate_tracks(t),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}})}e.push("
"),e.push("Signal Type");let t={rd_snp:"RD and BAF Likelihood",rd:"RD Signal",snp:"BAF Likelihood"};for(let i in t){const n=Kt(t[i],i===this.signal_name);e.push({object:ut(n),click:async()=>{this.signal_name=i,await this.recreate_tracks(this.bin_size),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}})}e.push("
"),e.push("CNV caller");for(let t of this.available_callers){const i=Kt(t,t===this.cnv_caller);e.push({object:ut(i),click:async()=>{this.cnv_caller=t,await this.recreate_tracks(this.bin_size),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}})}return e}async recreate_tracks(e){this.tracks=[];const t=[];e in this.wigFeatures_obj||(this.wigFeatures_obj={...this.wigFeatures_obj,...await this.cnvpytor_obj.get_rd_signal(e)}),this.signals=this.get_signals(),this.signal_colors=this.get_signal_colors();for(const[i,n]of Object.entries(this.wigFeatures_obj[e]))if(this.signals.includes(i)){let e={type:"wig",isMergedTrack:!0};e.features=n,e.name=i,e.color=this.signal_colors.filter((e=>e.singal_name===i)).map((e=>e.color));const r=await this.browser.createTrack(e);r?(r.autoscale=!1,this.tracks.push(r)):console.warn("Could not create track "+e),"function"==typeof r.postInit&&t.push(r.postInit())}this.flipAxis=!!this.config.flipAxis&&this.config.flipAxis,this.logScale=!!this.config.logScale&&this.config.logScale,this.autoscale=this.config.autoscale,this.autoscale||(this.dataRange={min:this.config.min||0,max:this.config.max});for(let e of this.tracks)e.autoscale=!1,e.dataRange=this.dataRange;return Promise.all(t)}async getFeatures(e,t,i,n){if(this.tracks){const r=this.tracks.map((r=>r.getFeatures(e,t,i,n)));return Promise.all(r)}}getScaleFactor(e,t,i,n){return n?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}computeYPixelValue(e,t){return(this.flipAxis?e-this.dataRange.min:this.dataRange.max-e)*t}computeYPixelValueInLogScale(e,t){let i=this.dataRange.max,n=this.dataRange.min;return i<=0?0:(n<=-1&&(n=0),n=n<=0?0:Math.log10(n+1),i=Math.log10(i+1),e=Math.log10(e+1),(this.flipAxis?e-n:i-e)*t)}draw(e){const t=e.features;if(!t)return;if(this.defaultScale&&("rd_snp"==this.signal_name?this.dataRange={min:this.config.min||this.dataRange.min||-2,max:this.config.max||this.dataRange.max||6}:"rd"==this.signal_name?this.dataRange={min:this.config.min||this.dataRange.min||0,max:this.config.max||this.dataRange.max||6}:"snp"==this.signal_name&&(this.dataRange={min:this.config.min||this.dataRange.min||-2,max:this.config.max||this.dataRange.max||0})),this.autoscale&&(this.dataRange=function(e,t){let i=0,n=-Number.MAX_VALUE;for(let e of t)for(let t of e)void 0===t.value||Number.isNaN(t.value)||(i=Math.min(i,t.value),n=Math.max(n,t.value));return{min:i,max:n}}(e.referenceFrame.chr,t)),this.tracks)for(let i=0,n=this.tracks.length;ithis.logScale?this.computeYPixelValueInLogScale(e,i):this.computeYPixelValue(e,i);if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=n(t.y),r={strokeStyle:t.color,strokeWidth:1};t.dotted?Eo.dashedLine(e.context,0,i,e.pixelWidth,i,5,r):Eo.strokeLine(e.context,0,i,e.pixelWidth,i,r)}}popupData(e,t){const i=t||e.viewport.cachedFeatures;if(i&&i.length===this.tracks.length){const t=[];for(let n=0;n0&&t.push("
"),t.push(`
${this.tracks[n].name}
`);const r=this.tracks[n].popupData(e,i[n]);t.push(...r)}return t}}}const k_=new Map([["ideogram",(e,t)=>new zv(e,t)],["sequence",(e,t)=>new jf(e,t)],["feature",(e,t)=>new PF(e,t)],["seg",(e,t)=>new uv(e,t)],["mut",(e,t)=>new uv(e,t)],["maf",(e,t)=>new uv(e,t)],["shoebox",(e,t)=>new uv(e,t)],["wig",(e,t)=>new zb(e,t)],["merged",(e,t)=>new mv(e,t)],["alignment",(e,t)=>new sb(e,t)],["interaction",(e,t)=>new bv(e,t)],["interact",(e,t)=>new bv(e,t)],["variant",(e,t)=>new Iv(e,t)],["eqtl",(e,t)=>new Qv(e,t)],["gwas",(e,t)=>new Nv(e,t)],["arc",(e,t)=>new Dv(e,t)],["gcnv",(e,t)=>new Mv(e,t)],["junction",(e,t)=>new Kv(e,t)],["spliceprediction",(e,t)=>new Wv(e,t)],["blat",(e,t)=>new WF(e,t)],["cnvpytor",(e,t)=>new x_(e,t)]]);class E_{constructor(e,t){const i=(new DOMParser).parseFromString(e,"text/xml");this.processRootNode(i,t);const n=i.getElementsByTagName("Resource"),r=i.getElementsByTagName("Track"),s=r&&r.length>0,o=[];this.tracks=o;const a=new Map;Array.from(n).forEach((function(e,t){var i={url:e.getAttribute("path"),indexURL:e.getAttribute("index"),order:t};a.set(i.url,i),s||o.push(i)})),s&&Array.from(r).forEach((function(e){const t=e.getElementsByTagName("Track");if(t&&t.length>0){const i={type:"merged",tracks:[]};I_(e,i),o.push(i),Array.from(t).forEach((function(e){e.processed=!0;const t=e.getAttribute("id"),n=a.get(t);n&&(i.tracks.push(n),I_(e,n),n.autoscale=!1,i.height=n.height)}))}else if(!e.processed){const t=e.getAttribute("id"),i=a.get(t);i&&(o.push(i),I_(e,i))}}))}processRootNode(e,t){const i=e.getElementsByTagName("Session");!i||i.length;const n=i.item(0),r=n.getAttribute("genome"),s=n.getAttribute("locus"),o=n.getAttribute("ucscID");t&&t.hasOwnProperty(r)?this.genome=r:(this.reference={fastaURL:r},o&&(this.reference.id=o)),s&&(this.locus=s)}}function I_(e,t){t.name=e.getAttribute("name");const i=e.getAttribute("color");i&&(t.color="rgb("+i+")");const n=e.getAttribute("altColor");i&&(t.altColor="rgb("+n+")");const r=e.getAttribute("height");r&&(t.height=parseInt(r));const s=e.getAttribute("autoScale");s&&(t.autoscale="true"===s);const o=e.getAttribute("autoscaleGroup");o&&(t.autoscaleGroup=o);const a=e.getAttribute("windowFunction");a&&(t.windowFunction=a);const A=e.getAttribute("visibilityWindow")||e.getAttribute("featureVisibilityWindow");A&&(t.visibilityWindow=A);const c=e.getAttribute("indexed");c&&(t.indexed="true"===c);const l=e.getAttribute("normalize");l&&(t.normalize="true"===l);const h=e.getElementsByTagName("DataRange");if(h.length>0){const e=h.item(0);t.min=Number(e.getAttribute("minimum")),t.max=Number(e.getAttribute("maximum")),t.logScale="LOG"===e.getAttribute("type")}}const U_=Zt;class Q_{constructor(){this.attributes={},this.plinkLoaded=!1}async loadPlinkFile(e,t){t||(t={});var i=tf(t);const n=await io.loadString(e,i);var r=U_(n);for(let e of r){var s=e.split(" ");this.attributes[s[1]]={familyId:s[0],fatherId:s[2],motherId:s[3],sex:s[4],phenotype:s[5]}}return this.plinkLoaded=!0,this}getAttributes(e){return this.attributes[e]}getAttributeNames(){return this.hasAttributes()?Object.keys(this.attributes[Object.keys(this.attributes)[0]]):[]}hasAttributes(){return Object.keys(this.attributes).length>0}}class S_{constructor(e,t){this.geneColors={},this.gene=null,this.snp=null,this.genesCount=0,e&&(this.gene=e.toUpperCase(),this.geneColors[this.gene]=H_[this.genesCount++]),t&&(this.snp=t.toUpperCase())}addGene(e){this.geneColors[e.toUpperCase()]||(this.geneColors[e.toUpperCase()]=H_[this.genesCount++])}colorForGene(e){return this.geneColors[e.toUpperCase()]}}var H_=[];H_.push("rgb(228,26,28)"),H_.push("rgb(55,126,184)"),H_.push("rgb(77,175,74)"),H_.push("rgb(166,86,40)"),H_.push("rgb(152,78,163)"),H_.push("rgb(255,127,0)"),H_.push("rgb(247,129,191)"),H_.push("rgb(153,153,153)"),H_.push("rgb(255,255,51)"),H_.push("rgb(102, 194, 165"),H_.push("rgb(252, 141, 98"),H_.push("rgb(141, 160, 203"),H_.push("rgb(231, 138, 195"),H_.push("rgb(166, 216, 84"),H_.push("rgb(255, 217, 47"),H_.push("rgb(229, 196, 148"),H_.push("rgb(179, 179, 179"),H_.push("rgb( 141, 211, 199"),H_.push("rgb(255, 255, 179"),H_.push("rgb(190, 186, 218"),H_.push("rgb(251, 128, 114"),H_.push("rgb(128, 177, 211"),H_.push("rgb(253, 180, 98"),H_.push("rgb(179, 222, 105"),H_.push("rgb(252, 205, 229"),H_.push("rgb(217, 217, 217"),H_.push("rgb(188, 128, 189"),H_.push("rgb(204, 235, 197"),H_.push("rgb(255, 237, 111");class N_{constructor(e,t,i,n,r){this.genome=e,this.chr=t,this.start=i,this.end=n,this.bpPerPixel=r,this.id=vt.guid()}extend(e){const t=Math.min(e.start,this.start),i=Math.max(e.end,this.end),n=(i-t)/(this.end-this.start);this.start=t,this.end=i,this.bpPerPixel*=n}calculateEnd(e){return this.start+this.bpPerPixel*e}calculateBPP(e,t){return(e-this.start)/t}set(e){this.chr=e.chr,this.start=e.start,this.bpPerPixel=e.bpPerPixel}toPixels(e){return e/this.bpPerPixel}toBP(e){return this.bpPerPixel*e}shiftPixels(e,t,i){const n=this.start,r=e*this.bpPerPixel;return this.start+=r,i&&this.clampStart(t),this.end=this.start+t*this.bpPerPixel,n!==this.start}clampStart(e){const t=this.genome.getChromosome(this.chr).bpStart||0;if(this.start=Math.max(t,this.start),e){const{bpLength:t}=this.genome.getChromosome(this.chr),i=t-e*this.bpPerPixel;this.start>i&&(this.start=i)}}async zoomWithScaleFactor(e,t,i,n){const r=void 0===n?this.start+this.toBP(i/2):n,{start:s,bpPerPixel:o}=this.start,{bpLength:a}=this.getChromosome(),A=t<1?e.minimumBases()/i:a/i;this.bpPerPixel=t<1?Math.max(this.bpPerPixel*t,A):Math.min(this.bpPerPixel*t,A);const c=this.bpPerPixel*i;this.start=r-.5*c,this.clampStart(i),this.end=this.start+c;(s!==this.start||o!==this.bpPerPixel)&&await e.updateViews(!0)}getChromosome(){return this.genome.getChromosome(this.chr)}getMultiLocusLabelBPLengthOnly(e){const t=" ",i=Math.floor(this.start)+1,n=Math.round(this.start+this.bpPerPixel*e);return`${t}${this.chr}${t}${of(n-i)}${t}`}getMultiLocusLabelLocusOnly(e){const t=" ",{chr:i,start:n,end:r}=this.getPresentationLocusComponents(e);return`${t}${i}:${n}-${r}${t}`}getMultiLocusLabel(e){const t=" ",{chr:i,start:n,end:r}=this.getPresentationLocusComponents(e),s=Math.floor(this.start)+1;return`${t}${i}:${n}-${r}${t}${t}(${of(Math.round(this.start+this.bpPerPixel*e)-s)})${t}`}getPresentationLocusComponents(e){if("all"===this.chr)return{chr:this.chr};{const t=Xt(Math.floor(this.start)+1),i=Xt(Math.round(this.start+this.bpPerPixel*e));return{chr:this.chr,start:t,end:i}}}getLocusString(){if("all"===this.chr)return"all";{const e=Xt(Math.floor(this.start)+1),t=Xt(Math.round(this.end));return`${this.chr}:${e}-${t}`}}description(e){console.log(` ${e||""} referenceFrame - ${this.chr} bpp ${this.bpPerPixel.toFixed(3)} start ${Xt(Math.round(this.start))} end ${Xt(Math.round(this.end))} `)}}const M_={timeout:5e3,type:"plain",url:"https://igv.org/genomes/locus.php?genome=$GENOME$&name=$FEATURE$",coords:0,chromosomeField:"chromosome",startField:"start",endField:"end",geneField:"gene",snpField:"snp"};async function L_(e,t){if(void 0===t||""===t.trim())return;(t&&"all"===t.trim().toLowerCase()||"*"===t)&&(t="all");const i=t.split(" ");let n=e.searchConfig||M_,r=[];const s=async i=>{let r=function(e,t){const i=t.split("\t");if(i.length>=3)try{const t=e.genome.getChromosomeName(i[0]),n=parseInt(i[1].replace(/,/g,""),10)-1,r=parseInt(i[2].replace(/,/g,""),10);if(!isNaN(n)&&!isNaN(r))return{chr:t,start:n,end:r}}catch(e){}const n=t.split(":"),r=n[0];if("all"===r&&e.genome.getChromosome(r))return{chr:r,start:0,end:e.genome.getChromosome(r).bpLength};if(void 0===e.genome.getChromosome(r))return;{const t={chr:e.genome.getChromosomeName(r),start:0,end:e.genome.getChromosome(r).bpLength};if(n.length>1){let i,r=n[1].split("-");if(r.length>2){if(!n[1].startsWith("-"))return;{const e=n[1].indexOf("-",1);if(e>0){r=[n[1].substring(0,e),n[1].substring(e+1)]}}}if(i=r[0].replace(/,/g,""),isNaN(i))return;if(t.start=parseInt(i,10)-1,t.end=t.start+1,1===r.length&&(t.start-=20,t.end+=20),2===r.length){if(i=r[1].replace(/,/g,""),isNaN(i))return;if(t.end=parseInt(i,10),t.start<0&&!e.isSoftclipped()){const e=-t.start;t.start+=e,t.end+=e}}}return t}}(e,i);if(!r){const n=e.genome.featureDB.get(i.toUpperCase());n&&(r={chr:n.chr,start:n.start,end:n.end,gene:n.name,locusSearchString:t})}if(!r&&e.config&&!1!==e.config.search)try{r=await async function(e,t,i){let n=i.url.replace("$FEATURE$",t.toUpperCase());n.indexOf("$GENOME$")>-1&&(n=n.replace("$GENOME$",e.genome.id?e.genome.id:"hg19"));const r=i.timeout?{timeout:i.timeout}:void 0,s=await io.loadString(n,r),o=function(e,t,i){let n;n="plain"===i.type?function(e,t){const i=[],n=[];return Zt(t).forEach((function(e){""===e||i.push(e)})),i.forEach((function(t){var i,r,s,o,a=t.split("\t");a.length>=3&&(s=(r=a[1].split(":"))[1].split("-"),i=a[2].trim(),o={gene:a[0],chromosome:e.genome.getChromosomeName(r[0].trim()),start:parseInt(s[0].replace(/,/g,"")),end:parseInt(s[1].replace(/,/g,"")),type:"gtex"===i?"snp":"gene"},n.push(o))})),n}(e,t):JSON.parse(t);i.resultsField&&(n=n[i.resultsField]);if(n&&0!==n.length){const t=i.chromosomeField||"chromosome",r=i.startField||"start",s=i.endField||"end",o=i.coords||1;let a;a=Array.isArray(n)?n[0]:n,a.hasOwnProperty(t)&&a.hasOwnProperty(r)||console.error("Search service results must include chromosome and start fields: "+a);const A=a[t],c=e.genome.getChromosome(A);if(!c)return;const l=c.name;let h=a[r]-o,d=a[s];void 0===d&&(d=h+1);const u={chr:l,start:h,end:d},f=a.type?a.type:"gene";return i.geneField&&"gene"===f&&(u.gene=a[i.geneField]),i.snpField&&"snp"===f&&(u.snp=a[i.snpField]),u}return}(e,s,i);o&&(o.locusSearchString=t);return o}(e,i,n)}catch(e){throw console.error(e),Error("Search service currently unavailable.")}return r};for(let e of i){const t=await s(e);t&&(t.locusSearchString=e,r.push(t))}if(0===r.length){const e=await s(t);e&&(e.locusSearchString=t,r.push(e))}return 0===r.length?void 0:r}class D_{constructor(e){this.browser=e}navbarDidResize(e){this.updateNavbar(this.createResponsiveClassSchedule(e))}updateNavbar(e){this.browser.$toggle_button_container.removeClass(),this.browser.$toggle_button_container.addClass(e.$toggle_button_container),ut(this.browser.zoomWidget.zoomContainer).removeClass(),ut(this.browser.zoomWidget.zoomContainer).addClass(e.zoomContainer)}createResponsiveClassSchedule(e){let t={};const i=this.browser.isMultiLocusWholeGenomeView()||this.browser.referenceFrameList&&Ap.isWholeGenomeView(this.browser.referenceFrameList[0].chr);return i?this.browser.windowSizePanel.hide():this.browser.windowSizePanel.show(),e>990?(t.$toggle_button_container="igv-navbar-toggle-button-container",t.zoomContainer="igv-zoom-widget"):e>860?(t.$toggle_button_container="igv-navbar-toggle-button-container",t.zoomContainer="igv-zoom-widget-900"):e>540?(t.$toggle_button_container="igv-navbar-toggle-button-container-750",t.zoomContainer="igv-zoom-widget-900"):(t.$toggle_button_container="igv-navbar-toggle-button-container-750",t.zoomContainer="igv-zoom-widget-900",this.browser.windowSizePanel.hide()),i&&(t.zoomContainer="igv-zoom-widget-hidden"),t}}const T_=function(e,t){this.container=vt.div({class:"igv-chromosome-select-widget-container"}),t.appendChild(this.container),this.select=document.createElement("select"),this.select.setAttribute("name","chromosome-select-widget"),this.container.appendChild(this.select),this.select.addEventListener("change",(()=>{this.select.blur(),""!==this.select.value&&e.search(this.select.value)})),this.showAllChromosomes=!1!==e.config.showAllChromosomes};T_.prototype.show=function(){this.container.style.display="flex"},T_.prototype.hide=function(){this.container.style.display="none"},T_.prototype.update=function(e){const t=this.showAllChromosomes?e.chromosomeNames.slice():e.wgChromosomeNames.slice();e.showWholeGenomeView()&&(t.unshift("all"),t.unshift("")),this.select.innerHTML="";for(let e of t){const t=document.createElement("option");t.setAttribute("value",e),t.innerText=e,this.select.appendChild(t)}};class R_{constructor(e,t){this.container=vt.div({class:"igv-windowsize-panel-container"}),e.appendChild(this.container),t.on("locuschange",(e=>{this.updatePanel(e)})),this.browser=t}show(){this.container.style.display="block"}hide(){this.container.style.display="none"}updatePanel(e){const t=this.browser.calculateViewportWidth(this.browser.referenceFrameList.length);this.container.innerText=1===e.length?of(Math.round(t*e[0].bpPerPixel)):""}}class z_{constructor(e,t){this.browser=t,this.columnContainer=e,this.horizontalGuide=vt.div({class:"igv-cursor-guide-horizontal"}),e.appendChild(this.horizontalGuide),this.verticalGuide=vt.div({class:"igv-cursor-guide-vertical"}),e.appendChild(this.verticalGuide),this.addMouseHandler(t),this.setVisibility(t.config.showCursorGuide)}addMouseHandler(e){this.boundMouseMoveHandler=function(t){t.target.tagName;const{x:i,y:n}=vt.translateMouseCoordinates(t,this.columnContainer);if(this.horizontalGuide.style.top=`${n}px`,"CANVAS"===t.target.tagName){const n=function(e,t){for(;e.parentElement;){if(e.parentElement.classList.contains(t))return e.parentElement;e=e.parentElement}return}(t.target,"igv-viewport");if(n&&e.getRulerTrackView()){this.verticalGuide.style.left=`${i}px`;const r=e.root.querySelectorAll(".igv-column");let s;const o=n.parentElement;for(let e=0;e{e.cursorGuideVisible=!e.cursorGuideVisible,e.setCursorGuideVisibility(e.cursorGuideVisible),this.setButtonState(e.cursorGuideVisible)})),this.setButtonState(e.cursorGuideVisible),e.config.showCursorTrackingGuideButton?this.show():this.hide()}setButtonState(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")}show(){this.button.style.display="block",this.setButtonState(this.browser.cursorGuideVisible)}hide(){this.button.style.display="none"}}class P_{constructor(e,t){this.browser=e,this.button=vt.div({class:"igv-navbar-button"}),t.appendChild(this.button),this.button.textContent="center line",this.button.addEventListener("click",(()=>{e.isCenterLineVisible=!e.isCenterLineVisible,e.setCenterLineVisibility(e.isCenterLineVisible),this.setButtonState(e.isCenterLineVisible)})),this.setButtonState(e.isCenterLineVisible),e.config.showCenterGuideButton?this.show():this.hide()}setButtonState(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")}show(){this.isVisible=!0,this.button.style.display="block",this.setButtonState(this.browser.isCenterLineVisible)}hide(){this.isVisible=!1,this.button.style.display="none"}}class V_{constructor(e,t){this.button=vt.div({class:"igv-navbar-button"}),e.appendChild(this.button),this.button.textContent="track labels",this.button.addEventListener("click",(()=>{t.trackLabelsVisible=!t.trackLabelsVisible,this.setState(t.trackLabelsVisible),t.setTrackLabelVisibility(t.trackLabelsVisible)})),this.browser=t,this.setVisibility(t.config.showTrackLabelButton),this.setState(t.trackLabelsVisible)}setVisibility(e){!0===e?this.show():this.hide()}setState(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")}show(){this.button.style.display="block",this.setState(this.browser.trackLabelsVisible)}hide(){this.button.style.display="none"}}class K_{constructor(e,t){this.button=vt.div({class:"igv-navbar-button"}),e.appendChild(this.button),this.button.innerText="Sample Names",this.setState(t.showSampleNames),this.setVisibility(t.showSampleNameButton),this.button.addEventListener("click",(()=>{t.showSampleNames=!t.showSampleNames,this.setState(t.showSampleNames);for(let{sampleNameViewport:e}of t.trackViews)!1===t.showSampleNames?e.hide():e.show();t.layoutChange()}))}setVisibility(e){!0===e?this.show():this.hide()}setState(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")}hide(){this.button.style.display="none"}show(){this.button.style.display="block"}}class G_{constructor(e,t){this.button=vt.div({class:"igv-navbar-button"}),e.appendChild(this.button),this.button.innerText="Sample Info",this.setButtonVisibility(!1),this.button.addEventListener("click",(()=>{this.showSampleInfo=!this.showSampleInfo,this.setButtonState(this.showSampleInfo),t.layoutChange()}))}setButtonVisibility(e){this.showSampleInfo=e,this.setButtonState(e),!0===e?this.show():this.hide()}setButtonState(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")}hide(){this.button.style.display="none"}show(){this.button.style.display="block"}}let q_=23,j_=0;const W_=function(e,t){this.browser=e,this.zoomContainer=vt.div({class:"igv-zoom-widget"}),t.appendChild(this.zoomContainer),this.zoomOutButton=vt.div(),this.zoomContainer.appendChild(this.zoomOutButton),this.zoomOutButton.appendChild(xt.createIcon("minus-circle")),this.zoomOutButton.addEventListener("click",(()=>{e.zoomOut()}));const i=vt.div();this.zoomContainer.appendChild(i),this.slider=document.createElement("input"),this.slider.type="range",this.slider.min="0",this.slider.max=`${q_}`,i.appendChild(this.slider),this.slider.addEventListener("change",(t=>{t.preventDefault(),t.stopPropagation();const i=e.referenceFrameList[0],{bpLength:n}=i.genome.getChromosome(i.chr),{end:r,start:s}=i,o=r-s,a=n/Math.pow(2,t.target.valueAsNumber);e.zoomWithScaleFactor(a/o)})),this.zoomInButton=vt.div(),this.zoomContainer.appendChild(this.zoomInButton),this.zoomInButton.appendChild(xt.createIcon("plus-circle")),this.zoomInButton.addEventListener("click",(()=>{e.zoomIn()})),e.on("locuschange",(e=>{this.browser.isMultiLocusMode()?this.disable():(this.enable(),this.update(e))}))};W_.prototype.update=function(e){const t=e[0],{bpLength:i}=t.genome.getChromosome(t.chr),{start:n,end:r}=t;q_=Math.ceil(Math.log2(i/this.browser.minimumBases())),this.slider.max=`${q_}`;const s=i/(r-n);j_=Math.log2(s),this.slider.value=`${Math.round(j_)}`},W_.prototype.enable=function(){this.slider.disabled=!1},W_.prototype.disable=function(){this.slider.disabled=!0},W_.prototype.hide=function(){this.zoomContainer.style.display="none"},W_.prototype.show=function(){this.zoomContainer.style.display="block"},W_.prototype.hideSlider=function(){this.slider.style.display="none"},W_.prototype.showSlider=function(){this.slider.style.display="block"};const $_=function(e,t){const i=vt.div({class:"igv-navbar-button"});e.append(i),i.textContent="Save SVG",i.addEventListener("click",(()=>t.saveSVGtoFile({})))},X_=(e,t)=>{const i=0===e?t.nextElementSibling:t.previousElementSibling;t.remove(),i.remove()},Z_=e=>{const t=vt.div({class:"igv-column-shim"});lf(t,e);const i=vt.div({class:"igv-column"});return lf(i,t),i},J_=(e,t)=>{for(let i=0;i1&&i>0){cf(vt.div({class:"igv-column-shim"}),n)}}};class Y_{constructor(e,t,i){this.browser=e,this.referenceFrame=t,this.column=i,this.container=vt.div({class:"igv-center-line"}),i.appendChild(this.container),e.isCenterLineVisible?this.show():this.hide()}repaint(){if(this.referenceFrame){if(1/this.referenceFrame.bpPerPixel>1){const e=Math.floor(this.referenceFrame.toPixels(1));this.container.style.width=`${e}px`,this.container.classList.remove("igv-center-line-thin"),this.container.classList.add("igv-center-line-wide")}else this.container.style.width="1px",this.container.classList.remove("igv-center-line-wide"),this.container.classList.add("igv-center-line-thin")}}show(){this.isVisible=!0,this.container.style.display="block",this.repaint()}hide(){this.isVisible=!1,this.container.style.display="none"}resize(){this.repaint()}}const ex=Xt;class tx{constructor(e){this.browser=e,this.height=40,this.name="",this.id="ruler",this.disableButtons=!0,this.ignoreTrackMenu=!0,this.order=.01*Number.MIN_SAFE_INTEGER,this.removable=!1,this.type="ruler"}async getFeatures(e,t,i){return[]}computePixelHeight(e){return this.height}draw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:n,bpPerPixel:r,bpStart:s}){Ap.isWholeGenomeView(t.chr)?this.drawWholeGenome({context:e,pixelWidth:i,pixelHeight:n,bpPerPixel:r}):this.doDraw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:n,bpStart:s})}drawWholeGenome({context:e,pixelWidth:t,pixelHeight:i,bpPerPixel:n}){e.save(),Eo.fillRect(e,0,0,t,i,{fillStyle:"white"});for(let t of this.browser.genome.wgChromosomeNames){let r=this.browser.genome.getCumulativeOffset(t),s=this.browser.genome.getChromosome(t).bpLength,o=Math.round(r/n),a=Math.round(s/n);this.renderChromosomeRect(e,o,0,a,i,t)}e.restore()}doDraw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:n,bpStart:r}){e.clearRect(0,0,i,n);const s=function(e,t){if(e<10)return new ix(1,"bp",1);const i=Math.floor(Math.log10(e));let n="bp",r=1;i>9?(n="gb",r=1e9):i>6?(n="mb",r=1e6):i>3&&(n="kb",r=1e3);const s=Math.pow(10,i-1),o=e/s,a=75,A=Math.pow(10,i-1),c=Math.pow(10,i)/2,l=o0&&d+A<=h&&(Eo.fillText(e,i,n,this.height-8),h=0),c>0&&Eo.strokeLine(e,c,this.height-6,c,this.height-2),l=Math.floor((1+o)*s.majorTick);let u=c+(Math.round(t.toPixels(l-1-r+.5))-c)/2;u>0&&Eo.strokeLine(e,u,this.height-6,u,this.height-2),++o,h+=a}while(ce.measureText(o).width&&Eo.fillText(e,o,t+n/2,i+r/2,{fillStyle:Ts.greyScale(68)})}get supportsWholeGenome(){return!0}dispose(){}}class ix{constructor(e,t,i){this.majorTick=e,this.minorTick=e/10,this.majorUnit=t,this.unitMultiplier=i}description(e){console.log((e||"")+" tick "+ex(this.majorTick)+" label width "+ex(this.labelWidthBP)+" multiplier "+this.unitMultiplier)}}const nx=function(e,t){this.button=vt.div({class:"igv-navbar-button"}),e.appendChild(this.button),this.button.textContent="circular view",this.button.addEventListener("click",(()=>{t.circularViewVisible=!t.circularViewVisible})),this.browser=t,this.setVisibility(t.config.showCircularViewButton),this.setState(t.circularViewVisible)};nx.prototype.setVisibility=function(e){!0===e?this.show():this.hide()},nx.prototype.setState=function(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")},nx.prototype.show=function(){this.button.style.display="block",this.setState(this.browser.circularViewVisible)},nx.prototype.hide=function(){this.button.style.display="none"};const rx=function(e,t,i){const n=vt.div({class:"igv-navbar-button"});e.append(n),n.textContent=i.label,n.addEventListener("click",(()=>i.callback(t)))};class sx{constructor(e,t,i,n,r){this.browser=e,this.roiMenu=t,this.roiTable=i,this.top=n,this.roiSets=r||[],this.boundLocusChangeHandler=ox.bind(this),e.on("locuschange",this.boundLocusChangeHandler)}async initialize(){this.roiSets.length>0&&(this.browser.showROITableButton=!0,this.browser.roiTableControl.setVisibility(this.browser.showROITableButton));const e=this.roiSets.map((e=>this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:e})));e.length>0&&await Promise.all(e);const t=await this.getTableRecords();this.roiTable.renderTable(t)}async loadROI(e,t){const i=Array.isArray(e)?e:[e];for(let e of i)this.roiSets.push(new Gw(e,t));await this.initialize()}clearROIs(){this.roiTable.clearTable();const e=this.browser.columnContainer.querySelectorAll(".igv-roi-region");for(let t of e)t.remove();for(let e of this.roiSets)e.dispose();this.roiSets=[]}async getTableRecords(){const e=[];for(let t of this.roiSets){const i=t.isUserDefined?"":t.name||"",n=await t.getAllFeatures();for(let t of Object.keys(n))for(let r of n[t])e.push({setName:i,feature:r})}return e}presentTable(){this.roiTable.present()}async repaintTable(){const e=await this.getTableRecords();this.roiTable.renderTable(e)}dismissTable(){this.roiTable.dismiss()}async updateUserDefinedROISet(e){let t=await this.getUserDefinedROISet();void 0===t&&(t=this.initializeUserDefinedROISet()),t.addFeature(e),!1===this.browser.showROITableButton&&this.setROITableButtonVisibility(!0),await this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:t});const i=await this.getTableRecords();this.roiTable.renderTable(i)}setROITableButtonVisibility(e){this.browser.showROITableButton=e,this.browser.roiTableControl.setVisibility(this.browser.showROITableButton)}async renderAllROISets(){for(let e of this.roiSets)await this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:e})}async renderROISet({browser:e,pixelTop:t,roiSet:i}){const n=e.columnContainer.querySelectorAll(".igv-column");for(let r=0;ra)&&e.remove()}const l=await i.getFeatures(s,o,a);if(l)for(let c of l){const l=ax(s,c.start,c.end),{x:h,width:d}=qw(Math.max(o,c.start),Math.min(a,c.end),o,A),u=n[r].querySelector(Ax(l));if(u)u.style.left=`${h}px`,u.style.width=`${d}px`;else{const s=this.createRegionElement(e.columnContainer,t,h,d,i,l,c.name);n[r].appendChild(s)}}}}createRegionElement(e,t,i,n,r,s,o){const a=vt.div({class:"igv-roi-region"});a.style.top=`${t}px`,a.style.left=`${i}px`,a.style.width=`${n}px`,a.style.backgroundColor=r.color,a.dataset.region=s;const A=vt.div();return a.appendChild(A),A.style.backgroundColor=r.headerColor,!0===r.isUserDefined?A.addEventListener("click",(t=>{t.preventDefault(),t.stopPropagation();const{x:i,y:n}=vt.translateMouseCoordinates(t,e);this.roiMenu.present(i,n,this,e,a)})):o?A.addEventListener("click",(t=>{t.preventDefault(),t.stopPropagation(),this.popover&&this.popover.dispose(),this.popover=new Ot(e,r.name),this.popover.presentContentWithEvent(t,o)})):A.style.pointerEvents="none",a}renderSVGContext(e,{deltaX:t,deltaY:i}){for(const n of document.querySelectorAll(".igv-roi-region")){const{x:r,y:s,width:o,height:a}=n.getBoundingClientRect();e.fillStyle=n.style.backgroundColor,e.fillRect(r+t,s+i,o,a);const A=n.querySelector("div"),{x:c,y:l,width:h,height:d}=A.getBoundingClientRect();e.fillStyle=A.style.backgroundColor,e.fillRect(c+t,l+i,h,d)}}async getUserDefinedROISet(){return this.roiSets.find((e=>!0===e.isUserDefined))}initializeUserDefinedROISet(){const e=new Gw({isUserDefined:!0,features:[]},this.browser.genome);return this.roiSets.push(e),e}async deleteUserDefinedRegionWithKey(e,t){t.querySelectorAll(Ax(e)).forEach((e=>e.remove()));const i=await this.findUserDefinedRegionWithKey(e),n=await this.getUserDefinedROISet();n&&n.removeFeature(i);0===(await this.getTableRecords()).length&&(this.browser.roiTableControl.buttonHandler(!1),this.setROITableButtonVisibility(!1))}async findUserDefinedRegionWithKey(e){const{chr:t,start:i,end:n}=cx(e),r=await this.getUserDefinedROISet();if(r){const e=await r.getFeatures(t,i,n);for(let r of e)if(r.chr===t&&r.start>=i&&r.end<=n)return r}}toJSON(){return this.roiSets.map((e=>e.toJSON()))}dispose(){this.browser.off("locuschange",this.boundLocusChangeHandler);const e=this.browser.columnContainer.querySelectorAll(".igv-roi-region");for(let t of e)t.remove();this.roiMenu&&this.roiMenu.dispose(),this.roiTable&&this.roiTable.dispose();for(let e of this.roiSets)e.dispose();for(let e of Object.keys(this))this[e]=void 0}}function ox(){this.renderAllROISets()}function ax(e,t,i){return`${e}-${t}-${i}`}function Ax(e){return`[data-region="${e}"]`}function cx(e){let[t,i,n]=e.split("-");return i=parseInt(i),n=parseInt(n),{chr:t,start:i,end:n,locus:`${t}:${i}-${n}`,bedRecord:`${t}\t${i}\t${n}`}}class lx extends VF{constructor(e){super(Object.assign({width:"512px"},e))}tableRowDOM(e){const t=vt.div({class:"igv-roi-table-row"}),{setName:i,feature:n}=e;t.dataset.region=ax(n.chr,n.start,n.end);let r=[n.chr,Xt(n.start),Xt(n.end),n.name||"",i];4===this.columnFormat.length&&(r=r.slice(0,4));for(let e=0;ee.remove())),e.length>0){const t=e.sort(((e,t)=>e.feature.chr.localeCompare(t.feature.chr)||e.feature.start-t.feature.start||e.feature.end-t.feature.end));for(let e of t){const t=this.tableRowDOM(e);this.tableRowContainer.appendChild(t)}}}dispose(){document.removeEventListener("click",this.boundGotoButtonHandler),this.browser.roiTableControl.buttonHandler(!1),super.dispose()}static getColumnFormatConfiguration(e){return!0===e?[{label:"Chr",width:"20%"},{label:"Start",width:"15%"},{label:"End",width:"15%"},{label:"Description",width:"30%"},{label:"ROI Set",width:"20%"}]:[{label:"Chr",width:"25%"},{label:"Start",width:"20%"},{label:"End",width:"20%"},{label:"Description",width:"35%"}]}static gotoButtonHandler(e){e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected"),i=[];for(let e of t){const{locus:t}=cx(e.dataset.region);i.push(t)}for(let e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");this.setTableRowSelectionState(!1),i.length>0&&this.browser.search(i.join(" "))}}class hx{constructor(e,t){this.browser=e,this.container=vt.div({class:"igv-roi-menu-next-gen"}),t.appendChild(this.container);const i=vt.div();this.container.appendChild(i),Et.attachDialogCloseHandlerWithParent(i,(()=>this.container.style.display="none")),this.body=vt.div(),this.container.appendChild(this.body),this.container.style.display="none"}async present(e,t,i,n,r){dx(this.body);const s=await this.browser.roiManager.findUserDefinedRegionWithKey(r.dataset.region),o=vt.div();this.body.appendChild(o);const a="Description",A=s.name||a;o.innerText=A,o.setAttribute("title",A),a===A?o.classList.add("igv-roi-placeholder"):o.classList.remove("igv-roi-placeholder");const c=vt.div();this.body.appendChild(c),c.innerText="Set Description",c.addEventListener("click",(e=>{e.stopPropagation(),this.container.style.display="none";const t={label:"Description",value:s.name||"",callback:()=>{const e=this.browser.inputDialog.input.value||"";s.name=e.trim(),this.container.style.display="none",this.browser.roiManager.repaintTable()}};this.browser.inputDialog.present(t,e)}));const l=vt.div();this.body.appendChild(l),l.innerText="Delete Region",l.addEventListener("click",(e=>{e.stopPropagation(),this.container.style.display="none",this.browser.roiManager.deleteUserDefinedRegionWithKey(r.dataset.region,this.browser.columnContainer)})),this.container.style.left=`${e}px`,this.container.style.top=`${t}px`,this.container.style.display="flex"}async __present(e,t,i,n,r){dx(this.container);const s=await this.browser.roiManager.findUserDefinedRegionWithKey(r.dataset.region);let o;o=vt.div({class:"igv-roi-menu-row-edit-description"}),this.container.appendChild(o),o.addEventListener("click",(e=>{e.stopPropagation()}));const a="description-input",A=document.createElement("label");o.appendChild(A),A.setAttribute("for",a),A.innerText="Description:";const c=document.createElement("input");o.appendChild(c),c.setAttribute("type","text"),c.setAttribute("name",a),c.setAttribute("placeholder",""),c.value=s.name||"",c.addEventListener("change",(async e=>{e.stopPropagation();(await this.browser.roiManager.findUserDefinedRegionWithKey(r.dataset.region)).name=c.value,c.blur(),this.container.style.display="none",await this.browser.roiManager.repaintTable()})),o=vt.div({class:"igv-roi-menu-row"}),o.innerText="Delete region",this.container.appendChild(o),o.addEventListener("click",(e=>{e.stopPropagation(),this.container.style.display="none",this.browser.roiManager.deleteUserDefinedRegionWithKey(r.dataset.region,this.browser.columnContainer)})),this.container.style.left=`${e}px`,this.container.style.top=`${t}px`,this.container.style.display="flex",n.addEventListener("click",(e=>{e.stopPropagation(),this.container.style.display="none"}))}dispose(){this.container.innerHTML=""}}function dx(e){for(;e.firstChild;)e.removeChild(e.firstChild)}class ux{constructor(e,t){this.name=e.name,this.featureSource=e.featureSource||Pw(e,t),this.color=e.color||Vw}async getFeatures(e,t,i){return this.featureSource.getFeatures({chr:e,start:t,end:i})}draw(e){const{context:t,bpPerPixel:i,bpStart:n,pixelTop:r,pixelHeight:s,pixelWidth:o,features:a}=e;if(!a)return;const A=n+o*i+1;for(let{start:e,end:o}of a){if(oA)break;const{x:a,width:c}=qw(e,o,n,i);Eo.fillRect(t,a,r,c,s,{fillStyle:this.color})}}}class fx{constructor(e,t){this.browser=t,this.button=vt.div({class:"igv-navbar-button"}),e.appendChild(this.button),this.button.textContent="ROI Table",this.button.addEventListener("click",(()=>{this.buttonHandler(!t.roiTableVisible)})),this.browser=t,this.setVisibility(t.showROITableButton),this.setState(t.roiTableVisible)}buttonHandler(e){this.browser.roiTableVisible=e,this.setState(this.browser.roiTableVisible),this.browser.setROITableVisibility(this.browser.roiTableVisible)}setVisibility(e){!0===e?this.show():this.hide()}setState(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")}show(){this.button.style.display="block",this.setState(this.browser.roiTableVisible)}hide(){this.button.style.display="none"}}class px{constructor(e,t){this.config=e,this.guid=vt.guid(),this.namespace=".browser_"+this.guid,this.parent=t,this.root=vt.div({class:"igv-container"}),t.appendChild(this.root),this.alert=new Ju(this.root),this.columnContainer=vt.div({class:"igv-column-container"}),this.root.appendChild(this.columnContainer),this.menuPopup=new Nb(this.columnContainer),this.initialize(e),this.trackViews=[],this.constants={dragThreshold:3,scrollThreshold:5,defaultColor:"rgb(0,0,150)",doubleClickDelay:e.doubleClickDelay||500},this.eventHandlers={},this.on("trackremoved",(()=>{0===this.findTracks((e=>"function"==typeof e.getSamples)).length&&(this.sampleInfoControl.setButtonVisibility(!1),this.sampleNameViewportWidth=void 0,this.showSampleNames=!1,this.sampleNameControl.setState(this.showSampleNames),this.sampleNameControl.hide(),this.layoutChange())})),this.addMouseHandlers(),this.sampleInfo=new xb(this),this.setControls(e)}initialize(e){e.gtex&&(SF.gtexLoaded=!0),this.flanking=e.flanking,this.crossDomainProxy=e.crossDomainProxy,this.formats=e.formats,this.trackDefaults=e.trackDefaults,this.nucleotideColors=e.nucleotideColors||zf;for(let e of Object.keys(this.nucleotideColors))this.nucleotideColors[e.toLowerCase()]=this.nucleotideColors[e];this.trackLabelsVisible=e.showTrackLabels,this.roiTableVisible=e.showROITable,this.showROITableButton=e.showROITableButton,this.isCenterLineVisible=e.showCenterGuide,this.cursorGuideVisible=e.showCursorGuide,this.showSampleInfoButton=!1,this.showSampleNames=e.showSampleNames,this.showSampleNameButton=e.showSampleNameButton,this.sampleNameViewportWidth=void 0,e.sampleNameViewportWidth&&(this.sampleNameViewportWidth=e.sampleNameViewportWidth),e.search&&(this.searchConfig={type:"json",url:e.search.url,coords:void 0===e.search.coords?1:e.search.coords,chromosomeField:e.search.chromosomeField||"chromosome",startField:e.search.startField||"start",endField:e.search.endField||"end",geneField:e.search.geneField||"gene",snpField:e.search.snpField||"snp",resultsField:e.search.resultsField})}setControls(e){const t=this.createStandardControls(e);t.insertBefore(ut(this.columnContainer)),this.$navigation=t,!1===e.showControls&&t.hide()}createStandardControls(e){this.navbarManager=new D_(this);const t=ut("
",{class:"igv-navbar"});this.$navigation=t;const i=ut("
",{class:"igv-navbar-left-container"});t.append(i);const n=ut("
",{class:"igv-logo"});i.append(n);const r=ut('IGV; ');r.css("width","34px"),r.css("height","32px"),n.append(r),this.$current_genome=ut("
",{class:"igv-current-genome"}),i.append(this.$current_genome),this.$current_genome.text("");const s=ut("
",{class:"igv-navbar-genomic-location"});i.append(s),this.chromosomeSelectWidget=new T_(this,s.get(0)),void 0===e.showChromosomeWidget&&(e.showChromosomeWidget=!0),!0===e.showChromosomeWidget?this.chromosomeSelectWidget.show():this.chromosomeSelectWidget.hide();const o=ut("
",{class:"igv-locus-size-group"});s.append(o);const a=ut("
",{class:"igv-search-container"});o.append(a),this.$searchInput=ut("",{class:"igv-search-input",type:"text",placeholder:"Locus Search"}),a.append(this.$searchInput),this.$searchInput.change((()=>this.doSearch(this.$searchInput.val())));const A=vt.div({class:"igv-search-icon-container"});a.append(ut(A)),A.appendChild(xt.createIcon("search")),A.addEventListener("click",(()=>this.doSearch(this.$searchInput.val()))),this.windowSizePanel=new R_(o.get(0),this);const c=ut("
",{class:"igv-navbar-right-container"});t.append(c);const l=ut('
');if(c.append(l),this.$toggle_button_container=l,this.cursorGuide=new z_(this.columnContainer,this),this.cursorGuideButton=new O_(this,l.get(0)),this.centerLineButton=new P_(this,l.get(0)),this.setTrackLabelVisibility(e.showTrackLabels),this.trackLabelControl=new V_(l.get(0),this),this.roiTableControl=new fx(l.get(0),this),this.sampleInfoControl=new G_(l.get(0),this),this.sampleNameControl=new K_(l.get(0),this),!0===e.showSVGButton&&(this.svgSaveControl=new $_(l.get(0),this)),e.customButtons)for(let t of e.customButtons)new rx(l.get(0),this,t);return this.zoomWidget=new W_(this,c.get(0)),!1===e.showNavigation&&this.$navigation.hide(),this.inputDialog=new Mt(this.root),this.inputDialog.container.id=`igv-input-dialog-${vt.guid()}`,this.dataRangeDialog=new Wt(this,ut(this.root)),this.dataRangeDialog.$container.get(0).id=`igv-data-range-dialog-${vt.guid()}`,this.genericColorPicker=new Vt({parent:this.columnContainer,width:432}),this.genericColorPicker.container.id=`igv-track-color-picker-${vt.guid()}`,t}getSampleNameViewportWidth(){return void 0===this.sampleNameViewportWidth||!1===this.showSampleNames?0:this.sampleNameViewportWidth}getSampleInfoViewportWidth(){return Ib.getSampleInfoColumnWidth(this)}isMultiLocusMode(){return this.referenceFrameList&&this.referenceFrameList.length>1}isMultiLocusWholeGenomeView(){if(void 0===this.referenceFrameList||1===this.referenceFrameList.length)return!1;for(let e of this.referenceFrameList)if("all"===e.chr.toLowerCase())return!0;return!1}currentLoci(){const e=e=>`${e.chr}:${e.start+1}-${e.end}`;return void 0===this.referenceFrameList||0===this.referenceFrameList.length?"":1===this.referenceFrameList.length?e(this.referenceFrameList[0]):this.referenceFrameList.map((t=>e(t)))}toSVG(){const{y:e,width:t,height:i}=this.columnContainer.getBoundingClientRect(),n=new rp({width:t,height:8e3,backdropColor:"white",multiLocusGap:0,viewbox:{x:0,y:0,width:t,height:8e3}}),r={deltaX:0,deltaY:-e};for(let e of this.trackViews)e.renderSVGContext(n,r);return this.roiManager.renderSVGContext(n,r),n.setHeight(i),n.getSerializedSvg(!0)}renderSVG(e){const t=this.toSVG();return e.empty(),e.append(t),t}saveSVGtoFile(e){let t=this.toSVG();e.$container&&(e.$container.empty(),e.$container.append(t));ii(e.filename||"igvjs.svg",URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})))}savePNGtoFile(e){(function(e,t){return void 0===t&&(t={}),Xu(e,t)})(this.columnContainer,{allowTaint:!0}).then((t=>{ii(e||"igvjs.png",t.toDataURL("image/png"))}))}async loadSession(e){let t;return this.sampleInfo.initialize(),this.roiSets=[],t=e.url||e.file?await async function(e){const t=e.url||e.file;if(e.url&&(e.url.startsWith("blob:")||e.url.startsWith("data:"))){const t=px.uncompressSession(e.url);return JSON.parse(t)}{let i=e.filename;if(i||(i=e.url?await sf(e.url):e.file.name),i.endsWith(".xml")){const e=Ap.KNOWN_GENOMES,i=await io.loadString(t);return new E_(i,e)}return i.endsWith(".json")?io.loadJson(t):void 0}}(e):e,this.loadSessionObject(t)}async loadSessionObject(e){this.cleanHouseForSession(),e.browsers&&(e=await async function(e){const t=e.browsers[0],i={},n=new av({url:t.url});await n.readHeaderAndFooter(),i.sampleNameViewportWidth=20,i.genome="hg38";const r=t.state.split(","),s=n.bpResolutions[Number.parseInt(r[2])],o=Number.parseInt(r[0]),a=Math.floor(Number.parseFloat(r[3])*s),A=a+Math.floor(1700*s);return i.locus=`${n.chromosomes[o].name}:${a}-${A}`,i.tracks=(t.tracks||[]).filter((e=>!("refgene"===e.format||"cellType"===e.name))),i.tracks.push({type:"shoebox",url:t.url,name:t.name,colorScale:t.colorScale,_hicFile:n}),i}(e)),this.sampleInfoControl.setButtonVisibility(!1),this.showSampleNames=e.showSampleNames||!1,this.sampleNameControl.setState(!0===this.showSampleNames),e.sampleNameViewportWidth&&(this.sampleNameViewportWidth=e.sampleNameViewportWidth),Af(this.columnContainer,"igv-axis-column"),Af(this.columnContainer,"igv-sample-info-column"),Af(this.columnContainer,"igv-sample-name-column"),Af(this.columnContainer,"igv-scrollbar-column"),Af(this.columnContainer,"igv-track-drag-column"),Af(this.columnContainer,"igv-gear-menu-column");const t=e.reference||e.genome;if(!t)return void console.warn("No genome or reference object specified");const i=await Ap.expandReference(this.alert,t);await this.loadReference(i,e.locus),this.centerLineList=this.createCenterLineList(this.columnContainer);let n=0;if(!1!==e.showIdeogram){const e=new zv(this);e.id="ideogram";const t=new Tb(this,this.columnContainer,e),{$viewport:i}=t.viewports[0];n=function(e){e="string"==typeof e?document.querySelector(e):e;const t=window.getComputedStyle(e),i=parseFloat(t.marginTop)+parseFloat(t.marginBottom),n=e.offsetHeight;return Math.ceil(i+n)}(i.get(0)),this.trackViews.push(t)}if(!1!==e.showRuler&&this.trackViews.push(new Tb(this,this.columnContainer,new tx(this))),e.gtexSelections)for(let t of this.referenceFrameList)for(let i of Object.keys(e.gtexSelections)){const n=e.gtexSelections[i].gene,r=e.gtexSelections[i].snp;t.selection=new S_(n,r)}this.roiManager&&this.roiManager.dispose();const r=new hx(this,this.columnContainer),s={browser:this,parent:this.columnContainer,headerTitle:"Regions of Interest",dismissHandler:()=>this.roiTableControl.buttonHandler(!1),gotoButtonHandler:lx.gotoButtonHandler};if(e.roi){const t=e.roi.map((e=>new Gw(e,this.genome))),i=t.filter((({name:e})=>void 0!==e&&e.length>0));s.columnFormat=lx.getColumnFormatConfiguration(i.length>0);const o=new lx(s);this.roiManager=new sx(this,r,o,n,t)}else{s.columnFormat=lx.getColumnFormatConfiguration(!1);const e=new lx(s);this.roiManager=new sx(this,r,e,n,void 0)}await this.roiManager.initialize();const o=i.tracks||[],a=e.tracks?o.concat(e.tracks):o;0===a.filter((e=>"sequence"===e.type&&!e.url&&!e.fastaURL)).length&&a.push({type:"sequence",order:Of});let A=1;for(let e of a)void 0===e.order&&(e.order=A++);await this.loadTrackList(a);for(let e of this.trackViews.filter((e=>"ruler"===e.track.type||"ideogram"===e.track.type)))e.updateViews();this.updateUIWithReferenceFrameList()}createCenterLineList(e){const t=e.querySelectorAll(".igv-center-line");for(let e=0;ee.remove())),this.trackViews=[],this.circularView&&this.circularView.clearChords()}updateNavbarDOMWithGenome(e){let t=e.id&&e.id.length<10?e.id:"";this.$current_genome.text(t),this.$current_genome.attr("title",e.id||""),this.chromosomeSelectWidget.update(e)}async loadGenome(e){const t=await Ap.expandReference(this.alert,e);await this.loadReference(t,void 0);const i=t.tracks||[];return 0===i.filter((e=>"sequence"===e.type)).length&&i.push({type:"sequence",order:Of}),await this.loadTrackList(i),await this.updateViews(),this.genome}updateUIWithReferenceFrameList(){const e=this.referenceFrameList;this.updateLocusSearchWidget();const t=this.isMultiLocusWholeGenomeView()||Ap.isWholeGenomeView(e[0].chr);this.navbarManager.navbarDidResize(this.$navigation.width(),t),Fx(this.trackViews,this.trackLabelsVisible),this.setCenterLineAndCenterLineButtonVisibility(!Ap.isWholeGenomeView(e[0].chr))}setTrackLabelVisibility(e){Fx(this.trackViews,e)}setROITableVisibility(e){!0===e?this.roiManager.presentTable():this.roiManager.dismissTable()}setCursorGuideVisibility(e){e?this.cursorGuide.show():this.cursorGuide.hide()}setCustomCursorGuideMouseHandler(e){this.cursorGuide.customMouseHandler=e}setCenterLineVisibility(e){for(let t of this.centerLineList)!0===e?(t.show(),t.repaint()):t.hide()}setCenterLineAndCenterLineButtonVisibility(e){for(let t of this.centerLineList){e&&t.isVisible?t.show():t.container.style.display="none"}e&&this.centerLineButton.isVisible?this.centerLineButton.show():this.centerLineButton.button.style.display="none"}async loadTrackList(e){const t=[];for(let i of e)t.push(this._loadTrack(i));const i=await Promise.all(t);return this.trackViews.filter((function(e){return e.track.autoscaleGroup})).length>0&&this.updateViews(),i}async loadTrack(e){const t=this._loadTrack(e);return t&&e.autoscaleGroup&&(await t,this.updateViews()),t}async _loadTrack(e){$t(e)&&(e=JSON.parse(e));try{const t=await this.createTrack(e);if("sampleinfo"===e.type)return void this.layoutChange();if(void 0===t)return;void 0===t.order&&(t.order=this.trackViews.length);const i=new Tb(this,this.columnContainer,t);if(this.trackViews.push(i),Fx(this.trackViews,this.trackLabelsVisible),"function"==typeof t.postInit)try{i.startSpinner(),await t.postInit()}finally{i.stopSpinner()}return t.autoscaleGroup||(e.sync?await i.updateViews():i.updateViews()),"function"==typeof t.hasSamples&&t.hasSamples()&&(this.sampleInfo.isInitialized()&&this.sampleInfoControl.setButtonVisibility(!0),!1!==this.config.showSampleNameButton&&this.sampleNameControl.show()),this.reorderTracks(),this.fireEvent("trackorderchanged",[this.getTrackOrder()]),t}catch(t){const i={401:"Access unauthorized",403:"Access forbidden",404:"Not found"};console.error(t);let n=t.message||t.error||t.toString();i.hasOwnProperty(n)&&(n=i[n]),n+=": "+e.url,this.alert.present(new Error(n),void 0)}}async loadROI(e){await this.roiManager.loadROI(e,this.genome)}clearROIs(){this.roiManager.clearROIs()}async getUserDefinedROIs(){if(this.roiManager){const e=await this.roiManager.getUserDefinedROISet();if(void 0===e)return[];const t=await e.getAllFeatures(),i=[];for(let e of Object.values(t))i.push(...e);return i}return[]}getRulerTrackView(){const e=this.trackViews.filter((({track:e})=>"ruler"===e.id));return e.length>0?e[0]:void 0}async createTrack(e){let t=await async function(e){return"function"==typeof e?e():e} /*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */(e.url||e.fastaURL);if($t(t)&&(t=t.trim()),t)if(e.format)e.format=e.format.toLowerCase();else if(e.fastaURL)e.format="fasta";else{let i=e.filename;i||(i=await sf(t));const n=wf(i);"tsv"===n?e.format=await vf(e):n?e.format=n:"htsget"===e.sourceType&&await Aw.inferFormat(e)}e.type&&bf(e);let i=e.type?e.type.toLowerCase():void 0;if(!i){if(e.format){if("hic"===e.format){const t=new av(e);if(await t.readHeaderAndFooter(),!t.chromosomeIndexMap.celltype)throw Error("'.hic' files not supported");i="shoebox",e._hicFile=t}else if(i=Ff(e.format),"bedtype"===i){const t=Pw(e,this.genome);e._featureSource=t;const n=await t.trackType();i=n||"annotation"}}else i="sampleinfo";e.type=i}if("sampleinfo"!==i){if(this.trackDefaults&&i){const t=this.trackDefaults[i];if(t)for(let i in t)t.hasOwnProperty(i)&&void 0===e[i]&&(e[i]=t[i])}const t=function(e,t,i){let n;switch(e){case"annotation":case"genes":case"fusionjuncspan":case"snp":n="feature";break;case"seg":case"maf":case"mut":n="seg";break;case"junctions":case"splicejunctions":n="junction";break;default:n=e}return k_.has(n)?k_.get(n)(t,i):void 0}(i,e,this);if(void 0!==t)return e.roi&&e.roi.length>0&&(t.roiSets=e.roi.map((e=>new ux(e,this.genome)))),t;this.alert.present(new Error(`Error creating track. Could not determine track type for file: ${e.url||e}`),void 0)}else await this.sampleInfo.loadSampleInfoFile(this,e.url)}reorderTracks(){this.trackViews.sort((function(e,t){const i=e=>"ideogram"===e.track.id?1:"ruler"===e.track.id?2:3,n=i(e),r=i(t);if(n===r){return(e.track.order||0)-(t.track.order||0)}return n-r}));for(let{axis:e,viewports:t,sampleInfoViewport:i,sampleNameViewport:n,outerScroll:r,dragHandle:s,gearContainer:o}of this.trackViews){e.remove();for(let{$viewport:e}of t)e.detach();i.viewport.remove(),n.viewport.remove(),r.remove(),s.remove(),o.remove()}const e=this.columnContainer.querySelectorAll(".igv-column");for(let{axis:t,viewports:i,sampleInfoViewport:n,sampleNameViewport:r,outerScroll:s,dragHandle:o,gearContainer:a}of this.trackViews){this.columnContainer.querySelector(".igv-axis-column").appendChild(t);for(let t=0;te.track&&e.track.name)).map((e=>e.track.name))}removeTrackByName(e){const t=this.trackViews.slice();for(let i of t)e===i.track.name&&this.removeTrack(i.track)}removeTrack(e){for(let t of this.trackViews)if(e===t.track){this._removeTrack(t.track);break}}_removeTrack(e){e.disposed||(this.trackViews.splice(this.trackViews.indexOf(e.trackView),1),this.fireEvent("trackremoved",[e]),this.fireEvent("trackorderchanged",[this.getTrackOrder()]),e.trackView&&e.trackView.dispose())}removeAllTracks(){const e=this.trackViews;this.trackViews=[];for(let t of e)"ruler"!==t.track.id&&"ideogram"!==t.track.id?(this.fireEvent("trackremoved",[t.track]),t.dispose()):this.trackViews.push(t)}findTracks(e,t){let i="function"==typeof e?t=>e(t.track):i=>t===i.track[e];return this.trackViews.filter(i).map((e=>e.track))}setTrackHeight(e){this.trackHeight=e,this.trackViews.forEach((function(t){t.setTrackHeight(e)}))}async visibilityChange(){this.layoutChange()}async layoutChange(){if(this.referenceFrameList.find((e=>e.bpPerPixel<0))){const e=this.calculateViewportWidth(this.referenceFrameList.length);for(let t of this.referenceFrameList)t.bpPerPixel=(t.end-t.start)/e}if(this.referenceFrameList){const e=this.isMultiLocusWholeGenomeView()||Ap.isWholeGenomeView(this.referenceFrameList[0].chr);this.navbarManager.navbarDidResize(this.$navigation.width(),e)}gx.call(this),await this.updateViews()}async updateViews(){const e=this.trackViews;this.updateLocusSearchWidget();for(let e of this.centerLineList)e.repaint();if(this.dragObject)for(let t of e)await t.updateViews();else{const r={},s=[];for(let i of e){const e=i.track.autoscaleGroup;if(e){var t=r[e];t||(t=[],r[e]=t),t.push(i)}else s.push(i)}if(Object.entries(r).length>0){const e=Object.keys(r);for(let t of e){const e=r[t],s=[];for(let t of e)s.push(t.getInViewFeatures());const o=await Promise.all(s);var i,n=[];for(let e of o)n=n.concat(e);i=nf(n);const a=[];for(let t of e)t.track.dataRange=i,t.track.autoscale=!1,a.push(t.updateViews());await Promise.all(a)}}await Promise.all(s.map((e=>e.updateViews())))}}repaintViews(){for(let e of this.trackViews)e.repaintViews()}updateLocusSearchWidget(){if(!this.referenceFrameList)return;const e=this.referenceFrameList,t=this.calculateViewportWidth(this.referenceFrameList.length);for(let i of e)i.end=i.start+i.bpPerPixel*t;this.chromosomeSelectWidget.select.value=1===e.length?this.referenceFrameList[0].chr:"";const i=this.referenceFrameList.map((e=>e.getLocusString())).join(" ");this.$searchInput.val(i),this.fireEvent("locuschange",[this.referenceFrameList])}calculateViewportWidth(e){let{width:t}=this.columnContainer.getBoundingClientRect();return t-=50+this.getSampleInfoViewportWidth()+this.getSampleNameViewportWidth()+14+12+28,t-=5*(e-1),Math.floor(t/e)}minimumBases(){return this.config.minimumBases}zoomIn(){this.zoomWithScaleFactor(.5)}zoomOut(){this.zoomWithScaleFactor(2)}async zoomWithScaleFactor(e,t,i){if(!this.referenceFrameList)return;const n=this.calculateViewportWidth(this.referenceFrameList.length);let r=i?[i]:this.referenceFrameList;for(let i of r)i.zoomWithScaleFactor(this,e,n,t)}async addMultiLocusPanel(e,t,i,n){if(!this.referenceFrameList)return;const r=this.calculateViewportWidth(1+this.referenceFrameList.length),s=this.calculateViewportWidth(this.referenceFrameList.length)/this.calculateViewportWidth(1+this.referenceFrameList.length);for(let e of this.referenceFrameList)e.bpPerPixel*=s;const o=(i-t)/r,a=new N_(this.genome,e,t,i,o),A=n?this.referenceFrameList.indexOf(n):this.referenceFrameList.length-1,c=1+A,{$viewport:l}=this.trackViews[0].viewports[A],h=Z_(l.get(0).parentElement);if(c===this.referenceFrameList.length){this.referenceFrameList.push(a);for(let e of this.trackViews){const t=gb(e,h,a);e.viewports.push(t)}}else{this.referenceFrameList.splice(c,0,a);for(let e of this.trackViews){const t=gb(e,h,a);e.viewports.splice(c,0,t)}}this.centerLineList=this.createCenterLineList(this.columnContainer),gx.call(this),await this.updateViews(!0)}async removeMultiLocusPanel(e){const t=this.referenceFrameList.indexOf(e),{$viewport:i}=this.trackViews[0].viewports[t];X_(t,i.parent().get(0));for(let{viewports:e}of this.trackViews)e[t].dispose(),e.splice(t,1);if(this.referenceFrameList.splice(t,1),1===this.referenceFrameList.length&&this.getRulerTrackView())for(let e of this.getRulerTrackView().viewports)e.dismissLocusLabel();const n=this.calculateViewportWidth(1+this.referenceFrameList.length)/this.calculateViewportWidth(this.referenceFrameList.length);await this.rescaleForMultiLocus(n)}async gotoMultilocusPanel(e){const t=this.referenceFrameList.indexOf(e);this.columnContainer.querySelectorAll(".igv-column").forEach(((e,i)=>{i===t||e.remove()})),this.columnContainer.querySelectorAll(".igv-column-shim").forEach((e=>e.remove()));for(let e of this.trackViews){const i=e.viewports[t];e.viewports.filter(((e,i)=>i!==t)).forEach((e=>e.dispose())),e.viewports=[i]}const i=this.calculateViewportWidth(1);e.bpPerPixel=(e.end-e.start)/i,this.referenceFrameList=[e],this.trackViews.forEach((({viewports:e})=>e.forEach((e=>e.setWidth(i))))),this.centerLineList=this.createCenterLineList(this.columnContainer),this.updateUIWithReferenceFrameList(),await this.updateViews(!0)}async rescaleForMultiLocus(e){const t=this.calculateViewportWidth(this.referenceFrameList.length);for(let t of this.referenceFrameList)t.bpPerPixel*=e;for(let{viewports:e}of this.trackViews)for(let i of e)i.setWidth(t);this.centerLineList=this.createCenterLineList(this.columnContainer),this.updateUIWithReferenceFrameList(),await this.updateViews()}async goto(e,t,i){await this.search(e+":"+t+"-"+i)}async doSearch(e,t){const i=await this.search(e,t);return i||this.alert.present(new Error(`Unrecognized locus: ${e} `)),i}async search(e,t){const i=await L_(this,e);if(i&&i.length>0){this.referenceFrameList=function(e,t,i,n,r,s){return e.map((e=>{if(i&&e.gene&&(e.start=Math.max(0,e.start-i),e.end+=i),!s){const i=t.getChromosome(e.chr);rf(i.bpLength,e,n)}const o=new N_(t,e.chr,e.start,e.end,(e.end-e.start)/r);return o.locusSearchString=e.locusSearchString,(e.gene||e.snp)&&(o.selection=new S_(e.gene,e.snp)),o}))}(i,this.genome,this.flanking,this.minimumBases(),this.calculateViewportWidth(i.length),this.isSoftclipped());for(let e of this.trackViews)e.removeDOMFromColumnContainer();this.columnContainer.querySelectorAll(".igv-column-shim, .igv-column").forEach((e=>e.remove())),J_(this.columnContainer.querySelector(".igv-sample-info-column"),this.referenceFrameList.length),this.centerLineList=this.createCenterLineList(this.columnContainer);for(let e of this.trackViews)e.addDOMToColumnContainer(this,this.columnContainer,this.referenceFrameList);return this.updateUIWithReferenceFrameList(),t||await this.updateViews(),!0}return!1}async loadSampleInformation(e){var t=e;ti(e)&&(t=e.name),"fam"===t.substr(t.lastIndexOf(".")+1)&&(this.sampleInformation=await function(e,t){return(new Q_).loadPlinkFile(e,t)}(e))}on(e,t){this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(t)}un(e,t){this.off(e,t)}off(e,t){if(e)if(t){const i=this.eventHandlers[e];if(i&&0!==i.length){const n=i.indexOf(t);-1!==n&&this.eventHandlers[e].splice(n,1)}else console.warn("No handlers to remove for event: "+e)}else this.eventHandlers[e]=[];else this.eventHandlers={}}fireEvent(e,t,i){const n=this.eventHandlers[e];if(void 0===n||0===n.length)return;const r=i||window;return n.map((function(e){return e.apply(r,t)}))[0]}dispose(){this.removeMouseHandlers();for(let e of this.trackViews)e.dispose()}toJSON(){const e={version:"2.16.0"};if(void 0!==this.showSampleNames&&(e.showSampleNames=this.showSampleNames),this.sampleNameViewportWidth&&(e.sampleNameViewportWidth=this.sampleNameViewportWidth),e.reference=this.genome.toJSON(),e.reference.fastaURL instanceof File)throw new Error(`Error. Sessions cannot include local file references ${e.reference.fastaURL.name}.`);if(e.reference.indexURL instanceof File)throw new Error(`Error. Sessions cannot include local file references ${e.reference.indexURL.name}.`);const t=[],i={};let n=!1,r=this.trackViews[0];for(let{referenceFrame:e}of r.viewports){const r=e.getLocusString();if(t.push(r),e.selection){const t={gene:e.selection.gene,snp:e.selection.snp};i[r]=t,n=!0}}e.locus=1===t.length?t[0]:t,n&&(e.gtexSelections=i),e.roi=this.roiManager.toJSON();const s=[];this.sampleInfo.toJSON(s);const o=[];for(let{track:e}of this.trackViews)try{let t;t="function"==typeof e.getState?e.getState():e.config,t&&(t.browser&&delete t.browser,t.order=e.order,s.push(t))}catch(t){console.error(`Track: ${e.name}: ${t}`),o.push(`Track: ${e.name}: ${t}`)}if(o.length>0){let e=1,t="Errors encountered saving session:
";for(let i of o)t+=` (${e++}) ${i.toString()}
`;throw Error(t)}return e.tracks=s,e}compressedSession(){return function(e){const t=new Uint8Array(e.length);for(var i=0;i0?e.substring(0,t):e)+"?sessionURL=blob:"+this.compressedSession()}mouseDownOnViewport(e,t){var i;i=vt.pageCoordinates(e),this.vpMouseDown={viewport:t,lastMouseX:i.x,mouseDownX:i.x,lastMouseY:i.y,mouseDownY:i.y,referenceFrame:t.referenceFrame}}cancelTrackPan(){const e=this.dragObject;this.dragObject=void 0,this.isScrolling=!1,this.vpMouseDown=void 0,e&&e.viewport.referenceFrame.start!==e.start&&(this.updateViews(),this.fireEvent("trackdragend"))}isTrackPanning(){return this.dragObject}isSoftclipped(){return void 0!==this.trackViews.find((e=>!0===e.track.showSoftClips))}startTrackDrag(e){this.dragTrack=e}updateTrackDrag(e){if(e&&this.dragTrack){const t=this.dragTrack,i=this.trackViews.indexOf(e),n=this.trackViews.indexOf(t),r=this.trackViews;r[i]=t,r[n]=e;const s=this.trackViews[i].track.order;this.trackViews[n].track.order=s;const o=r.length;let a=s;if(i0;e--){const t=r[e].track;if(!(t.order>=a))break;t.order=Math.max(-Number.MAX_SAFE_INTEGER,a-1),a=t.order}this.reorderTracks()}}endTrackDrag(){this.dragTrack?(this.dragTrack=void 0,this.fireEvent("trackorderchanged",[this.getTrackOrder()])):this.dragTrack=void 0}addMouseHandlers(){this.addWindowResizeHandler(),this.addRootMouseUpHandler(),this.addRootMouseLeaveHandler(),this.addColumnContainerEventHandlers()}removeMouseHandlers(){this.removeWindowResizeHandler(),this.removeRootMouseUpHandler(),this.removeRootMouseLeaveHandler(),this.removeColumnContainerEventHandlers()}addWindowResizeHandler(){this.boundWindowResizeHandler=gx.bind(this),window.addEventListener("resize",this.boundWindowResizeHandler)}removeWindowResizeHandler(){window.removeEventListener("resize",this.boundWindowResizeHandler)}addRootMouseUpHandler(){this.boundRootMouseUpHandler=mx.bind(this),this.root.addEventListener("mouseup",this.boundRootMouseUpHandler)}removeRootMouseUpHandler(){this.root.removeEventListener("mouseup",this.boundRootMouseUpHandler)}addRootMouseLeaveHandler(){this.boundRootMouseLeaveHandler=mx.bind(this),this.root.addEventListener("mouseleave",this.boundRootMouseLeaveHandler)}removeRootMouseLeaveHandler(){this.root.removeEventListener("mouseleave",this.boundRootMouseLeaveHandler)}addColumnContainerEventHandlers(){this.boundColumnContainerMouseMoveHandler=wx.bind(this),this.boundColumnContainerTouchMoveHandler=wx.bind(this),this.boundColumnContainerMouseLeaveHandler=mx.bind(this),this.boundColumnContainerMouseUpHandler=mx.bind(this),this.boundColumnContainerTouchEndHandler=mx.bind(this),this.columnContainer.addEventListener("mousemove",this.boundColumnContainerMouseMoveHandler),this.columnContainer.addEventListener("touchmove",this.boundColumnContainerTouchMoveHandler),this.columnContainer.addEventListener("mouseleave",this.boundColumnContainerMouseLeaveHandler),this.columnContainer.addEventListener("mouseup",this.boundColumnContainerMouseUpHandler),this.columnContainer.addEventListener("touchend",this.boundColumnContainerTouchEndHandler)}removeColumnContainerEventHandlers(){this.columnContainer.removeEventListener("mousemove",this.boundColumnContainerMouseMoveHandler),this.columnContainer.removeEventListener("touchmove",this.boundColumnContainerTouchMoveHandler),this.columnContainer.removeEventListener("mouseleave",this.boundColumnContainerMouseLeaveHandler),this.columnContainer.removeEventListener("mouseup",this.boundColumnContainerMouseUpHandler),this.columnContainer.removeEventListener("touchend",this.boundColumnContainerTouchEndHandler)}static uncompressSession(e){let t;if(e.indexOf("/gzip;base64")>0){t=Ns(e);let i="";for(let e of t)i+=String.fromCharCode(e);return i}return function(e){e=e.replace(/\./g,"+").replace(/_/g,"/").replace(/-/g,"=");const t=atob(e),i=[];for(let e=0;e{const r=e.data,s=r.mate;function o(e){e.chr=i.genome.getChromosomeName(e.refName);let t=!1;for(let n of i.referenceFrameList){const i=Ym.fromLocusString(n.getLocusString());if(i.contains(e)){t=!0;break}if(i.overlaps(e)){n.extend(e),t=!0;break}}if(!t){const t=2e3,n=(e.start+e.end)/2;i.addMultiLocusPanel(e.chr,n-t,n+t)}}o(r),o(s)}})),this.circularViewControl=new nx(this.$toggle_button_container.get(0),this),this.circularView.setAssembly({name:this.genome.id,id:this.genome.id,chromosomes:EF(this.genome)}),this.circularViewVisible=t,this.circularView}get circularViewVisible(){return void 0!==this.circularView&&this.circularView.visible}set circularViewVisible(e){this.circularView&&(this.circularView.visible=e,this.circularViewControl.setState(e))}}async function gx(){if(!this.referenceFrameList)return;const e=this.calculateViewportWidth(this.referenceFrameList.length);for(let t of this.referenceFrameList){const i=this.referenceFrameList.indexOf(t),{chr:n,genome:r}=t,{bpLength:s}=r.getChromosome(t.chr),o=t.toBP(e);Ap.isWholeGenomeView(n)||o>s?t.bpPerPixel=s/e:t.end=t.start+t.toBP(e);for(let{viewports:t}of this.trackViews)t[i].setWidth(e)}this.updateUIWithReferenceFrameList(),await this.updateViews(!0)}function wx(e){e.preventDefault();const{x:t,y:i}=vt.pageCoordinates(e);if(this.vpMouseDown){const{viewport:e,referenceFrame:n}=this.vpMouseDown,r=Math.abs(t-this.vpMouseDown.mouseDownX)>Math.abs(i-this.vpMouseDown.mouseDownY);if(!this.dragObject&&!this.isScrolling)if(r)this.vpMouseDown.mouseDownX&&Math.abs(t-this.vpMouseDown.mouseDownX)>this.constants.dragThreshold&&(this.dragObject={viewport:e,start:n.start});else if(this.vpMouseDown.mouseDownY&&Math.abs(i-this.vpMouseDown.mouseDownY)>this.constants.scrollThreshold){this.isScrolling=!0;const t=e.$viewport.height(),i=e.trackView.maxViewportContentHeight();this.vpMouseDown.r=t/i}if(this.dragObject){const i=!this.isSoftclipped();let r=this.vpMouseDown.lastMouseX-t;n.shiftPixels(r,e.$viewport.width(),i)&&this.updateViews(),this.fireEvent("trackdrag")}if(this.isScrolling){const t=this.vpMouseDown.r*(this.vpMouseDown.lastMouseY-i);e.trackView.moveScroller(t)}this.vpMouseDown.lastMouseX=t,this.vpMouseDown.lastMouseY=i}}function mx(e){this.cancelTrackPan(),this.endTrackDrag()}function Fx(e,t){for(let{viewports:i}of e)for(let e of i)e.$trackLabel&&(0===i.indexOf(e)&&!0===t?e.$trackLabel.show():e.$trackLabel.hide())}let bx=[];const vx=io.setApiKey;!function(){var e=document.createElement("style");e.setAttribute("type","text/css"),e.innerHTML='.igv-navbar {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-between;\n align-items: center;\n box-sizing: border-box;\n width: 100%;\n color: #444;\n font-size: 12px;\n font-family: "Open Sans", sans-serif;\n font-weight: 400;\n line-height: 32px;\n padding-left: 8px;\n padding-right: 8px;\n margin-top: 2px;\n margin-bottom: 6px;\n height: 32px;\n border-style: solid;\n border-radius: 3px;\n border-width: thin;\n border-color: #bfbfbf;\n background-color: #f3f3f3;\n}\n.igv-navbar .igv-navbar-left-container {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-between;\n align-items: center;\n height: 32px;\n line-height: 32px;\n}\n.igv-navbar .igv-navbar-left-container .igv-logo {\n width: 34px;\n height: 32px;\n margin-right: 8px;\n}\n.igv-navbar .igv-navbar-left-container .igv-current-genome {\n height: 32px;\n margin-left: 4px;\n margin-right: 4px;\n user-select: none;\n line-height: 32px;\n vertical-align: middle;\n text-align: center;\n}\n.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-between;\n align-items: center;\n height: 100%;\n}\n.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-chromosome-select-widget-container {\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: space-around;\n align-items: center;\n height: 100%;\n width: 125px;\n margin-right: 4px;\n}\n.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-chromosome-select-widget-container select {\n display: block;\n cursor: pointer;\n width: 100px;\n height: 75%;\n outline: none;\n font-size: 12px;\n font-family: "Open Sans", sans-serif;\n font-weight: 400;\n}\n.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-between;\n align-items: center;\n margin-left: 8px;\n height: 22px;\n}\n.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n width: 210px;\n height: 22px;\n line-height: 22px;\n}\n.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container input.igv-search-input {\n cursor: text;\n width: 85%;\n height: 22px;\n line-height: 22px;\n font-size: 12px;\n font-family: "Open Sans", sans-serif;\n font-weight: 400;\n text-align: left;\n padding-left: 8px;\n margin-right: 8px;\n outline: none;\n border-style: solid;\n border-radius: 3px;\n border-width: thin;\n border-color: #bfbfbf;\n background-color: white;\n}\n.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container .igv-search-icon-container {\n cursor: pointer;\n height: 16px;\n width: 16px;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: center;\n align-items: center;\n}\n.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-windowsize-panel-container {\n margin-left: 4px;\n user-select: none;\n}\n.igv-navbar .igv-navbar-right-container {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-between;\n align-items: center;\n height: 32px;\n line-height: 32px;\n}\n.igv-navbar .igv-navbar-right-container .igv-navbar-toggle-button-container {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-between;\n align-items: center;\n height: 100%;\n}\n.igv-navbar .igv-navbar-right-container .igv-navbar-toggle-button-container div {\n margin-left: 0;\n margin-right: 4px;\n}\n.igv-navbar .igv-navbar-right-container .igv-navbar-toggle-button-container div:last-child {\n margin-left: 0;\n margin-right: 0;\n}\n.igv-navbar .igv-navbar-right-container .igv-navbar-toggle-button-container-750 {\n display: none;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget {\n color: #737373;\n font-size: 18px;\n height: 32px;\n line-height: 32px;\n margin-left: 8px;\n user-select: none;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-end;\n align-items: center;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget div {\n cursor: pointer;\n margin-left: unset;\n margin-right: unset;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:first-child {\n height: 24px;\n width: 24px;\n margin-left: unset;\n margin-right: 8px;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:last-child {\n height: 24px;\n width: 24px;\n margin-left: 8px;\n margin-right: unset;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:nth-child(even) {\n display: block;\n height: fit-content;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget input {\n display: block;\n width: 125px;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget svg {\n display: block;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 {\n color: #737373;\n font-size: 18px;\n height: 32px;\n line-height: 32px;\n margin-left: 8px;\n user-select: none;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-end;\n align-items: center;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div {\n cursor: pointer;\n margin-left: unset;\n margin-right: unset;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:first-child {\n height: 24px;\n width: 24px;\n margin-left: unset;\n margin-right: 8px;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:last-child {\n height: 24px;\n width: 24px;\n margin-left: 8px;\n margin-right: unset;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:nth-child(even) {\n width: 0;\n height: 0;\n display: none;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 input {\n width: 0;\n height: 0;\n display: none;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 svg {\n display: block;\n}\n.igv-navbar .igv-navbar-right-container .igv-zoom-widget-hidden {\n display: none;\n}\n\n.igv-navbar-button {\n display: block;\n box-sizing: unset;\n padding-left: 6px;\n padding-right: 6px;\n height: 18px;\n text-transform: capitalize;\n user-select: none;\n line-height: 18px;\n text-align: center;\n vertical-align: middle;\n font-family: "Open Sans", sans-serif;\n font-size: 11px;\n font-weight: 200;\n color: #737373;\n background-color: #f3f3f3;\n border-color: #737373;\n border-style: solid;\n border-width: thin;\n border-radius: 6px;\n}\n\n.igv-navbar-button-clicked {\n color: white;\n background-color: #737373;\n}\n\n.igv-navbar-button:hover {\n cursor: pointer;\n}\n\n.igv-zoom-in-notice-container {\n z-index: 1024;\n position: absolute;\n top: 8px;\n left: 50%;\n transform: translate(-50%, 0%);\n display: flex;\n flex-direction: row;\n flex-wrap: nowrap;\n justify-content: center;\n align-items: center;\n background-color: white;\n}\n.igv-zoom-in-notice-container > div {\n padding-left: 4px;\n padding-right: 4px;\n padding-top: 2px;\n padding-bottom: 2px;\n width: 100%;\n height: 100%;\n font-family: "Open Sans", sans-serif;\n font-size: 14px;\n font-weight: 400;\n color: #3f3f3f;\n}\n\n.igv-zoom-in-notice {\n position: absolute;\n top: 10px;\n left: 50%;\n}\n.igv-zoom-in-notice div {\n position: relative;\n left: -50%;\n font-family: "Open Sans", sans-serif;\n font-size: medium;\n font-weight: 400;\n color: #3f3f3f;\n background-color: rgba(255, 255, 255, 0.51);\n z-index: 64;\n}\n\n.igv-container-spinner {\n position: absolute;\n top: 90%;\n left: 50%;\n transform: translate(-50%, -50%);\n z-index: 1024;\n width: 24px;\n height: 24px;\n pointer-events: none;\n color: #737373;\n}\n\n.igv-multi-locus-close-button {\n position: absolute;\n top: 2px;\n right: 0;\n padding-left: 2px;\n padding-right: 2px;\n width: 12px;\n height: 12px;\n color: #666666;\n background-color: white;\n z-index: 1000;\n}\n.igv-multi-locus-close-button > svg {\n vertical-align: top;\n}\n\n.igv-multi-locus-close-button:hover {\n cursor: pointer;\n color: #434343;\n}\n\n.igv-multi-locus-ruler-label {\n z-index: 64;\n position: absolute;\n top: 2px;\n left: 0;\n width: 100%;\n height: 12px;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: center;\n align-items: center;\n}\n.igv-multi-locus-ruler-label > div {\n font-family: "Open Sans", sans-serif;\n font-size: 12px;\n color: rgb(16, 16, 16);\n background-color: white;\n}\n.igv-multi-locus-ruler-label > div {\n cursor: pointer;\n}\n\n.igv-multi-locus-ruler-label-square-dot {\n z-index: 64;\n position: absolute;\n left: 50%;\n top: 5%;\n transform: translate(-50%, 0%);\n background-color: white;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-multi-locus-ruler-label-square-dot > div:first-child {\n width: 14px;\n height: 14px;\n}\n.igv-multi-locus-ruler-label-square-dot > div:last-child {\n margin-left: 16px;\n font-family: "Open Sans", sans-serif;\n font-size: 14px;\n font-weight: 400;\n color: rgb(16, 16, 16);\n}\n\n.igv-ruler-sweeper {\n display: none;\n pointer-events: none;\n position: absolute;\n top: 26px;\n bottom: 0;\n left: 0;\n width: 0;\n z-index: 99999;\n background-color: rgba(68, 134, 247, 0.25);\n}\n\n.igv-ruler-tooltip {\n pointer-events: none;\n z-index: 128;\n position: absolute;\n top: 0;\n left: 0;\n width: 1px;\n height: 32px;\n background-color: transparent;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-ruler-tooltip > div {\n pointer-events: none;\n width: 128px;\n height: auto;\n padding: 1px;\n color: #373737;\n font-size: 10px;\n font-family: "Open Sans", sans-serif;\n font-weight: 400;\n background-color: white;\n border-style: solid;\n border-width: thin;\n border-color: #373737;\n}\n\n.igv-track-label {\n position: absolute;\n left: 8px;\n top: 8px;\n width: auto;\n height: auto;\n max-width: 50%;\n padding-left: 4px;\n padding-right: 4px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n font-family: "Open Sans", sans-serif;\n font-size: small;\n font-weight: 400;\n text-align: center;\n user-select: none;\n -moz-user-select: none;\n -webkit-user-select: none;\n border-color: #444;\n border-radius: 2px;\n border-style: solid;\n border-width: thin;\n background-color: white;\n z-index: 128;\n cursor: pointer;\n}\n\n.igv-track-label:hover,\n.igv-track-label:focus,\n.igv-track-label:active {\n background-color: #e8e8e8;\n}\n\n.igv-track-label-popup-shim {\n padding-left: 8px;\n padding-right: 8px;\n padding-top: 4px;\n}\n\n.igv-center-line {\n display: none;\n pointer-events: none;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 50%;\n transform: translateX(-50%);\n z-index: 8;\n user-select: none;\n -moz-user-select: none;\n -webkit-user-select: none;\n border-left-style: dashed;\n border-left-width: thin;\n border-right-style: dashed;\n border-right-width: thin;\n}\n\n.igv-center-line-wide {\n background-color: rgba(0, 0, 0, 0);\n border-left-color: rgba(127, 127, 127, 0.51);\n border-right-color: rgba(127, 127, 127, 0.51);\n}\n\n.igv-center-line-thin {\n background-color: rgba(0, 0, 0, 0);\n border-left-color: rgba(127, 127, 127, 0.51);\n border-right-color: rgba(0, 0, 0, 0);\n}\n\n.igv-cursor-guide-horizontal {\n display: none;\n pointer-events: none;\n user-select: none;\n -moz-user-select: none;\n -webkit-user-select: none;\n position: absolute;\n left: 0;\n right: 0;\n top: 50%;\n height: 1px;\n z-index: 1;\n margin-left: 50px;\n margin-right: 54px;\n border-top-style: dotted;\n border-top-width: thin;\n border-top-color: rgba(127, 127, 127, 0.76);\n}\n\n.igv-cursor-guide-vertical {\n pointer-events: none;\n user-select: none;\n -moz-user-select: none;\n -webkit-user-select: none;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 50%;\n width: 1px;\n z-index: 1;\n border-left-style: dotted;\n border-left-width: thin;\n border-left-color: rgba(127, 127, 127, 0.76);\n display: none;\n}\n\n.igv-user-feedback {\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 512px;\n height: 360px;\n z-index: 2048;\n background-color: white;\n border-color: #a2a2a2;\n border-style: solid;\n border-width: thin;\n font-family: "Open Sans", sans-serif;\n font-size: medium;\n font-weight: 400;\n color: #444;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-user-feedback div:first-child {\n position: relative;\n height: 24px;\n width: 100%;\n background-color: white;\n border-bottom-color: #a2a2a2;\n border-bottom-style: solid;\n border-bottom-width: thin;\n}\n.igv-user-feedback div:first-child div {\n position: absolute;\n top: 2px;\n width: 16px;\n height: 16px;\n background-color: transparent;\n}\n.igv-user-feedback div:first-child div:first-child {\n left: 8px;\n}\n.igv-user-feedback div:first-child div:last-child {\n cursor: pointer;\n right: 8px;\n}\n.igv-user-feedback div:last-child {\n width: 100%;\n height: calc(100% - 24px);\n border-width: 0;\n}\n.igv-user-feedback div:last-child div {\n width: auto;\n height: auto;\n margin: 8px;\n}\n\n.igv-generic-dialog-container {\n position: absolute;\n top: 0;\n left: 0;\n width: 300px;\n height: 200px;\n border-color: #7F7F7F;\n border-radius: 4px;\n border-style: solid;\n border-width: thin;\n font-family: "Open Sans", sans-serif;\n font-size: medium;\n font-weight: 400;\n z-index: 2048;\n background-color: white;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-generic-dialog-container .igv-generic-dialog-header {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-end;\n align-items: center;\n width: 100%;\n height: 24px;\n cursor: move;\n border-top-left-radius: 4px;\n border-top-right-radius: 4px;\n border-bottom-color: #7F7F7F;\n border-bottom-style: solid;\n border-bottom-width: thin;\n background-color: #eee;\n}\n.igv-generic-dialog-container .igv-generic-dialog-header div {\n margin-right: 4px;\n margin-bottom: 2px;\n height: 12px;\n width: 12px;\n color: #7F7F7F;\n}\n.igv-generic-dialog-container .igv-generic-dialog-header div:hover {\n cursor: pointer;\n color: #444;\n}\n.igv-generic-dialog-container .igv-generic-dialog-one-liner {\n color: #373737;\n width: 95%;\n height: 24px;\n line-height: 24px;\n text-align: left;\n margin-top: 8px;\n padding-left: 8px;\n overflow-wrap: break-word;\n background-color: white;\n}\n.igv-generic-dialog-container .igv-generic-dialog-label-input {\n margin-top: 8px;\n width: 95%;\n height: 24px;\n color: #373737;\n line-height: 24px;\n padding-left: 8px;\n background-color: white;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-generic-dialog-container .igv-generic-dialog-label-input div {\n width: 30%;\n height: 100%;\n font-size: 16px;\n text-align: right;\n padding-right: 8px;\n background-color: white;\n}\n.igv-generic-dialog-container .igv-generic-dialog-label-input input {\n display: block;\n height: 100%;\n width: 100%;\n padding-left: 4px;\n font-family: "Open Sans", sans-serif;\n font-weight: 400;\n color: #373737;\n text-align: left;\n outline: none;\n border-style: solid;\n border-width: thin;\n border-color: #7F7F7F;\n background-color: white;\n}\n.igv-generic-dialog-container .igv-generic-dialog-label-input input {\n width: 50%;\n font-size: 16px;\n}\n.igv-generic-dialog-container .igv-generic-dialog-input {\n margin-top: 8px;\n width: calc(100% - 16px);\n height: 24px;\n color: #373737;\n line-height: 24px;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-around;\n align-items: center;\n}\n.igv-generic-dialog-container .igv-generic-dialog-input input {\n display: block;\n height: 100%;\n width: 100%;\n padding-left: 4px;\n font-family: "Open Sans", sans-serif;\n font-weight: 400;\n color: #373737;\n text-align: left;\n outline: none;\n border-style: solid;\n border-width: thin;\n border-color: #7F7F7F;\n background-color: white;\n}\n.igv-generic-dialog-container .igv-generic-dialog-input input {\n font-size: 16px;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok-cancel {\n width: 100%;\n height: 28px;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-around;\n align-items: center;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div {\n margin-top: 32px;\n color: white;\n font-family: "Open Sans", sans-serif;\n font-size: 14px;\n font-weight: 400;\n width: 75px;\n height: 28px;\n line-height: 28px;\n text-align: center;\n border-color: transparent;\n border-style: solid;\n border-width: thin;\n border-radius: 2px;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:first-child {\n margin-left: 32px;\n margin-right: 0;\n background-color: #5ea4e0;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:last-child {\n margin-left: 0;\n margin-right: 32px;\n background-color: #c4c4c4;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:first-child:hover {\n cursor: pointer;\n background-color: #3b5c7f;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:last-child:hover {\n cursor: pointer;\n background-color: #7f7f7f;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok {\n width: 100%;\n height: 36px;\n margin-top: 32px;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-around;\n align-items: center;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok div {\n width: 98px;\n height: 36px;\n line-height: 36px;\n text-align: center;\n color: white;\n font-family: "Open Sans", sans-serif;\n font-size: medium;\n font-weight: 400;\n border-color: white;\n border-style: solid;\n border-width: thin;\n border-radius: 4px;\n background-color: #2B81AF;\n}\n.igv-generic-dialog-container .igv-generic-dialog-ok div:hover {\n cursor: pointer;\n background-color: #25597f;\n}\n\n.igv-generic-container {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 2048;\n background-color: white;\n cursor: pointer;\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-generic-container div:first-child {\n cursor: move;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-end;\n align-items: center;\n height: 24px;\n width: 100%;\n background-color: #dddddd;\n}\n.igv-generic-container div:first-child i {\n display: block;\n color: #5f5f5f;\n cursor: pointer;\n width: 14px;\n height: 14px;\n margin-right: 8px;\n margin-bottom: 4px;\n}\n\n.igv-menu-popup {\n position: absolute;\n top: 0;\n left: 0;\n width: max-content;\n z-index: 4096;\n cursor: pointer;\n font-family: "Open Sans", sans-serif;\n font-size: small;\n font-weight: 400;\n color: #4b4b4b;\n background: white;\n border-radius: 4px;\n border-color: #7F7F7F;\n border-style: solid;\n border-width: thin;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-end;\n text-align: left;\n}\n.igv-menu-popup > div:not(:first-child) {\n width: 100%;\n}\n.igv-menu-popup > div:not(:first-child) > div {\n background: white;\n}\n.igv-menu-popup > div:not(:first-child) > div.context-menu {\n padding-left: 4px;\n padding-right: 4px;\n}\n.igv-menu-popup > div:not(:first-child) > div:last-child {\n border-bottom-left-radius: 4px;\n border-bottom-right-radius: 4px;\n border-bottom-color: transparent;\n border-bottom-style: solid;\n border-bottom-width: thin;\n}\n.igv-menu-popup > div:not(:first-child) > div:hover {\n background: #efefef;\n}\n\n.igv-menu-popup-shim {\n padding-left: 8px;\n padding-right: 8px;\n padding-bottom: 1px;\n padding-top: 1px;\n}\n\n.igv-menu-popup-header {\n position: relative;\n width: 100%;\n height: 24px;\n cursor: move;\n border-top-color: transparent;\n border-top-left-radius: 4px;\n border-top-right-radius: 4px;\n border-bottom-color: #7F7F7F;\n border-bottom-style: solid;\n border-bottom-width: thin;\n background-color: #eee;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-end;\n align-items: center;\n}\n.igv-menu-popup-header div {\n margin-right: 4px;\n height: 12px;\n width: 12px;\n color: #7F7F7F;\n}\n.igv-menu-popup-header div:hover {\n cursor: pointer;\n color: #444;\n}\n\n.igv-menu-popup-check-container {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n width: 100%;\n height: 20px;\n margin-right: 4px;\n background-color: transparent;\n}\n.igv-menu-popup-check-container div {\n padding-top: 2px;\n padding-left: 8px;\n}\n.igv-menu-popup-check-container div:first-child {\n position: relative;\n width: 12px;\n height: 12px;\n}\n.igv-menu-popup-check-container div:first-child svg {\n position: absolute;\n width: 12px;\n height: 12px;\n}\n\n.igv-user-feedback {\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 512px;\n height: 360px;\n z-index: 2048;\n background-color: white;\n border-color: #a2a2a2;\n border-style: solid;\n border-width: thin;\n font-family: "Open Sans", sans-serif;\n font-size: medium;\n font-weight: 400;\n color: #444;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-user-feedback div:first-child {\n position: relative;\n height: 24px;\n width: 100%;\n background-color: white;\n border-bottom-color: #a2a2a2;\n border-bottom-style: solid;\n border-bottom-width: thin;\n}\n.igv-user-feedback div:first-child div {\n position: absolute;\n top: 2px;\n width: 16px;\n height: 16px;\n background-color: transparent;\n}\n.igv-user-feedback div:first-child div:first-child {\n left: 8px;\n}\n.igv-user-feedback div:first-child div:last-child {\n cursor: pointer;\n right: 8px;\n}\n.igv-user-feedback div:last-child {\n width: 100%;\n height: calc(100% - 24px);\n border-width: 0;\n}\n.igv-user-feedback div:last-child div {\n width: auto;\n height: auto;\n margin: 8px;\n}\n\n.igv-loading-spinner-container {\n z-index: 1024;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 32px;\n height: 32px;\n display: flex;\n flex-direction: row;\n flex-wrap: nowrap;\n justify-content: center;\n align-items: center;\n}\n.igv-loading-spinner-container > div {\n box-sizing: border-box;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n border: 4px solid rgba(128, 128, 128, 0.5);\n border-top-color: rgb(255, 255, 255);\n animation: spin 1s ease-in-out infinite;\n -webkit-animation: spin 1s ease-in-out infinite;\n}\n\n@keyframes spin {\n to {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@-webkit-keyframes spin {\n to {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n.igv-roi-menu-next-gen {\n position: absolute;\n z-index: 512;\n font-family: "Open Sans", sans-serif;\n font-size: small;\n font-weight: 400;\n color: #4b4b4b;\n background-color: white;\n width: 192px;\n border-radius: 4px;\n border-color: #7F7F7F;\n border-style: solid;\n border-width: thin;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: stretch;\n}\n.igv-roi-menu-next-gen > div:first-child {\n height: 24px;\n border-top-color: transparent;\n border-top-left-radius: 4px;\n border-top-right-radius: 4px;\n border-bottom-color: #7F7F7F;\n border-bottom-style: solid;\n border-bottom-width: thin;\n background-color: #eee;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-end;\n align-items: center;\n}\n.igv-roi-menu-next-gen > div:first-child > div {\n margin-right: 4px;\n height: 12px;\n width: 12px;\n color: #7F7F7F;\n}\n.igv-roi-menu-next-gen > div:first-child > div:hover {\n cursor: pointer;\n color: #444;\n}\n.igv-roi-menu-next-gen > div:last-child {\n background-color: white;\n border-bottom-left-radius: 4px;\n border-bottom-right-radius: 4px;\n border-bottom-color: transparent;\n border-bottom-style: solid;\n border-bottom-width: 0;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: stretch;\n text-align: start;\n vertical-align: middle;\n}\n.igv-roi-menu-next-gen > div:last-child > div {\n height: 24px;\n padding-left: 4px;\n border-bottom-style: solid;\n border-bottom-width: thin;\n border-bottom-color: #7f7f7f;\n}\n.igv-roi-menu-next-gen > div:last-child > div:not(:first-child):hover {\n background-color: rgba(127, 127, 127, 0.1);\n}\n.igv-roi-menu-next-gen > div:last-child div:first-child {\n font-style: italic;\n text-align: center;\n padding-right: 4px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.igv-roi-menu-next-gen > div:last-child > div:last-child {\n border-bottom-width: 0;\n border-bottom-color: transparent;\n}\n\n.igv-roi-placeholder {\n font-style: normal;\n color: rgba(75, 75, 75, 0.6);\n}\n\n.igv-roi-table {\n position: absolute;\n z-index: 1024;\n width: min-content;\n max-width: 1600px;\n border-color: #7f7f7f;\n border-radius: 4px;\n border-style: solid;\n border-width: thin;\n font-family: "Open Sans", sans-serif;\n font-size: 12px;\n font-weight: 400;\n background-color: white;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: stretch;\n cursor: default;\n}\n.igv-roi-table > div {\n height: 24px;\n font-size: 14px;\n text-align: start;\n vertical-align: middle;\n line-height: 24px;\n}\n.igv-roi-table > div:first-child {\n border-color: transparent;\n border-top-left-radius: 4px;\n border-top-right-radius: 4px;\n border-top-width: 0;\n border-bottom-color: #7f7f7f;\n border-bottom-style: solid;\n border-bottom-width: thin;\n background-color: #eee;\n cursor: move;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-between;\n align-items: center;\n}\n.igv-roi-table > div:first-child > div:first-child {\n text-align: center;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n margin-left: 4px;\n margin-right: 4px;\n width: calc(100% - 4px - 12px);\n}\n.igv-roi-table > div:first-child > div:last-child {\n margin-right: 4px;\n margin-bottom: 2px;\n height: 12px;\n width: 12px;\n color: #7f7f7f;\n}\n.igv-roi-table > div:first-child > div:last-child > svg {\n display: block;\n}\n.igv-roi-table > div:first-child > div:last-child:hover {\n cursor: pointer;\n color: #444;\n}\n.igv-roi-table > .igv-roi-table-description {\n padding: 4px;\n margin-left: 4px;\n word-break: break-all;\n overflow-y: auto;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n background-color: transparent;\n}\n.igv-roi-table > .igv-roi-table-goto-explainer {\n margin-top: 5px;\n margin-left: 4px;\n color: #7F7F7F;\n font-style: italic;\n height: 24px;\n border-top: solid lightgray;\n background-color: transparent;\n}\n.igv-roi-table > .igv-roi-table-column-titles {\n height: 24px;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: stretch;\n align-items: stretch;\n padding-right: 16px;\n background-color: white;\n border-top-color: #7f7f7f;\n border-top-style: solid;\n border-top-width: thin;\n border-bottom-color: #7f7f7f;\n border-bottom-style: solid;\n border-bottom-width: thin;\n}\n.igv-roi-table > .igv-roi-table-column-titles > div {\n font-size: 14px;\n vertical-align: middle;\n line-height: 24px;\n text-align: left;\n margin-left: 4px;\n height: 24px;\n overflow: hidden;\n text-overflow: ellipsis;\n border-right-color: #7f7f7f;\n border-right-style: solid;\n border-right-width: thin;\n}\n.igv-roi-table > .igv-roi-table-column-titles > div:last-child {\n border-right: unset;\n}\n.igv-roi-table > .igv-roi-table-row-container {\n overflow: auto;\n resize: both;\n max-width: 1600px;\n height: 360px;\n background-color: transparent;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: stretch;\n}\n.igv-roi-table > .igv-roi-table-row-container > .igv-roi-table-row {\n height: 24px;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: stretch;\n align-items: stretch;\n}\n.igv-roi-table > .igv-roi-table-row-container > .igv-roi-table-row > div {\n font-size: 14px;\n vertical-align: middle;\n line-height: 24px;\n text-align: left;\n margin-left: 4px;\n height: 24px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n border-right-color: transparent;\n border-right-style: solid;\n border-right-width: thin;\n}\n.igv-roi-table > .igv-roi-table-row-container > .igv-roi-table-row > div:last-child {\n border-right: unset;\n}\n.igv-roi-table > .igv-roi-table-row-container > .igv-roi-table-row-hover {\n background-color: rgba(0, 0, 0, 0.04);\n}\n.igv-roi-table > div:last-child {\n height: 32px;\n line-height: 32px;\n border-top-color: #7f7f7f;\n border-top-style: solid;\n border-top-width: thin;\n border-bottom-color: transparent;\n border-bottom-left-radius: 4px;\n border-bottom-right-radius: 4px;\n border-bottom-width: 0;\n background-color: #eee;\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: space-around;\n align-items: center;\n}\n\n.igv-roi-table-row-selected {\n background-color: rgba(0, 0, 0, 0.125);\n}\n\n.igv-roi-table-button {\n cursor: pointer;\n height: 20px;\n user-select: none;\n line-height: 20px;\n text-align: center;\n vertical-align: middle;\n font-family: "Open Sans", sans-serif;\n font-size: 13px;\n font-weight: 400;\n color: black;\n padding-left: 6px;\n padding-right: 6px;\n background-color: rgb(239, 239, 239);\n border-color: black;\n border-style: solid;\n border-width: thin;\n border-radius: 3px;\n}\n\n.igv-roi-table-button:hover {\n font-weight: 400;\n background-color: rgba(0, 0, 0, 0.13);\n}\n\n.igv-roi-region {\n z-index: 64;\n position: absolute;\n top: 0;\n bottom: 0;\n pointer-events: none;\n overflow: visible;\n margin-top: 44px;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: stretch;\n}\n.igv-roi-region > div {\n position: relative;\n width: 100%;\n height: 8px;\n pointer-events: auto;\n}\n\n.igv-roi-menu {\n position: absolute;\n z-index: 1024;\n width: 144px;\n border-color: #7f7f7f;\n border-radius: 4px;\n border-style: solid;\n border-width: thin;\n font-family: "Open Sans", sans-serif;\n background-color: white;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: stretch;\n}\n.igv-roi-menu > div:not(:last-child) {\n border-bottom-color: rgba(128, 128, 128, 0.5);\n border-bottom-style: solid;\n border-bottom-width: thin;\n}\n.igv-roi-menu > div:first-child {\n border-top-left-radius: 4px;\n border-top-right-radius: 4px;\n border-top-color: transparent;\n border-top-style: solid;\n border-top-width: 0;\n}\n.igv-roi-menu > div:last-child {\n border-bottom-left-radius: 4px;\n border-bottom-right-radius: 4px;\n border-bottom-color: transparent;\n border-bottom-style: solid;\n border-bottom-width: 0;\n}\n\n.igv-roi-menu-row {\n height: 24px;\n padding-left: 8px;\n font-size: small;\n text-align: start;\n vertical-align: middle;\n line-height: 24px;\n background-color: white;\n}\n\n.igv-roi-menu-row-edit-description {\n width: -webkit-fill-available;\n font-size: small;\n text-align: start;\n vertical-align: middle;\n background-color: white;\n padding-left: 4px;\n padding-right: 4px;\n padding-bottom: 4px;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: stretch;\n align-items: stretch;\n}\n.igv-roi-menu-row-edit-description > label {\n margin-left: 2px;\n margin-bottom: 0;\n display: block;\n width: -webkit-fill-available;\n}\n.igv-roi-menu-row-edit-description > input {\n display: block;\n margin-left: 2px;\n margin-right: 2px;\n margin-bottom: 1px;\n width: -webkit-fill-available;\n}\n\n.igv-container {\n position: relative;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n padding-top: 4px;\n user-select: none;\n -webkit-user-select: none;\n -ms-user-select: none;\n}\n\n.igv-viewport {\n position: relative;\n margin-top: 5px;\n line-height: 1;\n overflow-x: hidden;\n overflow-y: hidden;\n}\n\n.igv-viewport-content {\n position: relative;\n width: 100%;\n}\n.igv-viewport-content > canvas {\n position: relative;\n display: block;\n}\n\n.igv-column-container {\n position: relative;\n display: flex;\n flex-direction: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: stretch;\n width: 100%;\n}\n\n.igv-column-shim {\n width: 1px;\n margin-left: 2px;\n margin-right: 2px;\n background-color: #545453;\n}\n\n.igv-axis-column {\n position: relative;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n box-sizing: border-box;\n height: 100%;\n width: 50px;\n}\n.igv-axis-column > div {\n margin-top: 5px;\n width: 100%;\n}\n\n.igv-column {\n position: relative;\n position: relative;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n box-sizing: border-box;\n height: 100%;\n}\n\n.igv-sample-info-column {\n position: relative;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n box-sizing: border-box;\n height: 100%;\n}\n\n.igv-sample-name-column {\n position: relative;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n box-sizing: border-box;\n height: 100%;\n}\n\n.igv-scrollbar-column {\n position: relative;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n box-sizing: border-box;\n height: 100%;\n width: 14px;\n}\n.igv-scrollbar-column > div {\n position: relative;\n margin-top: 5px;\n width: 14px;\n}\n.igv-scrollbar-column > div > div {\n cursor: pointer;\n position: absolute;\n top: 0;\n left: 2px;\n width: 8px;\n border-width: 1px;\n border-style: solid;\n border-color: #c4c4c4;\n border-top-left-radius: 4px;\n border-top-right-radius: 4px;\n border-bottom-left-radius: 4px;\n border-bottom-right-radius: 4px;\n}\n.igv-scrollbar-column > div > div:hover {\n background-color: #c4c4c4;\n}\n\n.igv-track-drag-column {\n position: relative;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n box-sizing: border-box;\n height: 100%;\n width: 12px;\n background-color: white;\n}\n.igv-track-drag-column > .igv-track-drag-handle {\n z-index: 512;\n position: relative;\n cursor: pointer;\n margin-top: 5px;\n width: 100%;\n border-style: solid;\n border-width: 0;\n border-top-right-radius: 6px;\n border-bottom-right-radius: 6px;\n background-color: #c4c4c4;\n}\n.igv-track-drag-column .igv-track-drag-handle-hover {\n background-color: #787878;\n}\n.igv-track-drag-column > .igv-track-drag-shim {\n position: relative;\n margin-top: 5px;\n width: 100%;\n border-style: solid;\n border-width: 0;\n}\n\n.igv-gear-menu-column {\n position: relative;\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n box-sizing: border-box;\n height: 100%;\n width: 28px;\n}\n.igv-gear-menu-column > div {\n display: flex;\n flex-direction: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n margin-top: 5px;\n width: 100%;\n background: white;\n}\n.igv-gear-menu-column > div > div {\n position: relative;\n margin-top: 4px;\n width: 16px;\n height: 16px;\n color: #7F7F7F;\n}\n.igv-gear-menu-column > div > div:hover {\n cursor: pointer;\n color: #444;\n}\n\n/*# sourceMappingURL=dom.css.map */\n',document.head.append(e)}();const Bx=io.oauth;var yx={TrackUtils:yf,IGVGraphics:Eo,MenuUtils:Gt,DataRangeDialog:Wt,createTrack:async function(e,t){return await px.prototype.createTrack.call(t,e)},createBrowser:async function(e,t){void 0===t&&(t={}),Ap.KNOWN_GENOMES||await Ap.initializeGenomes(t),function(e){void 0===e.minimumBases&&(e.minimumBases=40);void 0===e.showIdeogram&&(e.showIdeogram=!0);void 0===e.showCircularView&&(e.showCircularView=!1);void 0===e.showCircularViewButton&&(e.showCircularViewButton=!1);void 0===e.showTrackLabelButton&&(e.showTrackLabelButton=!0);void 0===e.showTrackLabels&&(e.showTrackLabels=!0);void 0===e.showROITableButton&&(e.showROITableButton=!1);void 0===e.showROITable&&(e.showROITable=!1);void 0===e.showCursorTrackingGuideButton&&(e.showCursorTrackingGuideButton=!0);void 0===e.showCursorGuide&&(e.showCursorGuide=e.showCursorTrackingGuide||!1);void 0===e.showCenterGuideButton&&(e.showCenterGuideButton=!0);void 0===e.showCenterGuide&&(e.showCenterGuide=!1);void 0===e.showSampleNames&&(e.showSampleNames=!1);void 0===e.showSVGButton&&(e.showSVGButton=!0);void 0===e.showControls&&(e.showControls=!0);void 0===e.showNavigation&&(e.showNavigation=!0);void 0===e.showRuler&&(e.showRuler=!0);void 0===e.flanking&&(e.flanking=1e3);void 0===e.pairsSupported&&(e.pairsSupported=!0);e.tracks||(e.tracks=[])}(t),t.queryParametersSupported&&function(e){var t,i,n,r,s,o,a,A,c;let l,h,d;if(a=window.location.href,s={},t=a.indexOf("?"),i=a.lastIndexOf("#"),t>=0)for(i<0&&(i=a.length),n=t+1;nt&&(i.indexURL=h[t]),d&&d.length>t&&(i.name=d[t]),e.tracks.push(i)}}}(t),t.apiKey&&io.setApiKey(t.apiKey),t.oauthToken&&io.setOauthToken(t.oauthToken),t.clientId&&!Ws()&&await async function(e){if(!google.accounts.oauth2.initTokenClient)throw new Error("Google accounts token client not loaded (https://accounts.google.com/gsi/client)");if(Ws())throw new Error("Google client is already initialized");const t={client_id:e.client_id,scope:e.scope||"https://www.googleapis.com/auth/userinfo.profile",state:e.state||"igv",error:e=>{throw new Error(e.type)},hint:e.hint,hosted_domain:e.hosted_domain},i=google.accounts.oauth2.initTokenClient(t);google.igv={tokenClient:i,apiKey:e.apiKey}}({clientId:t.clientId,apiKey:t.apiKey,scope:"https://www.googleapis.com/auth/userinfo.profile"});const i=new px(t,e);bx.push(i);const n=t.sessionURL||t.session;return n?await i.loadSession({url:n}):await i.loadSessionObject(t),i.navbarManager.navbarDidResize(i.$navigation.width()),i},removeBrowser:function(e){e.dispose(),e.root.remove(),bx=bx.filter((t=>t!==e))},removeAllBrowsers:function(){for(let e of bx)e.dispose(),e.root.remove();bx=[]},visibilityChange:async function(){for(let e of bx)await e.visibilityChange()},setGoogleOauthToken:function(e){return io.setOauthToken(e)},setOauthToken:function(e,t){return io.setOauthToken(e,t)},oauth:Bx,version:op,setApiKey:vx,TrackBase:ag,registerTrackClass:function(e,t){k_.set(e,((e,i)=>new t(e,i)))},registerTrackCreatorFunction:function(e,t){k_.set(e,t)},registerFileFormats:Bf};return yx})); //# sourceMappingURL=igv.min.js.map diff --git a/index.html b/index.html index 5a16424..b6a8b32 100644 --- a/index.html +++ b/index.html @@ -272,8 +272,8 @@
--> Sep 7, 2023
- added transcript toggling to simplify SpliceAI transcript output
- - added transcript strand to SpliceAI results
- - added score visualizations using custom IGV.js tracks
+ - added transcript strand to the results table
+ - added score visualizations for SpliceAI and Pangolin using custom IGV.js tracks

May 22, 2023
- changed defaults to 'masked' and max distance to 500bp
@@ -561,65 +561,105 @@ } // specify IGV tracks and the data to display in them - const reference = responseSpliceAI.hg == "37" ? "hg19" : "hg38" - const gencodeTrackPath = responseSpliceAI.hg == "37" ? - "gs://tgg-viewer/ref/GRCh37/gencode_v44/knownGene_v44.hg19.sorted.txt.gz" : - "gs://tgg-viewer/ref/GRCh38/gencode_v44/knownGene_v44.hg38.sorted.txt.gz" - const tracks = [] + tracks.push({ + "name": "Refseq", + "format": "refgene", + "url": responseSpliceAI.hg == "38" ? + "https://hgdownload.soe.ucsc.edu/goldenPath/hg38/database/ncbiRefSeq.txt.gz" : + "https://hgdownload.soe.ucsc.edu/goldenPath/hg19/database/ncbiRefSeq.txt.gz", + "indexed": false, + "infoURL": "https://www.ncbi.nlm.nih.gov/gene/?term=$$" + }) + + tracks.push({ + height: 30, + name: "Variant (?) ", + type: "vcf", + description: `This tracks shows the position of the ${chrom}:${pos} ${ref}>${alt} variant.`, + features: [ + { + chr: chrom, //see createVCFVariant function in the igv.js repo for the allowed fields + pos: pos, + start: pos - 1, + end: pos, + referenceAllele: ref, + alternateBases: alt, + names: ".", // id in VCF + info: { + variant: `${chrom}-${pos}-${ref}-${alt}`, + } + }, + ], + }) + if (responseSpliceAI) { tracks.push({ - height: 100, - rawOrDelta: "raw", - name: "SpliceAI", - tool: "spliceai", - type: "spliceprediction", - features: responseSpliceAI.allNonZeroScores, - strand: responseSpliceAI.allNonZeroScoresStrand, + name: `SpliceAI (?)`, + description: `Transcript: ${responseSpliceAI.allNonZeroScoresTranscriptId} (${responseSpliceAI.allNonZeroScoresStrand == '-' ? 'minus' : 'plus'} strand)
+ SpliceAI predictions of splice acceptor & donor sites within the +/- ${responseSpliceAI.distance}bp window
+ around ${chrom}:${pos} ${ref}>${alt}. This track shows markers that represent the scores for the
+ reference sequence (without the variant) and the
+ alternate sequence (with the variant).
+ A marker is shown at all positions where a score is ≥ 0.01.
+ SpliceAI outputs separate predictions for whether a given position is a splice acceptor and/or a splice donor, so
+ A's represent acceptor probability scores, and
+ D's represent donor probability scores.
+ The letters are shown up-side-down when the alternate sequence score is lower than the reference sequence score.
+ Numerical labels show the scores predicted from the reference sequence. + `, + height: 100, + rawOrDelta: "raw", + tool: "SpliceAI", + type: "spliceprediction", + features: responseSpliceAI.allNonZeroScores, + strand: responseSpliceAI.allNonZeroScoresStrand, }) tracks.push({ - height: 200, - rawOrDelta: "delta", - name: "SpliceAI", - tool: "spliceai", - type: "spliceprediction", - features: responseSpliceAI.allNonZeroScores, - strand: responseSpliceAI.allNonZeroScoresStrand, + name: `SpliceAI (?)`, + description: `Transcript: ${responseSpliceAI.allNonZeroScoresTranscriptId} (${responseSpliceAI.allNonZeroScoresStrand == '-' ? 'minus' : 'plus'} strand)
+ SpliceAI delta score predictions for gain and loss of splice acceptors and donors within a
+ +/- ${responseSpliceAI.distance}bp window around ${chrom}:${pos} ${ref}>${alt}.
+ This track shows markers at all positions where the |delta score| is ≥ 0.01.
+ Bar colors: red is for delta scores ≥ 0.8, + yellow is for delta scores ≥ 0.5, + green is for delta scores ≥ 0.2
+ A's represent acceptor probability scores
+ D's represent donor probability scores
+ `, + height: 200, + rawOrDelta: "delta", + tool: "SpliceAI", + type: "spliceprediction", + features: responseSpliceAI.allNonZeroScores, + strand: responseSpliceAI.allNonZeroScoresStrand, }) } if (responsePangolin) { tracks.push({ + name: `Pangolin (?)`, + description: `Gene: ${responsePangolin.allNonZeroScoresTranscriptId} (${responsePangolin.allNonZeroScoresStrand == '-' ? 'minus' : 'plus'} strand)
+ Pangolin delta score predictions for gain and loss of splice sites at positions
+ within a +/- ${responsePangolin.distance}bp window around ${chrom}:${pos} ${ref}>${alt}.
+ This track shows markers at all positions where the delta score is ≥ 0.1.
+ Bar colors: red is for delta scores ≥ 0.8, + yellow is for delta scores ≥ 0.5, + green is for delta scores ≥ 0.2
+ `, height: 200, rawOrDelta: "delta", - name: "Pangolin", - tool: "pangolin", + tool: "Pangolin", type: "spliceprediction", features: responsePangolin.allNonZeroScores, strand: responsePangolin.allNonZeroScoresStrand, }) } - tracks.push({ - height: 30, - name: "Variant", - type: "vcf", - features: [ - { - chr: chrom, //see createVCFVariant function in the igv.js repo for the allowed fields - pos: pos, - start: pos - 1, - end: pos, - referenceAllele: ref, - alternateBases: alt, - names: ".", // id in VCF - info: { - variant: `${chrom}-${pos}-${ref}-${alt}`, - } - }, - ], - }) + const gencodeTrackPath = responseSpliceAI.hg == "37" ? + "gs://tgg-viewer/ref/GRCh37/gencode_v44/knownGene_v44.hg19.sorted.txt.gz" : + "gs://tgg-viewer/ref/GRCh38/gencode_v44/knownGene_v44.hg38.sorted.txt.gz" tracks.push({ name: "Gencode v44", @@ -640,9 +680,13 @@ for (const splicePredictionType of ["loss", "gain"]) { tracks.push( { - height: 100, - name: `SpliceAI: splice ${splicePredictionType} score >= ${minScore}`, + name: `SpliceAI: A or D ${splicePredictionType} ≥ ${minScore} (?)`, + description: `This track visualizes Illumina's precomputed SpliceAI score tables for SNVs and small INDELs.
+ Each genomic location where an SNV or INDEL variant would have a SpliceAI score ≥ ${minScore} is shown as the origin of an arrow.
+ The arrow points to the location where that variant would most likely cause acceptor or donor ${splicePredictionType}. + Clicking on the arrow will display additional information.`, type: "spliceJunctions", + height: 100, url: `gs://tgg-viewer/ref/GRCh38/spliceai/spliceai_scores.raw.snps_and_indels.hg38.filtered.sorted.score_${minScore}.splice_${splicePredictionType}.bed.gz`, indexURL: `gs://tgg-viewer/ref/GRCh38/spliceai/spliceai_scores.raw.snps_and_indels.hg38.filtered.sorted.score_${minScore}.splice_${splicePredictionType}.bed.gz.tbi`, } @@ -651,16 +695,19 @@ } - for (const filenamePrefix of [ - "GTEX_muscle.803_samples", - "GTEX_blood.755_samples", - "GTEX_fibs.504_samples", - "GTEX_lymphocytes.174_samples", - "GTEX_brain_cortex.255_samples", - //"GTEX_frontal_cortex.209_samples", + for (const [filenamePrefix, tissue, sampleCount] of [ + ["GTEX_muscle.803_samples", "muscle", 803], + ["GTEX_blood.755_samples", "blood", 755], + ["GTEX_fibs.504_samples", "fibroblasts", 504], + ["GTEX_lymphocytes.174_samples", "lymphocytes", 174], + ["GTEX_brain_cortex.255_samples", "brain cortex", 255], + //["GTEX_frontal_cortex.209_samples", "frontal cortex", 803], ]) { tracks.push({ - name: filenamePrefix.replaceAll(".", ": ").replaceAll("_", " ").replace("fibs", "fibroblasts"), + name: `GTEx ${tissue}: ${sampleCount} samples (?)`, + description: `This track shows the combined splice junctions from all ${sampleCount} ${tissue} samples available in GTEx v8. + Splice junctions are labeled with the total number of RNA-seq reads that supported the junction, summed across the ${sampleCount} samples. + The coverage track shows the total number of RNA-seq reads that overlap each position, summed across all samples and divided by ${sampleCount}.`, type: "merged", height: 100, tracks: [{ @@ -679,10 +726,34 @@ }) } + let locusMargin = maxPos - minPos < 200 ? 15 : 50 + + // igv.js reference genome specs are copied from https://igv.org/genomes/genomes.json + // These must be specified explicitly rather than just setting the reference to "hg19" or "hg38" so that + // the RefSeq gene track can be the first track (as described in https://github.com/igvteam/igv.js/issues/1518) + let reference = responseSpliceAI.hg == "37" ? { + "id": "hg19", + "name": "Human (GRCh37/hg19)", + "fastaURL": "https://igv-genepattern-org.s3.amazonaws.com/genomes/seq/hg19/hg19.fasta", + "indexURL": "https://igv-genepattern-org.s3.amazonaws.com/genomes/seq/hg19/hg19.fasta.fai", + "cytobandURL": "https://igv-genepattern-org.s3.amazonaws.com/genomes/seq/hg19/cytoBand.txt", + "aliasURL": "https://s3.amazonaws.com/igv.org.genomes/hg19/hg19_alias.tab", + "chromosomeOrder": "chr1, chr2, chr3, chr4, chr5, chr6, chr7, chr8, chr9, chr10, chr11, chr12, chr13, chr14, chr15, chr16, chr17, chr18, chr19, chr20, chr21, chr22, chrX, chrY", + "tracks": tracks, + } : { + "id": "hg38", + "name": "Human (GRCh38/hg38)", + "fastaURL": "https://igv-genepattern-org.s3.amazonaws.com/genomes/seq/hg38/hg38.fa", + "indexURL": "https://igv-genepattern-org.s3.amazonaws.com/genomes/seq/hg38/hg38.fa.fai", + "cytobandURL": "https://s3.amazonaws.com/igv.org.genomes/hg38/annotations/cytoBandIdeo.txt.gz", + "aliasURL": "https://s3.amazonaws.com/igv.org.genomes/hg38/hg38_alias.tab", + "chromosomeOrder": "chr1, chr2, chr3, chr4, chr5, chr6, chr7, chr8, chr9, chr10, chr11, chr12, chr13, chr14, chr15, chr16, chr17, chr18, chr19, chr20, chr21, chr22, chrX, chrY", + "tracks": tracks, + } + return { reference: reference, - locus: `${chrom}:${minPos - 50}-${maxPos + 50}`, - tracks: tracks, + locus: `${chrom}:${minPos - locusMargin}-${maxPos + locusMargin}`, } } @@ -736,8 +807,6 @@ //sort by (gene name, is canonical transcript, is non-coding transcriipt) parsed_scores_or_errors = _.chain(parsed_scores_or_errors).sortBy('sort_key').value() - console.log("Parsed scores:", parsed_scores_or_errors) - return parsed_scores_or_errors.map(function(scores_or_error, index) { let scores = scores_or_error @@ -760,6 +829,8 @@ const biotype_link = `` const refseq_transcript_id_link = refseq_transcript_ids ? (" /" + ` ${refseq_transcript_ids[0]}`) : '' gene_and_transcript_id = `

${biotype_link}${canonical_transcript_text} ` + } else { + gene_and_transcript_id = ` ` } //round to 2 decimal places if (scores.is_pangolin) {